private BoxNode createBoxTree(ElementBox rootbox, Vector<BoxNode> boxlist, boolean useBounds, boolean useVisualBounds, boolean preserveAux)
    {
        //a working copy of the box list
        Vector<BoxNode> list = new Vector<BoxNode>(boxlist);

        //an artificial root node
        BoxNode root = new BoxNode(rootbox, page, zoom);
        root.setOrder(0);
        //detach the nodes from any old trees
        for (BoxNode node : list)
            node.removeFromTree();

        //when working with visual bounds, remove the boxes that are not visually separated
        if (!preserveAux)
        {
            for (Iterator<BoxNode> it = list.iterator(); it.hasNext(); )
            {
                BoxNode node = it.next();
                if (!node.isVisuallySeparated() || !node.isVisible())
                    it.remove();
            }
        }

        //let each node choose it's children - find the roots and parents
        for (BoxNode node : list)
        {
            if (useBounds)
                node.markNodesInside(list, useVisualBounds);
            else
                node.markChildNodes(list);
        }

        //choose the roots
        for (Iterator<BoxNode> it = list.iterator(); it.hasNext();)
        {
            BoxNode node = it.next();

            /*if (!full) //DEBUG
            {
               if (node.toString().contains("mediawiki") || node.toString().contains("globalWrapper"))
                    System.out.println(node + " => " + node.nearestParent);
            }*/

            if (node.isRootNode())
            {
                root.appendChild(node);
                it.remove();
            }
        }

        //recursively choose the children
        for (int i = 0; i < root.getChildCount(); i++)
            ((BoxNode) root.getChildAt(i)).takeChildren(list);

        return root;
    }

Creates a tree of box nesting based on the content bounds of the boxes.
This tree is only used for determining the backgrounds.

@param boxlist the list of boxes to build the tree from
@param useBounds when set to {@code true}, the full or visual bounds are used for constructing the tree
depending on the {@code useVisualBounds} parameter. Otherwise, the original box hierarchy is used.
@param useVisualBounds when set to {@code true} the visual bounds are used for constructing the tree. Otherwise,
the content bounds are used.
@param preserveAux when set to {@code true}, all boxes are preserved. Otherwise, only the visually
distinguished ones are preserved.

Creates a tree of box nesting based on the content bounds of the boxes . This tree is only used for determining the backgrounds .


private void computeBackgrounds(BoxNode root, Color currentbg)
    {
        Color newbg = root.getBackgroundColor();
        if (newbg == null)
            newbg = currentbg;
        root.setEfficientBackground(newbg);
        root.setBackgroundSeparated(!newbg.equals(currentbg));

        for (int i = 0; i < root.getChildCount(); i++)
            computeBackgrounds((BoxNode) root.getChildAt(i), newbg);
    }

private void computeBackgrounds ( BoxNode root , Color currentbg ) { Color newbg = root . getBackgroundColor ( ) ; if ( newbg == null ) newbg = currentbg ; root . setEfficientBackground ( newbg ) ; root . setBackgroundSeparated ( ! newbg . equals ( currentbg ) ) ; for ( int i = 0 ; i < root . getChildCount ( ) ; i ++ ) computeBackgrounds ( ( BoxNode ) root . getChildAt ( i ) , newbg ) ; }

Computes efficient background color for all the nodes in the tree


public void setMappingFile(URL url, String realFile){
        if (componentFiles == null) initFastIndexes("app", "lib", "repository");
        File file = new File(realFile);
        componentFiles.put(url.getFile(), file);
    }

public void setMappingFile ( URL url , String realFile ) { if ( componentFiles == null ) initFastIndexes ( "app" , "lib" , "repository" ) ; File file = new File ( realFile ) ; componentFiles . put ( url . getFile ( ) , file ) ; }

Set the real file of component url
@param url the component url
@param realFile the real file


public File getMappingFile(URL url) throws IOException {
        if (componentFiles == null) initFastIndexes("app", "lib", "repository");
        String fileName = FilenameUtils.normalize(url.getFile(), true);
        if( !fileName.endsWith(".jar") ) fileName = fileName + ".jar";
        if( fileName.startsWith("boot/") || fileName.startsWith("boot\\") ){
            fileName = "net.happyonroad/" + FilenameUtils.getName(fileName);
        }else if(fileName.startsWith("lib/") || fileName.startsWith("lib\\")){/* Only 3rd lib file will be put into jar classpath*/
            //正常的组件component url里面肯定不是lib开头；
            // 但是 spring-component-framework的Class-Path指定的那些url被normalize之后却会如此
            fileName  = ComponentUtils.relativePath(fileName);
        }
        File componentFile = componentFiles.get(fileName);
        if( componentFile == null )
        {
            // 当第一次建立的快速索引中没有相应文件时
            // 尝试看lib下后来有没有相应的文件
            componentFile = guessFile(url, "app", "lib", "repository");
            if( componentFile == null )
                throw new IOException("there is no component named as " + fileName);
        }
        return componentFile;
    }

// 当第一次建立的快速索引中没有相应文件时

// 尝试看lib下后来有没有相应的文件

Get the real file of component url
@param url the component url
@return the real file
@throws IOException


public static VersionRange createFromVersionSpec( String spec )
        throws InvalidVersionSpecificationException
    {
        if ( spec == null )
        {
            return null;
        }

        List<Restriction> restrictions = new ArrayList<Restriction>();
        String process = spec;
        ComponentVersion version = null;
        ComponentVersion upperBound = null;
        ComponentVersion lowerBound = null;

        while ( process.startsWith( "[" ) || process.startsWith( "(" ) )
        {
            int index1 = process.indexOf( ")" );
            int index2 = process.indexOf( "]" );

            int index = index2;
            if ( index2 < 0 || index1 < index2 )
            {
                if ( index1 >= 0 )
                {
                    index = index1;
                }
            }

            if ( index < 0 )
            {
                throw new InvalidVersionSpecificationException( "Unbounded range: " + spec );
            }

            Restriction restriction = parseRestriction( process.substring( 0, index + 1 ) );
            if ( lowerBound == null )
            {
                lowerBound = restriction.getLowerBound();
            }
            if ( upperBound != null )
            {
                if ( restriction.getLowerBound() == null || restriction.getLowerBound().compareTo( upperBound ) < 0 )
                {
                    throw new InvalidVersionSpecificationException( "Ranges overlap: " + spec );
                }
            }
            restrictions.add( restriction );
            upperBound = restriction.getUpperBound();

            process = process.substring( index + 1 ).trim();

            if ( process.length() > 0 && process.startsWith( "," ) )
            {
                process = process.substring( 1 ).trim();
            }
        }

        if ( process.length() > 0 )
        {
            if ( restrictions.size() > 0 )
            {
                throw new InvalidVersionSpecificationException(
                    "Only fully-qualified sets allowed in multiple set scenario: " + spec );
            }
            else
            {
                version = new ComponentVersion( process );
                restrictions.add( Restriction.EVERYTHING );
            }
        }

        return new VersionRange( version, restrictions );
    }

Create a version range from a string representation

Some spec examples are

1.0 Version 1.0

[1.0,2.0) Versions 1.0 (included) to 2.0 (not included)

[1.0,2.0] Versions 1.0 to 2.0 (both included)

[1.5,) Versions 1.5 and higher

(,1.0],[1.2,) Versions up to 1.0 (included) and 1.2 or higher

@param spec string representation of a version or version range
@return a new {@link VersionRange} object that represents the spec
@throws net.happyonroad.component.core.exception.InvalidVersionSpecificationException


public BoxTransform concatenate(BoxTransform src)
    {
        if (src.isEmpty())
            return this;
        else if (this.isEmpty())
            return src;
        else
        {
            BoxTransform ret = new BoxTransform(this);
            ret.transform = new AffineTransform(transform);
            ret.transform.concatenate(src.transform);
            return ret;
        }
    }

public BoxTransform concatenate ( BoxTransform src ) { if ( src . isEmpty ( ) ) return this ; else if ( this . isEmpty ( ) ) return src ; else { BoxTransform ret = new BoxTransform ( this ) ; ret . transform = new AffineTransform ( transform ) ; ret . transform . concatenate ( src . transform ) ; return ret ; } }

Concatenates another transformation to this transformation.
@param src
@return A new concatenated transformation.

Concatenates another transformation to this transformation .


public Rectangular transformRect(Rectangular rect)
    {
        if (transform != null)
        {
            Rectangle src = new Rectangle(rect.getX1(), rect.getY1(), rect.getWidth(), rect.getHeight());
            Shape dest = transform.createTransformedShape(src);
            Rectangle destr;
            if (dest instanceof Rectangle)
                destr = (Rectangle) dest;
            else
                destr = dest.getBounds();
            return new Rectangular(destr);
        }
        else
            return rect;
    }

public Rectangular transformRect ( Rectangular rect ) { if ( transform != null ) { Rectangle src = new Rectangle ( rect . getX1 ( ) , rect . getY1 ( ) , rect . getWidth ( ) , rect . getHeight ( ) ) ; Shape dest = transform . createTransformedShape ( src ) ; Rectangle destr ; if ( dest instanceof Rectangle ) destr = ( Rectangle ) dest ; else destr = dest . getBounds ( ) ; return new Rectangular ( destr ) ; } else return rect ; }

Transforms a rectangle to other rectangle using the given transformation.
@param rect the source rectangle
@return the bounding box of the transformed rectangle.

Transforms a rectangle to other rectangle using the given transformation .


private Rectangular getMinimalVisualBounds()
    {
        final Box box = getBox();
        if (box instanceof TextBox)
            return new RectangularZ(box.getAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds()), zoom);
        else if (box != null && box.isReplaced())
            return new RectangularZ(box.getMinimalAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds()), zoom);
        else
        {
        	Rectangular ret = null;
            for (int i = 0; i < getChildCount(); i++)
            {
                BoxNode subnode = (BoxNode) getChildAt(i);
                Box sub = subnode.getBox();
                Rectangular sb = subnode.getVisualBounds();
                if (sub.isDisplayed() && subnode.isVisible() && sb.getWidth() > 0 && sb.getHeight() > 0)
                {
	                if (ret == null)
	                	ret = new Rectangular(sb);
	                else
	                	ret.expandToEnclose(sb);
                }
            }
            //if nothing has been found return an empty rectangle at the top left corner
            if (ret == null)
            {
                Rectangle b = box.getAbsoluteBounds().intersection(box.getClipBlock().getClippedContentBounds());
            	return new RectangularZ(b.x, b.y, zoom);
            }
            else
            	return ret;
        }
    }

Returns the minimal bounds of the box for enclosing all the contained boxes.
@return the minimal visual bounds

Returns the minimal bounds of the box for enclosing all the contained boxes .


public void recomputeVisualBounds()
    {
        for (int i = 0; i < getChildCount(); i++)
            ((BoxNode) getChildAt(i)).recomputeVisualBounds();
        visual = computeVisualBounds();
    }

public void recomputeVisualBounds ( ) { for ( int i = 0 ; i < getChildCount ( ) ; i ++ ) ( ( BoxNode ) getChildAt ( i ) ) . recomputeVisualBounds ( ) ; visual = computeVisualBounds ( ) ; }

Re-computes the visual bounds of the whole subtree.

Re - computes the visual bounds of the whole subtree .


public void recomputeBounds()
    {
        bounds = new Rectangular(visual);
        for (int i = 0; i < getChildCount(); i++)
        {
            BoxNode child = (BoxNode) getChildAt(i);
            child.recomputeBounds();
            expandToEnclose(child);
        }
    }

public void recomputeBounds ( ) { bounds = new Rectangular ( visual ) ; for ( int i = 0 ; i < getChildCount ( ) ; i ++ ) { BoxNode child = ( BoxNode ) getChildAt ( i ) ; child . recomputeBounds ( ) ; expandToEnclose ( child ) ; } }

Recomputes the total bounds of the whole subtree. The bounds of each box will
correspond to its visual bounds. If the child boxes exceed the parent box,
the parent box bounds will be expanded accordingly.

Recomputes the total bounds of the whole subtree . The bounds of each box will correspond to its visual bounds . If the child boxes exceed the parent box the parent box bounds will be expanded accordingly .


private Rectangular computeContentBounds()
    {
        Box box = getBox();
        Rectangular ret = null;

        if (box instanceof Viewport)
        {
            ret = new RectangularZ(((Viewport) box).getClippedBounds(), zoom);
        }
        else if (box instanceof ElementBox)
        {
            ElementBox elem = (ElementBox) box;
            //at least one border - take the border bounds
            //TODO: when only one border is present, we shouldn't take the whole border box?
            if (elem.getBorder().top > 0 || elem.getBorder().left > 0 ||
                elem.getBorder().bottom > 0 || elem.getBorder().right > 0)
            {
                ret = new RectangularZ(elem.getAbsoluteBorderBounds(), zoom);
            }
            //no border
            else
            {
                ret = new RectangularZ(elem.getAbsoluteBackgroundBounds(), zoom);
            }
        }
        else //not an element - return the whole box
            ret = new RectangularZ(box.getAbsoluteBounds(), zoom);

        //clip with the clipping bounds
        if (box.getClipBlock() != null)
        {
            Rectangular clip = new RectangularZ(box.getClipBlock().getClippedContentBounds(), zoom);
            ret = ret.intersection(clip);
        }

        return ret;
    }

Computes node the content bounds. They correspond to the background bounds
however, when a border is present, it is included in the contents. Moreover,
the box is clipped by its clipping box.

Computes node the content bounds . They correspond to the background bounds however when a border is present it is included in the contents . Moreover the box is clipped by its clipping box .


@Override
    public int getTopBorder()
    {
        Box box = getBox();
        if (box instanceof ElementBox)
            return ((ElementBox) box).getBorder().top;
        else
            return 0;
    }

@ Override public int getTopBorder ( ) { Box box = getBox ( ) ; if ( box instanceof ElementBox ) return ( ( ElementBox ) box ) . getBorder ( ) . top ; else return 0 ; }

Obtains the top border of the box
@return the width of the border or 0 when there is no border


@Override
    public int getBottomBorder()
    {
        Box box = getBox();
        if (box instanceof ElementBox)
            return ((ElementBox) box).getBorder().bottom;
        else
            return 0;
    }

@ Override public int getBottomBorder ( ) { Box box = getBox ( ) ; if ( box instanceof ElementBox ) return ( ( ElementBox ) box ) . getBorder ( ) . bottom ; else return 0 ; }

Obtains the bottom border of the box
@return the width of the border or 0 when there is no border


@Override
    public int getLeftBorder()
    {
        Box box = getBox();
        if (box instanceof ElementBox)
            return ((ElementBox) box).getBorder().left;
        else
            return 0;
    }

@ Override public int getLeftBorder ( ) { Box box = getBox ( ) ; if ( box instanceof ElementBox ) return ( ( ElementBox ) box ) . getBorder ( ) . left ; else return 0 ; }

Obtains the left border of the box
@return the width of the border or 0 when there is no border


@Override
    public int getRightBorder()
    {
        Box box = getBox();
        if (box instanceof ElementBox)
            return ((ElementBox) box).getBorder().right;
        else
            return 0;
    }

@ Override public int getRightBorder ( ) { Box box = getBox ( ) ; if ( box instanceof ElementBox ) return ( ( ElementBox ) box ) . getBorder ( ) . right ; else return 0 ; }

Obtains the right border of the box
@return the width of the border or 0 when there is no border


public String getEfficientColor()
    {
        Box box = getBox();
        do
        {
            if (box instanceof ElementBox)
            {
                String color = ((ElementBox) box).getStylePropertyValue("color");
                if (!color.equals(""))
                    return color;
            }
            box = box.getParent();
        } while (box != null);
        return "";
    }

public String getEfficientColor ( ) { Box box = getBox ( ) ; do { if ( box instanceof ElementBox ) { String color = ( ( ElementBox ) box ) . getStylePropertyValue ( "color" ) ; if ( ! color . equals ( "" ) ) return color ; } box = box . getParent ( ) ; } while ( box != null ) ; return "" ; }

Get the effective text color. If the text color is set, it is returned.
When the color is not set, the parent boxes are considered.
@return the background color string

Get the effective text color . If the text color is set it is returned . When the color is not set the parent boxes are considered .


public boolean visuallyEncloses1(BoxNode childNode)
    {
        int cx1 = childNode.getVisualBounds().getX1();
        int cy1 = childNode.getVisualBounds().getY1();
        int cx2 = childNode.getVisualBounds().getX2();
        int cy2 = childNode.getVisualBounds().getY2();
        int px1 = getVisualBounds().getX1();
        int py1 = getVisualBounds().getY1();
        int px2 = getVisualBounds().getX2();
        int py2 = getVisualBounds().getY2();

        //check how many corners of the child are inside the parent exactly
        int xcnt = 0;
        if (cx1 >= px1 && cx1 <= px2 &&
            cy1 >= py1 && cy1 <= py2) xcnt++; //top left
        if (cx2 >= px1 && cx2 <= px2 &&
            cy1 >= py1 && cy1 <= py2) xcnt++; //top right
        if (cx1 >= px1 && cx1 <= px2 &&
            cy2 >= py1 && cy2 <= py2) xcnt++; //bottom left
        if (cx2 >= px1 && cx2 <= px2 &&
            cy2 >= py1 && cy2 <= py2) xcnt++; //bottom right

        /*if (childNode.toString().contains("globalWrapper") && this.toString().contains("mediawiki"))
            System.out.println("jo!");*/

        if ((cx1 == px1 && cy1 == py1 && cx2 == px2 && cy2 == py2)) //exact overlap
           return this.getOrder() < childNode.getOrder();
        else
            return xcnt == 4;
    }

Checks if another node is fully located inside the content bounds of this box.
@param childNode the node to check
@return true if the child node is completely inside this node, false otherwise

Checks if another node is fully located inside the content bounds of this box .


public void takeChildren(Vector<BoxNode> list)
    {
        for (Iterator<BoxNode> it = list.iterator(); it.hasNext();)
        {
            BoxNode node = it.next();
            if (node.nearestParent.equals(this))
            {
                appendChild(node);
                it.remove();
            }
        }

        //let the children take their children
        for (int i = 0; i < getChildCount(); i++)
            ((BoxNode) getChildAt(i)).takeChildren(list);
    }

public
void
takeChildren
(
Vector
<
BoxNode
>
list
)
{
for
(
Iterator
<
BoxNode
>
it
=
list
.
iterator
(
)
;
it
.
hasNext
(
)
;
)
{
BoxNode
node
=
it
.
next
(
)
;
if
(
node
.
nearestParent
.
equals
(
this
)
)
{
appendChild
(
node
)
;
it
.
remove
(
)
;
}
}
//let the children take their children
for
(
int
i
=
0
;
i
<
getChildCount
(
)
;
i
++
)
(
(
BoxNode
)
getChildAt
(
i
)
)
.
takeChildren
(
list
)
;
}

Goes through the parent's children, takes all the nodes that are inside of this node
and makes them the children of this node. Then, recursively calls the children to take
their nodes.

Goes through the parent s children takes all the nodes that are inside of this node and makes them the children of this node . Then recursively calls the children to take their nodes .


protected void process(String command) {
        try {
            Method method = this.getClass().getMethod(command);
            logger.info("Try to delegate '{}' to launcher directly.", command);
            method.invoke(this);
            logger.info("Invoke '{}' to launcher directly successfully. \r\n", command);
        } catch (NoSuchMethodException e) {
            logger.warn("unrecognized command: '{}'", command);
        } catch (Exception e) {
            logger.warn("Failed to execute: '{}'", command);
        }
    }

Process user specified command

@param command the command


@Bean
	public DataSource dataSource() {

        // Replace this with your own datasource.
        return new EmbeddedDatabaseBuilder()
                .setName("test")
                .setType(EmbeddedDatabaseType.HSQL)
                .addScript("classpath:hsql-schema.sql")
                .build();
	}

Use this data source to create an embedded database.

Use this data source to create an embedded database .


@Bean
    public DataSource dataSource_plain() {

        SimpleDriverDataSource ds =
                new SimpleDriverDataSource();

        ds.setDriverClass(null);
        ds.setUrl("jdbc:oracle:thin:@<server>[:<1521>]:<database_name>");
        ds.setUsername("");
        ds.setPassword("");

        return ds;
    }

Use this data source to connect to an existing database.

Use this data source to connect to an existing database .


public void setup(PlatformConfiguration config, Environment env) {
        this.configuration = Preconditions.checkNotNull(config, "Configuration cannot be null.");
        this.environment = Preconditions.checkNotNull(env, "Environment cannot be null.");
    }

public
void
setup
(
PlatformConfiguration
config
,
Environment
env
)
{
this
.
configuration
=
Preconditions
.
checkNotNull
(
config
,
"Configuration cannot be null."
)
;
this
.
environment
=
Preconditions
.
checkNotNull
(
env
,
"Environment cannot be null."
)
;
}

Called when the configuration and environment come into scope.

@param config Provided by Dropwizard.
@param env    Provided by Dropwizard.

Called when the configuration and environment come into scope .


public <T> T query(MethodMap methodMap, ArgMap argMap, Class<T> responseType ) throws OpenStatesException {
		BufferedReader reader = null;
		HttpURLConnection conn = null;
		String charSet = "utf-8";
		try {
			if ( isCaching(methodMap, argMap) ) {
				File file = getCacheFile(methodMap, argMap);

				long fileLength = file.length();
				logger.fine("Length of File in cache:" + fileLength + ": " + file.getName());
				if ( fileLength == 0L ) {
					OpenStates.cacheFileFromAPI(methodMap, argMap, file, responseType);
				}
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charSet));
			} else {
				conn = OpenStates.getConnectionFromAPI(methodMap, argMap);
				charSet = getCharset(conn);
			    // better check it first
				int rcode = conn.getResponseCode();
			    if ( rcode / 100 != 2) {
			    	String msg = conn.getResponseMessage();
			    	conn.disconnect();
			    	throw new OpenStatesException(rcode, msg, methodMap, argMap, responseType);
			    }
				reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), charSet));
			}

        	return mapper.readValue( reader, responseType );
		} catch (JsonParseException e) {
			throw new OpenStatesException(e, methodMap, argMap, responseType);
		} catch (JsonMappingException e) {
			throw new OpenStatesException(e, methodMap, argMap, responseType);
		} catch (URISyntaxException e) {
			throw new OpenStatesException(e, methodMap, argMap, responseType);
		} catch (IOException e) {
			throw new OpenStatesException(e, methodMap, argMap, responseType);
		} finally {
			suspendCache = false;
			if ( conn != null ) conn.disconnect();
			if ( reader != null ) {
				try {
					reader.close();
				} catch (IOException e) {
					throw new OpenStatesException(e, methodMap, argMap, responseType);
				}
			}
		}
	}

public
<
T
>
T
query
(
MethodMap
methodMap
,
ArgMap
argMap
,
Class
<
T
>
responseType
)
throws
OpenStatesException
{
BufferedReader
reader
=
;
HttpURLConnection
conn
=
;
String
charSet
=
"utf-8"
;
try
{
if
(
isCaching
(
methodMap
,
argMap
)
)
{
File
file
=
getCacheFile
(
methodMap
,
argMap
)
;
long
fileLength
=
file
.
length
(
)
;
logger
.
fine
(
"Length of File in cache:"
+
fileLength
+
": "
+
file
.
getName
(
)
)
;
if
(
fileLength
==
0L
)
{
OpenStates
.
cacheFileFromAPI
(
methodMap
,
argMap
,
file
,
responseType
)
;
}
reader
=
new
BufferedReader
(
new
InputStreamReader
(
new
FileInputStream
(
file
)
,
charSet
)
)
;
}
else
{
conn
=
OpenStates
.
getConnectionFromAPI
(
methodMap
,
argMap
)
;
charSet
=
getCharset
(
conn
)
;
// better check it first
int
rcode
=
conn
.
getResponseCode
(
)
;
if
(
rcode
/
100
!=
2
)
{
String
msg
=
conn
.
getResponseMessage
(
)
;
conn
.
disconnect
(
)
;
throw
new
OpenStatesException
(
rcode
,
msg
,
methodMap
,
argMap
,
responseType
)
;
}
reader
=
new
BufferedReader
(
new
InputStreamReader
(
conn
.
getInputStream
(
)
,
charSet
)
)
;
}
return
mapper
.
readValue
(
reader
,
responseType
)
;
}
catch
(
JsonParseException
e
)
{
throw
new
OpenStatesException
(
e
,
methodMap
,
argMap
,
responseType
)
;
}
catch
(
JsonMappingException
e
)
{
throw
new
OpenStatesException
(
e
,
methodMap
,
argMap
,
responseType
)
;
}
catch
(
URISyntaxException
e
)
{
throw
new
OpenStatesException
(
e
,
methodMap
,
argMap
,
responseType
)
;
}
catch
(
IOException
e
)
{
throw
new
OpenStatesException
(
e
,
methodMap
,
argMap
,
responseType
)
;
}
finally
{
suspendCache
=
false
;
if
(
conn
!=
)
conn
.
disconnect
(
)
;
if
(
reader
!=
)
{
try
{
reader
.
close
(
)
;
}
catch
(
IOException
e
)
{
throw
new
OpenStatesException
(
e
,
methodMap
,
argMap
,
responseType
)
;
}
}
}
}

Handles the actual API calls and caching.

This is part of a static class and therefore is not thread-safe. This method
is not for public consumption.

Handles the actual API calls and caching .


public void register(Command command) {
		Preconditions.checkArgument(command != null, "Parameter 'command' must not be [" + command + "]");
		register(command.name(), command);
	}

public
void
register
(
Command
command
)
{
Preconditions
.
checkArgument
(
command
!=
,
"Parameter 'command' must not be ["
+
command
+
"]"
)
;
register
(
command
.
name
(
)
,
command
)
;
}

Registers the specified command instance into the shell.

@param command Command to be registered.

Registers the specified command instance into the shell .


public void register(String name, Command command) {
		Preconditions.checkArgument(name != null && !name.isEmpty(), "Parameter 'name' must not be [" + name + "]");
		Preconditions.checkArgument(command != null, "Parameter 'command' must not be [" + command + "]");
		commands.put(name, command);
	}

public
void
register
(
String
name
,
Command
command
)
{
Preconditions
.
checkArgument
(
name
!=
&&
!
name
.
isEmpty
(
)
,
"Parameter 'name' must not be ["
+
name
+
"]"
)
;
Preconditions
.
checkArgument
(
command
!=
,
"Parameter 'command' must not be ["
+
command
+
"]"
)
;
commands
.
put
(
name
,
command
)
;
}

Registers the specified command instance into the shell with the specified name.

@param name Name of command.
@param command Command to be registered.

Registers the specified command instance into the shell with the specified name .


public void unregister(String name) {
		Preconditions.checkArgument(name != null && !name.isEmpty(), "Parameter 'name' must not be [" + name + "]");
		commands.remove(name);
	}

public
void
unregister
(
String
name
)
{
Preconditions
.
checkArgument
(
name
!=
&&
!
name
.
isEmpty
(
)
,
"Parameter 'name' must not be ["
+
name
+
"]"
)
;
commands
.
remove
(
name
)
;
}

Unregisters the command corresponding to the specified name from the shell.

@param name Name of command.

Unregisters the command corresponding to the specified name from the shell .


@SuppressWarnings("unchecked")
	public void exec(String line) {
		String[] strings = line.split("\\s");

		if (strings.length == 0) {
			return;
		}

		String cmd = strings[0];

		if (strings[0] == null || strings[0].isEmpty()) {
			return;
		}

		String[] args = {};

		if (strings.length > 1) {
			args = new String[strings.length - 1];
			System.arraycopy(strings, 1, args, 0, args.length);
		}

		Command command = commands.get(cmd);

		if (command == null) {
			//$NON-NLS-N$
			console.println(cmd + ": command not found");
			return;
		}

		Usage usage = command.usage();
		Options opts = options.get(command.name());

		if (opts == null) {
			opts = new Options();

			for (Usage.Option option : usage.options()) {
				Option opt = new Option(option.opt(), option.longOpt(), false, option.description());
				opt.setRequired(option.required());
				String arg = option.arg();

				if (arg == null || arg.isEmpty()) {
					opt.setArgs(1);
					opt.setArgName(arg);
				}

				opts.addOption(opt);
			}

			options.put(command.name(), opts);
		}

		CommandLineParser parser = new GnuParser();
		CommandLine commandLine = null;

		try {
			commandLine = parser.parse(opts, args);
		} catch (ParseException e) {
			console().println(usage.toString());
			return;
		}

		Map<String, String> options = new HashMap<>();

		for (Option option : commandLine.getOptions()) {
			String opt = option.getOpt();

			if (opt != null && !opt.isEmpty()) {
				options.put(opt, option.getValue());
			}

			String longOpt = option.getLongOpt();

			if (longOpt != null && !longOpt.isEmpty()) {
				options.put(longOpt, option.getValue());
			}
		}

		Line l = new Line(cmd, options, commandLine.getArgList());

		try {
			command.run(l);
		} catch (Exception e) {
			e.printStackTrace(new PrintWriter(console.reader().getOutput()));
		}
	}

@
SuppressWarnings
(
"unchecked"
)
public
void
exec
(
String
line
)
{
String
[
]
strings
=
line
.
split
(
"\\s"
)
;
if
(
strings
.
length
==
0
)
{
return
;
}
String
cmd
=
strings
[
0
]
;
if
(
strings
[
0
]
==
||
strings
[
0
]
.
isEmpty
(
)
)
{
return
;
}
String
[
]
args
=
{
}
;
if
(
strings
.
length
>
1
)
{
args
=
new
String
[
strings
.
length
1
]
;
System
.
arraycopy
(
strings
,
1
,
args
,
0
,
args
.
length
)
;
}
Command
command
=
commands
.
get
(
cmd
)
;
if
(
command
==
)
{
//$NON-NLS-N$
console
.
println
(
cmd
+
": command not found"
)
;
return
;
}
Usage
usage
=
command
.
usage
(
)
;
Options
opts
=
options
.
get
(
command
.
name
(
)
)
;
if
(
opts
==
)
{
opts
=
new
Options
(
)
;
for
(
Usage
.
Option
option
:
usage
.
options
(
)
)
{
Option
opt
=
new
Option
(
option
.
opt
(
)
,
option
.
longOpt
(
)
,
false
,
option
.
description
(
)
)
;
opt
.
setRequired
(
option
.
required
(
)
)
;
String
arg
=
option
.
arg
(
)
;
if
(
arg
==
||
arg
.
isEmpty
(
)
)
{
opt
.
setArgs
(
1
)
;
opt
.
setArgName
(
arg
)
;
}
opts
.
addOption
(
opt
)
;
}
options
.
put
(
command
.
name
(
)
,
opts
)
;
}
CommandLineParser
parser
=
new
GnuParser
(
)
;
CommandLine
commandLine
=
;
try
{
commandLine
=
parser
.
parse
(
opts
,
args
)
;
}
catch
(
ParseException
e
)
{
console
(
)
.
println
(
usage
.
toString
(
)
)
;
return
;
}
Map
<
String
,
String
>
options
=
new
HashMap
<>
(
)
;
for
(
Option
option
:
commandLine
.
getOptions
(
)
)
{
String
opt
=
option
.
getOpt
(
)
;
if
(
opt
!=
&&
!
opt
.
isEmpty
(
)
)
{
options
.
put
(
opt
,
option
.
getValue
(
)
)
;
}
String
longOpt
=
option
.
getLongOpt
(
)
;
if
(
longOpt
!=
&&
!
longOpt
.
isEmpty
(
)
)
{
options
.
put
(
longOpt
,
option
.
getValue
(
)
)
;
}
}
Line
l
=
new
Line
(
cmd
,
options
,
commandLine
.
getArgList
(
)
)
;
try
{
command
.
run
(
l
)
;
}
catch
(
Exception
e
)
{
e
.
printStackTrace
(
new
PrintWriter
(
console
.
reader
(
)
.
getOutput
(
)
)
)
;
}
}

Executes the specified command line input.

@param line Command line input.

Executes the specified command line input .


public void start() {
		repl.set(true);
		String line = null;

		while (repl.get() && ((line = console.readLine()) != null)) {
			exec(line);
		}
	}

public void start ( ) { repl . set ( true ) ; String line = null ; while ( repl . get ( ) && ( ( line = console . readLine ( ) ) != null ) ) { exec ( line ) ; } }


public Committees searchByStateChamber(String state, String chamber) throws OpenStatesException {
		return api.query(
			new MethodMap("committees"),
			new ArgMap("state", state, "chamber", chamber),
			Committees.class
		);
	}

public Committees searchByStateChamber ( String state , String chamber ) throws OpenStatesException { return api . query ( new MethodMap ( "committees" ) , new ArgMap ( "state" , state , "chamber" , chamber ) , Committees . class ) ; }

Committee Search
This method allows searching by state and chamber.
Committee objects returned by this method do not include the list of members by default.

@param state
@param chamber
@return {@link Committees}

Committee Search This method allows searching by state and chamber . Committee objects returned by this method do not include the list of members by default .


public Committee detail(String id) throws OpenStatesException {
		return api.query(new MethodMap("committees", id), null, Committee.class);
	}

public Committee detail ( String id ) throws OpenStatesException { return api . query ( new MethodMap ( "committees" , id ) , null , Committee . class ) ; }

Committee Detail
This method returns the full committee object given a committee id.

@param id
@return {@link Committee} object given a committee id.

Committee Detail This method returns the full committee object given a committee id .


private static JMXConnector connect(String host, String port, String login, String password) throws IOException {

        // Set the service URL.
        JMXServiceURL serviceUrl = new JMXServiceURL(
                new StringBuffer()
                    .append("service:jmx:rmi://")
                    .append(host)
                    .append(":")
                    .append(port)
                    .append("/jndi/rmi://")
                    .append(host)
                    .append(":")
                    .append(port)
                    .append("/jmxrmi")
                    .toString());

        // Set the service environment.
        Map<String,Object> serviceEnv = new HashMap<String,Object>();
        serviceEnv.put("jmx.remote.credentials", new String[]{login, password});

        // Connect to the JMX service.
        return JMXConnectorFactory.connect(serviceUrl, serviceEnv);
    }

private
static
JMXConnector
connect
(
String
host
,
String
port
,
String
login
,
String
password
)
throws
IOException
{
// Set the service URL.
JMXServiceURL
serviceUrl
=
new
JMXServiceURL
(
new
StringBuffer
(
)
.
append
(
"service:jmx:rmi://"
)
.
append
(
host
)
.
append
(
":"
)
.
append
(
port
)
.
append
(
"/jndi/rmi://"
)
.
append
(
host
)
.
append
(
":"
)
.
append
(
port
)
.
append
(
"/jmxrmi"
)
.
toString
(
)
)
;
// Set the service environment.
Map
<
String
,
Object
>
serviceEnv
=
new
HashMap
<
String
,
Object
>
(
)
;
serviceEnv
.
put
(
"jmx.remote.credentials"
,
new
String
[
]
{
login
,
password
}
)
;
// Connect to the JMX service.
return
JMXConnectorFactory
.
connect
(
serviceUrl
,
serviceEnv
)
;
}

Connect to the JMX service.

@param  host      the host.
@param  port      the port.
@param  login     the login.
@param  password  the password.

@return  the JMX connector.

@throws  IOException  if unable to connect to the JMX service.


private static String getProperty(Properties properties, String key) {

        // Check if the properties do not exist.
        if (properties == null || properties.getProperty(key) == null) {
            throw new IllegalArgumentException("The property " + key + " does not exist.");
        }

        return properties.getProperty(key);
    }

Get the property.

@param  properties  the properties.
@param  key         the property key.

@return  the property.

@throws  IllegalArgumentException  if the property does not exist.


@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        Object result;
        JMXConnector connector = null;

        try {

            // Connect to the JMX service.
            connector = connect(this.host, this.port, this.login, this.password);

            // Create the MBean.
            T object = JMX.newMXBeanProxy(connector.getMBeanServerConnection(), this.objectName, this.interfaceClass);

            // Invoke a method on the MBean.
            result = method.invoke(object, args);
        }
        finally {

            // Close the JMX service.
            close(connector);
        }

        return result;
    }

@
Override
public
Object
invoke
(
Object
proxy
,
Method
method
,
Object
[
]
args
)
throws
Throwable
{
Object
result
;
JMXConnector
connector
=
;
try
{
// Connect to the JMX service.
connector
=
connect
(
this
.
host
,
this
.
port
,
this
.
login
,
this
.
password
)
;
// Create the MBean.
T
object
=
JMX
.
newMXBeanProxy
(
connector
.
getMBeanServerConnection
(
)
,
this
.
objectName
,
this
.
interfaceClass
)
;
// Invoke a method on the MBean.
result
=
method
.
invoke
(
object
,
args
)
;
}
finally
{
// Close the JMX service.
close
(
connector
)
;
}
return
result
;
}

Invoke the method and return the result.

@param  proxy   the proxy.
@param  method  the method.
@param  args    the method arguments.

@return  the result of invoking the method.

@throws  Throwable  if unable to invoke the method.

Invoke the method and return the result .


public Districts searchByState(String state) throws OpenStatesException {
		return api.query(new MethodMap("districts", state), null, Districts.class);
	}

public Districts searchByState ( String state ) throws OpenStatesException { return api . query ( new MethodMap ( "districts" , state ) , null , Districts . class ) ; }

List districts for state.

@param state
@return {@link Districts}


public Districts search(String state, String chamber) throws OpenStatesException {
		return api.query(new MethodMap("districts", state, chamber), null, Districts.class);
	}

public Districts search ( String state , String chamber ) throws OpenStatesException { return api . query ( new MethodMap ( "districts" , state , chamber ) , null , Districts . class ) ; }

List districts for state and chamber.

@param state
@param chamber
@return {@link Districts}


public District boundaryLookup(String boundary_id) throws OpenStatesException {
		return api.query(new MethodMap("districts", "boundary", boundary_id ), null, District.class);
	}

public District boundaryLookup ( String boundary_id ) throws OpenStatesException { return api . query ( new MethodMap ( "districts" , "boundary" , boundary_id ) , null , District . class ) ; }

Get geographic boundary for a district.

@param boundary_id
@return {@link District}

Get geographic boundary for a district .


public Metadata state(String state) throws OpenStatesException {
		return api.query(new MethodMap("metadata", state), null, Metadata.class);
	}

public Metadata state ( String state ) throws OpenStatesException { return api . query ( new MethodMap ( "metadata" , state ) , null , Metadata . class ) ; }

Get detailed metadata for a particular state.

@param state
@return {@link Metadata}

Get detailed metadata for a particular state .


private static <T> T createObject(Class<T> interfaceClass) {

        ServiceLoader<T> loader = ServiceLoader.load(interfaceClass);

        T object = null;

        // Loop through the services.
        for (T loadedObject : loader) {

            // Check if a factory has not been found.
            if (object == null) {

                // Set the factory.
                object = loadedObject;
            } else {
                throw new IllegalArgumentException("More than one MBean object found.");
            }
        }

        // Check if a object has not been found.
        if (object == null) {
            throw new IllegalArgumentException("No MBean object found.");
        }

        return object;
    }

Create the MBean object.

@param  interfaceClass  the MBean interface class.

@return  the MBean object.


public static <T> ObjectName register(Class<T> interfaceClass, ObjectName objectName) throws MBeanException {

        // Check if the interface class is valid.
        if (interfaceClass == null) {
            throw new IllegalArgumentException("The interface class is invalid.");
        }

        try {

            // Get the MBean server.
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

            // Check if the MBean is not registered with the MBean server.
            if (!mBeanServer.isRegistered(objectName)) {

                // Register the MBean with the MBean server.
                ObjectInstance objectInstance = mBeanServer.registerMBean(createObject(interfaceClass), objectName);

                // Get the object name for the registered MBean.
                objectName = objectInstance.getObjectName();
            }
        } catch (Exception e) {
            throw new MBeanException(e, "Unable to register the MBean.");
        }

        return objectName;
    }

Register the MBean represented by the interface class.

@param  interfaceClass  the MBean interface class.
@param  objectName      the MBean object name.

@return  the MBean object name.

@throws  IllegalArgumentException  if the interface class is invalid.
@throws  MBeanException            if unable to register the MBean.

Register the MBean represented by the interface class .


public static void unregister(ObjectName objectName) throws MBeanException {

        try {

            // Get the MBean server.
            MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();

            // Check if the MBean is registered with the MBean server.
            if (mBeanServer.isRegistered(objectName)) {

                // Unregister the MBean with the MBean server.
                mBeanServer.unregisterMBean(objectName);
            }
        } catch (Exception e) {
            throw new MBeanException(e,
                    "Unable to unregister the MBean " +
                    objectName.getCanonicalName() + ".");
        }
    }

Unregister the MBean represented by the object name.

@param  objectName  the MBean object name.

@throws  MBeanException  if unable to unregister the MBean.

Unregister the MBean represented by the object name .


protected static void validateMBean(Class interfaceClass, ObjectName objectName, MBeanServerConnection mBeanServerConnection)  throws MBeanException {

        try {

            // Check if the interface class is null.
            if (interfaceClass == null) {
                throw new IllegalArgumentException(
                        "The interface class is null.");
            }

            // Check if the interface class is not a MXBean interface.
            if (!JMX.isMXBeanInterface(interfaceClass)) {
                throw new IllegalArgumentException(
                        "The interface class " + interfaceClass.getName() +
                        " is not a MXBean interface.");
            }

            // Check if the object name is not registered.
            if (!mBeanServerConnection.isRegistered(objectName)) {
                throw new IllegalArgumentException(
                        "The object name " + objectName.getCanonicalName() +
                        " is not registered.");
            }

            // Check if the object name is not an instance of the interface class.
            if (!mBeanServerConnection.isInstanceOf(objectName, interfaceClass.getName())) {
                throw new IllegalArgumentException(
                        "The object name " + objectName.getCanonicalName() +
                        " is not an instance of the interface class " +
                        interfaceClass.getName() + ".");
            }
        } catch (InstanceNotFoundException e) {
            throw new IllegalArgumentException(
                    "The object name " + objectName.getCanonicalName() +
                    " is not found.");
        } catch (IOException e) {
            throw new MBeanException(e,
                    "Unable to validate the MBean represented by the interface class " +
                    interfaceClass.getName() + " and object name " +
                    objectName.getCanonicalName() + ".");
        }
    }

Validate the MBean represented by the interface class and object name.

@param  interfaceClass         the MBean interface class.
@param  objectName             the MBean object name.
@param  mBeanServerConnection  the MBean server connection.

@throws  IllegalArgumentException  if the MBean is invalid.
@throws  IOException               if unable to validate the MBean.

Validate the MBean represented by the interface class and object name .


@Override
    public String get() {

        try (final Timer.Context context = timer.time()) {
            final String s = randomUUID().toString();

            if (length == 0 || count == 0) {
                return s;
            }

            final StringJoiner joiner = new StringJoiner("/", "", "/" + s);
            IntStream.rangeClosed(0, count - 1)
                     .forEach(x -> joiner.add(s.substring(x * length, (x + 1) * length)));

            return joiner.toString();
        }
    }

@ Override public String get ( ) { try ( final Timer . Context context = timer . time ( ) ) { final String s = randomUUID ( ) . toString ( ) ; if ( length == 0 || count == 0 ) { return s ; } final StringJoiner joiner = new StringJoiner ( "/" , "" , "/" + s ) ; IntStream . rangeClosed ( 0 , count - 1 ) . forEach ( x -> joiner . add ( s . substring ( x * length , ( x + 1 ) * length ) ) ) ; return joiner . toString ( ) ; } }

Mint a unique identifier as a UUID

@return uuid


public void addValue(String value, boolean isDefault) {
        p("Adding " + (isDefault ? "default " : "") + "value:" + value + " to parameter:" + m_field.getName());
        String name = m_wrappedParameter.names()[0];
        if (m_assigned && !isMultiOption()) {
            throw new ParameterException("Can only specify option " + name + " once.");
        }

        validateParameter(name, value);

        Class<?> type = m_field.getType();

        Object convertedValue = m_jCommander.convertValue(this, value);
        boolean isCollection = Collection.class.isAssignableFrom(type);

        try {
            if (isCollection) {
                @SuppressWarnings("unchecked") Collection<Object> l = (Collection<Object>) m_field.get(m_object);
                if (l == null || fieldIsSetForTheFirstTime(isDefault)) {
                    l = newCollection(type);
                    m_field.set(m_object, l);
                }
                if (convertedValue instanceof Collection) {
                    l.addAll((Collection) convertedValue);
                } else { // if (isMainParameter || m_parameterAnnotation.arity() > 1) {
                    l.add(convertedValue);
//        } else {
//          l.
                }
            } else {
                m_wrappedParameter.addValue(m_field, m_object, convertedValue);
            }
            if (!isDefault) m_assigned = true;
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        }
    }

Add the specified value to the field. First, validate the value if a
validator was specified. Then look up any field converter, then any type
converter, and if we can't find any, throw an exception.

Add the specified value to the field . First validate the value if a validator was specified . Then look up any field converter then any type converter and if we can t find any throw an exception .


public Legislators searchByState(
			String state
	) throws OpenStatesException {
		return api.query(
			new MethodMap("legislators"),
			new ArgMap( "state", state ),
			Legislators.class
		);
	}

public Legislators searchByState ( String state ) throws OpenStatesException { return api . query ( new MethodMap ( "legislators" ) , new ArgMap ( "state" , state ) , Legislators . class ) ; }

Get Legislators by State.

@param state Filter by state.
@return {@link Legislators}


public Legislators searchByStateActive(
			String state,
			Boolean active
	) throws OpenStatesException {
		return api.query(
			new MethodMap("legislators"),
			new ArgMap(
				"state", state,
				"active", active.toString()
			),
			Legislators.class
		);
	}

public Legislators searchByStateActive ( String state , Boolean active ) throws OpenStatesException { return api . query ( new MethodMap ( "legislators" ) , new ArgMap ( "state" , state , "active" , active . toString ( ) ) , Legislators . class ) ; }

Get Legislators by State and Active filters.

@param state Filter by state.
@param active 'true' (default) to only include current legislators, 'false' will include all legislators
@return {@link Legislators}

Get Legislators by State and Active filters .


public Legislators searchByStateTerm(
			String state,
			String term
	) throws OpenStatesException {
		return api.query(
			new MethodMap("legislators"),
			new ArgMap(
				"state", state,
				"term", term
			),
			Legislators.class
		);
	}

public Legislators searchByStateTerm ( String state , String term ) throws OpenStatesException { return api . query ( new MethodMap ( "legislators" ) , new ArgMap ( "state" , state , "term" , term ) , Legislators . class ) ; }

Search for Legislators by State and Term.

@param state Filter by state.
@param term Only legislators that have a role in a certain term.
@return {@link Legislators}

Search for Legislators by State and Term .


public Legislators search(
			String state,
			Boolean active,
			String term,
			String chamber,
			String district,
			String party,
			String first_name,
			String last_name
	) throws OpenStatesException {
		return api.query(
			new MethodMap("legislators"),
			new ArgMap(
				"state", state,
				"first_name", first_name,
				"last_name", last_name,
				"chamber", chamber,
				"active", active==null?null:active.toString(),
				"term", term,
				"party", party,
				"district", district
			),
			Legislators.class
		);
	}

public Legislators search ( String state , Boolean active , String term , String chamber , String district , String party , String first_name , String last_name ) throws OpenStatesException { return api . query ( new MethodMap ( "legislators" ) , new ArgMap ( "state" , state , "first_name" , first_name , "last_name" , last_name , "chamber" , chamber , "active" , active == null ? null : active . toString ( ) , "term" , term , "party" , party , "district" , district ) , Legislators . class ) ; }

This method allows looking up a legislator by a number of parameters, the results do not include the roles or old_roles items by default.

Pass null for parameters that are not being filtered.

@param state Filter by state.
@param active 'true' (default) to only include current legislators, 'false' will include all legislators
@param term Only legislators that have a role in a certain term.
@param chamber Only legislators with a role in the specified chamber.
@param district Only legislators that have represented the specified district.
@param party Only legislators that have been associated with a specified party
@param first_name Filter by first name.
@param last_name Filter by last name.

This method allows looking up a legislator by a number of parameters the results do not include the roles or old_roles items by default .


public Legislator detail(String id) throws OpenStatesException {
		return api.query(new MethodMap("legislators", id), null, Legislator.class);
	}

public Legislator detail ( String id ) throws OpenStatesException { return api . query ( new MethodMap ( "legislators" , id ) , null , Legislator . class ) ; }

This method returns the full detail for a legislator.

@param id
@return {@link Legislator}

This method returns the full detail for a legislator .


public int compareTo(E o) {
		if (o.getClass() != getClass()) {
			throw new ClassCastException();
		}

		return ordinal - TypesafeEnum.class.cast(o).ordinal;
	}

public int compareTo ( E o ) { if ( o . getClass ( ) != getClass ( ) ) { throw new ClassCastException ( ) ; } return ordinal - TypesafeEnum . class . cast ( o ) . ordinal ; }

Compares with the specified object by ordinal.

@param o The object to be compared.
@return 0 If this object is the same ordinal to the
specified object.

Compares with the specified object by ordinal .


public void setMappedClass(Class<T> mappedClass) {
        if (this.mappedClass == null) {
            initialize(mappedClass);
        }
        else {
            if (!this.mappedClass.equals(mappedClass)) {
                throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to " +
                        mappedClass + " since it is already providing mapping for " + this.mappedClass);
            }
        }
    }

Set the class that each row should be mapped to.

Set the class that each row should be mapped to .


@SuppressWarnings("unchecked")
	public R proceed() throws Throwable {
		try {
			return (R) method().invoke(target, args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}

@ SuppressWarnings ( "unchecked" ) public R proceed ( ) throws Throwable { try { return ( R ) method ( ) . invoke ( target , args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } }

Proceeds this method invocation.

@return The result of this invocation proceeding.
@throws Throwable If any exceptions occur while this method invocation is
proceeding.


public long stop() {
		if (isRunning()) {
			stop = System.nanoTime();
			total += stop - start;
			running = false;
		}

		return Math.round(total * getPrecision().value);
	}

public long stop ( ) { if ( isRunning ( ) ) { stop = System . nanoTime ( ) ; total += stop - start ; running = false ; } return Math . round ( total * getPrecision ( ) . value ) ; }

Stops to measure.

@return Elapsed time.


protected HttpClient buildClient() {
        HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties().setConnectionManager(connManager);
        if (!isBlank(username) && !isBlank(password)) {
            final URI uri = URI.create(url);
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
                new UsernamePasswordCredentials(username, password));
            builder = builder.setDefaultCredentialsProvider(credsProvider);
        }
        return builder.build();
    }

protected HttpClient buildClient ( ) { HttpClientBuilder builder = HttpClientBuilder . create ( ) . useSystemProperties ( ) . setConnectionManager ( connManager ) ; if ( ! isBlank ( username ) && ! isBlank ( password ) ) { final URI uri = URI . create ( url ) ; final CredentialsProvider credsProvider = new BasicCredentialsProvider ( ) ; credsProvider . setCredentials ( new AuthScope ( uri . getHost ( ) , uri . getPort ( ) ) , new UsernamePasswordCredentials ( username , password ) ) ; builder = builder . setDefaultCredentialsProvider ( credsProvider ) ; } return builder . build ( ) ; }

Setup authentication in httpclient.
@return the setup of authentication


private HttpUriRequest minterRequest() {
        switch (method.toUpperCase()) {
            case "GET":
                return new HttpGet(url);
            case "PUT":
                return new HttpPut(url);
            default:
                return new HttpPost(url);
        }
    }

private HttpUriRequest minterRequest ( ) { switch ( method . toUpperCase ( ) ) { case "GET" : return new HttpGet ( url ) ; case "PUT" : return new HttpPut ( url ) ; default : return new HttpPost ( url ) ; } }

Instantiate a request object based on the method variable.

Instantiate a request object based on the method variable .


protected String responseToPid( final String responseText ) throws IOException {
        LOGGER.debug("responseToPid({})", responseText);
        if ( !isBlank(regex) ) {
            return responseText.replaceFirst(regex,"");
        } else if ( xpath != null ) {
            try {
                return xpath( responseText, xpath );
            } catch (ParserConfigurationException | SAXException | XPathExpressionException e) {
                throw new IOException(e);
            }
        } else {
            return responseText;
        }
    }

protected String responseToPid ( final String responseText ) throws IOException { LOGGER . debug ( "responseToPid({})" , responseText ) ; if ( ! isBlank ( regex ) ) { return responseText . replaceFirst ( regex , "" ) ; } else if ( xpath != null ) { try { return xpath ( responseText , xpath ) ; } catch ( ParserConfigurationException | SAXException | XPathExpressionException e ) { throw new IOException ( e ) ; } } else { return responseText ; } }

Remove unwanted text from the minter service response to produce the desired identifier.
Override this method for processing more complex than a simple regex replacement.
@param responseText the response text
@throws IOException if exception occurred
@return the response

Remove unwanted text from the minter service response to produce the desired identifier . Override this method for processing more complex than a simple regex replacement .


private static String xpath( final String xml, final XPathExpression xpath )
            throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
        final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder();
        final Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
        return xpath.evaluate(doc);
    }

private static String xpath ( final String xml , final XPathExpression xpath ) throws ParserConfigurationException , SAXException , IOException , XPathExpressionException { final DocumentBuilder builder = DOCUMENT_BUILDER_FACTORY . newDocumentBuilder ( ) ; final Document doc = builder . parse ( new ByteArrayInputStream ( xml . getBytes ( ) ) ) ; return xpath . evaluate ( doc ) ; }

Extract the desired identifier value from an XML response using XPath


@Timed
    @Override
    public String get() {
        try {
            LOGGER.debug("mintPid()");
            final HttpResponse resp = client.execute( minterRequest() );
            return responseToPid( EntityUtils.toString(resp.getEntity()) );
        } catch ( final IOException ex ) {
            LOGGER.warn("Error minting pid from {}: {}", url, ex.getMessage());
            throw new PidMintingException("Error minting pid", ex);
        } catch ( final Exception ex ) {
            LOGGER.warn("Error processing minter response", ex.getMessage());
            throw new PidMintingException("Error processing minter response", ex);
        }
    }

@
Timed
@
Override
public
String
get
(
)
{
try
{
LOGGER
.
debug
(
"mintPid()"
)
;
final
HttpResponse
resp
=
client
.
execute
(
minterRequest
(
)
)
;
return
responseToPid
(
EntityUtils
.
toString
(
resp
.
getEntity
(
)
)
)
;
}
catch
(
final
IOException
ex
)
{
LOGGER
.
warn
(
"Error minting pid from {}: {}"
,
url
,
ex
.
getMessage
(
)
)
;
throw
new
PidMintingException
(
"Error minting pid"
,
ex
)
;
}
catch
(
final
Exception
ex
)
{
LOGGER
.
warn
(
"Error processing minter response"
,
ex
.
getMessage
(
)
)
;
throw
new
PidMintingException
(
"Error processing minter response"
,
ex
)
;
}
}

Mint a unique identifier using an external HTTP API.
@return The generated identifier.

Mint a unique identifier using an external HTTP API .


public static <T extends Configuration> ConfigurationBinder<T> forClass(Class<T> klass, Binder binder) {
        return new ConfigurationBinder<>(klass, binder);
    }

public static < T extends Configuration > ConfigurationBinder < T > forClass ( Class < T > klass , Binder binder ) { return new ConfigurationBinder <> ( klass , binder ) ; }

The starting point for using a ConfigurationBinder. A class needs to be passed through, along with a binder to
eventually bind the configuration with.

@param klass  The Configuration Class to load & bind.
@param binder The {@link com.google.inject.Binder} from the {@link io.graceland.plugin.AbstractPlugin}.
@param <T>    The Configuration Type.
@return Returns a working ConfigurationBinder using the provided type and class information.

The starting point for using a ConfigurationBinder . A class needs to be passed through along with a binder to eventually bind the configuration with .


public void toInstance(Config configuration) {
        Preconditions.checkNotNull(configuration, "Configuration Instance cannot be null.");

        if (annotationClass == null) {
            binder.bind(configClass).toInstance(configuration);

        } else {
            binder.bind(configClass).annotatedWith(annotationClass).toInstance(configuration);
        }
    }

This method will bind the class to a particular instance.

@param configuration

This method will bind the class to a particular instance .


public static FilterPattern newInstance(
            EnumSet<DispatcherType> dispatcherTypes,
            boolean matchAfter,
            Iterable<String> patterns) {

        return new FilterPattern(dispatcherTypes, matchAfter, ImmutableList.copyOf(patterns));
    }

public static FilterPattern newInstance ( EnumSet < DispatcherType > dispatcherTypes , boolean matchAfter , Iterable < String > patterns ) { return new FilterPattern ( dispatcherTypes , matchAfter , ImmutableList . copyOf ( patterns ) ) ; }

Returns a new instance of FilterPattern, using the passed in arguments.

Returns a new instance of FilterPattern using the passed in arguments .


public T proceed() throws Throwable {
		try {
			return constructor().newInstance(args);
		} catch (InvocationTargetException e) {
			throw e.getTargetException();
		}
	}

public T proceed ( ) throws Throwable { try { return constructor ( ) . newInstance ( args ) ; } catch ( InvocationTargetException e ) { throw e . getTargetException ( ) ; } }

Proceeds this constructor invocation.

@return The instance of the specified class.
@throws Throwable If any exceptions occur while this invocation is
proceeding.