text:
#include "linkableobject.h"
#include "utils.h"

#include <iostream>
#include <fstream>
#include <stdexcept>
#include <utility>
#include <cassert>
#include <cstdlib>

std::string LinkableObject::name() const {
	return _name;
}

void LinkableObject::setName(const std::string &str) {
	_name=str;
}

LinkableObject::Word LinkableObject::virtualAddress() const {
	return _virtualAddress;
}

void LinkableObject::setVirtualAddress(Word addr) {
	_virtualAddress=addr;
}

LinkableObject::Byte *LinkableObject::code() {
	return _code.data();
}

const LinkableObject::Byte *LinkableObject::code() const {
	return _code.data();
}

std::size_t LinkableObject::codeSize() const {
	return _code.size();
}

LinkableObject::Word LinkableObject::addWord(Word w) {
	auto rva=addPadding(sizeof(Word));
// Note: this code doesn't depend on host machine's endianness
	_code.push_back(static_cast<Byte>(w));
	_code.push_back(static_cast<Byte>(w>>8));
	_code.push_back(static_cast<Byte>(w>>16));
	_code.push_back(static_cast<Byte>(w>>24));
	return rva;
}

LinkableObject::Word LinkableObject::addByte(Byte b) {
	auto rva=static_cast<LinkableObject::Word>(_code.size());
	_code.push_back(b);
	return rva;
}

LinkableObject::Word LinkableObject::addBytes(const Byte *p,std::size_t n) {
	auto rva=static_cast<LinkableObject::Word>(_code.size());
	_code.insert(_code.end(),p,p+n);
	return rva;
}

LinkableObject::Word LinkableObject::addZeros(std::size_t n) {
	auto rva=static_cast<LinkableObject::Word>(_code.size());
	_code.resize(_code.size()+n);
	return rva;
}

LinkableObject::Word LinkableObject::addPadding(std::size_t size) {
	auto padding=(size-_code.size()%size)%size;
	if(padding>0) _code.resize(_code.size()+padding);
	return static_cast<LinkableObject::Word>(_code.size());
}

LinkableObject::Word LinkableObject::getWord(Word rva) const {
	Word w=0;
	if(rva<codeSize()) w|=static_cast<Word>(_code[rva++]);
	if(rva<codeSize()) w|=static_cast<Word>(_code[rva++])<<8;
	if(rva<codeSize()) w|=static_cast<Word>(_code[rva++])<<16;
	if(rva<codeSize()) w|=static_cast<Word>(_code[rva++])<<24;
	return w;
}

void LinkableObject::replaceWord(Word rva,Word value) {
	assert(rva+sizeof(Word)<=codeSize());
// Note: this code doesn't depend on host machine's endianness
	_code[rva++]=static_cast<Byte>(value);
	_code[rva++]=static_cast<Byte>(value>>8);
	_code[rva++]=static_cast<Byte>(value>>16);
	_code[rva++]=static_cast<Byte>(value>>24);
}

void LinkableObject::addSymbol(const std::string &name,Word rva) {
	auto &data=symbol(name);
	if(data.type!=Unknown) throw std::runtime_error("Symbol \""+name+"\" is already defined");
	data.type=Local;
	data.rva=rva;
}

void LinkableObject::addImportedSymbol(const std::string &name) {
	auto &data=symbol(name);
	if(data.type!=Unknown) throw std::runtime_error("Symbol \""+name+"\" is already defined");
	data.type=Imported;
}

void LinkableObject::exportSymbol(const std::string &name) {
	auto it=_symbols.find(name);
	if(it==_symbols.end()||it->second.type==Unknown) throw std::runtime_error("Undefined symbol \""+name+"\"");
	if(it->second.type==Imported) throw std::runtime_error("Symbol \""+name+"\" can't be both imported and exported at the same time");
	if(it->second.type==Exported) throw std::runtime_error("Symbol \""+name+"\" has been already exported");
	it->second.type=Exported;
}

void LinkableObject::addReference(const std::string &symbolName,const Reference &ref) {
	auto &data=symbol(symbolName);
	data.refs.push_back(ref);
}

LinkableObject::SymbolData &LinkableObject::symbol(const std::string &name) {
	return _symbols[name];
}

const LinkableObject::SymbolData &LinkableObject::symbol(const std::string &name) const {
	auto const it=_symbols.find(name);
	if(it==_symbols.end()) throw std::runtime_error("Undefined symbol \""+name+"\"");
	return it->second;
}

const LinkableObject::SymbolTable &LinkableObject::symbols() const {
	return _symbols;
}

void LinkableObject::serialize(const std::string &filename) const {
	std::ofstream out(filename,std::ios_base::out);
	if(!out) throw std::runtime_error("Cannot open \""+filename+"\" for writing");

	out<<"LinkableObject"<<std::endl;
	if(!_name.empty()) out<<"Name "<<Utils::urlEncode(_name)<<std::endl;
	out<<"VirtualAddress 0x"<<Utils::hex(_virtualAddress)<<std::endl;

	out<<std::endl;
	out<<"Start Code"<<std::endl;

	for(Word rva=0;rva<_code.size();rva+=sizeof(Word)) {
		out<<"\t0x"<<Utils::hex(getWord(rva))<<std::endl;
	}

	out<<"End Code"<<std::endl;

	for(auto const &sym: _symbols) {
		if(sym.second.type==Unknown)
			throw std::runtime_error("Undefined symbol: \""+sym.first+"\"");
		out<<std::endl;
		out<<"Start Symbol"<<std::endl;
		out<<"\tName "<<Utils::urlEncode(sym.first)<<std::endl;
		if(sym.second.type==Local) out<<"\tType Local"<<std::endl;
		else if(sym.second.type==Exported) out<<"\tType Exported"<<std::endl;
		else out<<"\tType Imported"<<std::endl;
		if(sym.second.type!=Imported) out<<"\tRVA 0x"<<Utils::hex(sym.second.rva)<<std::endl;
		for(auto const &ref: sym.second.refs) {
			out<<"\tRef ";
			out<<Utils::urlEncode(ref.source)<<" ";
			out<<ref.line<<" ";
			out<<"0x"<<Utils::hex(ref.rva)<<" ";
			out<<ref.offset<<" ";
			if(ref.type==Regular) out<<"Regular"<<std::endl;
			else if(ref.type==Short) out<<"Short"<<std::endl;
		}
		out<<"End Symbol"<<std::endl;
	}
}

void LinkableObject::deserialize(const std::string &filename) {
	std::ifstream in(filename,std::ios_base::in);
	if(!in) throw std::runtime_error("Cannot open \""+filename+"\"");

	operator=(LinkableObject());

	std::string line;
	for(;;) {
		if(!std::getline(in,line)) throw std::runtime_error("Bad object format");
		auto tokens=tokenize(line);
		if(tokens.empty()) continue;
		else if(tokens[0]!="LinkableObject") throw std::runtime_error("Bad object format");
		break;
	}

	while(std::getline(in,line)) {
		auto tokens=tokenize(line);
		if(tokens.empty()) continue;
		if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
		else if(tokens[0]=="Name") _name=Utils::urlDecode(tokens[1]);
		else if(tokens[0]=="VirtualAddress") _virtualAddress=std::strtoul(tokens[1].c_str(),NULL,0);
		else if(tokens[0]=="Start") {
			if(tokens[1]=="Code") deserializeCode(in);
			else if(tokens[1]=="Symbol") deserializeSymbol(in);
			else throw std::runtime_error("Unexpected token: \""+tokens[1]+"\"");
		}
		else throw std::runtime_error("Unexpected token: \""+tokens[0]+"\"");
	}
}

/*
 * Private members
 */

void LinkableObject::deserializeCode(std::istream &in) {
	std::string line;
	while(std::getline(in,line)) {
		auto tokens=tokenize(line);
		if(tokens.empty()) continue;
		if(tokens[0]=="End") {
			if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
			if(tokens[1]=="Code") return;
			throw std::runtime_error("Unexpected token: \""+tokens[1]+"\"");
		}
		auto w=static_cast<Word>(std::strtoul(tokens[0].c_str(),NULL,0));
		addWord(w);
	}
	throw std::runtime_error("Unexpected end of file");
}

void LinkableObject::deserializeSymbol(std::istream &in) {
	std::string line;
	std::string name;
	SymbolData data;
	while(std::getline(in,line)) {
		auto tokens=tokenize(line);
		if(tokens.empty()) continue;
		if(tokens[0]=="End") {
			if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
			if(tokens[1]=="Symbol") {
				if(name.empty()) throw std::runtime_error("Symbol name is not defined");
				if(data.type==Unknown) throw std::runtime_error("Bad symbol type");
				_symbols.emplace(std::move(name),std::move(data));
				return;
			}
			throw std::runtime_error("Unexpected token: \""+tokens[1]+"\"");
		}
		else if(tokens[0]=="Name") {
			if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
			name=Utils::urlDecode(tokens[1]);
		}
		else if(tokens[0]=="Type") {
			if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
			if(tokens[1]=="Local") data.type=Local;
			else if(tokens[1]=="Exported") data.type=Exported;
			else if(tokens[1]=="Imported") data.type=Imported;
			else throw std::runtime_error("Bad symbol type");
		}
		else if(tokens[0]=="RVA") {
			if(tokens.size()<2) throw std::runtime_error("Unexpected end of line");
			data.rva=std::strtoul(tokens[1].c_str(),NULL,0);
		}
		else if(tokens[0]=="Ref") {
			Reference ref;
			if(tokens.size()<4) throw std::runtime_error("Unexpected end of line");
			ref.source=Utils::urlDecode(tokens[1]);
			ref.line=std::strtoul(tokens[2].c_str(),NULL,0);
			ref.rva=std::strtoul(tokens[3].c_str(),NULL,0);
			ref.offset=std::strtoll(tokens[4].c_str(),NULL,0);
			if(tokens[5]=="Regular") ref.type=Regular;
			else if(tokens[5]=="Short") ref.type=Short;
			else throw std::runtime_error("Invalid reference type: \""+tokens[5]+"\"");
			data.refs.push_back(std::move(ref));
		}
	}
	throw std::runtime_error("Unexpected end of file");
}

std::vector<std::string> LinkableObject::tokenize(const std::string &str) {
	std::vector<std::string> tokens;
	for(std::size_t pos=0;;) {
		auto start=str.find_first_not_of(" \t\r\n",pos);
		if(start==std::string::npos) return tokens;
		auto end=str.find_first_of(" \t\r\n",start);
		if(end==std::string::npos) {
			tokens.push_back(str.substr(start));
			return tokens;
		}
		else tokens.push_back(str.substr(start,end-start));
		pos=end;
	}
}


text:
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt linguist.
'''
from __future__ import division,print_function,unicode_literals
from subprocess import Popen, PIPE
import glob
import operator
import os
import sys

OUT_CPP="qt/slingstrings.cpp"
EMPTY=['""']

def parse_po(text):
    """
    Parse 'po' format produced by xgettext.
    Return a list of (msgid,msgstr) tuples.
    """
    messages = []
    msgid = []
    msgstr = []
    in_msgid = False
    in_msgstr = False

    for line in text.split('\n'):
        line = line.rstrip('\r')
        if line.startswith('msgid '):
            if in_msgstr:
                messages.append((msgid, msgstr))
                in_msgstr = False
            # message start
            in_msgid = True

            msgid = [line[6:]]
        elif line.startswith('msgstr '):
            in_msgid = False
            in_msgstr = True
            msgstr = [line[7:]]
        elif line.startswith('"'):
            if in_msgid:
                msgid.append(line)
            if in_msgstr:
                msgstr.append(line)

    if in_msgstr:
        messages.append((msgid, msgstr))

    return messages

files = sys.argv[1:]

# xgettext -n --keyword=_ $FILES
XGETTEXT=os.getenv('XGETTEXT', 'xgettext')
if not XGETTEXT:
    print('Cannot extract strings: xgettext utility is not installed or not configured.',file=sys.stderr)
    print('Please install package "gettext" and re-run \'./configure\'.',file=sys.stderr)
    exit(1)
child = Popen([XGETTEXT,'--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()

messages = parse_po(out.decode('utf-8'))

f = open(OUT_CPP, 'w')
f.write("""

#include <QtGlobal>

// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
""")
f.write('static const char UNUSED *sling_strings[] = {\n')
messages.sort(key=operator.itemgetter(0))
for (msgid, msgstr) in messages:
    if msgid != EMPTY:
        f.write('QT_TRANSLATE_NOOP("sling-core", %s),\n' % ('\n'.join(msgid)))
f.write('};\n')
f.close()

redpajama_set_name: RedPajamaGithub


text:
package org.robolectric.util.inject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.ServiceConfigurationError;

/**
 * A simple service-provider locating facility.
 *
 * ServiceFinder is adapted from Android 9's {@link java.util.ServiceLoader}, the sole difference
 * being that rather than returning instances of the requested service, it returns the registered
 * provider classes without instantiating them.
 *
 * @see java.util.ServiceLoader
 */
@SuppressWarnings("NewApi")
final class ServiceFinder<S>
    implements Iterable<Class<? extends S>>
{

  private static final String PREFIX = "META-INF/services/";

  // The class or interface representing the service being loaded
  private final Class<S> service;

  // The class loader used to locate, load, and instantiate providers
  private final ClassLoader loader;

  // The access control context taken when the ServiceFinder is created
  // Android-changed: do not use legacy security code.
  // private final AccessControlContext acc;

  // Cached providers, in instantiation order
  private LinkedHashMap<String,Class<S>> providers = new LinkedHashMap<>();

  // The current lazy-lookup iterator
  private LazyIterator lookupIterator;

  /**
   * Clear this loader's provider cache so that all providers will be
   * reloaded.
   *
   *
 After invoking this method, subsequent invocations of the {@link
   * #iterator() iterator} method will lazily look up and instantiate
   * providers from scratch, just as is done by a newly-created loader.
   *
   *
 This method is intended for use in situations in which new providers
   * can be installed into a running Java virtual machine.
   */
  public void reload() {
    providers.clear();
    lookupIterator = new LazyIterator(service, loader);
  }

  private ServiceFinder(Class<S> svc, ClassLoader cl) {
    service = Objects.requireNonNull(svc, "Service interface cannot be null");
    loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
    // Android-changed: Do not use legacy security code.
    // On Android, System.getSecurityManager() is always null.
    // acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
    reload();
  }

  private static void fail(Class<?> service, String msg, Throwable cause)
      throws ServiceConfigurationError
  {
    throw new ServiceConfigurationError(service.getName() + ": " + msg,
        cause);
  }

  private static void fail(Class<?> service, String msg)
      throws ServiceConfigurationError
  {
    throw new ServiceConfigurationError(service.getName() + ": " + msg);
  }

  private static void fail(Class<?> service, URL u, int line, String msg)
      throws ServiceConfigurationError
  {
    fail(service, u + ":" + line + ": " + msg);
  }

  // Parse a single line from the given configuration file, adding the name
  // on the line to the names list.
  //
  private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,
      List<String> names)
      throws IOException, ServiceConfigurationError
  {
    String ln = r.readLine();
    if (ln == null) {
      return -1;
    }
    int ci = ln.indexOf('#');
    if (ci >= 0) ln = ln.substring(0, ci);
    ln = ln.trim();
    int n = ln.length();
    if (n != 0) {
      if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
        fail(service, u, lc, "Illegal configuration-file syntax");
      int cp = ln.codePointAt(0);
      if (!Character.isJavaIdentifierStart(cp))
        fail(service, u, lc, "Illegal provider-class name: " + ln);
      for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
        cp = ln.codePointAt(i);
        if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
          fail(service, u, lc, "Illegal provider-class name: " + ln);
      }
      if (!providers.containsKey(ln) && !names.contains(ln))
        names.add(ln);
    }
    return lc + 1;
  }

  // Parse the content of the given URL as a provider-configuration file.
  //
  // @param  service
  //         The service type for which providers are being sought;
  //         used to construct error detail strings
  //
  // @param  u
  //         The URL naming the configuration file to be parsed
  //
  // @return A (possibly empty) iterator that will yield the provider-class
  //         names in the given configuration file that are not yet members
  //         of the returned set
  //
  // @throws ServiceConfigurationError
  //         If an I/O error occurs while reading from the given URL, or
  //         if a configuration-file format error is detected
  //
  private Iterator<String> parse(Class<?> service, URL u)
      throws ServiceConfigurationError
  {
    InputStream in = null;
    BufferedReader r = null;
    ArrayList<String> names = new ArrayList<>();
    try {
      in = u.openStream();
      r = new BufferedReader(new InputStreamReader(in, "utf-8"));
      int lc = 1;
      while ((lc = parseLine(service, u, r, lc, names)) >= 0);
    } catch (IOException x) {
      fail(service, "Error reading configuration file", x);
    } finally {
      try {
        if (r != null) r.close();
        if (in != null) in.close();
      } catch (IOException y) {
        fail(service, "Error closing configuration file", y);
      }
    }
    return names.iterator();
  }

  // Private inner class implementing fully-lazy provider lookup
  //
  private class LazyIterator
      implements Iterator<Class<S>>
  {

    Class<S> service;
    ClassLoader loader;
    Enumeration<URL> configs = null;
    Iterator<String> pending = null;
    String nextName = null;

    private LazyIterator(Class<S> service, ClassLoader loader) {
      this.service = service;
      this.loader = loader;
    }

    private boolean hasNextService() {
      if (nextName != null) {
        return true;
      }
      if (configs == null) {
        try {
          String fullName = PREFIX + service.getName();
          if (loader == null)
            configs = ClassLoader.getSystemResources(fullName);
          else
            configs = loader.getResources(fullName);
        } catch (IOException x) {
          fail(service, "Error locating configuration files", x);
        }
      }
      while ((pending == null) || !pending.hasNext()) {
        if (!configs.hasMoreElements()) {
          return false;
        }
        pending = parse(service, configs.nextElement());
      }
      nextName = pending.next();
      return true;
    }

    private Class<S> nextService() {
      if (!hasNextService())
        throw new NoSuchElementException();
      String cn = nextName;
      nextName = null;
      Class<?> c = null;
      try {
        c = Class.forName(cn, false, loader);
      } catch (ClassNotFoundException x) {
        fail(service,
            // Android-changed: Let the ServiceConfigurationError have a cause.
            "Provider " + cn + " not found", x);
        // "Provider " + cn + " not found");
      }
      if (!service.isAssignableFrom(c)) {
        // Android-changed: Let the ServiceConfigurationError have a cause.
        ClassCastException cce = new ClassCastException(
            service.getCanonicalName() + " is not assignable from " + c.getCanonicalName());
        fail(service,
            "Provider " + cn  + " not a subtype", cce);
        // fail(service,
        //        "Provider " + cn  + " not a subtype");
      }
      try {
        // S p = service.cast(c.newInstance());
        // providers.put(cn, c);
        // return p;
        Class<S> clazz = (Class<S>) c;
        providers.put(cn, clazz);
        return clazz;
      } catch (Throwable x) {
        fail(service,
            "Provider " + cn + " could not be instantiated",
            x);
      }
      throw new Error();          // This cannot happen
    }

    @Override
    public boolean hasNext() {
      // Android-changed: do not use legacy security code
      /* if (acc == null) { */
      return hasNextService();
            /*
            } else {
                PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
                    public Boolean run() { return hasNextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
            */
    }

    @Override
    public Class<S> next() {
      // Android-changed: do not use legacy security code
      /* if (acc == null) { */
      return nextService();
            /*
            } else {
                PrivilegedAction<S> action = new PrivilegedAction<S>() {
                    public S run() { return nextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
            */
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException();
    }

  }

  /**
   * Lazily loads the available providers of this loader's service.
   *
   *
 The iterator returned by this method first yields all of the
   * elements of the provider cache, in instantiation order.  It then lazily
   * loads and instantiates any remaining providers, adding each one to the
   * cache in turn.
   *
   *
 To achieve laziness the actual work of parsing the available
   * provider-configuration files and instantiating providers must be done by
   * the iterator itself.  Its {@link java.util.Iterator#hasNext hasNext} and
   * {@link java.util.Iterator#next next} methods can therefore throw a
   * {@link ServiceConfigurationError} if a provider-configuration file
   * violates the specified format, or if it names a provider class that
   * cannot be found and instantiated, or if the result of instantiating the
   * class is not assignable to the service type, or if any other kind of
   * exception or error is thrown as the next provider is located and
   * instantiated.  To write robust code it is only necessary to catch {@link
   * ServiceConfigurationError} when using a service iterator.
   *
   *
 If such an error is thrown then subsequent invocations of the
   * iterator will make a best effort to locate and instantiate the next
   * available provider, but in general such recovery cannot be guaranteed.
   *
   *
Design Note
   * Throwing an error in these cases may seem extreme.  The rationale for
   * this behavior is that a malformed provider-configuration file, like a
   * malformed class file, indicates a serious problem with the way the Java
   * virtual machine is configured or is being used.  As such it is
   * preferable to throw an error rather than try to recover or, even worse,
   * fail silently.

   *
   *
 The iterator returned by this method does not support removal.
   * Invoking its {@link java.util.Iterator#remove() remove} method will
   * cause an {@link UnsupportedOperationException} to be thrown.
   *
   * @implNote When adding providers to the cache, the {@link #iterator
   * Iterator} processes resources in the order that the {@link
   * java.lang.ClassLoader#getResources(java.lang.String)
   * ClassLoader.getResources(String)} method finds the service configuration
   * files.
   *
   * @return  An iterator that lazily loads providers for this loader's
   *          service
   */
  @Override
  public Iterator<Class<? extends S>> iterator() {
    return new Iterator<Class<? extends S>>() {

      Iterator<Map.Entry<String,Class<S>>> knownProviders
          = providers.entrySet().iterator();

      @Override
      public boolean hasNext() {
        if (knownProviders.hasNext())
          return true;
        return lookupIterator.hasNext();
      }

      @Override
      public Class<S> next() {
        if (knownProviders.hasNext())
          return knownProviders.next().getValue();
        return lookupIterator.next();
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }

    };
  }

  /**
   * Creates a new service loader for the given service type and class
   * loader.
   *
   * @param  <S> the class of the service type
   *
   * @param  service
   *         The interface or abstract class representing the service
   *
   * @param  loader
   *         The class loader to be used to load provider-configuration files
   *         and provider classes, or <tt>null</tt> if the system class
   *         loader (or, failing that, the bootstrap class loader) is to be
   *         used
   *
   * @return A new service loader
   */
  public static <S> ServiceFinder<S> load(Class<S> service,
      ClassLoader loader)
  {
    return new ServiceFinder<>(service, loader);
  }

  /**
   * Creates a new service loader for the given service type, using the
   * current thread's {@linkplain java.lang.Thread#getContextClassLoader
   * context class loader}.
   *
   *
 An invocation of this convenience method of the form
   *
   *

   * ServiceFinder.load(service)

   *
   * is equivalent to
   *
   *

   * ServiceFinder.load(service,
   *                    Thread.currentThread().getContextClassLoader())

   *
   * @param  <S> the class of the service type
   *
   * @param  service
   *         The interface or abstract class representing the service
   *
   * @return A new service loader
   */
  public static <S> ServiceFinder<S> load(Class<S> service) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    return load(service, cl);
  }

  /**
   * Creates a new service loader for the given service type, using the
   * extension class loader.
   *
   *
 This convenience method simply locates the extension class loader,
   * call it <tt>extClassLoader</tt>, and then returns
   *
   *

   * ServiceFinder.load(service, extClassLoader)

   *
   *
 If the extension class loader cannot be found then the system class
   * loader is used; if there is no system class loader then the bootstrap
   * class loader is used.
   *
   *
 This method is intended for use when only installed providers are
   * desired.  The resulting service will only find and load providers that
   * have been installed into the current Java virtual machine; providers on
   * the application's class path will be ignored.
   *
   * @param  <S> the class of the service type
   *
   * @param  service
   *         The interface or abstract class representing the service
   *
   * @return A new service loader
   */
  public static <S> ServiceFinder<S> loadInstalled(Class<S> service) {
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    ClassLoader prev = null;
    while (cl != null) {
      prev = cl;
      cl = cl.getParent();
    }
    return load(service, prev);
  }

  // BEGIN Android-added: loadFromSystemProperty(), for internal use.
  // Instantiates a class from a system property (used elsewhere in libcore).
  /**
   * Internal API to support built-in SPIs that check a system property first.
   * Returns an instance specified by a property with the class' binary name, or null if
   * no such property is set.
   * @hide
   */
  public static <S> S loadFromSystemProperty(final Class<S> service) {
    try {
      final String className = System.getProperty(service.getName());
      if (className != null) {
        Class<?> c = ClassLoader.getSystemClassLoader().loadClass(className);
        return (S) c.newInstance();
      }
      return null;
    } catch (Exception e) {
      throw new Error(e);
    }
  }
  // END Android-added: loadFromSystemProperty(), for internal use.

  /**
   * Returns a string describing this service.
   *
   * @return  A descriptive string
   */
  @Override
  public String toString() {
    return ServiceFinder.class.getName() + "[" + service.getName() + "]";
  }

}


text:
//
//  CMRNamedColorsViewController.m
//  HTMLColorsDemo
//
//  Created by James Lawton on 12/10/12.
//  Copyright (c) 2012 James Lawton. All rights reserved.
//

#import "CMRNamedColorsViewController.h"
#import "UIColor+HTMLColors.h"

static NSString *CellIdentifier = @"Cell";

// A simple table cell with a color square, textLabel and detailTextLabel
@interface CMRNamedColorTableViewCell : UITableViewCell
@property (nonatomic, strong) UIColor *color;
@end

@interface CMRNamedColorsViewController ()
@property (nonatomic, strong) NSArray *colorNames;
@end

@implementation CMRNamedColorsViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.colorNames = [UIColor W3CColorNames];

    [self.tableView registerClass:[CMRNamedColorTableViewCell class] forCellReuseIdentifier:CellIdentifier];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.colorNames.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CMRNamedColorTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    NSString *colorName = self.colorNames[indexPath.row];
    UIColor *color = [UIColor colorWithW3CNamedColor:colorName];
    NSString *hexColor = [color hexStringValue];

    cell.color = color;
    cell.textLabel.text = colorName;
    cell.detailTextLabel.text = hexColor;

    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.colorSelected) {
        self.colorSelected(self.colorNames[indexPath.row]);
    }
}

@end

@implementation CMRNamedColorTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
    if (self) {
        self.imageView.image = [UIImage imageNamed:@"Transparent22"];
    }
    return self;
}

- (void)prepareForReuse
{
    [super prepareForReuse];
    self.color = nil;
}

- (UIColor *)color
{
    return self.imageView.backgroundColor;
}

- (void)setColor:(UIColor *)color
{
    self.imageView.backgroundColor = color;
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/pad.iml" filepath="$PROJECT_DIR$/.idea/modules/pad.iml" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/pad_main.iml" filepath="$PROJECT_DIR$/.idea/modules/pad_main.iml" group="pad" />
      <module fileurl="file://$PROJECT_DIR$/.idea/modules/pad_test.iml" filepath="$PROJECT_DIR$/.idea/modules/pad_test.iml" group="pad" />
    </modules>
  </component>
</project>


text:
<html>
 <head>
  <script language="javascript" src="../../../../../foam.js"></script>
  <script language="javascript" src="../../../misc/Colors.js"></script>
  <script language="javascript" src="Clock.js"></script>
  <title>Clock</title>
 </head>
 <body>
   <foam class="com.google.foam.demos.clock.Clock"></foam>
   <foam class="com.google.foam.demos.clock.Clock" border="red" y="300" x="300" radius="150" drawTicks="true"></foam>
 </body>
</html>


text:
package TrimaBinarySearchTree;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {

    private boolean checkRange(int v, int L, int R) {
        return v >= L && v <= R;
    }

    public TreeNode trimBST(TreeNode root, int L, int R) {
        if (root == null)
            return null;

        while (!checkRange(root.val, L, R)) {
            if (root.val < L) {
                root = root.right;
            } else if (root.val > R) {
                root = root.left;
            }
            if (root == null)
                return null;
        }
        root.left = trimBST(root.left, L, R);
        root.right = trimBST(root.right, L, R);
        return root;
    }
}


text:
/**
 * @file commands info
 * @author zdying
 */
'use strict';

module.exports = {
  init: require('./init'),
  open: require('./open'),
  restart: require('./restart'),
  start: require('./start'),
  state: require('./state'),
  stop: require('./stop')
};


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- (c) Copyright IBM Corp. 2004, 2005 All Rights Reserved. -->

<!DOCTYPE topic PUBLIC "-//OASIS//DTD DITA Topic//EN"
 "../../dtd/topic.dtd">
<topic id="installing" xml:lang="en-us">
<title>Installing</title>
<shortdesc>You install components to make them available for your
solution.</shortdesc>
<body>
<note conref="task_preface.xml#task_preface/demo_bookmap"/>
<p>Usually, you can install the components once and then forget about the
details of this task.
Before installing the components, you should make a plan
for what you need to accomplish and the components
that will support these goals.
After installing the components, you will probably want to perform
some preliminary configuration. </p>
</body>
</topic>


text:
ITKMinimalPathExtraction
========================

.. image:: https://github.com/InsightSoftwareConsortium/ITKMinimalPathExtraction/workflows/Build,%20test,%20package/badge.svg

Overview
--------

This is an `ITK <http://itk.org>`_ module that implements a minimal path
extraction framework based on Fast Marching arrival functions.

A more detailed description can be found in
`the Insight Journal article <http://hdl.handle.net/1926/1332>`_::

  Mueller, D.
  "Fast Marching Minimal Path Extraction in ITK"
  The Insight Journal. January-June, 2008.
  http://hdl.handle.net/1926/1332
  http://www.insight-journal.org/browse/publication/213

Installation
------------

To install the binary Python packages::

  python -m pip install itk-minimalpathextraction

Since ITK 4.8.0, this module is available in the ITK source tree as a remote
module. To enable it, set::

  Module_MinimalPathExtraction:BOOL=ON

in ITK's CMake build configuration.

License
-------

This software is distributed under the Apache 2.0 license. Please see
the *LICENSE* file for details.


text:
from oslo_log import versionutils
from oslo_policy import policy

from keystone.common.policies import base

DEPRECATED_REASON = (
    "The credential API is now aware of system scope and default roles."
)

deprecated_get_credential = policy.DeprecatedRule(
    name=base.IDENTITY % 'get_credential',
    check_str=base.RULE_ADMIN_REQUIRED,
    deprecated_reason=DEPRECATED_REASON,
    deprecated_since=versionutils.deprecated.STEIN
)
deprecated_list_credentials = policy.DeprecatedRule(
    name=base.IDENTITY % 'list_credentials',
    check_str=base.RULE_ADMIN_REQUIRED,
    deprecated_reason=DEPRECATED_REASON,
    deprecated_since=versionutils.deprecated.STEIN
)
deprecated_create_credential = policy.DeprecatedRule(
    name=base.IDENTITY % 'create_credential',
    check_str=base.RULE_ADMIN_REQUIRED,
    deprecated_reason=DEPRECATED_REASON,
    deprecated_since=versionutils.deprecated.STEIN
)
deprecated_update_credential = policy.DeprecatedRule(
    name=base.IDENTITY % 'update_credential',
    check_str=base.RULE_ADMIN_REQUIRED,
    deprecated_reason=DEPRECATED_REASON,
    deprecated_since=versionutils.deprecated.STEIN
)
deprecated_delete_credential = policy.DeprecatedRule(
    name=base.IDENTITY % 'delete_credential',
    check_str=base.RULE_ADMIN_REQUIRED,
    deprecated_reason=DEPRECATED_REASON,
    deprecated_since=versionutils.deprecated.STEIN
)

credential_policies = [
    policy.DocumentedRuleDefault(
        name=base.IDENTITY % 'get_credential',
        check_str=base.SYSTEM_READER_OR_CRED_OWNER,
        scope_types=['system', 'project'],
        description='Show credentials details.',
        operations=[{'path': '/v3/credentials/{credential_id}',
                     'method': 'GET'}],
        deprecated_rule=deprecated_get_credential,
    ),
    policy.DocumentedRuleDefault(
        name=base.IDENTITY % 'list_credentials',
        check_str=base.SYSTEM_READER_OR_CRED_OWNER,
        scope_types=['system', 'project'],
        description='List credentials.',
        operations=[{'path': '/v3/credentials',
                     'method': 'GET'}],
        deprecated_rule=deprecated_list_credentials,
    ),
    policy.DocumentedRuleDefault(
        name=base.IDENTITY % 'create_credential',
        check_str=base.SYSTEM_ADMIN_OR_CRED_OWNER,
        scope_types=['system', 'project'],
        description='Create credential.',
        operations=[{'path': '/v3/credentials',
                     'method': 'POST'}],
        deprecated_rule=deprecated_create_credential,
    ),
    policy.DocumentedRuleDefault(
        name=base.IDENTITY % 'update_credential',
        check_str=base.SYSTEM_ADMIN_OR_CRED_OWNER,
        scope_types=['system', 'project'],
        description='Update credential.',
        operations=[{'path': '/v3/credentials/{credential_id}',
                     'method': 'PATCH'}],
        deprecated_rule=deprecated_update_credential,
    ),
    policy.DocumentedRuleDefault(
        name=base.IDENTITY % 'delete_credential',
        check_str=base.SYSTEM_ADMIN_OR_CRED_OWNER,
        scope_types=['system', 'project'],
        description='Delete credential.',
        operations=[{'path': '/v3/credentials/{credential_id}',
                     'method': 'DELETE'}],
        deprecated_rule=deprecated_delete_credential,
    )
]

def list_rules():
    return credential_policies


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.redkale.boot;

import java.io.*;
import java.lang.reflect.*;
import java.math.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.*;
import java.util.logging.*;
import javax.persistence.*;
import org.redkale.convert.*;
import org.redkale.convert.json.*;
import org.redkale.mq.MessageMultiConsumer;
import org.redkale.net.http.*;
import org.redkale.service.RetResult;
import org.redkale.source.*;
import org.redkale.util.*;

/**
 * API接口文档生成类,作用:生成Application实例中所有HttpServer的可用HttpServlet的API接口方法

 * 继承 HttpBaseServlet 是为了获取 HttpMapping 信息

 * https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
 *
 *

 * 详情见: https://redkale.org
 *
 * @author zhangjx
 */
public final class ApiDocCommand {

    private static final java.lang.reflect.Type TYPE_RETRESULT_OBJECT = new TypeToken<RetResult<Object>>() {
    }.getType();

    private static final java.lang.reflect.Type TYPE_RETRESULT_STRING = new TypeToken<RetResult<String>>() {
    }.getType();

    private static final java.lang.reflect.Type TYPE_RETRESULT_INTEGER = new TypeToken<RetResult<Integer>>() {
    }.getType();

    private static final java.lang.reflect.Type TYPE_RETRESULT_LONG = new TypeToken<RetResult<Long>>() {
    }.getType();

    private final Application app; //Application全局对象

    public ApiDocCommand(Application app) {
        this.app = app;
    }

    public String command(String cmd, String[] params) throws Exception {
        //是否跳过RPC接口
        boolean skipRPC = true;
        String apiHost = "http://localhost";

        if (params != null && params.length > 0) {
            for (String param : params) {
                if (param == null) continue;
                param = param.toLowerCase();
                if (param.startsWith("--api-skiprpc=")) {
                    skipRPC = "true".equalsIgnoreCase(param.substring("--api-skiprpc=".length()));
                } else if (param.startsWith("--api-host=")) {
                    apiHost = param.substring("--api-host=".length());
                }
            }
        }

        List<Map> serverList = new ArrayList<>();
        Field __prefix = HttpServlet.class.getDeclaredField("_prefix");
        __prefix.setAccessible(true);
        Map<String, Map<String, Map<String, Object>>> typesMap = new LinkedHashMap<>();
        //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md
        Map<String, Object> swaggerPathsMap = new LinkedHashMap<>();
        List<Map> swaggerServers = new ArrayList<>();
        List<Map> swaggerTags = new ArrayList<>();
        Map<String, Map<String, Object>> swaggerComponentsMap = new LinkedHashMap<>();
        for (NodeServer node : app.servers) {
            if (!(node instanceof NodeHttpServer)) continue;
            final Map<String, Object> map = new LinkedHashMap<>();
            serverList.add(map);
            HttpServer server = node.getServer();
            map.put("address", server.getSocketAddress());
            swaggerServers.add(Utility.ofMap("url", apiHost + ":" + server.getSocketAddress().getPort()));
            List<Map<String, Object>> servletsList = new ArrayList<>();
            map.put("servlets", servletsList);
            String plainContentType = server.getResponseConfig() == null ? "application/json" : server.getResponseConfig().plainContentType;
            if (plainContentType == null || plainContentType.isEmpty()) plainContentType = "application/json";
            if (plainContentType.indexOf(';') > 0) plainContentType = plainContentType.substring(0, plainContentType.indexOf(';'));

            for (HttpServlet servlet : server.getDispatcherServlet().getServlets()) {
                if (!(servlet instanceof HttpServlet)) continue;
                if (servlet instanceof WebSocketServlet) continue;
                if (servlet.getClass().getAnnotation(MessageMultiConsumer.class) != null) {
                    node.logger.log(Level.INFO, servlet + " be skipped because has @MessageMultiConsumer");
                    continue;
                }
                WebServlet ws = servlet.getClass().getAnnotation(WebServlet.class);
                if (ws == null) {
                    node.logger.log(Level.WARNING, servlet + " not found @WebServlet");
                    continue;
                }
                if (ws.name().isEmpty()) {
                    node.logger.log(Level.INFO, servlet + " be skipped because @WebServlet.name is empty");
                    continue;
                }
                final String tag = ws.name().isEmpty() ? servlet.getClass().getSimpleName().replace("Servlet", "").toLowerCase() : ws.name();
                final Map<String, Object> servletMap = new LinkedHashMap<>();
                String prefix = (String) __prefix.get(servlet);
                String[] urlregs = ws.value();
                if (prefix != null && !prefix.isEmpty()) {
                    for (int i = 0; i < urlregs.length; i++) {
                        urlregs[i] = prefix + urlregs[i];
                    }
                }
                servletMap.put("urlregs", urlregs);
                servletMap.put("moduleid", ws.moduleid());
                servletMap.put("name", ws.name());
                servletMap.put("comment", ws.comment());

                List<Map> mappingsList = new ArrayList<>();
                servletMap.put("mappings", mappingsList);
                final Class selfClz = servlet.getClass();
                Class clz = servlet.getClass();
                HashSet<String> actionUrls = new HashSet<>();
                do {
                    if (Modifier.isAbstract(clz.getModifiers())) break;
                    for (Method method : clz.getMethods()) {
                        if (method.getParameterCount() != 2) continue;
                        HttpMapping action = method.getAnnotation(HttpMapping.class);
                        if (action == null) continue;
                        if (!action.inherited() && selfClz != clz) continue; //忽略不被继承的方法
                        if (actionUrls.contains(action.url())) continue;
                        if (HttpScope.class.isAssignableFrom(action.result())) continue; //忽略模板引擎的方法
                        if (action.rpconly() && skipRPC) continue; //不生成RPC接口

                        final List<Map<String, Object>> swaggerParamsList = new ArrayList<>();

                        final Map<String, Object> mappingMap = new LinkedHashMap<>();
                        mappingMap.put("url", prefix + action.url());
                        actionUrls.add(action.url());
                        mappingMap.put("auth", action.auth());
                        mappingMap.put("actionid", action.actionid());
                        mappingMap.put("comment", action.comment());
                        List<Map> paramsList = new ArrayList<>();
                        mappingMap.put("params", paramsList);
                        List<String> results = new ArrayList<>();
                        Type resultType = action.result();
                        if (!action.resultref().isEmpty()) {
                            Field f = servlet.getClass().getDeclaredField(action.resultref());
                            f.setAccessible(true);
                            resultType = (Type) f.get(servlet);
                        }
//                        for (final Class rtype : action.results()) {
//                            results.add(rtype.getName());
//                            if (typesMap.containsKey(rtype.getName())) continue;
//                            if (rtype.getName().startsWith("java.")) continue;
//                            if (rtype.getName().startsWith("javax.")) continue;
//                            final boolean filter = FilterBean.class.isAssignableFrom(rtype);
//                            final Map<String, Map<String, Object>> typeMap = new LinkedHashMap<>();
//                            Class loop = rtype;
//                            do {
//                                if (loop == null || loop.isInterface()) break;
//                                for (Field field : loop.getDeclaredFields()) {
//                                    if (Modifier.isFinal(field.getModifiers())) continue;
//                                    if (Modifier.isStatic(field.getModifiers())) continue;
//
//                                    Map<String, Object> fieldmap = new LinkedHashMap<>();
//                                    fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());
//
//                                    Comment comment = field.getAnnotation(Comment.class);
//                                    Column col = field.getAnnotation(Column.class);
//                                    FilterColumn fc = field.getAnnotation(FilterColumn.class);
//                                    if (comment != null) {
//                                        fieldmap.put("comment", comment.value());
//                                    } else if (col != null) {
//                                        fieldmap.put("comment", col.comment());
//                                    } else if (fc != null) {
//                                        fieldmap.put("comment", fc.comment());
//                                    }
//                                    fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
//                                    fieldmap.put("updatable", (filter || col == null || col.updatable()));
//                                    if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
//                                        if (field.getAnnotation(RestAddress.class) != null) continue;
//                                    }
//
//                                    typeMap.put(field.getName(), fieldmap);
//                                }
//                            } while ((loop = loop.getSuperclass()) != Object.class);
//                            typesMap.put(rtype.getName(), typeMap);
//                        }
                        mappingMap.put("results", results);
                        boolean hasbodyparam = false;
                        Map<String, Object> swaggerRequestBody = new LinkedHashMap<>();
                        for (HttpParam param : method.getAnnotationsByType(HttpParam.class)) {
                            final Map<String, Object> oldapisParamMap = new LinkedHashMap<>();
                            final boolean isarray = param.type().isArray();
                            final Class ptype = isarray ? param.type().getComponentType() : param.type();
                            oldapisParamMap.put("name", param.name());
                            oldapisParamMap.put("radix", param.radix());
                            oldapisParamMap.put("type", ptype.getName() + (isarray ? "[]" : ""));
                            oldapisParamMap.put("style", param.style());
                            oldapisParamMap.put("comment", param.comment());
                            oldapisParamMap.put("required", param.required());
                            paramsList.add(oldapisParamMap);
                            {
                                final Map<String, Object> paramSchemaMap = new LinkedHashMap<>();
                                Type paramGenericType = param.type();
                                if (!param.typeref().isEmpty()) {
                                    Field f = servlet.getClass().getDeclaredField(param.typeref());
                                    f.setAccessible(true);
                                    paramGenericType = (Type) f.get(servlet);
                                }
                                simpleSchemaType(null, node.getLogger(), swaggerComponentsMap, param.type(), paramGenericType, paramSchemaMap, true);
                                if (param.style() == HttpParam.HttpParameterStyle.BODY) {
                                    swaggerRequestBody.put("description", param.comment());
                                    swaggerRequestBody.put("content", Utility.ofMap(plainContentType, Utility.ofMap("schema", paramSchemaMap)));
                                } else {
                                    final Map<String, Object> swaggerParamMap = new LinkedHashMap<>();
                                    swaggerParamMap.put("name", param.name());
                                    swaggerParamMap.put("in", param.style().name().toLowerCase());
                                    swaggerParamMap.put("description", param.comment());
                                    swaggerParamMap.put("required", param.required());
                                    if (param.deprecated()) {
                                        swaggerParamMap.put("deprecated", param.deprecated());
                                    }
                                    //https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameterStyle
                                    swaggerParamMap.put("style", param.style() == HttpParam.HttpParameterStyle.HEADER || param.name().indexOf('#') == 0 ? "simple" : "form");
                                    swaggerParamMap.put("explode", true);
                                    swaggerParamMap.put("schema", paramSchemaMap);
                                    Object example = formatExample(null, param.example(), param.type(), paramGenericType);
                                    if (example != null) {
                                        swaggerParamMap.put("example", example);
                                    } else if (!param.example().isEmpty()) {
                                        swaggerParamMap.put("example", param.example());
                                    }
                                    swaggerParamsList.add(swaggerParamMap);
                                }
                            }
                            if (param.style() == HttpParam.HttpParameterStyle.BODY) hasbodyparam = true;
                            if (ptype.isPrimitive() || ptype == String.class) continue;
                            if (typesMap.containsKey(ptype.getName())) continue;
                            if (ptype.getName().startsWith("java.")) continue;
                            if (ptype.getName().startsWith("javax.")) continue;

                            final Map<String, Map<String, Object>> typeMap = new LinkedHashMap<>();
                            Class loop = ptype;
                            final boolean filter = FilterBean.class.isAssignableFrom(loop);
                            do {
                                if (loop == null || loop.isInterface()) break;
                                for (Field field : loop.getDeclaredFields()) {
                                    if (Modifier.isFinal(field.getModifiers())) continue;
                                    if (Modifier.isStatic(field.getModifiers())) continue;

                                    Map<String, Object> fieldmap = new LinkedHashMap<>();
                                    fieldmap.put("type", field.getType().isArray() ? (field.getType().getComponentType().getName() + "[]") : field.getGenericType().getTypeName());

                                    Column col = field.getAnnotation(Column.class);
                                    FilterColumn fc = field.getAnnotation(FilterColumn.class);
                                    Comment comment = field.getAnnotation(Comment.class);
                                    if (comment != null) {
                                        fieldmap.put("comment", comment.value());
                                    } else if (col != null) {
                                        fieldmap.put("comment", col.comment());
                                    } else if (fc != null) {
                                        fieldmap.put("comment", fc.comment());
                                    }
                                    fieldmap.put("primary", !filter && (field.getAnnotation(Id.class) != null));
                                    fieldmap.put("updatable", (filter || col == null || col.updatable()));

                                    if (servlet.getClass().getAnnotation(Rest.RestDyn.class) != null) {
                                        if (field.getAnnotation(RestAddress.class) != null) continue;
                                    }

                                    typeMap.put(field.getName(), fieldmap);
                                }
                            } while ((loop = loop.getSuperclass()) != Object.class);

                            typesMap.put(ptype.getName(), typeMap);
                        }
                        mappingMap.put("result", action.result().getSimpleName().replace("void", "Object"));
                        mappingsList.add(mappingMap);

                        final Map<String, Object> swaggerOperatMap = new LinkedHashMap<>();
                        swaggerOperatMap.put("tags", new String[]{tag});
                        swaggerOperatMap.put("operationId", action.name());
                        if (method.getAnnotation(Deprecated.class) != null) {
                            swaggerOperatMap.put("deprecated", true);
                        }
                        Map<String, Object> respSchemaMap = new LinkedHashMap<>();
                        JsonFactory returnFactory = Rest.createJsonFactory(false, method.getAnnotationsByType(RestConvert.class), method.getAnnotationsByType(RestConvertCoder.class));
                        simpleSchemaType(returnFactory, node.getLogger(), swaggerComponentsMap, action.result(), resultType, respSchemaMap, true);

                        Map<String, Object> respMap = new LinkedHashMap<>();
                        respMap.put("schema", respSchemaMap);
                        Object example = formatExample(returnFactory, action.example(), action.result(), resultType);
                        if (example != null) respSchemaMap.put("example", example);
                        if (!swaggerRequestBody.isEmpty()) swaggerOperatMap.put("requestBody", swaggerRequestBody);
                        swaggerOperatMap.put("parameters", swaggerParamsList);
                        String actiondesc = action.comment();
                        if (action.rpconly()) actiondesc = "[Only for RPC API] " + actiondesc;
                        swaggerOperatMap.put("responses", Utility.ofMap("200", Utility.ofMap("description", actiondesc, "content", Utility.ofMap("application/json", respMap))));

                        String m = action.methods() == null || action.methods().length == 0 ? null : action.methods()[0].toLowerCase();
                        if (m == null) {
                            m = hasbodyparam || TYPE_RETRESULT_STRING.equals(resultType) || TYPE_RETRESULT_INTEGER.equals(resultType)
                                || TYPE_RETRESULT_LONG.equals(resultType) || action.name().contains("create") || action.name().contains("insert")
                                || action.name().contains("update") || action.name().contains("delete") || action.name().contains("send") ? "post" : "get";
                        }
                        swaggerPathsMap.put(prefix + action.url(), Utility.ofMap("description", action.comment(), m, swaggerOperatMap));
                    }
                } while ((clz = clz.getSuperclass()) != HttpServlet.class);
                mappingsList.sort((o1, o2) -> ((String) o1.get("url")).compareTo((String) o2.get("url")));
                servletsList.add(servletMap);
                if (!actionUrls.isEmpty()) swaggerTags.add(Utility.ofMap("name", tag, "description", ws.comment()));
            }
            servletsList.sort((o1, o2) -> {
                String[] urlregs1 = (String[]) o1.get("urlregs");
                String[] urlregs2 = (String[]) o2.get("urlregs");
                return urlregs1.length > 0 ? (urlregs2.length > 0 ? urlregs1[0].compareTo(urlregs2[0]) : 1) : -1;
            });
        }
        { // https://github.com/OAI/OpenAPI-Specification
            Map<String, Object> swaggerResultMap = new LinkedHashMap<>();
            swaggerResultMap.put("openapi", "3.0.0");
            Map<String, Object> infomap = new LinkedHashMap<>();
            infomap.put("title", "Redkale generate apidoc");
            infomap.put("version", "1.0.0");
            swaggerResultMap.put("info", infomap);
            swaggerResultMap.put("servers", swaggerServers);
            swaggerResultMap.put("paths", swaggerPathsMap);
            swaggerResultMap.put("tags", swaggerTags);
            if (!swaggerComponentsMap.isEmpty()) swaggerResultMap.put("components", Utility.ofMap("schemas", swaggerComponentsMap));
            final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "openapi-doc.json"));
            out.write(JsonConvert.root().convertTo(swaggerResultMap).getBytes(StandardCharsets.UTF_8));
            out.close();
        }
        {
            Map<String, Object> oldapisResultMap = new LinkedHashMap<>();
            oldapisResultMap.put("servers", serverList);
            oldapisResultMap.put("types", typesMap);
            final String json = JsonConvert.root().convertTo(oldapisResultMap);
            final FileOutputStream out = new FileOutputStream(new File(app.getHome(), "apidoc.json"));
            out.write(json.getBytes(StandardCharsets.UTF_8));
            out.close();
            File doctemplate = new File(app.getConfPath().toString(), "apidoc-template.html");
            InputStream in = null;
            if (doctemplate.isFile() && doctemplate.canRead()) {
                in = new FileInputStream(doctemplate);
            }
            if (in != null) {
                String content = Utility.read(in).replace("'${content}'", json);
                in.close();
                FileOutputStream outhtml = new FileOutputStream(new File(app.getHome(), "apidoc.html"));
                outhtml.write(content.getBytes(StandardCharsets.UTF_8));
                outhtml.close();
            }
        }
        return "apidoc success";
    }

    private static void simpleSchemaType(JsonFactory factory, Logger logger, Map<String, Map<String, Object>> componentsMap, Class type, Type genericType, Map<String, Object> schemaMap, boolean recursive) {
        if (type == int.class || type == Integer.class || type == AtomicInteger.class) {
            schemaMap.put("type", "integer");
            schemaMap.put("format", "int32");
        } else if (type == long.class || type == Long.class
            || type == AtomicLong.class || type == LongAdder.class || type == BigInteger.class) {
            schemaMap.put("type", "integer");
            schemaMap.put("format", "int64");
        } else if (type == float.class || type == Float.class) {
            schemaMap.put("type", "number");
            schemaMap.put("format", "float");
        } else if (type == double.class || type == Double.class || type == BigDecimal.class) {
            schemaMap.put("type", "number");
            schemaMap.put("format", "double");
        } else if (type == boolean.class || type == Boolean.class || type == AtomicBoolean.class) {
            schemaMap.put("type", "boolean");
        } else if (type.isPrimitive() || Number.class.isAssignableFrom(type)) {
            schemaMap.put("type", "number");
        } else if (type == String.class || CharSequence.class.isAssignableFrom(type)) {
            schemaMap.put("type", "string");
        } else if (recursive && (type.isArray() || Collection.class.isAssignableFrom(type))) {
            schemaMap.put("type", "array");
            Map<String, Object> sbumap = new LinkedHashMap<>();
            if (type.isArray()) {
                simpleSchemaType(factory, logger, componentsMap, type.getComponentType(), type.getComponentType(), sbumap, false);
            } else if (genericType instanceof ParameterizedType) {
                Type subpt = ((ParameterizedType) genericType).getActualTypeArguments()[0];
                if (subpt instanceof Class) {
                    simpleSchemaType(factory, logger, componentsMap, (Class) subpt, subpt, sbumap, false);
                } else if (subpt instanceof ParameterizedType && ((ParameterizedType) subpt).getOwnerType() instanceof Class) {
                    simpleSchemaType(factory, logger, componentsMap, (Class) ((ParameterizedType) subpt).getOwnerType(), subpt, sbumap, false);
                } else {
                    sbumap.put("type", "object");
                }
            } else {
                sbumap.put("type", "object");
            }
            schemaMap.put("items", sbumap);
        } else if (!type.getName().startsWith("java.") && !type.getName().startsWith("javax.")) {
            String ct = simpleComponentType(factory, logger, componentsMap, type, genericType);
            if (ct == null) {
                schemaMap.put("type", "object");
            } else {
                schemaMap.put("$ref", "#/components/schemas/" + ct);
            }
        } else {
            schemaMap.put("type", "object");
        }
    }

    private static String simpleComponentType(JsonFactory factory, Logger logger, Map<String, Map<String, Object>> componentsMap, Class type, Type genericType) {
        try {
            Set<Type> types = new HashSet<>();
            Encodeable encodeable = JsonFactory.root().loadEncoder(genericType);
            String ct = componentKey(factory, logger, types, componentsMap, null, encodeable, true);
            if (ct == null || ct.length() == 0) return null;
            if (componentsMap.containsKey(ct)) return ct;
            Map<String, Object> cmap = new LinkedHashMap<>();
            componentsMap.put(ct, cmap); //必须在调用simpleSchemaType之前put,不然嵌套情况下死循环

            cmap.put("type", "object");
            List<String> requireds = new ArrayList<>();
            Map<String, Object> properties = new LinkedHashMap<>();
            if (encodeable instanceof ObjectEncoder) {
                for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
                    Map<String, Object> schemaMap = new LinkedHashMap<>();
                    simpleSchemaType(factory, logger, componentsMap, TypeToken.typeToClassOrElse(member.getEncoder().getType(), Object.class), member.getEncoder().getType(), schemaMap, true);
                    String desc = "";
                    if (member.getField() != null) {
                        Column col = member.getField().getAnnotation(Column.class);
                        if (col == null) {
                            FilterColumn fcol = member.getField().getAnnotation(FilterColumn.class);
                            if (fcol != null) {
                                desc = fcol.comment();
                                if (fcol.required()) requireds.add(member.getAttribute().field());
                            }
                        } else {
                            desc = col.comment();
                            if (!col.nullable()) requireds.add(member.getAttribute().field());
                        }
                        if (desc.isEmpty() && member.getField().getAnnotation(Comment.class) != null) {
                            desc = member.getField().getAnnotation(Comment.class).value();
                        }
                    } else if (member.getMethod() != null) {
                        Column col = member.getMethod().getAnnotation(Column.class);
                        if (col == null) {
                            FilterColumn fcol = member.getMethod().getAnnotation(FilterColumn.class);
                            if (fcol != null) {
                                desc = fcol.comment();
                                if (fcol.required()) requireds.add(member.getAttribute().field());
                            }
                        } else {
                            desc = col.comment();
                            if (!col.nullable()) requireds.add(member.getAttribute().field());
                        }
                        if (desc.isEmpty() && member.getMethod().getAnnotation(Comment.class) != null) {
                            desc = member.getMethod().getAnnotation(Comment.class).value();
                        }
                    }
                    if (!desc.isEmpty()) schemaMap.put("description", desc);
                    properties.put(member.getAttribute().field(), schemaMap);
                }
            }
            if (!requireds.isEmpty()) cmap.put("required", requireds);
            cmap.put("properties", properties);
            return ct;
        } catch (Exception e) {
            logger.log(Level.WARNING, genericType + " generate component info error", e);
            return null;
        }
    }

    private static String componentKey(JsonFactory factory, Logger logger, Set<Type> types, Map<String, Map<String, Object>> componentsMap, EnMember field, Encodeable encodeable, boolean first) {
        if (encodeable instanceof ObjectEncoder) {
            if (types.contains(encodeable.getType())) return "";
            types.add(encodeable.getType());
            StringBuilder sb = new StringBuilder();
            sb.append(((ObjectEncoder) encodeable).getTypeClass().getSimpleName());
            for (EnMember member : ((ObjectEncoder) encodeable).getMembers()) {
                if (member.getEncoder() instanceof ArrayEncoder
                    || member.getEncoder() instanceof CollectionEncoder) {
                    String subsb = componentKey(factory, logger, types, componentsMap, member, member.getEncoder(), false);
                    if (subsb == null) return null;
                    AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
                    if (real == null) continue;
                    Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
                    Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
                    if (cz == ct) continue;
                    if (field == null && encodeable.getType() instanceof Class) continue;
                    if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
                    sb.append(subsb);
                } else if (member.getEncoder() instanceof ObjectEncoder || member.getEncoder() instanceof SimpledCoder) {
                    AccessibleObject real = member.getField() == null ? member.getMethod() : member.getField();
                    if (real == null) continue;
                    if (types.contains(member.getEncoder().getType())) continue;
                    types.add(member.getEncoder().getType());
                    if (member.getEncoder() instanceof SimpledCoder) {
                        simpleSchemaType(factory, logger, componentsMap, ((SimpledCoder) member.getEncoder()).getType(), ((SimpledCoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
                    } else {
                        simpleSchemaType(factory, logger, componentsMap, ((ObjectEncoder) member.getEncoder()).getTypeClass(), ((ObjectEncoder) member.getEncoder()).getType(), new LinkedHashMap<>(), true);
                    }
                    Class cz = real instanceof Field ? ((Field) real).getType() : ((Method) real).getReturnType();
                    Type ct = real instanceof Field ? ((Field) real).getGenericType() : ((Method) real).getGenericReturnType();
                    if (cz == ct) continue;
                    String subsb = componentKey(factory, logger, types, componentsMap, member, member.getEncoder(), false);
                    if (subsb == null) return null;
                    if (field == null && member.getEncoder().getType() instanceof Class) continue;
                    if (sb.length() > 0 && subsb.length() > 0) sb.append("_");
                    sb.append(subsb);
                } else if (member.getEncoder() instanceof MapEncoder) {
                    continue;
                } else {
                    return null;
                }
            }
            return sb.toString();
        } else if (encodeable instanceof ArrayEncoder || encodeable instanceof CollectionEncoder) {
            final boolean array = (encodeable instanceof ArrayEncoder);
            Encodeable subEncodeable = array ? ((ArrayEncoder) encodeable).getComponentEncoder() : ((CollectionEncoder) encodeable).getComponentEncoder();
            if (subEncodeable instanceof SimpledCoder && field != null) return "";
            final String sb = componentKey(factory, logger, types, componentsMap, null, subEncodeable, false);
            if (sb == null || sb.isEmpty()) return sb;
            if (field != null && field.getField() != null && field.getField().getDeclaringClass() == Sheet.class) {
                return sb;
            }
            return sb + (array ? "_Array" : "_Collection");
        } else if (encodeable instanceof SimpledCoder) {
            Class stype = ((SimpledCoder) encodeable).getType();
            if (stype.isPrimitive() || stype == Boolean.class || Number.class.isAssignableFrom(stype) || CharSequence.class.isAssignableFrom(stype)) {
                return stype.getSimpleName();
            }
            return "";
        } else if (encodeable instanceof MapEncoder) {
            return first ? null : "";
        } else {
            return null;
        }
    }

    private static Object formatExample(JsonFactory factory, String example, Class type, Type genericType) {
        if (example != null && !example.isEmpty()) return example;
        JsonFactory jsonFactory = factory == null || factory == JsonFactory.root() ? exampleFactory : factory;
        if (type == Flipper.class) {
            return new Flipper();
        } else if (TYPE_RETRESULT_OBJECT.equals(genericType)) {
            return RetResult.success();
        } else if (TYPE_RETRESULT_STRING.equals(genericType)) {
            return RetResult.success();
        } else if (TYPE_RETRESULT_INTEGER.equals(genericType)) {
            return RetResult.success(0);
        } else if (TYPE_RETRESULT_LONG.equals(genericType)) {
            return RetResult.success(0L);
        } else if (type == boolean.class || type == Boolean.class) {
            return true;
        } else if (type.isPrimitive()) {
            return 0;
        } else if (type == boolean[].class || type == Boolean[].class) {
            return new boolean[]{true, false};
        } else if (type == byte[].class || type == Byte[].class) {
            return new byte[]{0, 0};
        } else if (type == char[].class || type == Character[].class) {
            return new char[]{'a', 'b'};
        } else if (type == short[].class || type == Short[].class) {
            return new short[]{0, 0};
        } else if (type == int[].class || type == Integer[].class) {
            return new int[]{0, 0};
        } else if (type == long[].class || type == Long[].class) {
            return new long[]{0, 0};
        } else if (type == float[].class || type == Float[].class) {
            return new float[]{0, 0};
        } else if (type == double[].class || type == Double[].class) {
            return new double[]{0, 0};
        } else if (Number.class.isAssignableFrom(type)) {
            return 0;
        } else if (CharSequence.class.isAssignableFrom(type)) {
            return "";
        } else if (CompletableFuture.class.isAssignableFrom(type)) {
            if (genericType instanceof ParameterizedType) {
                try {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type valType = pt.getActualTypeArguments()[0];
                    return formatExample(factory, example, valType instanceof ParameterizedType ? (Class) ((ParameterizedType) valType).getRawType() : ((Class) valType), valType);
                } catch (Throwable t) {
                }
            }
        } else if (Sheet.class.isAssignableFrom(type)) { //要在Collection前面
            if (genericType instanceof ParameterizedType) {
                try {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type valType = pt.getActualTypeArguments()[0];
                    Class valClass = valType instanceof ParameterizedType ? (Class) ((ParameterizedType) valType).getRawType() : (Class) valType;
                    Object val = formatExample(factory, example, valClass, valType);
                    return new StringWrapper(jsonFactory.getConvert().convertTo(jsonFactory.getConvert().convertFrom(genericType, "{'rows':[" + val + "," + val + "]}")));
                } catch (Throwable t) {
                }
            }
        } else if (type.isArray()) {
            try {
                Object val = formatExample(factory, example, type.getComponentType(), type.getComponentType());
                return new StringWrapper(jsonFactory.getConvert().convertTo(jsonFactory.getConvert().convertFrom(genericType, "[" + val + "," + val + "]")));
            } catch (Throwable t) {
            }
        } else if (Collection.class.isAssignableFrom(type)) {
            if (genericType instanceof ParameterizedType) {
                try {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type valType = pt.getActualTypeArguments()[0];
                    Class valClass = valType instanceof ParameterizedType ? (Class) ((ParameterizedType) valType).getRawType() : (Class) valType;
                    Object val = formatExample(factory, example, valClass, valType);
                    return new StringWrapper(jsonFactory.getConvert().convertTo(jsonFactory.getConvert().convertFrom(genericType, "[" + val + "," + val + "]")));
                } catch (Throwable t) {
                }
            }
        } else if (type == RetResult.class) {
            if (genericType instanceof ParameterizedType) {
                try {
                    ParameterizedType pt = (ParameterizedType) genericType;
                    Type valType = pt.getActualTypeArguments()[0];
                    Class valClass = valType instanceof ParameterizedType ? (Class) ((ParameterizedType) valType).getRawType() : (Class) valType;
                    Object val = formatExample(factory, example, valClass, valType);
                    return new StringWrapper(jsonFactory.getConvert().convertTo(jsonFactory.getConvert().convertFrom(genericType, "{'result':" + val + "}")));
                } catch (Throwable t) {
                }
            }
        } else if (type != void.class) {
            try {
                Decodeable decoder = jsonFactory.loadDecoder(genericType);
                if (decoder instanceof ObjectDecoder) {
                    StringBuilder json = new StringBuilder();
                    json.append("{");
                    int index = 0;
                    for (DeMember member : ((ObjectDecoder) decoder).getMembers()) {
                        if (!(member.getDecoder() instanceof ObjectDecoder)) continue;
                        if (index > 0) json.append(",");
                        json.append('"').append(member.getAttribute().field()).append("\":{}");
                        index++;
                    }
                    json.append("}");
                    Object val = jsonFactory.getConvert().convertFrom(genericType, json.toString());
                    return new StringWrapper(jsonFactory.getConvert().convertTo(val));
                }
                Creator creator = Creator.create(type);
                return new StringWrapper(jsonFactory.getConvert().convertTo(creator.create()));
            } catch (Throwable t) {
            }
        }
        return example;
    }

    private static final JsonFactory exampleFactory = JsonFactory.create().tiny(false);

}


text:
<?php

/**
 * Wraps Exceptions thrown by code under test.
 *
 * Re-instantiates Exceptions thrown by user-space code to retain their original
 * class names, properties, and stack traces (but without arguments).
 *
 * Unlike PHPUnit_Framework_Exception, the complete stack of previous Exceptions
 * is processed.
 *
 * @since Class available since Release 4.3.0
 */
class PHPUnit_Framework_ExceptionWrapper extends PHPUnit_Framework_Exception
{
    /**
     * @var string
     */
    protected $className;

    /**
     * @var PHPUnit_Framework_ExceptionWrapper|null
     */
    protected $previous;

    /**
     * @param Throwable|Exception $e
     */
    public function __construct($e)
    {
        // PDOException::getCode() is a string.
        // @see http://php.net/manual/en/class.pdoexception.php#95812
        parent::__construct($e->getMessage(), (int) $e->getCode());

        $this->className = get_class($e);
        $this->file      = $e->getFile();
        $this->line      = $e->getLine();

        $this->serializableTrace = $e->getTrace();

        foreach ($this->serializableTrace as $i => $call) {
            unset($this->serializableTrace[$i]['args']);
        }

        if ($e->getPrevious()) {
            $this->previous = new self($e->getPrevious());
        }
    }

    /**
     * @return string
     */
    public function getClassName()
    {
        return $this->className;
    }

    /**
     * @return PHPUnit_Framework_ExceptionWrapper
     */
    public function getPreviousWrapped()
    {
        return $this->previous;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $string = PHPUnit_Framework_TestFailure::exceptionToString($this);

        if ($trace = PHPUnit_Util_Filter::getFilteredStacktrace($this)) {
            $string .= "\n" . $trace;
        }

        if ($this->previous) {
            $string .= "\nCaused by\n" . $this->previous;
        }

        return $string;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadiusRatio="2.3"
    android:shape="ring"
    android:thickness="8dp"
    android:useLevel="true">
    <solid android:color="@color/circular_progress"/>
</shape>


text:
package org.openqa.selenium.jre.server;

import com.sun.net.httpserver.HttpExchange;
import org.openqa.selenium.remote.http.HttpMethod;
import org.openqa.selenium.remote.http.HttpRequest;

import java.util.AbstractMap;
import java.util.Arrays;

import static org.openqa.selenium.remote.http.Contents.memoize;

class JreMessages {

  static HttpRequest asRequest(HttpExchange exchange) {
    HttpRequest request = new HttpRequest(
      HttpMethod.valueOf(exchange.getRequestMethod()),
      exchange.getRequestURI().getPath());

    String query = exchange.getRequestURI().getQuery();
    if (query != null) {
      Arrays.stream(query.split("&"))
        .map(q -> {
          int i = q.indexOf("=");
          if (i == -1) {
            return new AbstractMap.SimpleImmutableEntry<>(q, "");
          }
          return new AbstractMap.SimpleImmutableEntry<>(q.substring(0, i), q.substring(i + 1));
        })
        .forEach(entry -> request.addQueryParameter(entry.getKey(), entry.getValue()));
    }

    exchange.getRequestHeaders().forEach((name, values) -> values.forEach(value -> request.addHeader(name, value)));

    request.setContent(memoize(exchange::getRequestBody));

    return request;
  }

}