org.apache.velocity.tools.generic
Class LinkTool

java.lang.Object
  extended by org.apache.velocity.tools.generic.SafeConfig
      extended by org.apache.velocity.tools.generic.LinkTool
All Implemented Interfaces:
java.lang.Cloneable

@DefaultKey(value="link")
@ValidScope(value="request")
public class LinkTool
extends SafeConfig
implements java.lang.Cloneable

The LinkTool provides many methods to work with URIs and can help you:

This GenericTools (i.e. non-servlet based) version of LinkTool is largely based upon the same API and behavior as the older VelocityView version, with a few differences, particularly in internal representation and query handling. You can expect that in the future work will be done to more closely align the APIs. It is likely that the VelocityView version will become a subclass of this version that adds on servlet-awareness and related features. For now, though, they are entirely separate but similar tools.

The LinkTool is somewhat special in that nearly all public methods return a new instance of LinkTool. This facilitates greatly the repeated use of the LinkTool in Velocity and leads to an elegant syntax.

 Template example(s):
   #set( $base = $link.relative('MyPage.vm').anchor('view') )
   <a href="$base.param('select','this')">this</a>
   <a href="$base.param('select','that')">that</a>

 Toolbox configuration:
 <tools>
   <toolbox scope="request">
     <tool class="org.apache.velocity.tools.generic.LinkTool"
              uri="http://velocity.apache.org/tools/devel/"/>
   </toolbox>
 </tools>
 

Since:
VelocityTools 2.0
Version:
$Id: LinkTool.java 601976 2007-12-07 03:50:51Z nbubna $
Author:
Nathan Bubna

Field Summary
protected  java.lang.String charset
           
static java.lang.String CHARSET_KEY
           
static java.lang.String DEFAULT_CHARSET
           
static java.lang.String DEFAULT_SCHEME
           
protected  java.lang.String fragment
           
static java.lang.String FRAGMENT_KEY
           
protected  java.lang.String host
           
static java.lang.String HOST_KEY
           
static java.lang.String HTML_QUERY_DELIMITER
          Standard HTML delimiter for query data ('&')
protected  org.apache.velocity.runtime.log.Log LOG
           
private  boolean opaque
           
protected  java.lang.String path
           
static java.lang.String PATH_KEY
           
protected  int port
           
static java.lang.String PORT_KEY
           
protected  java.lang.String query
           
static java.lang.String QUERY_KEY
           
protected  java.lang.String queryDelim
           
protected  java.lang.String scheme
           
static java.lang.String SCHEME_KEY
           
static java.lang.String SECURE_SCHEME
           
private  LinkTool self
           
static java.lang.String URI_KEY
           
protected  java.lang.String user
           
static java.lang.String USER_KEY
           
static java.lang.String XHTML_MODE_KEY
           
static java.lang.String XHTML_QUERY_DELIMITER
          XHTML delimiter for query data ('&amp;')
 
Fields inherited from class org.apache.velocity.tools.generic.SafeConfig
LOCK_CONFIG_KEY, OLD_LOCK_CONFIG_KEY, SAFE_MODE_KEY
 
Constructor Summary
LinkTool()
          Default constructor.
 
Method Summary
 LinkTool absolute(java.lang.Object obj)
          Returns a copy of the link with the specified URI reference either used as or converted to an absolute (non-relative) URI reference.
 LinkTool anchor(java.lang.Object anchor)
          Returns a copy of the link with the specified anchor to be added to the end of the generated hyperlink.
 LinkTool append(java.lang.Object pth)
          Appends the given value to the end of the current path value.
private  void appendAsArray(java.lang.StringBuilder out, java.lang.Object key, java.lang.Object[] arr)
           
protected  void appendPath(java.lang.Object obj)
           
protected  void appendQuery(java.lang.Object obj)
           
protected  java.lang.String combinePath(java.lang.String start, java.lang.String end)
           
protected  java.lang.String combineQuery(java.lang.String current, java.lang.String add)
           
protected  void configure(ValueParser props)
          Does the actual configuration.
protected  java.net.URI createURI()
           
 java.lang.String decode(java.lang.Object obj)
          Delegates decoding of the specified url content to URLDecoder.decode(java.lang.String) using the configured character encoding.
protected  LinkTool duplicate()
          Equivalent to clone, but with no checked exceptions.
 java.lang.String encode(java.lang.Object obj)
          Delegates encoding of the specified url content to URLEncoder.encode(java.lang.String) using the configured character encoding.
 boolean equals(java.lang.Object obj)
          This instance is considered equal to any LinkTool instance whose toString() method returns a String equal to that returned by this instance's toString()
 java.lang.String getAnchor()
          Returns the anchor (internal document reference) set for this link.
 java.lang.String getBaseRef()
          Returns the full URI of this template without any query data.
 java.lang.String getContextPath()
          At this level, this method returns all "directories" in the set getPath() value, by just trimming of the last "/" and all that follows.
 java.lang.String getContextURL()
          Returns the URI that addresses the current "directory" of this instance.
 java.lang.String getHost()
          Return the host value for this instance.
 java.util.Map getParams()
           
 java.lang.String getPath()
          Returns the current path value for this instance.
 java.lang.Integer getPort()
          Returns the port value, if any.
 java.lang.String getQuery()
          Returns the current query string, if any.
 java.lang.String getRequestPath()
          At this level, this method returns the last section of the path, from the final "/" onward.
 java.lang.String getRoot()
          Returns the "root" for this URI, if it has one.
 java.lang.String getScheme()
          Return the scheme value for this instance.
 LinkTool getSelf()
           
 java.net.URI getUri()
          If the tool is not in "safe mode"--which it is by default-- this will return the URI representation of this instance, if any.
 java.lang.String getUser()
          Returns the URI.getUserInfo() value for this instance.
 int hashCode()
          Returns the hash code for the result of toString().
 LinkTool host(java.lang.Object host)
          Returns a new instance with the specified value set as its host.
 LinkTool insecure()
          Returns a new instance with the scheme set to "http".
 boolean isAbsolute()
          Returns true if this instance has a scheme value.
 boolean isOpaque()
          Returns true if this instance represents an opaque URI.
 boolean isSecure()
          Returns true if this instance's scheme is "https".
private  void logError(java.lang.String msg, java.lang.Throwable t)
           
 LinkTool param(java.lang.Object key, java.lang.Object value)
          Adds a key=value pair to the query data.
 LinkTool params(java.util.Map parameters)
          Adds multiple key=value pairs to the query data.
protected  java.util.Map<java.lang.String,java.lang.Object> parseQuery(java.lang.String query)
           
 LinkTool path(java.lang.Object pth)
          Returns a new instance with the specified value set as its path.
 LinkTool port(java.lang.Object port)
          Returns a new instance with the specified value set as its port number.
 LinkTool query(java.lang.Object query)
          Sets the specified value as the current query string, after normalizing the pair delimiters.
 LinkTool relative(java.lang.Object obj)
          Returns a copy of the link with the specified context-relative URI reference converted to a server-relative URI reference.
 LinkTool scheme(java.lang.Object scheme)
          Returns a new instance with the specified value set as its scheme.
 LinkTool secure()
          Returns a new instance with the scheme set to "https".
protected  void setFragment(java.lang.Object obj)
           
protected  boolean setFromURI(java.lang.Object obj)
           
protected  void setHost(java.lang.Object obj)
           
protected  void setPath(java.lang.Object obj)
           
protected  void setPort(java.lang.Object obj)
           
protected  void setQuery(java.lang.Object obj)
           
protected  void setScheme(java.lang.Object obj)
           
protected  void setUserInfo(java.lang.Object obj)
           
protected  void setXHTML(boolean xhtml)
          Controls the delimiter used for separating query data pairs.
protected  java.lang.String toQuery(java.lang.Object key, java.lang.Object value)
           
 java.lang.String toString()
          Returns the full URI reference that's been built with this tool, including the query string and anchor, e.g.
 LinkTool uri(java.lang.Object uri)
          Returns a copy of the link with the given URI reference set.
 LinkTool user(java.lang.Object info)
          Returns a new instance with the specified value set as its user info.
 
Methods inherited from class org.apache.velocity.tools.generic.SafeConfig
configure, isConfigLocked, isSafeMode, setLockConfig, setSafeMode
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Field Detail

HTML_QUERY_DELIMITER

public static final java.lang.String HTML_QUERY_DELIMITER
Standard HTML delimiter for query data ('&')

See Also:
Constant Field Values

XHTML_QUERY_DELIMITER

public static final java.lang.String XHTML_QUERY_DELIMITER
XHTML delimiter for query data ('&amp;')

See Also:
Constant Field Values

DEFAULT_CHARSET

public static final java.lang.String DEFAULT_CHARSET
See Also:
Constant Field Values

DEFAULT_SCHEME

public static final java.lang.String DEFAULT_SCHEME
See Also:
Constant Field Values

SECURE_SCHEME

public static final java.lang.String SECURE_SCHEME
See Also:
Constant Field Values

URI_KEY

public static final java.lang.String URI_KEY
See Also:
Constant Field Values

SCHEME_KEY

public static final java.lang.String SCHEME_KEY
See Also:
Constant Field Values

USER_KEY

public static final java.lang.String USER_KEY
See Also:
Constant Field Values

HOST_KEY

public static final java.lang.String HOST_KEY
See Also:
Constant Field Values

PORT_KEY

public static final java.lang.String PORT_KEY
See Also:
Constant Field Values

PATH_KEY

public static final java.lang.String PATH_KEY
See Also:
Constant Field Values

QUERY_KEY

public static final java.lang.String QUERY_KEY
See Also:
Constant Field Values

FRAGMENT_KEY

public static final java.lang.String FRAGMENT_KEY
See Also:
Constant Field Values

CHARSET_KEY

public static final java.lang.String CHARSET_KEY
See Also:
Constant Field Values

XHTML_MODE_KEY

public static final java.lang.String XHTML_MODE_KEY
See Also:
Constant Field Values

LOG

protected org.apache.velocity.runtime.log.Log LOG

scheme

protected java.lang.String scheme

user

protected java.lang.String user

host

protected java.lang.String host

port

protected int port

path

protected java.lang.String path

query

protected java.lang.String query

fragment

protected java.lang.String fragment

charset

protected java.lang.String charset

queryDelim

protected java.lang.String queryDelim

opaque

private boolean opaque

self

private final LinkTool self
Constructor Detail

LinkTool

public LinkTool()
Default constructor. Tool typically is configured before use.

Method Detail

logError

private void logError(java.lang.String msg,
                      java.lang.Throwable t)

configure

protected void configure(ValueParser props)
Description copied from class: SafeConfig
Does the actual configuration. This is protected, so subclasses may share the same ValueParser and call configure at any time, while preventing templates from doing so when configure(Map) is locked.

Overrides:
configure in class SafeConfig

setXHTML

protected void setXHTML(boolean xhtml)

Controls the delimiter used for separating query data pairs. By default, the standard '&' character is used.

This is not exposed to templates as this decision is best not made at that level.

Subclasses may easily override the init() method to set this appropriately and then call super.init()

Parameters:
xhtml - if true, the XHTML query data delimiter ('&amp;') will be used. if false, then '&' will be used.
See Also:
Using Ampersands in Attribute Values (and Elsewhere)

duplicate

protected LinkTool duplicate()
Equivalent to clone, but with no checked exceptions. If for some unfathomable reason clone() doesn't work, this will throw a RuntimeException.


setScheme

protected void setScheme(java.lang.Object obj)

setUserInfo

protected void setUserInfo(java.lang.Object obj)

setHost

protected void setHost(java.lang.Object obj)

setPort

protected void setPort(java.lang.Object obj)

setPath

protected void setPath(java.lang.Object obj)

appendPath

protected void appendPath(java.lang.Object obj)

combinePath

protected java.lang.String combinePath(java.lang.String start,
                                       java.lang.String end)

setQuery

protected void setQuery(java.lang.Object obj)

appendQuery

protected void appendQuery(java.lang.Object obj)

combineQuery

protected java.lang.String combineQuery(java.lang.String current,
                                        java.lang.String add)

toQuery

protected java.lang.String toQuery(java.lang.Object key,
                                   java.lang.Object value)

appendAsArray

private void appendAsArray(java.lang.StringBuilder out,
                           java.lang.Object key,
                           java.lang.Object[] arr)

parseQuery

protected java.util.Map<java.lang.String,java.lang.Object> parseQuery(java.lang.String query)

setFragment

protected void setFragment(java.lang.Object obj)

setFromURI

protected boolean setFromURI(java.lang.Object obj)

createURI

protected java.net.URI createURI()

scheme

public LinkTool scheme(java.lang.Object scheme)
Returns a new instance with the specified value set as its scheme.


secure

public LinkTool secure()
Returns a new instance with the scheme set to "https".


insecure

public LinkTool insecure()
Returns a new instance with the scheme set to "http".


getScheme

public java.lang.String getScheme()
Return the scheme value for this instance.


isSecure

public boolean isSecure()
Returns true if this instance's scheme is "https".


isAbsolute

public boolean isAbsolute()
Returns true if this instance has a scheme value.


isOpaque

public boolean isOpaque()
Returns true if this instance represents an opaque URI.

See Also:
URI

user

public LinkTool user(java.lang.Object info)
Returns a new instance with the specified value set as its user info.


getUser

public java.lang.String getUser()
Returns the URI.getUserInfo() value for this instance.


host

public LinkTool host(java.lang.Object host)
Returns a new instance with the specified value set as its host. If no scheme has yet been set, the new instance will also have its scheme set to the DEFAULT_SCHEME (http).


getHost

public java.lang.String getHost()
Return the host value for this instance.


port

public LinkTool port(java.lang.Object port)
Returns a new instance with the specified value set as its port number. If the value cannot be parsed into an integer, the returned instance will always return null for toString() and other createURI()-dependent methods to alert the user to the error.


getPort

public java.lang.Integer getPort()
Returns the port value, if any.


path

public LinkTool path(java.lang.Object pth)
Returns a new instance with the specified value set as its path.


getPath

public java.lang.String getPath()
Returns the current path value for this instance.


append

public LinkTool append(java.lang.Object pth)
Appends the given value to the end of the current path value.


getContextPath

public java.lang.String getContextPath()
At this level, this method returns all "directories" in the set getPath() value, by just trimming of the last "/" and all that follows.


getRequestPath

public java.lang.String getRequestPath()
At this level, this method returns the last section of the path, from the final "/" onward.


getRoot

public java.lang.String getRoot()
Returns the "root" for this URI, if it has one. This does not stick close to URI dogma and will try to insert the default scheme if there is none, and will return null if there is no host, as that is the core piece of the "root". It thus will return null for any opaque URLs as well.


getContextURL

public java.lang.String getContextURL()

Returns the URI that addresses the current "directory" of this instance. This string does not end with a "/" and is essentially a concatenation of getRoot() and getContextPath()


relative

public LinkTool relative(java.lang.Object obj)

Returns a copy of the link with the specified context-relative URI reference converted to a server-relative URI reference. This method will overwrite any previous URI reference settings but will copy the query string.

Example:
<a href='$link.relative("/templates/login/index.vm")'>Login Page</a>
produces something like
<a href="/myapp/templates/login/index.vm">Login Page</a>

Parameters:
obj - A context-relative URI reference. A context-relative URI is a URI that is relative to the root of this web application.
Returns:
a new instance of LinkTool with the specified URI

absolute

public LinkTool absolute(java.lang.Object obj)

Returns a copy of the link with the specified URI reference either used as or converted to an absolute (non-relative) URI reference. This method will overwrite any previous URI reference settings but will copy the query string.

Example:
<a href='$link.absolute("/templates/login/index.vm")'>Login Page</a>
produces something like
<a href="http://myserver.net/myapp/templates/login/index.vm">Login Page</a>
and
<a href='$link.absolute("http://theirserver.com/index.jsp")'>Their, Inc.</a>
produces something like
<a href="http://theirserver.net/index.jsp">Their, Inc.</a>

Parameters:
obj - A context-relative URI reference or absolute URL.
Returns:
a new instance of LinkTool with the specified URI
Since:
VelocityTools 1.3
See Also:
uri(Object uri)

uri

public LinkTool uri(java.lang.Object uri)

Returns a copy of the link with the given URI reference set. Few changes are applied to the given URI reference. The URI reference can be absolute, server-relative, relative and may contain query parameters. This method will overwrite all previous settings for scheme, host port, path, query and anchor.

Parameters:
uri - URI reference to set
Returns:
a new instance of LinkTool
Since:
VelocityTools 1.3

getUri

public java.net.URI getUri()
If the tool is not in "safe mode"--which it is by default-- this will return the URI representation of this instance, if any.

See Also:
SafeConfig.isSafeMode()

getBaseRef

public java.lang.String getBaseRef()
Returns the full URI of this template without any query data. e.g. http://myserver.net/myapp/stuff/View.vm Note! The returned String will not represent any URI reference or query data set for this LinkTool. A typical application of this method is with the HTML base tag. For example: <base href="$link.baseRef">


query

public LinkTool query(java.lang.Object query)
Sets the specified value as the current query string, after normalizing the pair delimiters.


getQuery

public java.lang.String getQuery()
Returns the current query string, if any.


param

public LinkTool param(java.lang.Object key,
                      java.lang.Object value)

Adds a key=value pair to the query data. This returns a new LinkTool containing both a copy of this LinkTool's query data and the new data. Query data is URL encoded before it is appended.

Parameters:
key - key of new query parameter
value - value of new query parameter
Returns:
a new instance of LinkTool
Since:
VelocityTools 1.3

params

public LinkTool params(java.util.Map parameters)

Adds multiple key=value pairs to the query data. This returns a new LinkTool containing both a copy of this LinkTool's query data and the new data. Query data is URL encoded before it is appended.

Parameters:
parameters - map of new query data keys to values
Returns:
a new instance of LinkTool
Since:
VelocityTools 1.3

getParams

public java.util.Map getParams()

anchor

public LinkTool anchor(java.lang.Object anchor)

Returns a copy of the link with the specified anchor to be added to the end of the generated hyperlink.

Example:
<a href='$link.setAnchor("foo")'>Foo</a>
produces something like
<a href="#foo">Foo</a>

Parameters:
anchor - an internal document reference
Returns:
a new instance of LinkTool with the set anchor
Since:
VelocityTools 1.3

getAnchor

public java.lang.String getAnchor()
Returns the anchor (internal document reference) set for this link.


getSelf

public LinkTool getSelf()

toString

public java.lang.String toString()
Returns the full URI reference that's been built with this tool, including the query string and anchor, e.g. http://myserver.net/myapp/stuff/View.vm?id=42&type=blue#foo. Typically, it is not necessary to call this method explicitely. Velocity will call the toString() method automatically to obtain a representable version of an object.

Overrides:
toString in class java.lang.Object

equals

public boolean equals(java.lang.Object obj)
This instance is considered equal to any LinkTool instance whose toString() method returns a String equal to that returned by this instance's toString()

Overrides:
equals in class java.lang.Object
See Also:
toString()

hashCode

public int hashCode()
Returns the hash code for the result of toString(). If toString() returns null (yes, we do break that contract), this will return -1.

Overrides:
hashCode in class java.lang.Object

encode

public java.lang.String encode(java.lang.Object obj)
Delegates encoding of the specified url content to URLEncoder.encode(java.lang.String) using the configured character encoding.

Returns:
String - the encoded url.

decode

public java.lang.String decode(java.lang.Object obj)
Delegates decoding of the specified url content to URLDecoder.decode(java.lang.String) using the configured character encoding.

Returns:
String - the decoded url.


Copyright (c) 2003-2007 Apache Software Foundation