text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="exclude">

<TITLE>
Uses of Package java.util (Java 2 Platform SE 5.0)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
java.util

Packages that use java.util

java.applet
Provides the classes necessary to create an applet and the classes an applet
uses to communicate with its applet context.

java.awt
Contains all of the classes for creating user
interfaces and for painting graphics and images.

java.awt.datatransfer
Provides interfaces and classes for transferring data
between and within applications.

java.awt.dnd
Drag and Drop is a direct manipulation gesture found in many Graphical
User Interface systems that provides a mechanism to transfer
information between two entities logically associated with presentation
elements in the GUI.

java.awt.event
Provides interfaces and classes for dealing with different
types of events fired by AWT components.

java.awt.font
Provides classes and interface relating to fonts.

java.awt.im
Provides classes and interfaces for the input method framework.

java.awt.im.spi
Provides interfaces that enable the development of input methods
that can be used with any Java runtime environment.

java.awt.image
Provides classes for creating and modifying images.

java.awt.image.renderable
Provides classes and interfaces for producing
rendering-independent images.

java.beans
Contains classes related to developing
beans -- components
based on the JavaBeansTM architecture.

java.beans.beancontext
Provides classes and interfaces relating to bean context.

java.io
Provides for system input and output through data streams,
serialization and the file system.

java.lang
Provides classes that are fundamental to the design of the Java
programming language.

java.lang.management
Provides the management interface for monitoring and management of the
Java virtual machine as well as the operating system on which the
Java virtual machine is running.

java.math
Provides classes for performing arbitrary-precision integer arithmetic
(BigInteger) and arbitrary-precision decimal arithmetic (BigDecimal).

java.net
Provides the classes for implementing networking applications.

java.nio.channels
Defines channels, which represent connections to entities that are capable of
performing I/O operations, such as files and sockets; defines selectors, for
multiplexed, non-blocking I/O operations.

java.nio.channels.spi
Service-provider classes for the <tt>java.nio.channels</tt> package.

java.nio.charset
Defines charsets, decoders, and encoders, for translating between bytes and
Unicode characters.

java.nio.charset.spi
Service-provider classes for the <tt>java.nio.charset</tt> package.

java.rmi.activation
Provides support for RMI Object Activation.

java.security
Provides the classes and interfaces for the security framework.

java.security.acl
The classes and interfaces in this package have been
superseded by classes in the java.security package.

java.security.cert
Provides classes and interfaces for parsing and managing
certificates, certificate revocation lists (CRLs), and
certification paths.

java.sql
Provides the API for accessing and processing data stored in a
data source (usually a relational database) using the
JavaTM programming language.

java.text
Provides classes and interfaces for handling text, dates, numbers, and messages
in a manner independent of natural languages.

java.util
Contains the collections framework, legacy collection classes, event model,
date and time facilities, internationalization, and miscellaneous utility
classes (a string tokenizer, a random-number generator, and a bit array).

java.util.concurrent
 Utility classes commonly useful in concurrent programming.

java.util.concurrent.locks
Interfaces and classes providing a framework for locking and waiting
for conditions that is distinct from built-in synchronization and
monitors.

java.util.jar
Provides classes for reading and writing the JAR (Java ARchive) file
format, which is based on the standard ZIP file format with an
optional manifest file.

java.util.logging

Provides the classes and interfaces of
the JavaTM 2
 platform's core logging facilities.

java.util.prefs
This package allows applications to store and retrieve user and system
preference and configuration data.

java.util.zip
Provides classes for reading and writing the standard ZIP and GZIP
file formats.

javax.accessibility
Defines a contract between user-interface components and an assistive technology
that provides access to those components.

javax.imageio
The main package of the Java Image I/O API.

javax.imageio.event
A package of the Java Image I/O API dealing with synchronous
notification of events during the reading and writing of images.

javax.imageio.metadata
A package of the Java Image I/O API dealing with reading and writing
metadata.

javax.imageio.plugins.bmp
Package containing the public classes used by the built-in BMP plug-in.

javax.imageio.plugins.jpeg
Classes supporting the built-in JPEG plug-in.

javax.imageio.spi
A package of the Java Image I/O API containing the plug-in interfaces
for readers, writers, transcoders, and streams, and a runtime
registry.

javax.management
Provides the core classes for the Java Management Extensions.

javax.management.loading
Provides the classes which implement advanced dynamic
        loading.

javax.management.monitor
Provides the definition of the monitor classes.

javax.management.openmbean
Provides the open data types and Open MBean descriptor classes.

javax.management.relation
Provides the definition of the Relation Service.

javax.management.remote
Interfaces for remote access to
        JMX MBean servers.

javax.management.remote.rmi
The RMI connector is a connector for the JMX Remote API that
      uses RMI to transmit client requests to a remote MBean server.

javax.management.timer
Provides the definition of the Timer MBean.

javax.naming
Provides the classes and interfaces for accessing naming services.

javax.naming.directory
Extends the <tt>javax.naming</tt> package to provide functionality
for accessing directory services.

javax.naming.event
Provides support for event notification when accessing naming and
directory services.

javax.naming.ldap
Provides support for LDAPv3 extended operations and controls.

javax.naming.spi
Provides the means for dynamically plugging in support for accessing
naming and directory services through the <tt>javax.naming</tt>
and related packages.

javax.net.ssl
Provides classes for the secure socket package.

javax.print.attribute
Provides classes and interfaces
that describe the types of JavaTM Print
Service attributes and how they can be collected into attribute sets.

javax.print.attribute.standard
Package javax.print.attribute.standard
contains classes for specific printing attributes.

javax.print.event
Package javax.print.event contains event classes  and listener interfaces.

javax.security.auth
This package provides a framework for authentication and
    authorization.

javax.security.auth.callback
This package provides the classes necessary for services
        to interact with applications in order to retrieve
        information (authentication data including usernames
        or passwords, for example) or to display information
        (error and warning messages, for example).

javax.security.auth.kerberos
This package contains utility classes related to the Kerberos network
    authentication protocol.

javax.security.auth.login
This package provides a pluggable authentication framework.

javax.security.auth.spi
This package provides the interface to be used for
        implementing pluggable authentication modules.

javax.security.sasl
Contains class and interfaces for supporting SASL.

javax.sound.midi
Provides interfaces and classes for I/O, sequencing, and synthesis of MIDI
(Musical Instrument Digital Interface) data.

javax.sound.sampled
Provides interfaces and classes for capture, processing, and playback of sampled audio data.

javax.sql
Provides the API for server side data source access and processing from
the JavaTM programming language.

javax.sql.rowset
Standard interfaces and base classes for JDBC RowSet
implementations.

javax.sql.rowset.serial
Provides utility classes to allow serializable mappings between SQL types
and data types in the Java programming language.

javax.sql.rowset.spi
The standard classes and interfaces that a third party vendor has to
use in its implementation of a synchronization provider.

javax.swing
Provides a set of "lightweight"
(all-Java language) components that,
to the maximum degree possible, work the same on all platforms.

javax.swing.event
Provides for events fired by Swing components.

javax.swing.plaf.basic
Provides user interface objects built according to the
Basic look and feel.

javax.swing.plaf.metal
Provides user interface objects built according to
the Java look and feel (once codenamed Metal),
which is the default look and feel.

javax.swing.plaf.multi
Provides user interface objects that combine two or more look and feels.

javax.swing.table
Provides classes and interfaces for dealing with
javax.swing.JTable.

javax.swing.text
Provides classes and interfaces that deal with editable
and noneditable text components.

javax.swing.text.html
Provides the class HTMLEditorKit and supporting classes
for creating HTML text editors.

javax.swing.text.html.parser
Provides the default HTML parser, along with support classes.

javax.swing.tree
Provides classes and interfaces for dealing with
javax.swing.JTree.

javax.swing.undo
Allows developers to provide support for undo/redo
in applications such as text editors.

javax.xml.datatype
XML/Java Type Mappings.

javax.xml.namespace
XML Namespace processing.

javax.xml.transform
This package defines the generic APIs for processing transformation
instructions, and performing a transformation from source to result.

javax.xml.xpath
This package provides an object-model neutral API for the
evaluation of XPath expressions and access to the evaluation
environment.

org.omg.CORBA
Provides the mapping of the OMG CORBA APIs to the JavaTM
programming language, including the class <TT>ORB</TT>, which is implemented
so that a programmer can use it as a fully-functional Object Request Broker
(ORB).

org.xml.sax
 This package provides the core SAX APIs.

org.xml.sax.helpers
This package contains "helper" classes, including
support for bootstrapping SAX-based applications.

Classes in java.util used by java.applet

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Iterator

          An iterator over a collection.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by java.awt

Collection

          The root interface in the collection hierarchy.

EmptyStackException

          Thrown by methods in the Stack class to indicate
 that the stack is empty.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Hashtable

          This class implements a hashtable, which maps keys to values.

List

          An ordered collection (also known as a sequence).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Map.Entry

          A map entry (key-value pair).

Properties

          The Properties class represents a persistent set of
 properties.

ResourceBundle

          Resource bundles contain locale-specific objects.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.awt.datatransfer

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Classes in java.util used by java.awt.dnd

ArrayList

          Resizable-array implementation of the <tt>List</tt> interface.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

TooManyListenersException

 The  TooManyListenersException  Exception is used as part of
 the Java Event model to annotate and implement a unicast special case of
 a multicast Event Source.

Classes in java.util used by java.awt.event

EventListener

          A tagging interface that all event listener interfaces must extend.

EventListenerProxy

          An abstract wrapper class for an EventListener class which associates a set
 of additional parameters with the listener.

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by java.awt.font

Map

          An object that maps keys to values.

Classes in java.util used by java.awt.im

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Classes in java.util used by java.awt.im.spi

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by java.awt.image

Hashtable

          This class implements a hashtable, which maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by java.awt.image.renderable

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by java.beans

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventListenerProxy

          An abstract wrapper class for an EventListener class which associates a set
 of additional parameters with the listener.

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by java.beans.beancontext

ArrayList

          Resizable-array implementation of the <tt>List</tt> interface.

Collection

          The root interface in the collection hierarchy.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

HashMap

          Hash table based implementation of the <tt>Map</tt> interface.

Iterator

          An iterator over a collection.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

TooManyListenersException

 The  TooManyListenersException  Exception is used as part of
 the Java Event model to annotate and implement a unicast special case of
 a multicast Event Source.

Classes in java.util used by java.io

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by java.lang

Comparator

          A comparison function, which imposes a total ordering on some
 collection of objects.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Properties

          The Properties class represents a persistent set of
 properties.

Classes in java.util used by java.lang.management

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Classes in java.util used by java.math

Random

          An instance of this class is used to generate a stream of
 pseudorandom numbers.

Classes in java.util used by java.net

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Classes in java.util used by java.nio.channels

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.nio.channels.spi

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.nio.charset

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Set

          A collection that contains no duplicate elements.

SortedMap

          A map that further guarantees that it will be in ascending key order,
 sorted according to the natural ordering of its keys (see the
 <tt>Comparable</tt> interface), or by a comparator provided at sorted map
 creation time.

Classes in java.util used by java.nio.charset.spi

Iterator

          An iterator over a collection.

Classes in java.util used by java.rmi.activation

Properties

          The Properties class represents a persistent set of
 properties.

Classes in java.util used by java.security

Collection

          The root interface in the collection hierarchy.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Dictionary

          The Dictionary class is the abstract parent of any
 class, such as Hashtable, which maps keys to values.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Hashtable

          This class implements a hashtable, which maps keys to values.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Map.Entry

          A map entry (key-value pair).

Properties

          The Properties class represents a persistent set of
 properties.

Random

          An instance of this class is used to generate a stream of
 pseudorandom numbers.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.security.acl

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Classes in java.util used by java.security.cert

Collection

          The root interface in the collection hierarchy.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.sql

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Map

          An object that maps keys to values.

Properties

          The Properties class represents a persistent set of
 properties.

Classes in java.util used by java.text

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

Comparator

          A comparison function, which imposes a total ordering on some
 collection of objects.

Currency

          Represents a currency.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Set

          A collection that contains no duplicate elements.

TimeZone

          TimeZone represents a time zone offset, and also figures out daylight
 savings.

Classes in java.util used by java.util

AbstractCollection

          This class provides a skeletal implementation of the <tt>Collection</tt>
 interface, to minimize the effort required to implement this interface.

AbstractList

          This class provides a skeletal implementation of the <tt>List</tt>
 interface to minimize the effort required to implement this interface
 backed by a "random access" data store (such as an array).

AbstractMap

          This class provides a skeletal implementation of the <tt>Map</tt>
 interface, to minimize the effort required to implement this interface.

AbstractQueue

          This class provides skeletal implementations of some Queue
 operations.

AbstractSequentialList

          This class provides a skeletal implementation of the <tt>List</tt>
 interface to minimize the effort required to implement this interface
 backed by a "sequential access" data store (such as a linked list).

AbstractSet

          This class provides a skeletal implementation of the <tt>Set</tt>
 interface to minimize the effort required to implement this
 interface.

ArrayList

          Resizable-array implementation of the <tt>List</tt> interface.

BitSet

          This class implements a vector of bits that grows as needed.

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

Collection

          The root interface in the collection hierarchy.

Comparator

          A comparison function, which imposes a total ordering on some
 collection of objects.

Currency

          Represents a currency.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Dictionary

          The Dictionary class is the abstract parent of any
 class, such as Hashtable, which maps keys to values.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EnumMap

          A specialized Map implementation for use with enum type keys.

EnumSet

          A specialized Set implementation for use with enum types.

EventListener

          A tagging interface that all event listener interfaces must extend.

Formatter

          An interpreter for printf-style format strings.

Formatter.BigDecimalLayoutForm

HashMap

          Hash table based implementation of the <tt>Map</tt> interface.

HashSet

          This class implements the <tt>Set</tt> interface, backed by a hash table
 (actually a <tt>HashMap</tt> instance).

Hashtable

          This class implements a hashtable, which maps keys to values.

IllegalFormatException

          Unchecked exception thrown when a format string contains an illegal syntax
 or a format specifier that is incompatible with the given arguments.

InvalidPropertiesFormatException

          Thrown to indicate that an operation could not complete because
 the input did not conform to the appropriate XML document type
 for a collection of properties, as per the Properties
 specification.

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

ListIterator

          An iterator for lists that allows the programmer
 to traverse the list in either direction, modify
 the list during iteration, and obtain the iterator's
 current position in the list.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Map.Entry

          A map entry (key-value pair).

MissingResourceException

          Signals that a resource is missing.

NoSuchElementException

          Thrown by the nextElement method of an
 Enumeration to indicate that there are no more
 elements in the enumeration.

Observable

          This class represents an observable object, or "data"
 in the model-view paradigm.

Observer

          A class can implement the Observer interface when it
 wants to be informed of changes in observable objects.

PriorityQueue

          An unbounded priority queue based on a priority
 heap.

Properties

          The Properties class represents a persistent set of
 properties.

Queue

          A collection designed for holding elements prior to processing.

Random

          An instance of this class is used to generate a stream of
 pseudorandom numbers.

RandomAccess

          Marker interface used by <tt>List</tt> implementations to indicate that
 they support fast (generally constant time) random access.

ResourceBundle

          Resource bundles contain locale-specific objects.

Scanner

          A simple text scanner which can parse primitive types and strings using
 regular expressions.

Set

          A collection that contains no duplicate elements.

SortedMap

          A map that further guarantees that it will be in ascending key order,
 sorted according to the natural ordering of its keys (see the
 <tt>Comparable</tt> interface), or by a comparator provided at sorted map
 creation time.

SortedSet

          A set that further guarantees that its iterator will traverse the set in
 ascending element order, sorted according to the natural ordering of
 its elements (see Comparable), or by a Comparator provided at sorted set
 creation time.

TimerTask

          A task that can be scheduled for one-time or repeated execution by a Timer.

TimeZone

          TimeZone represents a time zone offset, and also figures out daylight
 savings.

UUID

          A class that represents an immutable universally unique identifier (UUID).

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by java.util.concurrent

AbstractCollection

          This class provides a skeletal implementation of the <tt>Collection</tt>
 interface, to minimize the effort required to implement this interface.

AbstractMap

          This class provides a skeletal implementation of the <tt>Map</tt>
 interface, to minimize the effort required to implement this interface.

AbstractQueue

          This class provides skeletal implementations of some Queue
 operations.

AbstractSet

          This class provides a skeletal implementation of the <tt>Set</tt>
 interface to minimize the effort required to implement this
 interface.

Collection

          The root interface in the collection hierarchy.

Comparator

          A comparison function, which imposes a total ordering on some
 collection of objects.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

ListIterator

          An iterator for lists that allows the programmer
 to traverse the list in either direction, modify
 the list during iteration, and obtain the iterator's
 current position in the list.

Map

          An object that maps keys to values.

Map.Entry

          A map entry (key-value pair).

Queue

          A collection designed for holding elements prior to processing.

RandomAccess

          Marker interface used by <tt>List</tt> implementations to indicate that
 they support fast (generally constant time) random access.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by java.util.concurrent.locks

Collection

          The root interface in the collection hierarchy.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Classes in java.util used by java.util.jar

Collection

          The root interface in the collection hierarchy.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Map

          An object that maps keys to values.

Map.Entry

          A map entry (key-value pair).

Set

          A collection that contains no duplicate elements.

SortedMap

          A map that further guarantees that it will be in ascending key order,
 sorted according to the natural ordering of its keys (see the
 <tt>Comparable</tt> interface), or by a comparator provided at sorted map
 creation time.

Classes in java.util used by java.util.logging

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

List

          An ordered collection (also known as a sequence).

ResourceBundle

          Resource bundles contain locale-specific objects.

Classes in java.util used by java.util.prefs

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by java.util.zip

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Classes in java.util used by javax.accessibility

ListResourceBundle

          ListResourceBundle is an abstract subclass of
 ResourceBundle that manages resources for a locale
 in a convenient and easy to use list.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

ResourceBundle

          Resource bundles contain locale-specific objects.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.imageio

Iterator

          An iterator over a collection.

List

          An ordered collection (also known as a sequence).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.imageio.event

EventListener

          A tagging interface that all event listener interfaces must extend.

Classes in java.util used by javax.imageio.metadata

List

          An ordered collection (also known as a sequence).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.imageio.plugins.bmp

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.imageio.plugins.jpeg

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.imageio.spi

Iterator

          An iterator over a collection.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.management

AbstractCollection

          This class provides a skeletal implementation of the <tt>Collection</tt>
 interface, to minimize the effort required to implement this interface.

AbstractList

          This class provides a skeletal implementation of the <tt>List</tt>
 interface to minimize the effort required to implement this interface
 backed by a "random access" data store (such as an array).

ArrayList

          Resizable-array implementation of the <tt>List</tt> interface.

Collection

          The root interface in the collection hierarchy.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Hashtable

          This class implements a hashtable, which maps keys to values.

List

          An ordered collection (also known as a sequence).

RandomAccess

          Marker interface used by <tt>List</tt> implementations to indicate that
 they support fast (generally constant time) random access.

Set

          A collection that contains no duplicate elements.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.management.loading

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.management.monitor

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by javax.management.openmbean

Collection

          The root interface in the collection hierarchy.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.management.relation

AbstractCollection

          This class provides a skeletal implementation of the <tt>Collection</tt>
 interface, to minimize the effort required to implement this interface.

AbstractList

          This class provides a skeletal implementation of the <tt>List</tt>
 interface to minimize the effort required to implement this interface
 backed by a "random access" data store (such as an array).

ArrayList

          Resizable-array implementation of the <tt>List</tt> interface.

Collection

          The root interface in the collection hierarchy.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

RandomAccess

          Marker interface used by <tt>List</tt> implementations to indicate that
 they support fast (generally constant time) random access.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.management.remote

EventObject

 The root class from which all event state objects shall be derived.

Map

          An object that maps keys to values.

Classes in java.util used by javax.management.remote.rmi

Map

          An object that maps keys to values.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.management.timer

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

EventObject

 The root class from which all event state objects shall be derived.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.naming

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Hashtable

          This class implements a hashtable, which maps keys to values.

Properties

          The Properties class represents a persistent set of
 properties.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.naming.directory

Hashtable

          This class implements a hashtable, which maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.naming.event

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by javax.naming.ldap

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Hashtable

          This class implements a hashtable, which maps keys to values.

List

          An ordered collection (also known as a sequence).

Classes in java.util used by javax.naming.spi

Hashtable

          This class implements a hashtable, which maps keys to values.

Classes in java.util used by javax.net.ssl

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

List

          An ordered collection (also known as a sequence).

Classes in java.util used by javax.print.attribute

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.print.attribute.standard

AbstractCollection

          This class provides a skeletal implementation of the <tt>Collection</tt>
 interface, to minimize the effort required to implement this interface.

AbstractMap

          This class provides a skeletal implementation of the <tt>Map</tt>
 interface, to minimize the effort required to implement this interface.

AbstractSet

          This class provides a skeletal implementation of the <tt>Set</tt>
 interface to minimize the effort required to implement this
 interface.

Collection

          The root interface in the collection hierarchy.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

HashMap

          Hash table based implementation of the <tt>Map</tt> interface.

HashSet

          This class implements the <tt>Set</tt> interface, backed by a hash table
 (actually a <tt>HashMap</tt> instance).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.print.event

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by javax.security.auth

Set

          A collection that contains no duplicate elements.

Classes in java.util used by javax.security.auth.callback

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by javax.security.auth.kerberos

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Classes in java.util used by javax.security.auth.login

Map

          An object that maps keys to values.

Classes in java.util used by javax.security.auth.spi

Map

          An object that maps keys to values.

Classes in java.util used by javax.security.sasl

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Map

          An object that maps keys to values.

Classes in java.util used by javax.sound.midi

EventListener

          A tagging interface that all event listener interfaces must extend.

List

          An ordered collection (also known as a sequence).

Map

          An object that maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.sound.sampled

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Map

          An object that maps keys to values.

Classes in java.util used by javax.sql

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Map

          An object that maps keys to values.

Classes in java.util used by javax.sql.rowset

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

Collection

          The root interface in the collection hierarchy.

Map

          An object that maps keys to values.

Classes in java.util used by javax.sql.rowset.serial

Map

          An object that maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.sql.rowset.spi

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Classes in java.util used by javax.swing

Comparator

          A comparison function, which imposes a total ordering on some
 collection of objects.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

Dictionary

          The Dictionary class is the abstract parent of any
 class, such as Hashtable, which maps keys to values.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Hashtable

          This class implements a hashtable, which maps keys to values.

List

          An ordered collection (also known as a sequence).

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Map

          An object that maps keys to values.

Set

          A collection that contains no duplicate elements.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.event

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Classes in java.util used by javax.swing.plaf.basic

EventListener

          A tagging interface that all event listener interfaces must extend.

Hashtable

          This class implements a hashtable, which maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.plaf.metal

EventListener

          A tagging interface that all event listener interfaces must extend.

Classes in java.util used by javax.swing.plaf.multi

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.table

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.text

Dictionary

          The Dictionary class is the abstract parent of any
 class, such as Hashtable, which maps keys to values.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.text.html

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.text.html.parser

BitSet

          This class implements a vector of bits that grows as needed.

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Hashtable

          This class implements a hashtable, which maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.tree

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

EventListener

          A tagging interface that all event listener interfaces must extend.

EventObject

 The root class from which all event state objects shall be derived.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.swing.undo

EventListener

          A tagging interface that all event listener interfaces must extend.

Hashtable

          This class implements a hashtable, which maps keys to values.

Vector

          The Vector class implements a growable array of
 objects.

Classes in java.util used by javax.xml.datatype

Calendar

          The Calendar class is an abstract class that provides methods
 for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH,
 DAY_OF_MONTH, HOUR, and so on, and for
 manipulating the calendar fields, such as getting the date of the next
 week.

Date

          The class Date represents a specific instant
 in time, with millisecond precision.

GregorianCalendar

          GregorianCalendar is a concrete subclass of
 Calendar and provides the standard calendar system
 used by most of the world.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

TimeZone

          TimeZone represents a time zone offset, and also figures out daylight
 savings.

Classes in java.util used by javax.xml.namespace

Iterator

          An iterator over a collection.

Classes in java.util used by javax.xml.transform

Properties

          The Properties class represents a persistent set of
 properties.

Classes in java.util used by javax.xml.xpath

List

          An ordered collection (also known as a sequence).

Classes in java.util used by org.omg.CORBA

Properties

          The Properties class represents a persistent set of
 properties.

Classes in java.util used by org.xml.sax

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

Classes in java.util used by org.xml.sax.helpers

Enumeration

          An object that implements the Enumeration interface generates a
 series of elements, one at a time.

Locale

          A Locale object represents a specific geographical, political,
 or cultural region.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
from oslo_serialization import jsonutils as json

from tempest.lib.common import rest_client

class VersionsClient(rest_client.RestClient):
    api_version = "v2"

    def list_versions(self):
        """List API versions"""
        version_url = self._get_base_version_url()

        resp, body = self.raw_request(version_url, 'GET')
        self._error_checker(resp, body)

        self.expected_success(300, resp.status)
        body = json.loads(body)
        return rest_client.ResponseBody(resp, body)

    def has_version(self, version):
        """Return True if a version is supported."""
        version = 'v%s' % version
        supported = ['SUPPORTED', 'CURRENT']
        versions = self.list_versions()
        for version_struct in versions['versions']:
            if version_struct['id'] == version:
                return version_struct['status'] in supported
        return False

redpajama_set_name: RedPajamaGithub


text:
/**
 * Components to display workbooks and sheets in Swing applications.
 */
@NotNullApi
package com.dua3.meja.ui.swing;

import com.dua3.cabe.annotations.NotNullApi;


text:
package schema;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import parser.Expression;

public class Metadata {

	class TableMetadata
	{
		int[] keyFields;
		Class[] fieldTypes;

		public TableMetadata(int[] keyFields, Class[] fieldTypes) {
			this.keyFields = keyFields;
			this.fieldTypes = fieldTypes;
		}

		public int[] getKeyFields()
		{
			return keyFields;
		}

		public Class[] getFieldTypes()
		{
			return fieldTypes;
		}
	}

	Map<String, TableMetadata> metadata = new HashMap<String, Metadata.TableMetadata>();

	public void setMetadata(String tableName, int[] keyFields, Class[] fieldTypes)
	{
		if (!metadata.containsKey(tableName))
		{
			TableMetadata tableMetadata = new TableMetadata(keyFields, fieldTypes);
			metadata.put(tableName, tableMetadata);
		}
	}

	public int[] getKeyFields(String tableName)
	{
		return metadata.get(tableName).getKeyFields();
	}

	public Class[] getFieldTypes(String tableName)
	{
		return metadata.get(tableName).getFieldTypes();
	}

	public Class[] getTypes(Expression[] outputFields)
	{
		int numberOfOutputFields = outputFields.length;
		Class[] types = new Class[numberOfOutputFields];
		for (int i=0; i<numberOfOutputFields; i++)
			types[i] = outputFields[i].getType(this);
		return types;
	}

}


text:
#include "EventCounter.h"
#include <qs/log/LogLevel.h>
#include <commonlib/sys/fs/FileLock.h>

#include <org/invenireaude/qsystem/workers/Connection.h>

#include <org/invenireaude/qsystem/workers/ec/DataFactory.h>

#include "Data.h"

using namespace org::invenireaude::qsystem::workers;

namespace IAS {
namespace QS {
namespace Workers {
namespace Proc {
namespace EC {
namespace Simple {

/*************************************************************************/
EventCounter::EventCounter(const ::org::invenireaude::qsystem::workers::ec::SimpleEventCounter* dmParameters):
		pSamples(0),
		pKeys(0){
	IAS_TRACER;

	Data::Settings settings;

	strName = "EC.";
	strName +=  dmParameters->getConnection()->getLocation();

	settings.iMaxNumSamples = PrimeNumbers::GetNextGtEq(2*dmParameters->getSize());

	settings.iResetInterval = dmParameters->isSetResetInterval() ? dmParameters->getResetInterval() : 3600;

	settings.iKeyStorageSize = settings.iMaxNumSamples *
				(dmParameters->isSetAvgKeyLen() ? dmParameters->getAvgKeyLen() : 32);

	IAS_LOG(QS::LogLevel::INSTANCE.isInfo(),"EC Name: "<<strName);
	IAS_LOG(QS::LogLevel::INSTANCE.isInfo(),"Size:    "<<settings.iMaxNumSamples);

	SYS::FS::FileLock lock(String("/tmp/ias.qs.ec.")+strName+".lck");
	SYS::Locker locker(&lock);

	SharedMemoryFile::Descriptor descriptor;

	descriptor.setDomain(SharedMemoryFile::Descriptor::DM_SHARED_MEMORY);
	descriptor.setOpenMode(SharedMemoryFile::Descriptor::OM_CREATE_IF_NEEDED);

	descriptor.setName(strName);

	ptrShared=IAS_DFT_FACTORY< SharedContent<Data> >::Create(descriptor, settings);

	descriptor.setSize(sizeof(Data::Sample)*settings.iMaxNumSamples);

	descriptor.setName(strName+".s");
	ptrSamples  = IAS_DFT_FACTORY<SharedMemoryFile>::Create(descriptor);

	descriptor.setSize(settings.iKeyStorageSize);

	descriptor.setName(strName+".k");
	ptrKeys = IAS_DFT_FACTORY<SharedMemoryFile>::Create(descriptor);

	pData   = ptrShared->get();

	pSamples = static_cast<Data::Sample*>(ptrSamples->getAddress());
	pKeys = static_cast<char*>(ptrKeys->getAddress());
}
/*************************************************************************/
EventCounter::~EventCounter() throw(){
	IAS_TRACER;
}

/*************************************************************************/
void EventCounter::resetIfNeeded(long ts) {
	IAS_TRACER;

	IAS_LOG(QS::LogLevel::INSTANCE.isDetailedInfo(),"reset ? "<<ts<<" at: "<<pData->tsVersion<<", interval="<<pData->settings.iResetInterval);

	if( pData->isEmpty() || ts >= pData->tsVersion + pData->settings.iResetInterval){
		pData->tsVersion = ts / pData->settings.iResetInterval *  pData->settings.iResetInterval ;
		pData->iKeyStorageUsed=0;
		pData->iNumSamples=0;
	}
}
/*************************************************************************/
void EventCounter::update(const String& strKey,	unsigned int iValue, long ts, ec::Ext::RecordPtr& dmOutput){

	IAS_TRACER;

	Mutex::Locker locker(pData->theMutex);

	resetIfNeeded(ts);

	Data::Sample* pSample;

	dmOutput = ec::DataFactory::GetInstance()->getRecordType()->createRecord();

	if(lookup(strKey,pSample)){

		pSample->tsUpdate=ts;

		Data::Record& record(pSample->record);

		record.iCount++;
		record.iTotal+=iValue;

		if(iValue > record.iMax)
			record.iMax=iValue;

		if(iValue < record.iMin)
			record.iMin=iValue;

		dmOutput->setTotal(record.iTotal);
		dmOutput->setAvg(record.iTotal/record.iCount);
		dmOutput->setMax(record.iMax);
		dmOutput->setMin(record.iMin);
		dmOutput->setCount(record.iCount);

	}else{

		if((pData->settings.iMaxNumSamples / 2) < pData->iNumSamples)
			IAS_THROW(BadUsageException("EventCounter: Simple HashTable is too small.")
					<<(pData->settings.iMaxNumSamples / 2) << " " << pData->iNumSamples)

		pData->iNumSamples++;

		pSample->tsUpdate=ts;
		pSample->iKeyOffset=appendKey(strKey);

		Data::Record& record(pSample->record);

		record.iCount=1;
		record.iTotal=iValue;
		record.iMax=iValue;
		record.iMin=iValue;

		dmOutput->setTotal(record.iTotal);
		dmOutput->setAvg(iValue);
		dmOutput->setMax(iValue);
		dmOutput->setMin(iValue);
		dmOutput->setCount(1);

	}

}
/*************************************************************************/
bool EventCounter::lookup(const String& strKey, Data::Sample* &pSample){
	IAS_TRACER;

	_Hash<String> hash;

	unsigned int iSampleIdx = hash(strKey) % pData->settings.iMaxNumSamples;

	int iCheck = pData->settings.iMaxNumSamples;

	do{
		iSampleIdx = iSampleIdx % pData->settings.iMaxNumSamples;
		pSample = pSamples + iSampleIdx;

		if(pSample->tsUpdate < pData->tsVersion)
			return false;

		if(strKey.compare(pKeys + pSample->iKeyOffset) == 0)
			return true;

		iSampleIdx++; //TODO better hashing.

	}while(iCheck-- > 0);

	IAS_THROW(InternalException("Infinite loop detected in EventCounter::lookup()."));

}

/*************************************************************************/
size_t EventCounter::appendKey(const String& strKey){
	IAS_TRACER;

	size_t iResult = pData->iKeyStorageUsed;

	char* tKeyStorageEnd  = pKeys + pData->iKeyStorageUsed;

	size_t iCount=0;
	size_t iLeft=pData->settings.iKeyStorageSize - pData->iKeyStorageUsed;

	IAS_LOG(QS::LogLevel::INSTANCE.isInfo(),"appending: "<<strKey<<" at: "<<iResult);

	for(String::const_iterator it=strKey.begin();
			it != strKey.end(); it++){

		*tKeyStorageEnd++=*it;
		iCount++;
		iLeft--;

		if(iLeft == 0)
			IAS_THROW(BadUsageException("appendKey, key storage too small."));

	}

	*tKeyStorageEnd++=0;
    pData->iKeyStorageUsed += iCount+1;

	return iResult;
}
/*************************************************************************/
bool EventCounter::read(const String& strKey,
		  	  	  	  	org::invenireaude::qsystem::workers::ec::Ext::RecordPtr& dmRecord){
	IAS_TRACER;

	Mutex::Locker locker(pData->theMutex);

	Data::Sample* pSample;

	if(lookup(strKey,pSample)){

		dmRecord = ec::DataFactory::GetInstance()->getRecordType()->createRecord();

		Data::Record& record(pSample->record);

		dmRecord->setAvg(record.iTotal/record.iCount);
		dmRecord->setMax(record.iMax);
		dmRecord->setMin(record.iMin);
		dmRecord->setTotal(record.iTotal);
		dmRecord->setCount(record.iCount);

		return true;
	}

	return false;
}
/*
 * Linear search but it should not be used for large key sets, anyway.
 */
/*************************************************************************/
void EventCounter::readAll(DM::DataObjectList& dmRecordsList,
		 	 	 	 	   bool bReset){
	IAS_TRACER;

	Mutex::Locker locker(pData->theMutex);

	Data::Sample* pSample=pSamples;

	for(int iIdx = 0;
			iIdx < pData->settings.iMaxNumSamples;
			iIdx++, pSample++)
		if(pSample->tsUpdate > pData->tsVersion){

		ec::Ext::RecordPtr dmRecord = ec::DataFactory::GetInstance()->getRecordType()->createRecord();

		Data::Record& record(pSample->record);

		dmRecord->setKey(pKeys + pSample->iKeyOffset);
		dmRecord->setAvg(record.iTotal/record.iCount);
		dmRecord->setMax(record.iMax);
		dmRecord->setMin(record.iMin);
		dmRecord->setCount(record.iCount);

		IAS_LOG(QS::LogLevel::INSTANCE.isInfo(),"found: "<<pKeys + pSample->iKeyOffset<<" count: "<<record.iCount);

		dmRecordsList.add(dmRecord);

		if(bReset)
			pSample->tsUpdate = 0;
	}

	if(bReset){

		DateTime ts(true);

		pData->tsVersion       = ts;
		pData->iKeyStorageUsed = 0;
		pData->iNumSamples     = 0;
	}

}
/*************************************************************************/
}
}
}
}
}
}


text:
package org.apache.geode.management.internal.cli.util;

import static java.util.stream.Collectors.toSet;

import java.util.Arrays;
import java.util.Collection;
import java.util.Set;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;

/**
 * Utility class to scan class-path & load classes.
 *
 * @since GemFire 7.0
 */
public class ClasspathScanLoadHelper implements AutoCloseable {

  private final ScanResult scanResult;

  public ClasspathScanLoadHelper(Collection<String> packagesToScan) {
    scanResult = new ClassGraph().whitelistPackages(packagesToScan.toArray(new String[] {}))
        .enableClassInfo()
        .enableAnnotationInfo().scan(1);
  }

  public Set<Class<?>> scanPackagesForClassesImplementing(Class<?> implementedInterface,
      String... onlyFromPackages) {
    ClassInfoList classInfoList = scanResult.getClassesImplementing(implementedInterface.getName())
        .filter(ci -> !ci.isAbstract() && !ci.isInterface() && ci.isPublic());

    classInfoList = classInfoList
        .filter(ci -> Arrays.stream(onlyFromPackages)
            .anyMatch(p -> classMatchesPackage(ci.getName(), p)));

    return classInfoList.loadClasses().stream().collect(toSet());
  }

  public Set<Class<?>> scanClasspathForAnnotation(Class<?> annotation, String... onlyFromPackages) {
    ClassInfoList classInfoList = scanResult.getClassesWithAnnotation(annotation.getName());

    classInfoList = classInfoList
        .filter(ci -> Arrays.stream(onlyFromPackages)
            .anyMatch(p -> classMatchesPackage(ci.getName(), p)));

    return classInfoList.loadClasses().stream().collect(toSet());
  }

  /**
   * replaces shell-style glob characters with their regexp equivalents
   */
  private static String globToRegex(final String glob) {
    return "^" + glob.replace(".", "\\.").replace("*", ".*") + "$";
  }

  private static boolean classMatchesPackage(String className, String packageSpec) {
    if (!packageSpec.contains("*")) {
      return className.startsWith(packageSpec);
    }

    return className.matches(globToRegex(packageSpec));
  }

  @Override
  public void close() {
    if (scanResult != null)
      scanResult.close();
  }
}


text:
  Google Drive Rivers

{{river.id}}   {{river.name}}

Elasticsearch mapping: {{ river.index }}/{{ river.type }}

Root folder: {{ river.folder }}

Includes: {{ river.includes }}

Excludes: {{ river.excludes }}

Update rate: {{ river.update_rate/1000 }} seconds

        <button class="btn btn-primary" type="button" ng-click="addRiver()">Add River</button>


text:
package safe.safelang

import scala.collection.mutable.{Set => MutableSet}

import safe.safelog.{Index, MutableCache, Statement, ParserException}

import model.SignedCredentialHolder

trait ParserService extends safe.safelog.ParserService {
  private[safe] def parseCertificate(source: String): SetTerm
  private[safe] def parseCertificate(source: java.io.Reader): SetTerm
  private[safe] def parseFileAsCertificate(fileName: String): SetTerm
}

class Parser(
    val self: String
  , val saysOperator: Boolean
  , val _statementCache: MutableCache[Index, MutableSet[Statement]]
) extends ParserService with parser.ParserImpl

object Parser {
  def apply() = new Parser(Config.config.self, Config.config.saysOperator, new MutableCache[Index, MutableSet[Statement]]())
  def apply(self: String) = new Parser(self, true, new MutableCache[Index, MutableSet[Statement]]())

  def parseSignedCredential(speaker: String, name: String, stmts: String): SignedCredentialHolder = (name, stmts) match {
    case ("", "") => throw ParserException(s"identity set cannot be empty")
    case ("", _) => SafelogParserContext(speaker).parseSignedCredential(speaker, "", stmts)
    case (_, "") => SignedCredentialHolder(name, "", Map.empty[Index, Set[Statement]], Nil, Nil, None, Nil, Nil)
    case _       => SafelogParserContext(speaker).parseSignedCredential(speaker, name, stmts)
  }
}


text:
#include <aws/kinesisanalytics/model/ApplicationDetail.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace KinesisAnalytics
{
namespace Model
{

ApplicationDetail::ApplicationDetail() :
    m_applicationNameHasBeenSet(false),
    m_applicationDescriptionHasBeenSet(false),
    m_applicationARNHasBeenSet(false),
    m_applicationStatus(ApplicationStatus::NOT_SET),
    m_applicationStatusHasBeenSet(false),
    m_createTimestampHasBeenSet(false),
    m_lastUpdateTimestampHasBeenSet(false),
    m_inputDescriptionsHasBeenSet(false),
    m_outputDescriptionsHasBeenSet(false),
    m_referenceDataSourceDescriptionsHasBeenSet(false),
    m_cloudWatchLoggingOptionDescriptionsHasBeenSet(false),
    m_applicationCodeHasBeenSet(false),
    m_applicationVersionId(0),
    m_applicationVersionIdHasBeenSet(false)
{
}

ApplicationDetail::ApplicationDetail(JsonView jsonValue) :
    m_applicationNameHasBeenSet(false),
    m_applicationDescriptionHasBeenSet(false),
    m_applicationARNHasBeenSet(false),
    m_applicationStatus(ApplicationStatus::NOT_SET),
    m_applicationStatusHasBeenSet(false),
    m_createTimestampHasBeenSet(false),
    m_lastUpdateTimestampHasBeenSet(false),
    m_inputDescriptionsHasBeenSet(false),
    m_outputDescriptionsHasBeenSet(false),
    m_referenceDataSourceDescriptionsHasBeenSet(false),
    m_cloudWatchLoggingOptionDescriptionsHasBeenSet(false),
    m_applicationCodeHasBeenSet(false),
    m_applicationVersionId(0),
    m_applicationVersionIdHasBeenSet(false)
{
  *this = jsonValue;
}

ApplicationDetail& ApplicationDetail::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("ApplicationName"))
  {
    m_applicationName = jsonValue.GetString("ApplicationName");

    m_applicationNameHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationDescription"))
  {
    m_applicationDescription = jsonValue.GetString("ApplicationDescription");

    m_applicationDescriptionHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationARN"))
  {
    m_applicationARN = jsonValue.GetString("ApplicationARN");

    m_applicationARNHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationStatus"))
  {
    m_applicationStatus = ApplicationStatusMapper::GetApplicationStatusForName(jsonValue.GetString("ApplicationStatus"));

    m_applicationStatusHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CreateTimestamp"))
  {
    m_createTimestamp = jsonValue.GetDouble("CreateTimestamp");

    m_createTimestampHasBeenSet = true;
  }

  if(jsonValue.ValueExists("LastUpdateTimestamp"))
  {
    m_lastUpdateTimestamp = jsonValue.GetDouble("LastUpdateTimestamp");

    m_lastUpdateTimestampHasBeenSet = true;
  }

  if(jsonValue.ValueExists("InputDescriptions"))
  {
    Array<JsonView> inputDescriptionsJsonList = jsonValue.GetArray("InputDescriptions");
    for(unsigned inputDescriptionsIndex = 0; inputDescriptionsIndex < inputDescriptionsJsonList.GetLength(); ++inputDescriptionsIndex)
    {
      m_inputDescriptions.push_back(inputDescriptionsJsonList[inputDescriptionsIndex].AsObject());
    }
    m_inputDescriptionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("OutputDescriptions"))
  {
    Array<JsonView> outputDescriptionsJsonList = jsonValue.GetArray("OutputDescriptions");
    for(unsigned outputDescriptionsIndex = 0; outputDescriptionsIndex < outputDescriptionsJsonList.GetLength(); ++outputDescriptionsIndex)
    {
      m_outputDescriptions.push_back(outputDescriptionsJsonList[outputDescriptionsIndex].AsObject());
    }
    m_outputDescriptionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ReferenceDataSourceDescriptions"))
  {
    Array<JsonView> referenceDataSourceDescriptionsJsonList = jsonValue.GetArray("ReferenceDataSourceDescriptions");
    for(unsigned referenceDataSourceDescriptionsIndex = 0; referenceDataSourceDescriptionsIndex < referenceDataSourceDescriptionsJsonList.GetLength(); ++referenceDataSourceDescriptionsIndex)
    {
      m_referenceDataSourceDescriptions.push_back(referenceDataSourceDescriptionsJsonList[referenceDataSourceDescriptionsIndex].AsObject());
    }
    m_referenceDataSourceDescriptionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("CloudWatchLoggingOptionDescriptions"))
  {
    Array<JsonView> cloudWatchLoggingOptionDescriptionsJsonList = jsonValue.GetArray("CloudWatchLoggingOptionDescriptions");
    for(unsigned cloudWatchLoggingOptionDescriptionsIndex = 0; cloudWatchLoggingOptionDescriptionsIndex < cloudWatchLoggingOptionDescriptionsJsonList.GetLength(); ++cloudWatchLoggingOptionDescriptionsIndex)
    {
      m_cloudWatchLoggingOptionDescriptions.push_back(cloudWatchLoggingOptionDescriptionsJsonList[cloudWatchLoggingOptionDescriptionsIndex].AsObject());
    }
    m_cloudWatchLoggingOptionDescriptionsHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationCode"))
  {
    m_applicationCode = jsonValue.GetString("ApplicationCode");

    m_applicationCodeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("ApplicationVersionId"))
  {
    m_applicationVersionId = jsonValue.GetInt64("ApplicationVersionId");

    m_applicationVersionIdHasBeenSet = true;
  }

  return *this;
}

JsonValue ApplicationDetail::Jsonize() const
{
  JsonValue payload;

  if(m_applicationNameHasBeenSet)
  {
   payload.WithString("ApplicationName", m_applicationName);

  }

  if(m_applicationDescriptionHasBeenSet)
  {
   payload.WithString("ApplicationDescription", m_applicationDescription);

  }

  if(m_applicationARNHasBeenSet)
  {
   payload.WithString("ApplicationARN", m_applicationARN);

  }

  if(m_applicationStatusHasBeenSet)
  {
   payload.WithString("ApplicationStatus", ApplicationStatusMapper::GetNameForApplicationStatus(m_applicationStatus));
  }

  if(m_createTimestampHasBeenSet)
  {
   payload.WithDouble("CreateTimestamp", m_createTimestamp.SecondsWithMSPrecision());
  }

  if(m_lastUpdateTimestampHasBeenSet)
  {
   payload.WithDouble("LastUpdateTimestamp", m_lastUpdateTimestamp.SecondsWithMSPrecision());
  }

  if(m_inputDescriptionsHasBeenSet)
  {
   Array<JsonValue> inputDescriptionsJsonList(m_inputDescriptions.size());
   for(unsigned inputDescriptionsIndex = 0; inputDescriptionsIndex < inputDescriptionsJsonList.GetLength(); ++inputDescriptionsIndex)
   {
     inputDescriptionsJsonList[inputDescriptionsIndex].AsObject(m_inputDescriptions[inputDescriptionsIndex].Jsonize());
   }
   payload.WithArray("InputDescriptions", std::move(inputDescriptionsJsonList));

  }

  if(m_outputDescriptionsHasBeenSet)
  {
   Array<JsonValue> outputDescriptionsJsonList(m_outputDescriptions.size());
   for(unsigned outputDescriptionsIndex = 0; outputDescriptionsIndex < outputDescriptionsJsonList.GetLength(); ++outputDescriptionsIndex)
   {
     outputDescriptionsJsonList[outputDescriptionsIndex].AsObject(m_outputDescriptions[outputDescriptionsIndex].Jsonize());
   }
   payload.WithArray("OutputDescriptions", std::move(outputDescriptionsJsonList));

  }

  if(m_referenceDataSourceDescriptionsHasBeenSet)
  {
   Array<JsonValue> referenceDataSourceDescriptionsJsonList(m_referenceDataSourceDescriptions.size());
   for(unsigned referenceDataSourceDescriptionsIndex = 0; referenceDataSourceDescriptionsIndex < referenceDataSourceDescriptionsJsonList.GetLength(); ++referenceDataSourceDescriptionsIndex)
   {
     referenceDataSourceDescriptionsJsonList[referenceDataSourceDescriptionsIndex].AsObject(m_referenceDataSourceDescriptions[referenceDataSourceDescriptionsIndex].Jsonize());
   }
   payload.WithArray("ReferenceDataSourceDescriptions", std::move(referenceDataSourceDescriptionsJsonList));

  }

  if(m_cloudWatchLoggingOptionDescriptionsHasBeenSet)
  {
   Array<JsonValue> cloudWatchLoggingOptionDescriptionsJsonList(m_cloudWatchLoggingOptionDescriptions.size());
   for(unsigned cloudWatchLoggingOptionDescriptionsIndex = 0; cloudWatchLoggingOptionDescriptionsIndex < cloudWatchLoggingOptionDescriptionsJsonList.GetLength(); ++cloudWatchLoggingOptionDescriptionsIndex)
   {
     cloudWatchLoggingOptionDescriptionsJsonList[cloudWatchLoggingOptionDescriptionsIndex].AsObject(m_cloudWatchLoggingOptionDescriptions[cloudWatchLoggingOptionDescriptionsIndex].Jsonize());
   }
   payload.WithArray("CloudWatchLoggingOptionDescriptions", std::move(cloudWatchLoggingOptionDescriptionsJsonList));

  }

  if(m_applicationCodeHasBeenSet)
  {
   payload.WithString("ApplicationCode", m_applicationCode);

  }

  if(m_applicationVersionIdHasBeenSet)
  {
   payload.WithInt64("ApplicationVersionId", m_applicationVersionId);

  }

  return payload;
}

} // namespace Model
} // namespace KinesisAnalytics
} // namespace Aws


text:
/* Space out content a bit */
body {
    padding-bottom: 20px;

}

/* Everything but the jumbotron gets side spacing for mobile first views */
.header,
.marketing,
.footer {
  padding-left: 15px;
  padding-right: 15px;
}

/* Custom page header */
.header {
  border-bottom: 1px solid #e5e5e5;
}
/* Make the masthead heading the same height as the navigation */
.header h3 {
  margin-top: 0;
  margin-bottom: 0;
  line-height: 40px;
  padding-bottom: 19px;
}

/* Custom page footer */
.footer {
  padding-top: 19px;
  color: #777;
  border-top: 1px solid #e5e5e5;
}

/* Customize container */
@media (min-width: 768px) {
  .container {
    max-width: 730px;
  }
}
.container-narrow > hr {
  margin: 30px 0;
}

/* Main marketing message and sign up button */
.jumbotron {
  text-align: center;
  border-bottom: 1px solid #e5e5e5;
}
.jumbotron .btn {
  font-size: 21px;
  padding: 14px 24px;
}

/* Supporting marketing content */
.marketing {
  margin: 40px 0;
}
.marketing p + h4 {
  margin-top: 28px;
}

/* Responsive: Portrait tablets and up */
@media screen and (min-width: 768px) {
  /* Remove the padding we set earlier */
  .header,
  .marketing,
  .footer {
    padding-left: 0;
    padding-right: 0;
  }
  /* Space out the masthead */
  .header {
    margin-bottom: 30px;
  }
  /* Remove the bottom border on the jumbotron for visual effect */
  .jumbotron {
    border-bottom: 0;
  }
}

.nav>li.active>a {
text-decoration: none;
background-color: #eee;
}

.filtro{
  margin-top: 20px;
  margin-bottom: 30px;
  right: 0;
}

.content-wrapper{
  min-height: 590px;
}

.right-0{
  float: right;
}

.bodyTable{
  width: 514px;

}

.descriptionTable{   /*position: relative;*/
  min-height: 1px;
  padding-right: 15px;
  padding-left: 15px;
  float: left;
  width: 50%; } /*.box-header.with-border{ border-bottom: 1px solid #f4f4f4; width:50%; }*/

.bodyTable{
  width: 100%;
  position: absolute;
  background-color:#F7F7F7;
}

.human-readable-example {
  background-color: transparent;
  border-collapse: collapse;
  border-spacing: 0px;
  color: #333;
  width: 100%;
}

.human-readable-example td {
  padding: 6px 3px 6px 3px;
}

.human-readable-example tr:first-child td:first-child {
  width: 25%;
}

.human-readable-example tr:nth-child(even) {
  background-color: #F7F7F7;
}

.human-readable-example tr:nth-child(odd) {
  background-color: #FFFFFF;
}


text:
@interface ShuttleStopMapAnnotation : NSObject <MKAnnotation>
{
	ShuttleStop* _shuttleStop;

	NSString* _subtitle;
}

-(id) initWithShuttleStop:(ShuttleStop*)shuttleStop;

@property (readonly) ShuttleStop* shuttleStop;

-(void) setSubtitle:(NSString*) subtitle;

@end


text:
Nginx Reverse Proxy

how to boot nginx

```
$ grunt dk-build:test/ng
$ grunt yrunt:test/ng:8080 --target=start
$ grunt yrunt:test/ng:8081 --target=start
$ grunt yrunt:test/ng:8082 --target=start
$ curl http://localhost:8080
$ curl http://localhost:8081
$ curl http://localhost:8082
$ grunt dk-psip
Running "exec:dk_ps" (exec) task
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
9dc04f57506f        test/ng:latest      /yrunt.sh start     2 minutes ago       Up 2 minutes        0.0.0.0:8082->80/tcp   stoic_galileo
bf8c716a4d53        test/ng:latest      /yrunt.sh start     2 minutes ago       Up 2 minutes        0.0.0.0:8081->80/tcp   berserk_bohr
fbac9ffbd7be        test/ng:latest      /yrunt.sh start     2 minutes ago       Up 2 minutes        0.0.0.0:8080->80/tcp   backstabbing_ritchie

Running "exec:dk_ip" (exec) task
/stoic_galileo 172.17.0.4
/berserk_bohr 172.17.0.3
/backstabbing_ritchie 172.17.0.2
```

how to inject Gruntfile.js
```
$ nano Gruntfile.js.inject
// inside container # grunt cat:/root/package.json
$ grunt yrunt:test/ng:8099 --target=cat:/root/package.json
```

grunt task
```
Available tasks
         clean  Clean files and folders. *
          exec  Execute shell commands. *
         watch  Run predefined tasks whenever watched files change.
           zip  Zip files together *
         unzip  Unzip files into a folder *
        concat  Concatenate files. *
         shell  Run shell commands *
      dk-build  build docker image
         yrunt  run grunt in container, ex grunt yrunt:test/img:80
                --target=start
    dk-stopall  Stop all docker container
       dk-psip  docker ps and ip
      dk-clean  Alias for "exec:dk_rm", "exec:dk_rmi" tasks.
       default  Alias for "exec:grunt_help" task.
```


text:
@interface JSObjectionInjector : NSObject {
  NSDictionary *_globalContext;
  NSMutableDictionary *_context;
  NSSet *_eagerSingletons;
}

- (id)initWithContext:(NSDictionary *)theGlobalContext;
- (id)initWithContext:(NSDictionary *)theGlobalContext andModule:(JSObjectionModule *)theModule;
- (id)getObject:(id)classOrProtocol;
@end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Test React</title>


text:
<?php
$this->loadJs(array(
	'admin/bootstrap.min.js"',
	'admin/plugins/metismenu.min.js',
	'admin/plugins/pace.min.js',
	'admin/plugins/gritter.min.js',
	'admin/plugins/bootstrap-tabdrop.min.js',
	'admin/plugins/bootstrap-switch.min.js',
	'admin/plugins/bootstrap-spinbox.min.js',
	'admin/plugins/bootstrap-confirmation.min.js',
	'admin/plugins/bootstrap-editable.min.js',
	'admin/plugins/bootstrap-fileinput.min.js',
	'admin/plugins/icheck.min.js',
	'admin/plugins/bootstrap-datepicker.min.js',
	'admin/plugins/bootstrap-select2.min.js',
	'admin/plugins/typeahead.min.js',
	'admin/plugins/jquery-nestable.min.js',
	'admin/th.js',
));
$this->loadJs($this->Js);

echo $this->onDomready();
?>
</body>


text:
Subscription Matched Status              {#DCPS_Status_SubscriptionMatched}
===========================

        Attribute
        Attribute Meaning

        total_count
        Total cumulative count the concerned DataReader discovered a
            "match" with a DataWriter. That is, it found a DataWriter for the
            same Topic with a requested QoS that is compatible with that offered
            by the DataReader.

        total_count_change
        The change in total_count since the last time the listener was called or
            the status was read.

        last_subscription_handle
        Handle to the last DataWriter that matched the DataReader causing the
            status to change.

        current_count
        The number of DataWriters currently matched to the concerned
            DataReader.

        current_count_change
        The change in current_count since the last time the listener was called
            or the status was read.

The DataReader has found a DataWriter that matches the Topic and has compatible QoS or
ceased to be matched with a DataWriter.


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {

template <typename Device, typename Functor>
class LgammaOp : public UnaryOp<Device, Functor> {
 public:
  explicit LgammaOp(OpKernelConstruction* ctx) : UnaryOp<Device, Functor>(ctx) {
    TF_ANNOTATE_BENIGN_RACE(&signgam, "signgam output from lgamma is unused");
  }
};

REGISTER3(LgammaOp, CPU, "Lgamma", functor::lgamma, float, Eigen::half, double);
#if GOOGLE_CUDA
REGISTER3(LgammaOp, GPU, "Lgamma", functor::lgamma, float, Eigen::half, double);
#endif
}  // namespace tensorflow


text:
var express = require('express');
var app = express();
var _ = require('underscore');

app.use(express.static('public'));
app.set('view engine', 'pug');
app.get('/', function(req, res) {
  var og = {
    title: 'PiscoBot',
    url: 'http://devacademy-piscobot.herokuapp.com',
    image: 'https://cdn.rawgit.com/twitter/twemoji/gh-pages/72x72/1f379.png',
    favicon: 'https://cdn.rawgit.com/twitter/twemoji/gh-pages/36x36/1f379.png',
    icon: 'https://cdn.rawgit.com/twitter/twemoji/gh-pages/72x72/1f379.png',
    description: 'A Slackbot by devAcademy. Enjoy responsibly.',
    svg: 'https://cdn.rawgit.com/twitter/twemoji/gh-pages/svg/1f379.svg'
  };
  var responses = [
    'Pretty cool, amirite?',
    '"Hey, that\'s pretty good."',
    'It\'s something.',
    '¯\\_(ツ)_/¯',
    'We did it, Reddit!',
    '
git clone https://github.com/devacademyla/PiscoBot
',
    '#BienKattya',
    'baia baia',
    'Pretty awesome.',
    '[insert witty text here]',
    ':v',
    'This was a triumph.',
    'I\'m making a note here: HUGE SUCCESS.',
    'It\'s hard to overstate my satisfaction.',
    'Aperture Science.',
    'We do what we must because we can.',
    'For the good of all of us. Except the ones who are dead.',
    'But there\'s no sense crying over every mistake.',
    'You just keep on trying till you run out of cake.',
    'And the science gets done and you make a neat gun.',
    'For the people who are still alive.'
  ];
  res.render('index', {
    og: og,
    caption: _.sample(responses, 1)
  });
});
app.listen(process.env.PORT || 3000);


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cafe.Tab;
using System.Text.RegularExpressions;
using WebFrontend.ActionFilters;

namespace WebFrontend.Controllers
{
    [IncludeLayoutData]
    public class ChefController : Controller
    {
        public ActionResult Index()
        {
            return View(Domain.ChefTodoListQueries.GetTodoList());
        }

        public ActionResult MarkPrepared(Guid id, FormCollection form)
        {
            Domain.Dispatcher.SendCommand(new MarkFoodPrepared
            {
                Id = id,
                MenuNumbers = (from entry in form.Keys.Cast<string>()
                               where form[entry] != "false"
                               let m = Regex.Match(entry, @"prepared_\d+_(\d+)")
                               where m.Success
                               select int.Parse(m.Groups[1].Value)
                              ).ToList()
            });

            return RedirectToAction("Index");
        }
    }
}


text:
from __future__ import absolute_import

"""SSL Context

Copyright (c) 1999-2004 Ng Pheng Siong. All rights reserved."""

from M2Crypto import BIO, Err, RSA, X509, m2, util  # noqa
from M2Crypto.SSL import cb  # noqa
from M2Crypto.SSL.Session import Session  # noqa
from weakref import WeakValueDictionary
if util.py27plus:
    from typing import Any, AnyStr, Callable, Optional, Union  # noqa

__all__ = ['ctxmap', 'Context', 'map']

class _ctxmap(object):
    singleton = None  # type: Optional[_ctxmap]

    def __init__(self):
        # type: () -> None
        """Simple WeakReffed list.
        """
        self._ctxmap = WeakValueDictionary()

    def __getitem__(self, key):
        # type: (int) -> Any
        return self._ctxmap[key]

    def __setitem__(self, key, value):
        # type: (int, Any) -> None
        self._ctxmap[key] = value

    def __delitem__(self, key):
        # type: (int) -> None
        del self._ctxmap[key]

def ctxmap():
    # type: () -> _ctxmap
    if _ctxmap.singleton is None:
        _ctxmap.singleton = _ctxmap()
    return _ctxmap.singleton
# deprecated!!!
map = ctxmap

class Context(object):

    """'Context' for SSL connections."""

    m2_ssl_ctx_free = m2.ssl_ctx_free

    def __init__(self, protocol='tls', weak_crypto=None,
                 post_connection_check=None):
        # type: (str, Optional[int], Optional[Callable]) -> None
        proto = getattr(m2, protocol + '_method', None)
        if proto is None:
            # default is 'sslv23' for older versions of OpenSSL
            if protocol == 'tls':
                proto = getattr(m2, 'sslv23_method')
            else:
                raise ValueError("no such protocol '%s'" % protocol)
        self.ctx = m2.ssl_ctx_new(proto())
        self.allow_unknown_ca = 0  # type: Union[int, bool]
        self.post_connection_check = post_connection_check
        ctxmap()[int(self.ctx)] = self
        m2.ssl_ctx_set_cache_size(self.ctx, 128)
        if weak_crypto is None and protocol in ('sslv23', 'tls'):
            self.set_options(m2.SSL_OP_ALL | m2.SSL_OP_NO_SSLv2 |
                             m2.SSL_OP_NO_SSLv3)

    def __del__(self):
        # type: () -> None
        if getattr(self, 'ctx', None):
            self.m2_ssl_ctx_free(self.ctx)

    def close(self):
        # type: () -> None
        del ctxmap()[int(self.ctx)]

    def load_cert(self, certfile, keyfile=None,
                  callback=util.passphrase_callback):
        # type: (AnyStr, Optional[AnyStr], Callable) -> None
        """Load certificate and private key into the context.

        :param certfile: File that contains the PEM-encoded certificate.
        :param keyfile:  File that contains the PEM-encoded private key.
                         Default value of None indicates that the private key
                         is to be found in 'certfile'.
        :param callback: Callable object to be invoked if the private key is
                         passphrase-protected. Default callback provides a
                         simple terminal-style input for the passphrase.
        """
        m2.ssl_ctx_passphrase_callback(self.ctx, callback)
        m2.ssl_ctx_use_cert(self.ctx, certfile)
        if not keyfile:
            keyfile = certfile
        m2.ssl_ctx_use_privkey(self.ctx, keyfile)
        if not m2.ssl_ctx_check_privkey(self.ctx):
            raise ValueError('public/private key mismatch')

    def load_cert_chain(self, certchainfile, keyfile=None,
                        callback=util.passphrase_callback):
        # type: (AnyStr, Optional[AnyStr], Callable) -> None
        """Load certificate chain and private key into the context.

        :param certchainfile: File object containing the PEM-encoded
                              certificate chain.
        :param keyfile:       File object containing the PEM-encoded private
                              key. Default value of None indicates that the
                              private key is to be found in 'certchainfile'.
        :param callback:      Callable object to be invoked if the private key
                              is passphrase-protected. Default callback
                              provides a simple terminal-style input for the
                              passphrase.
        """
        m2.ssl_ctx_passphrase_callback(self.ctx, callback)
        m2.ssl_ctx_use_cert_chain(self.ctx, certchainfile)
        if not keyfile:
            keyfile = certchainfile
        m2.ssl_ctx_use_privkey(self.ctx, keyfile)
        if not m2.ssl_ctx_check_privkey(self.ctx):
            raise ValueError('public/private key mismatch')

    def set_client_CA_list_from_file(self, cafile):
        # type: (AnyStr) -> None
        """Load CA certs into the context. These CA certs are sent to the
        peer during *SSLv3 certificate request*.

        :param cafile: File object containing one or more PEM-encoded CA
                       certificates concatenated together.
        """
        m2.ssl_ctx_set_client_CA_list_from_file(self.ctx, cafile)

    # Deprecated.
    load_client_CA = load_client_ca = set_client_CA_list_from_file

    def load_verify_locations(self, cafile=None, capath=None):
        # type: (Optional[AnyStr], Optional[AnyStr]) -> int
        """Load CA certs into the context.

        These CA certs are used during verification of the peer's
        certificate.

        :param cafile: File containing one or more PEM-encoded CA
                       certificates concatenated together.

        :param capath: Directory containing PEM-encoded CA certificates
                       (one certificate per file).

        :return: 0 if the operation failed because CAfile and CApath are NULL
                  or the processing at one of the locations specified failed.
                  Check the error stack to find out the reason.

                1 The operation succeeded.
        """
        if cafile is None and capath is None:
            raise ValueError("cafile and capath can not both be None.")
        return m2.ssl_ctx_load_verify_locations(self.ctx, cafile, capath)

    # Deprecated.
    load_verify_info = load_verify_locations

    def set_session_id_ctx(self, id):
        # type: (bytes) -> None
        """Sets the session id for the SSL.Context w/in a session can be reused.

        :param id: Sessions are generated within a certain context. When
                   exporting/importing sessions with
                   i2d_SSL_SESSION/d2i_SSL_SESSION it would be possible,
                   to re-import a session generated from another context
                   (e.g. another application), which might lead to
                   malfunctions. Therefore each application must set its
                   own session id context sid_ctx which is used to
                   distinguish the contexts and is stored in exported
                   sessions. The sid_ctx can be any kind of binary data
                   with a given length, it is therefore possible to use
                   e.g. the name of the application and/or the hostname
                   and/or service name.
        """
        ret = m2.ssl_ctx_set_session_id_context(self.ctx, id)
        if not ret:
            raise Err.SSLError(Err.get_error_code(), '')

    def set_default_verify_paths(self):
        # type: () -> int
        """
        Specifies that the default locations from which CA certs are
        loaded should be used.

        There is one default directory and one default file. The default
        CA certificates directory is called "certs" in the default
        OpenSSL directory. Alternatively the SSL_CERT_DIR environment
        variable can be defined to override this location. The default
        CA certificates file is called "cert.pem" in the default OpenSSL
        directory. Alternatively the SSL_CERT_FILE environment variable
        can be defined to override this location.

        @return 0 if the operation failed. A missing default location is
                  still treated as a success. No error code is set.

                1 The operation succeeded.
        """
        ret = m2.ssl_ctx_set_default_verify_paths(self.ctx)
        if not ret:
            raise ValueError('Cannot use default SSL certificate store!')

    def set_allow_unknown_ca(self, ok):
        # type: (Union[int, bool]) -> None
        """Set the context to accept/reject a peer certificate if the
        certificate's CA is unknown.

        :param ok:       True to accept, False to reject.
        """
        self.allow_unknown_ca = ok

    def get_allow_unknown_ca(self):
        # type: () -> Union[int, bool]
        """Get the context's setting that accepts/rejects a peer
        certificate if the certificate's CA is unknown.

        FIXME 2Bconverted to bool
        """
        return self.allow_unknown_ca

    def set_verify(self, mode, depth, callback=None):
        # type: (int, int, Optional[Callable]) -> None
        """
        Set verify options. Most applications will need to call this
        method with the right options to make a secure SSL connection.

        :param mode:     The verification mode to use. Typically at least
                         SSL.verify_peer is used. Clients would also typically
                         add SSL.verify_fail_if_no_peer_cert.
        :param depth:    The maximum allowed depth of the certificate chain
                         returned by the peer.
        :param callback: Callable that can be used to specify custom
                         verification checks.
        """
        if callback is None:
            m2.ssl_ctx_set_verify_default(self.ctx, mode)
        else:
            m2.ssl_ctx_set_verify(self.ctx, mode, callback)
        m2.ssl_ctx_set_verify_depth(self.ctx, depth)

    def get_verify_mode(self):
        # type: () -> int
        return m2.ssl_ctx_get_verify_mode(self.ctx)

    def get_verify_depth(self):
        # type: () -> int
        """Returns the verification mode currently set in the SSL Context."""
        return m2.ssl_ctx_get_verify_depth(self.ctx)

    def set_tmp_dh(self, dhpfile):
        # type: (AnyStr) -> int
        """Load ephemeral DH parameters into the context.

        :param dhpfile: Filename of the file containing the PEM-encoded
                        DH parameters.
        """
        f = BIO.openfile(dhpfile)
        dhp = m2.dh_read_parameters(f.bio_ptr())
        return m2.ssl_ctx_set_tmp_dh(self.ctx, dhp)

    def set_tmp_dh_callback(self, callback=None):
        # type: (Optional[Callable]) -> None
        """Sets the callback function for SSL.Context.

        :param callback: Callable to be used when a DH parameters are required.
        """
        if callback is not None:
            m2.ssl_ctx_set_tmp_dh_callback(self.ctx, callback)

    def set_tmp_rsa(self, rsa):
        # type: (RSA.RSA) -> int
        """Load ephemeral RSA key into the context.

        :param rsa: RSA.RSA instance.
        """
        if isinstance(rsa, RSA.RSA):
            return m2.ssl_ctx_set_tmp_rsa(self.ctx, rsa.rsa)
        else:
            raise TypeError("Expected an instance of RSA.RSA, got %s." % rsa)

    def set_tmp_rsa_callback(self, callback=None):
        # type: (Optional[Callable]) -> None
        """Sets the callback function to be used when
        a temporary/ephemeral RSA key is required.
        """
        if callback is not None:
            m2.ssl_ctx_set_tmp_rsa_callback(self.ctx, callback)

    def set_info_callback(self, callback=cb.ssl_info_callback):
        # type: (Callable) -> None
        """Set a callback function to get state information.

        It can be used to get state information about the SSL
        connections that are created from this context.

        :param callback: Callback function. The default prints
                         information to stderr.
        """
        m2.ssl_ctx_set_info_callback(self.ctx, callback)

    def set_cipher_list(self, cipher_list):
        # type: (str) -> int
        """Sets the list of available ciphers.

        :param cipher_list: The format of the string is described in
                            ciphers(1).
        :return: 1 if any cipher could be selected and 0 on complete
                 failure.
        """
        return m2.ssl_ctx_set_cipher_list(self.ctx, cipher_list)

    def add_session(self, session):
        # type: (Session) -> int
        """Add the session to the context.

        :param session: the session to be added.

        :return: 0 The operation failed. It was tried to add the same
                   (identical) session twice.

                 1 The operation succeeded.
        """
        return m2.ssl_ctx_add_session(self.ctx, session._ptr())

    def remove_session(self, session):
        # type: (Session) -> int
        """Remove the session from the context.

        :param session: the session to be removed.

        :return: 0 The operation failed. The session was not found in
                   the cache.

                 1 The operation succeeded.
        """
        return m2.ssl_ctx_remove_session(self.ctx, session._ptr())

    def get_session_timeout(self):
        # type: () -> int
        """Get current session timeout.

        Whenever a new session is created, it is assigned a maximum
        lifetime.  This lifetime is specified by storing the creation
        time of the session and the timeout value valid at this time. If
        the actual time is later than creation time plus timeout, the
        session is not reused.

        Due to this realization, all sessions behave according to the
        timeout value valid at the time of the session negotiation.
        Changes of the timeout value do not affect already established
        sessions.

        Expired sessions are removed from the internal session cache,
        whenever SSL_CTX_flush_sessions(3) is called, either directly by
        the application or automatically (see
        SSL_CTX_set_session_cache_mode(3))

        The default value for session timeout is decided on a per
        protocol basis, see SSL_get_default_timeout(3).  All currently
        supported protocols have the same default timeout value of 300
        seconds.

        SSL_CTX_set_timeout() returns the previously set timeout value.

        :return: the currently set timeout value.
        """
        return m2.ssl_ctx_get_session_timeout(self.ctx)

    def set_session_timeout(self, timeout):
        # type: (int) -> int
        """Set new session timeout.

        See self.get_session_timeout() for explanation of the session
        timeouts.

        :param timeout: new timeout value.

        :return: the previously set timeout value.
        """
        return m2.ssl_ctx_set_session_timeout(self.ctx, timeout)

    def set_session_cache_mode(self, mode):
        # type: (int) -> int
        """Enables/disables session caching.

        The mode is set by using m2.SSL_SESS_CACHE_* constants.

        :param mode: new mode value.

        :return: the previously set cache mode value.
        """
        return m2.ssl_ctx_set_session_cache_mode(self.ctx, mode)

    def get_session_cache_mode(self):
        # type: () -> int
        """Gets the current session caching.

        The mode is set to m2.SSL_SESS_CACHE_* constants.

        :return: the previously set cache mode value.
        """
        return m2.ssl_ctx_get_session_cache_mode(self.ctx)

    def set_options(self, op):
        # type: (int) -> int
        """Adds the options set via bitmask in options to the Context.

        !!! Options already set before are not cleared!

        The behaviour of the SSL library can be changed by setting
        several options.  The options are coded as bitmasks and can be
        combined by a logical or operation (|).

        SSL.Context.set_options() and SSL.set_options() affect the
        (external) protocol behaviour of the SSL library. The (internal)
        behaviour of the API can be changed by using the similar
        SSL.Context.set_mode() and SSL.set_mode() functions.

        During a handshake, the option settings of the SSL object are
        used. When a new SSL object is created from a context using
        SSL(), the current option setting is copied. Changes to ctx
        do not affect already created SSL objects. SSL.clear() does not
        affect the settings.

        :param op: bitmask of additional options specified in
                   SSL_CTX_set_options(3) manpage.

        :return: the new options bitmask after adding options.
        """
        return m2.ssl_ctx_set_options(self.ctx, op)

    def get_cert_store(self):
        # type: () -> X509.X509
        """
        Get the certificate store associated with this context.

        :warning: The store is NOT refcounted, and as such can not be relied
                  to be valid once the context goes away or is changed.
        """
        return X509.X509_Store(m2.ssl_ctx_get_cert_store(self.ctx))