@Cached
    @DontLabel
    public Rule unicodeRange(final int low, final int high)
    {
        if (!Character.isValidCodePoint(low))
            throw new InvalidGrammarException("invalid code point " + low);
        if (!Character.isValidCodePoint(high))
            throw new InvalidGrammarException("invalid code point " + high);
        if (low > high)
            throw new InvalidGrammarException("invalid code point range: "
                + low + " > " + high);
        return low == high ? new CodePointMatcher(low)
            : new CodePointRangeMatcher(low, high);
    }

@
Cached
@
DontLabel
public
Rule
unicodeRange
(
final
int
low
,
final
int
high
)
{
if
(
!
Character
.
isValidCodePoint
(
low
)
)
throw
new
InvalidGrammarException
(
"invalid code point "
+
low
)
;
if
(
!
Character
.
isValidCodePoint
(
high
)
)
throw
new
InvalidGrammarException
(
"invalid code point "
+
high
)
;
if
(
low
>
high
)
throw
new
InvalidGrammarException
(
"invalid code point range: "
+
low
+
" > "
+
high
)
;
return
low
==
high
new
CodePointMatcher
(
low
)
:
new
CodePointRangeMatcher
(
low
,
high
)
;
}

Match a Unicode character range

Note that this method will delegate to "regular" character matchers if
part of, or all of, the specified range is into the basic multilingual
plane.

@param low the lower code point (inclusive)
@param high the upper code point (inclusive)
@return a rule


@DontLabel
    public Rule anyOf(final String characters)
    {
        Objects.requireNonNull(characters);
        // TODO: see in this Characters class whether it is possible to wrap
        return anyOf(characters.toCharArray());
    }

Match any of the characters in the given string

This method delegates to {@link #anyOf(Characters)}.

@param characters the characters
@return a rule

@see #anyOf(Characters)


@Cached
    @DontLabel
    public Rule anyOf(final Characters characters)
    {
        Objects.requireNonNull(characters);
        if (!characters.isSubtractive() && characters.getChars().length == 1)
            return ch(characters.getChars()[0]);
        if (characters.equals(Characters.NONE))
            return NOTHING;
        return new AnyOfMatcher(characters);
    }

@ Cached @ DontLabel public Rule anyOf ( final Characters characters ) { Objects . requireNonNull ( characters ) ; if ( ! characters . isSubtractive ( ) && characters . getChars ( ) . length == 1 ) return ch ( characters . getChars ( ) [ 0 ] ) ; if ( characters . equals ( Characters . NONE ) ) return NOTHING ; return new AnyOfMatcher ( characters ) ; }

Match any given character among a set of characters

Both {@link #anyOf(char[])} and {@link #anyOf(String)} ultimately
delegate to this method, which caches its resuls.

@param characters the characters
@return a new rule


@DontLabel
    public Rule string(final String string)
    {
        Objects.requireNonNull(string);
        return string(string.toCharArray());
    }

@ DontLabel public Rule string ( final String string ) { Objects . requireNonNull ( string ) ; return string ( string . toCharArray ( ) ) ; }

Match a string literal

@param string the string to match
@return a rule


@Cached
    @DontLabel
    public Rule string(final char... characters)
    {
        if (characters.length == 1)
            return ch(characters[0]); // optimize one-char strings
        return new StringMatcher(new String(characters));
    }

@
Cached
@
DontLabel
public
Rule
string
(
final
char
...
characters
)
{
if
(
characters
.
length
==
1
)
return
ch
(
characters
[
0
]
)
;
// optimize one-char strings
return
new
StringMatcher
(
new
String
(
characters
)
)
;
}

Match a given set of characters as a string literal

@param characters the characters of the string to match
@return a rule


@DontLabel
    public Rule ignoreCase(final String string)
    {
        Objects.requireNonNull(string);
        return ignoreCase(string.toCharArray());
    }

@ DontLabel public Rule ignoreCase ( final String string ) { Objects . requireNonNull ( string ) ; return ignoreCase ( string . toCharArray ( ) ) ; }

Match a string literal in a case insensitive manner

@param string the string to match
@return a rule


@Cached
    @DontLabel
    public Rule optional(final Object rule)
    {
        Objects.requireNonNull(rule);
        return new OptionalMatcher(toRule(rule));
    }

@ Cached @ DontLabel public Rule optional ( final Object rule ) { Objects . requireNonNull ( rule ) ; return new OptionalMatcher ( toRule ( rule ) ) ; }

Try and match a rule zero or one time

This rule therefore always succeeds.

@param rule the subrule
@return a rule


@DontLabel
    public Rule optional(final Object rule, final Object rule2,
        final Object... moreRules)
    {
        Objects.requireNonNull(moreRules);
        return optional(sequence(rule, rule2, moreRules));
    }

@ DontLabel public Rule optional ( final Object rule , final Object rule2 , final Object ... moreRules ) { Objects . requireNonNull ( moreRules ) ; return optional ( sequence ( rule , rule2 , moreRules ) ) ; }

Try and match a given set of rules once

This rule will therefore never fail.

@param rule the first subrule
@param rule2 the second subrule
@param moreRules the other subrules
@return a rule


@DontLabel
    public final RepeatMatcherBuilder<V> repeat(final Object rule,
        final Object rule2, final Object... moreRules)
    {
        Objects.requireNonNull(moreRules);
        return repeat(sequence(rule, rule2, moreRules));
    }

@ DontLabel public final RepeatMatcherBuilder < V > repeat ( final Object rule , final Object rule2 , final Object ... moreRules ) { Objects . requireNonNull ( moreRules ) ; return repeat ( sequence ( rule , rule2 , moreRules ) ) ; }

Kickstart a repeat rule

Like {@link #repeat(Object)}, except several rules are accepted as
arguments.

@param rule first rule
@param rule2 second rule
@param moreRules other rules
@return a rule

@see #sequence(Object, Object, Object...)


@DontLabel
    public Rule zeroOrMore(final Object rule, final Object rule2,
        final Object... moreRules)
    {
        return repeat(rule, rule2, moreRules).min(0);
    }

@ DontLabel public Rule zeroOrMore ( final Object rule , final Object rule2 , final Object ... moreRules ) { return repeat ( rule , rule2 , moreRules ) . min ( 0 ) ; }

Try and match a set of rules zero or more times

This is an alias for {@code repeat(rule, rule2, ...).min(0)}.

@param rule the first subrule
@param rule2 the second subrule
@param moreRules the other subrules
@return a rule


@DontExtend
    protected Rule fromStringLiteral(final String string)
    {
        Objects.requireNonNull(string);
        return fromCharArray(string.toCharArray());
    }

@ DontExtend protected Rule fromStringLiteral ( final String string ) { Objects . requireNonNull ( string ) ; return fromCharArray ( string . toCharArray ( ) ) ; }

Convert a string literal to a parser rule

@param string the string
@return the rule


@DontExtend
    public Rule[] toRules(final Object... objects)
    {
        return Arrays.stream(objects).map(this::toRule).toArray(Rule[]::new);
    }

@ DontExtend public Rule [ ] toRules ( final Object ... objects ) { return Arrays . stream ( objects ) . map ( this :: toRule ) . toArray ( Rule [ ] :: new ) ; }

Convert the given object array to an array of rules

@param objects the objects to convert
@return the rules corresponding to the given objects


@DontExtend
    public Rule toRule(final Object obj)
    {
        Objects.requireNonNull(obj);
        if (obj instanceof Rule)
            return (Rule) obj;
        if (obj instanceof Character)
            return fromCharLiteral((Character) obj);
        if (obj instanceof String)
            return fromStringLiteral((String) obj);
        if (obj instanceof char[])
            return fromCharArray((char[]) obj);
        if (obj instanceof Action) {
            final Action<?> action = (Action<?>) obj;
            return new ActionMatcher(action);
        }

        final String errmsg = obj instanceof  Boolean
            ? "unwrapped Boolean value in rule (wrap it with ACTION())"
            : "'" + obj + "' cannot be automatically converted to a rule";
        throw new InvalidGrammarException(errmsg);
    }

Converts the given object to a rule

@param obj the object to convert
@return the rule corresponding to the given object


public boolean push(final int down, final V value)
    {
        check();
        context.getValueStack().push(down, value);
        return true;
    }

public boolean push ( final int down , final V value ) { check ( ) ; context . getValueStack ( ) . push ( down , value ) ; return true ; }

Inserts the given value a given number of elements below the current top
of the value stack

@param down the number of elements to skip before inserting the value (0
being equivalent to {@code push(value)})
@param value the value
@return true

@throws IllegalArgumentException the stack does not contain enough
elements to perform this operation


public <E extends V> E popAs(@Nonnull final Class<E> c)
    {
        return c.cast(pop());
    }

public < E extends V > E popAs ( @ Nonnull final Class < E > c ) { return c . cast ( pop ( ) ) ; }

Removes the value at the top of the value stack and casts it before
returning it

@param c the class to cast to
@param <E> type of the class
@return the current top value
@throws IllegalArgumentException the stack is empty

@see #pop()


public <E extends V> E popAs(final Class<E> c, final int down)
    {
        return c.cast(pop(down));
    }

public < E extends V > E popAs ( final Class < E > c , final int down ) { return c . cast ( pop ( down ) ) ; }

Removes the value the given number of elements below the top of the value
stack and casts it before returning it

@param c the class to cast to
@param down the number of elements to skip before removing the value (0
being equivalent to {@code pop()})
@param <E> type of the class
@return the value
@throws IllegalArgumentException the stack does not contain enough
elements to perform this operation

@see #pop(int)


public <E extends V> E peekAs(final Class<E> c)
    {
        return c.cast(peek());
    }

public < E extends V > E peekAs ( final Class < E > c ) { return c . cast ( peek ( ) ) ; }

Returns and casts the value at the top of the value stack without
removing it

@param c the class to cast to
@param <E> type of the class
@return the value

@see #peek()


public boolean poke(final int down, final V value)
    {
        check();
        context.getValueStack().poke(down, value);
        return true;
    }

public boolean poke ( final int down , final V value ) { check ( ) ; context . getValueStack ( ) . poke ( down , value ) ; return true ; }

Replaces the element the given number of elements below the current top
of the value stack

@param down the number of elements to skip before replacing the value (0
being equivalent to {@code poke(value)})
@param value the value to replace with
@return true

@throws IllegalArgumentException the stack does not contain enough
elements to perform this operation


@Override
    public <T> boolean match(final MatcherContext<T> context)
    {
        final Matcher matcher = context.getMatcher();

        final PreMatchEvent<T> preMatchEvent = new PreMatchEvent<>(context);
        bus.post(preMatchEvent);

        if (throwable != null)
            throw new GrappaException("parsing listener error (before match)",
                throwable);

        // FIXME: is there any case at all where context.getMatcher() is null?
        @SuppressWarnings("ConstantConditions")
        final boolean match = matcher.match(context);

        final MatchContextEvent<T> postMatchEvent = match
            ? new MatchSuccessEvent<>(context)
            : new MatchFailureEvent<>(context);

        bus.post(postMatchEvent);

        if (throwable != null)
            throw new GrappaException("parsing listener error (after match)",
                throwable);

        return match;
    }

Internal method. DO NOT USE!

@param context the MatcherContext
@param <T> type parameter of the values on the parser stack
@return true on a match; false otherwise


public boolean overlapsWith(final IndexRange other)
    {
        Objects.requireNonNull(other, "other");
        return end > other.start && other.end > start;
    }

public boolean overlapsWith ( final IndexRange other ) { Objects . requireNonNull ( other , "other" ) ; return end > other . start && other . end > start ; }

Determines whether this range overlaps with the given other one.

@param other the other range
@return true if there is at least one index that is contained in both ranges

Determines whether this range overlaps with the given other one .


public boolean touches(final IndexRange other)
    {
        Objects.requireNonNull(other, "other");
        return other.end == start || end == other.start;
    }

public boolean touches ( final IndexRange other ) { Objects . requireNonNull ( other , "other" ) ; return other . end == start || end == other . start ; }

Determines whether this range immediated follows or precedes the given other one.

@param other the other range
@return true if this range immediated follows or precedes the given other one.

Determines whether this range immediated follows or precedes the given other one .


public IndexRange mergedWith(final IndexRange other)
    {
        Objects.requireNonNull(other, "other");
        return new IndexRange(Math.min(start, other.start),
            Math.max(end, other.end));
    }

public IndexRange mergedWith ( final IndexRange other ) { Objects . requireNonNull ( other , "other" ) ; return new IndexRange ( Math . min ( start , other . start ) , Math . max ( end , other . end ) ) ; }

Created a new IndexRange that spans all characters between the smallest and the highest index of the two ranges.

@param other the other range
@return a new IndexRange instance

Created a new IndexRange that spans all characters between the smallest and the highest index of the two ranges .


public static <P extends BaseParser<V>, V> byte[] getByteCode(
        final Class<P> parserClass)
    {
        try {
            return ParserTransformer.getByteCode(parserClass);
        } catch (Exception e) {
            throw new RuntimeException("failed to generate byte code", e);
        }
    }

public
static
<
P
extends
BaseParser
<
V
>
,
V
>
byte
[
]
getByteCode
(
final
Class
<
P
>
parserClass
)
{
try
{
return
ParserTransformer
.
getByteCode
(
parserClass
)
;
}
catch
(
Exception
e
)
{
throw
new
RuntimeException
(
"failed to generate byte code"
,
e
)
;
}
}

Generate the byte code of a transformed parser class

When you create a parser using {@link
#createParser(Class, Object...)}, Parboiled generates a new class which
is the one you actually use for parsing. This method allows to get the
byte code of such a generated class in a byte array.

@param parserClass the parser class
@param
 class of the parser
@param <V> see {@link BaseParser}
@return the byte code

@throws RuntimeException byte code generation failure
@see ParserTransformer#getByteCode(Class)


private void doAddWord(final CharBuffer buffer)
    {
        if (!buffer.hasRemaining()) {
            fullWord = true;
            return;
        }

        final char c = buffer.get();
        TrieNodeBuilder builder = subnodes.get(c);
        if (builder == null) {
            builder = new TrieNodeBuilder();
            subnodes.put(c, builder);
        }
        builder.doAddWord(buffer);
    }

private void doAddWord ( final CharBuffer buffer ) { if ( ! buffer . hasRemaining ( ) ) { fullWord = true ; return ; } final char c = buffer . get ( ) ; TrieNodeBuilder builder = subnodes . get ( c ) ; if ( builder == null ) { builder = new TrieNodeBuilder ( ) ; subnodes . put ( c , builder ) ; } builder . doAddWord ( buffer ) ; }

Add a word

Here also, a {@link CharBuffer} is used, which changes position as we
progress into building the tree, character by character, node by node.

If the buffer is "empty" when entering this method, it means a match
must be recorded (see {@link #fullWord}).

@param buffer the buffer (never null)


public static Matcher unwrap(final Matcher matcher)
    {
        if (matcher instanceof ProxyMatcher) {
            final ProxyMatcher proxyMatcher = (ProxyMatcher) matcher;
            if (proxyMatcher.dirty)
                proxyMatcher.apply();
            return proxyMatcher.target == null ? proxyMatcher
                : proxyMatcher.target;
        }
        return matcher;
    }

public static Matcher unwrap ( final Matcher matcher ) { if ( matcher instanceof ProxyMatcher ) { final ProxyMatcher proxyMatcher = ( ProxyMatcher ) matcher ; if ( proxyMatcher . dirty ) proxyMatcher . apply ( ) ; return proxyMatcher . target == null ? proxyMatcher : proxyMatcher . target ; } return matcher ; }

Retrieves the innermost Matcher that is not a ProxyMatcher.

@param matcher the matcher to unwrap
@return the given instance if it is not a ProxyMatcher, otherwise the innermost non-proxy Matcher

Retrieves the innermost Matcher that is not a ProxyMatcher .


public final boolean register(@Nonnull final Object listener)
    {
        bus.register(Objects.requireNonNull(listener));
        return true;
    }

public final boolean register ( @ Nonnull final Object listener ) { bus . register ( Objects . requireNonNull ( listener ) ) ; return true ; }

Register a listener to the event bus

@param listener the listener
@return always true

@see EventBus#register(Object)


public final boolean post(@Nonnull final Object object)
    {
        Objects.requireNonNull(object);
        bus.post(object);
        return true;
    }

public final boolean post ( @ Nonnull final Object object ) { Objects . requireNonNull ( object ) ; bus . post ( object ) ; return true ; }

Post an arbitrary, non null, object on the bus

@param object the object (must not be null)
@return always true

Post an arbitrary non null object on the bus


@Override
    public <V> MatcherContext<V> getSubContext(final MatcherContext<V> context)
    {
        return context.getSubContext(this);
    }

@ Override public < V > MatcherContext < V > getSubContext ( final MatcherContext < V > context ) { return context . getSubContext ( this ) ; }

default implementation is to simply delegate to the context


public Rule min(final int nrCycles)
    {
        Preconditions.checkArgument(nrCycles >= 0,
            "illegal repetition number specified (" + nrCycles
                + "), must be 0 or greater");
        return range(Range.atLeast(nrCycles));
    }

public
Rule
min
(
final
int
nrCycles
)
{
Preconditions
.
checkArgument
(
nrCycles
>=
0
,
"illegal repetition number specified ("
+
nrCycles
+
"), must be 0 or greater"
)
;
return
range
(
Range
.
atLeast
(
nrCycles
)
)
;
}

Return a rule with a minimum number of cycles to run

@param nrCycles the number of cycles
@return a rule
@throws IllegalArgumentException {@code nrCycles} is less than 0

@see Range#atLeast(Comparable)


public Rule max(final int nrCycles)
    {
        Preconditions.checkArgument(nrCycles >= 0,
            "illegal repetition number specified (" + nrCycles
                + "), must be 0 or greater");
        return range(Range.atMost(nrCycles));
    }

public
Rule
max
(
final
int
nrCycles
)
{
Preconditions
.
checkArgument
(
nrCycles
>=
0
,
"illegal repetition number specified ("
+
nrCycles
+
"), must be 0 or greater"
)
;
return
range
(
Range
.
atMost
(
nrCycles
)
)
;
}

Return a rule with a maximum number of cycles to run

@param nrCycles the number of cycles
@return a rule
@throws IllegalArgumentException {@code nrCycles} is less than 0

@see Range#atMost(Comparable)


public Rule times(final int nrCycles)
    {
        Preconditions.checkArgument(nrCycles >= 0,
            "illegal repetition number specified (" + nrCycles
                + "), must be 0 or greater");
        return range(Range.singleton(nrCycles));
    }

public
Rule
times
(
final
int
nrCycles
)
{
Preconditions
.
checkArgument
(
nrCycles
>=
0
,
"illegal repetition number specified ("
+
nrCycles
+
"), must be 0 or greater"
)
;
return
range
(
Range
.
singleton
(
nrCycles
)
)
;
}

Return a rule with an exact number of cycles to run

@param nrCycles the number of cycles
@return a rule
@throws IllegalArgumentException {@code nrCycles} is less than 0

@see Range#singleton(Comparable)


public Rule times(final int minCycles, final int maxCycles)
    {
        Preconditions.checkArgument(minCycles >= 0,
            "illegal repetition number specified (" + minCycles
                + "), must be 0 or greater");
        Preconditions.checkArgument(maxCycles >= minCycles,
            "illegal range specified (" + minCycles + ", " + maxCycles
                + "): maximum must be greater than minimum");
        return range(Range.closed(minCycles, maxCycles));
    }

Return a rule with both lower and upper bounds on the number of cycles

Note that the range of cycles to run is closed on both ends (that is,
the minimum and maximum number of cycles) are inclusive.

@param minCycles the minimum number of cycles
@param maxCycles the maximum number of cycles
@return a rule
@throws IllegalArgumentException minimum number of cycles is negative; or
maximum number of cycles is less than the minimum

@see Range#closed(Comparable, Comparable)


@Cached
    @DontLabel
    public Rule range(final Range<Integer> range)
    {
        Objects.requireNonNull(range, "range must not be null");

        final Range<Integer> realRange = normalizeRange(range);

        /*
         * We always have a lower bound
         */
        final int lowerBound = realRange.lowerEndpoint();

        /*
         * Handle the case where there is no upper bound
         */
        if (!realRange.hasUpperBound())
            return boundedDown(lowerBound);

        /*
         * There is an upper bound. Handle the case where it is 0 or 1. Since
         * the range is legal, we know that if it is 0, so is the lowerbound;
         * and if it is one, the lower bound is either 0 or 1.
         */
        final int upperBound = realRange.upperEndpoint();
        if (upperBound == 0)
            return parser.empty();
        if (upperBound == 1)
            return lowerBound == 0 ? parser.optional(rule) : rule;

        /*
         * So, upper bound is 2 or greater; return the appropriate matcher
         * according to what the lower bound is.
         *
         * Also, if the lower and upper bounds are equal, return a matcher doing
         * a fixed number of matches.
         */
        if (lowerBound == 0)
            return boundedUp(upperBound);

        return lowerBound == upperBound
            ? exactly(lowerBound)
            : boundedBoth(lowerBound, upperBound);
    }

/*
         * We always have a lower bound
         */

Core method for building a repeating matcher

This is the method which all other methods (min, max, times) delegate
to; among other things it is responsible for the logic of simplifying
matchers where possible.

The simplifications are as follows:

[0..0]: returns an {@link EmptyMatcher};

[0..1]: returns an {@link OptionalMatcher} with the rule as a
submatcher;

[1..1]: returns the rule itself.

If none of these apply, this method delegates as follows:

[n..+∞) for whatever n: delegates to {@link #boundedDown(int)};

[0..n] for n >= 2: delegates to {@link #boundedUp(int)};

[n..n] for n >= 2: delegates to {@link #exactly(int)};

[n..m] with 0 < n < m: delegates to {@link
#boundedBoth(int, int)}.

@param range the range
@return the final resulting rule


public static Characters allBut(final char... chars)
    {
        final int length = chars.length;
        if (length == 0)
            return ALL;
        final char[] array = Arrays.copyOf(chars, length);
        Arrays.sort(array);
        return new Characters(true, array);
    }

public static Characters allBut ( final char ... chars ) { final int length = chars . length ; if ( length == 0 ) return ALL ; final char [ ] array = Arrays . copyOf ( chars , length ) ; Arrays . sort ( array ) ; return new Characters ( true , array ) ; }

Creates a new Characters instance containing all characters minus the given ones.

@param chars the chars to NOT include
@return a new Characters object

Creates a new Characters instance containing all characters minus the given ones .


public List<JAXBElement<? extends DeploymentDescriptorType>> getDeploymentDescriptor() {
        if (deploymentDescriptor == null) {
            deploymentDescriptor = new ArrayList<JAXBElement<? extends DeploymentDescriptorType>>();
        }
        return this.deploymentDescriptor;
    }

public List < JAXBElement < ? extends DeploymentDescriptorType > > getDeploymentDescriptor ( ) { if ( deploymentDescriptor == null ) { deploymentDescriptor = new ArrayList < JAXBElement < ? extends DeploymentDescriptorType > > ( ) ; } return this . deploymentDescriptor ; }

Gets the value of the deploymentDescriptor property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the deploymentDescriptor property.

For example, to add a new item, do as follows:

getDeploymentDescriptor().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link DeploymentDescriptorFactory }{@code >}
{@link JAXBElement }{@code <}{@link Modules }{@code >}
{@link JAXBElement }{@code <}{@link DeploymentDescriptorType }{@code >}
{@link JAXBElement }{@code <}{@link StartAsOneOf }{@code >}
{@link JAXBElement }{@code <}{@link CustomTSMPlugInConfiguration }{@code >}
{@link JAXBElement }{@code <}{@link DiffExcludeFilter }{@code >}
{@link JAXBElement }{@code <}{@link ClassLoaderExtension }{@code >}
{@link JAXBElement }{@code <}{@link RequiresAuthentication }{@code >}
{@link JAXBElement }{@code <}{@link NameValuePairs }{@code >}
{@link JAXBElement }{@code <}{@link SupportsFaultTolerance }{@code >}
{@link JAXBElement }{@code <}{@link RequiredComponents }{@code >}

Gets the value of the deploymentDescriptor property .


public List<JAXBElement<? extends AuthenticationConfigurationType>> getAuthenticationConfiguration() {
        if (authenticationConfiguration == null) {
            authenticationConfiguration = new ArrayList<JAXBElement<? extends AuthenticationConfigurationType>>();
        }
        return this.authenticationConfiguration;
    }

public List < JAXBElement < ? extends AuthenticationConfigurationType > > getAuthenticationConfiguration ( ) { if ( authenticationConfiguration == null ) { authenticationConfiguration = new ArrayList < JAXBElement < ? extends AuthenticationConfigurationType > > ( ) ; } return this . authenticationConfiguration ; }

Gets the value of the authenticationConfiguration property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the authenticationConfiguration property.

For example, to add a new item, do as follows:

getAuthenticationConfiguration().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link CookieAuthenticationConfiguration }{@code >}
{@link JAXBElement }{@code <}{@link URLAuthenticationConfiguration }{@code >}
{@link JAXBElement }{@code <}{@link CustomAuthenticationConfiguration }{@code >}
{@link JAXBElement }{@code <}{@link WebServerAuthenticationConfiguration }{@code >}
{@link JAXBElement }{@code <}{@link AuthenticationConfigurationType }{@code >}
{@link JAXBElement }{@code <}{@link HttpSessionAuthenticationConfiguration }{@code >}

Gets the value of the authenticationConfiguration property .


private List<Bw> getBWServices() {
		List<Bw> result = new ArrayList<Bw>();

		for (JAXBElement<? extends ServiceType> jaxbElement : application.getServices().getBaseService()) {
			if (jaxbElement.getName().getLocalPart().equals("bw")) {
				result.add((Bw) jaxbElement.getValue());
			}
		}

		return result;
	}

private List < Bw > getBWServices ( ) { List < Bw > result = new ArrayList < Bw > ( ) ; for ( JAXBElement < ? extends ServiceType > jaxbElement : application . getServices ( ) . getBaseService ( ) ) { if ( jaxbElement . getName ( ) . getLocalPart ( ) . equals ( "bw" ) ) { result . add ( ( Bw ) jaxbElement . getValue ( ) ) ; } } return result ; }

This method retrieves the list of objects of type "BWServiceType".

This method retrieves the list of objects of type BWServiceType .


public void addMonitoringEventsToAllServices(Events events) {
		List<JAXBElement<? extends EventType>> events_ = events.getEvent();
		if (events_ != null && !events_.isEmpty()) {
			for (Bw service : this.getBWServices()) {
				Monitor monitor = service.getMonitor();
				if (monitor != null) {
					monitor.setEvents(events);
				}
			}
		}
	}

public void addMonitoringEventsToAllServices ( Events events ) { List < JAXBElement < ? extends EventType > > events_ = events . getEvent ( ) ; if ( events_ != null && ! events_ . isEmpty ( ) ) { for ( Bw service : this . getBWServices ( ) ) { Monitor monitor = service . getMonitor ( ) ; if ( monitor != null ) { monitor . setEvents ( events ) ; } } } }

Add <events> in <monitor> element of all <bw> elements.
@param events

Add &lt ; events > in &lt ; monitor > element of all &lt ; bw > elements .


public List<GlobalVariables.GlobalVariable> getGlobalVariable() {
        if (globalVariable == null) {
            globalVariable = new ArrayList<GlobalVariables.GlobalVariable>();
        }
        return this.globalVariable;
    }

public List < GlobalVariables . GlobalVariable > getGlobalVariable ( ) { if ( globalVariable == null ) { globalVariable = new ArrayList < GlobalVariables . GlobalVariable > ( ) ; } return this . globalVariable ; }

Gets the value of the globalVariable property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the globalVariable property.

For example, to add a new item, do as follows:

getGlobalVariable().add(newItem);

Objects of the following type(s) are allowed in the list
{@link GlobalVariables.GlobalVariable }

Gets the value of the globalVariable property .


public List<JAXBElement<? extends ServiceType>> getBaseService() {
        if (baseService == null) {
            baseService = new ArrayList<JAXBElement<? extends ServiceType>>();
        }
        return this.baseService;
    }

public List < JAXBElement < ? extends ServiceType > > getBaseService ( ) { if ( baseService == null ) { baseService = new ArrayList < JAXBElement < ? extends ServiceType > > ( ) ; } return this . baseService ; }

Gets the value of the baseService property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the baseService property.

For example, to add a new item, do as follows:

getBaseService().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link Bw }{@code >}
{@link JAXBElement }{@code <}{@link Service }{@code >}
{@link JAXBElement }{@code <}{@link ServiceType }{@code >}
{@link JAXBElement }{@code <}{@link Im }{@code >}
{@link JAXBElement }{@code <}{@link FormFlow }{@code >}
{@link JAXBElement }{@code <}{@link Adapter }{@code >}

Gets the value of the baseService property .


public List<JAXBElement<? extends EventType>> getEvent() {
        if (event == null) {
            event = new ArrayList<JAXBElement<? extends EventType>>();
        }
        return this.event;
    }

public List < JAXBElement < ? extends EventType > > getEvent ( ) { if ( event == null ) { event = new ArrayList < JAXBElement < ? extends EventType > > ( ) ; } return this . event ; }

Gets the value of the event property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the event property.

For example, to add a new item, do as follows:

getEvent().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link EventType }{@code >}
{@link JAXBElement }{@code <}{@link LogEvent }{@code >}
{@link JAXBElement }{@code <}{@link SuspendProcessEvent }{@code >}
{@link JAXBElement }{@code <}{@link FailureEvent }{@code >}


private void checkBWProject() throws MojoExecutionException {
		if (projectDirectory == null) {
			projectNotFound();
		} else if (!projectDirectory.exists() || !projectDirectory.isDirectory()) {
			projectNotFound();
		}
	}

private void checkBWProject ( ) throws MojoExecutionException { if ( projectDirectory == null ) { projectNotFound ( ) ; } else if ( ! projectDirectory . exists ( ) || ! projectDirectory . isDirectory ( ) ) { projectNotFound ( ) ; } }

This will check that the BW project specified in the POM project exists.

TODO : add additional checks about BW project integrity

@throws MojoExecutionException

This will check that the BW project specified in the POM project exists .


protected List<Dependency> readDependenciesFromFile(String resolvedFileName, String dependencyType) throws IOException {
		List<Dependency> dependencies = new ArrayList<Dependency>();

		File resolvedFile = new File(resolvedFileName);
		if (!resolvedFile.exists()) {
			return dependencies;
		}

		FileInputStream fstream = new FileInputStream(resolvedFile);
		DataInputStream ds = new DataInputStream(fstream);
		BufferedReader br = new BufferedReader(new InputStreamReader(ds));
		Pattern p = Pattern.compile("   (.*):(.*):" + dependencyType + ":(.*):(.*)"); // keep only selected type (projlib or jar or bw-ear) dependencies
		String strLine;
		while ((strLine = br.readLine()) != null) {
			Matcher m = p.matcher(strLine);
			if (m.matches()) {
				getLog().debug(m.group(0));

				String groupId = m.group(1);
				String artifactId = m.group(2);
				String version = m.group(3);
				String scope = m.group(4);

				// create the dependency
				Dependency dependency = new Dependency();
				dependency.setGroupId(groupId);
				dependency.setArtifactId(artifactId);
				dependency.setVersion(version);
				dependency.setType(dependencyType);
				dependency.setScope(scope);

				dependencies.add(dependency);
			}
		}
		br.close();

		return dependencies;
	}

This will read the dependencies from the 'resolved' file found in the
build directory. This file was created earlier in the build by the
'resolve-bw-dependencies' execution of the 'process-resources' phase.

@return The list of dependencies of type {@link dependencyType}
@throws IOException

This will read the dependencies from the resolved file found in the build directory . This file was created earlier in the build by the resolve - bw - dependencies execution of the process - resources phase .


protected void launchTIBCOBinary(File binary, List<File> tras, ArrayList<String> arguments, File workingDir, String errorMsg) throws IOException, MojoExecutionException {
		launchTIBCOBinary(binary, tras, arguments, workingDir, errorMsg, false, true);
	}

protected void launchTIBCOBinary ( File binary , List < File > tras , ArrayList < String > arguments , File workingDir , String errorMsg ) throws IOException , MojoExecutionException { launchTIBCOBinary ( binary , tras , arguments , workingDir , errorMsg , false , true ) ; }

Same as launchTIBCOBinary with 'fork=false' and 'synchronous=true'

Same as launchTIBCOBinary with fork = false and synchronous = true


public List<JAXBElement<? extends ActionType>> getAction() {
        if (action == null) {
            action = new ArrayList<JAXBElement<? extends ActionType>>();
        }
        return this.action;
    }

public List < JAXBElement < ? extends ActionType > > getAction ( ) { if ( action == null ) { action = new ArrayList < JAXBElement < ? extends ActionType > > ( ) ; } return this . action ; }

Gets the value of the action property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the action property.

For example, to add a new item, do as follows:

getAction().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link AlertAction }{@code >}
{@link JAXBElement }{@code <}{@link ActionType }{@code >}
{@link JAXBElement }{@code <}{@link CustomAction }{@code >}
{@link JAXBElement }{@code <}{@link EmailAction }{@code >}


protected boolean cleanDirectory(File directory) {
        if (directory.isDirectory() && directory.listFiles().length != 0) {
            for (File file : directory.listFiles()) {
                if (file.isFile()) {
                    file.delete();
                }
            }
        }
        return directory.delete();
    }

protected boolean cleanDirectory ( File directory ) { if ( directory . isDirectory ( ) && directory . listFiles ( ) . length != 0 ) { for ( File file : directory . listFiles ( ) ) { if ( file . isFile ( ) ) { file . delete ( ) ; } } } return directory . delete ( ) ; }

Delete all file of a directory and then delete this directory

@param directory
@return


public java.util.List<String> getFinal() {
        if (_final == null) {
            _final = new ArrayList<String>();
        }
        return this._final;
    }

public java . util . List < String > getFinal ( ) { if ( _final == null ) { _final = new ArrayList < String > ( ) ; } return this . _final ; }

Gets the value of the final property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the final property.

For example, to add a new item, do as follows:

getFinal().add(newItem);

Objects of the following type(s) are allowed in the list
{@link String }


public List<Rulebases.Rulebase> getRulebase() {
        if (rulebase == null) {
            rulebase = new ArrayList<Rulebases.Rulebase>();
        }
        return this.rulebase;
    }

public List < Rulebases . Rulebase > getRulebase ( ) { if ( rulebase == null ) { rulebase = new ArrayList < Rulebases . Rulebase > ( ) ; } return this . rulebase ; }

Gets the value of the rulebase property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the rulebase property.

For example, to add a new item, do as follows:

getRulebase().add(newItem);

Objects of the following type(s) are allowed in the list
{@link Rulebases.Rulebase }

Gets the value of the rulebase property .


private void addAlias(ArrayList<HashMap<String,Object>> list, String aliasName) {
		for (HashMap<String, Object> h : list) {
			String name = (String) h.get("name");
			if (name != null && name.equals(aliasName)) {
				return; // avoid duplicates
			}
		}
		HashMap<String, Object> h = new HashMap<String, Object>();
		h.put("isClasspathFile", Boolean.TRUE);
		h.put("name", aliasName);
		h.put("includeInDeployment", Boolean.TRUE);

		list.add(h);
	}

private
void
addAlias
(
ArrayList
<
HashMap
<
String
,
Object
>
>
list
,
String
aliasName
)
{
for
(
HashMap
<
String
,
Object
>
h
:
list
)
{
String
name
=
(
String
)
h
.
get
(
"name"
)
;
if
(
name
!=
&&
name
.
equals
(
aliasName
)
)
{
return
;
// avoid duplicates
}
}
HashMap
<
String
,
Object
>
h
=
new
HashMap
<
String
,
Object
>
(
)
;
h
.
put
(
"isClasspathFile"
,
Boolean
.
TRUE
)
;
h
.
put
(
"name"
,
aliasName
)
;
h
.
put
(
"includeInDeployment"
,
Boolean
.
TRUE
)
;
list
.
add
(
h
)
;
}

This method add an alias in the object used internally by TIBCO
BusinessWorks.

@param list, an object used internally by TIBCO BusinessWorks.
@param aliasName, the name of the alias as normalized b
{@link AbstractBWMojo}.

This method add an alias in the object used internally by TIBCO BusinessWorks .


public void processFile(File f) throws MojoExecutionException {
		try {
			RepositoryModel repositoryModel = new RepositoryModel(f);

			ArrayList<HashMap<String, Object>> aliases = readXMLBean(repositoryModel, f);

			// reset old references
			if (!keepOriginalAliasLib) {
				aliases.clear();
			}

			// adding the JAR dependencies
			for (Dependency dependency : jarDependencies) {
				addAlias(aliases, getJarAlias(dependency, false));
			}

			writeXMLBean(repositoryModel, f, aliases);
		} catch (Exception e) {
			throw new MojoExecutionException(e.getMessage(), e);
		}
	}

public
void
processFile
(
File
f
)
throws
MojoExecutionException
{
try
{
RepositoryModel
repositoryModel
=
new
RepositoryModel
(
f
)
;
ArrayList
<
HashMap
<
String
,
Object
>
>
aliases
=
readXMLBean
(
repositoryModel
,
f
)
;
// reset old references
if
(
!
keepOriginalAliasLib
)
{
aliases
.
clear
(
)
;
}
// adding the JAR dependencies
for
(
Dependency
dependency
:
jarDependencies
)
{
addAlias
(
aliases
,
getJarAlias
(
dependency
,
false
)
)
;
}
writeXMLBean
(
repositoryModel
,
f
,
aliases
)
;
}
catch
(
Exception
e
)
{
throw
new
MojoExecutionException
(
e
.
getMessage
(
)
,
e
)
;
}
}

This method adds the JAR aliases to a ".aliaslib" file

@param f, the ".aliaslib" file to update
@throws MojoExecutionException

This method adds the JAR aliases to a . aliaslib file


public List<JAXBElement<? extends TExtensibleAttributesDocumented>> getRest() {
        if (rest == null) {
            rest = new ArrayList<JAXBElement<? extends TExtensibleAttributesDocumented>>();
        }
        return this.rest;
    }

public List < JAXBElement < ? extends TExtensibleAttributesDocumented > > getRest ( ) { if ( rest == null ) { rest = new ArrayList < JAXBElement < ? extends TExtensibleAttributesDocumented > > ( ) ; } return this . rest ; }

Gets the rest of the content model.

You are getting this "catch-all" property because of the following reason:
The field name "Output" is used by two different parts of a schema. See:
line 217 of file:/C:/temp/tibco_xsd/bw/wsdl.xsd
line 209 of file:/C:/temp/tibco_xsd/bw/wsdl.xsd

To get rid of this property, apply a property customization to one
of both of the following declarations to change their names:
Gets the value of the rest property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the rest property.

For example, to add a new item, do as follows:

getRest().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link TParam }{@code >}
{@link JAXBElement }{@code <}{@link TParam }{@code >}
{@link JAXBElement }{@code <}{@link TFault }{@code >}


public List<JAXBElement<? extends NVPairType>> getNVPair() {
        if (nvPair == null) {
            nvPair = new ArrayList<JAXBElement<? extends NVPairType>>();
        }
        return this.nvPair;
    }

public List < JAXBElement < ? extends NVPairType > > getNVPair ( ) { if ( nvPair == null ) { nvPair = new ArrayList < JAXBElement < ? extends NVPairType > > ( ) ; } return this . nvPair ; }

Gets the value of the nvPair property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the nvPair property.

For example, to add a new item, do as follows:

getNVPair().add(newItem);

Objects of the following type(s) are allowed in the list
{@link JAXBElement }{@code <}{@link NVPairType }{@code >}
{@link JAXBElement }{@code <}{@link NameValuePairInteger }{@code >}
{@link JAXBElement }{@code <}{@link NameValuePairPassword }{@code >}
{@link JAXBElement }{@code <}{@link NameValuePairBoolean }{@code >}
{@link JAXBElement }{@code <}{@link NameValuePair }{@code >}


public static void addDependency(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
		Model model = getModelFromPOM(pom, logger);

		model.addDependency(dependency);

		writeModelToPOM(model, pom, logger);
	}

public static void addDependency ( File pom , Dependency dependency , Log logger ) throws IOException , XmlPullParserException { Model model = getModelFromPOM ( pom , logger ) ; model . addDependency ( dependency ) ; writeModelToPOM ( model , pom , logger ) ; }

Add the Maven dependency to a POM file.

@param pom
@param dependency
@throws IOException
@throws XmlPullParserException

Add the Maven dependency to a POM file .


public static void removeDependency(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
		Model model = getModelFromPOM(pom, logger);

		for (Iterator<Dependency> it = model.getDependencies().iterator(); it.hasNext();){
			if (dependenciesEqual(it.next(), dependency)) {
				it.remove();
			}
		}

		writeModelToPOM(model, pom, logger);
	}

public static void removeDependency ( File pom , Dependency dependency , Log logger ) throws IOException , XmlPullParserException { Model model = getModelFromPOM ( pom , logger ) ; for ( Iterator < Dependency > it = model . getDependencies ( ) . iterator ( ) ; it . hasNext ( ) ; ) { if ( dependenciesEqual ( it . next ( ) , dependency ) ) { it . remove ( ) ; } } writeModelToPOM ( model , pom , logger ) ; }

Remove the Maven dependency from a POM file.

@param pom
@param dependency
@throws IOException
@throws XmlPullParserException

Remove the Maven dependency from a POM file .


private static boolean dependencyExists(Dependency dependency, List<Dependency> dependencies) {
		for (Dependency d : dependencies) {
			if (dependenciesEqual(dependency, d)) {
				return true;
			}
		}
		return false;

	}

private static boolean dependencyExists ( Dependency dependency , List < Dependency > dependencies ) { for ( Dependency d : dependencies ) { if ( dependenciesEqual ( dependency , d ) ) { return true ; } } return false ; }

Check whether a dependency exists in a list of dependencies.

@param dependency
@param dependencies
@return true if the dependency exists in dependencies list

Check whether a dependency exists in a list of dependencies .


public static boolean dependencyExists(File pom, Dependency dependency, Log logger) throws IOException, XmlPullParserException {
		Model model = getModelFromPOM(pom, logger);

		return dependencyExists(dependency, model.getDependencies());
	}

public static boolean dependencyExists ( File pom , Dependency dependency , Log logger ) throws IOException , XmlPullParserException { Model model = getModelFromPOM ( pom , logger ) ; return dependencyExists ( dependency , model . getDependencies ( ) ) ; }

Check whether a dependency exists in a POM.

@param pom
@param dependency
@param logger
@return true if the dependency exists in the POM
@throws IOException
@throws XmlPullParserException

Check whether a dependency exists in a POM .


public static void addProjectAsModule(File pom, String relativePath, String profileId, Log logger) throws IOException, XmlPullParserException {
		if (relativePath == null) return;

		Model model = getModelFromPOM(pom, logger);

		relativePath = relativePath.replace("\\", "/");

		if (profileId != null && !profileId.isEmpty()) {
			Profile p = getProfile(model, profileId);
			if (p != null) {
				p.addModule(relativePath);
			}
		} else {
			model.addModule(relativePath);
		}

		writeModelToPOM(model, pom, logger);
	}

public static void addProjectAsModule ( File pom , String relativePath , String profileId , Log logger ) throws IOException , XmlPullParserException { if ( relativePath == null ) return ; Model model = getModelFromPOM ( pom , logger ) ; relativePath = relativePath . replace ( "\\" , "/" ) ; if ( profileId != null && ! profileId . isEmpty ( ) ) { Profile p = getProfile ( model , profileId ) ; if ( p != null ) { p . addModule ( relativePath ) ; } } else { model . addModule ( relativePath ) ; } writeModelToPOM ( model , pom , logger ) ; }

Add a project as a module.

@param pom
@param relativePath
@param logger
@throws IOException
@throws XmlPullParserException


public static boolean moduleExists(File pom, String relativePath, String profileId, Log logger) throws IOException, XmlPullParserException {
		if (relativePath == null) return false;

		Model model = getModelFromPOM(pom, logger);

		relativePath = relativePath.replace("\\", "/");

		if (profileId != null && !profileId.isEmpty()) {
			Profile p = getProfile(model, profileId);
			if (p != null) {
				return p.getModules().indexOf(relativePath) >= 0;
			}
		} else {
			return model.getModules().indexOf(relativePath) >= 0;
		}

		return false;
	}

public static boolean moduleExists ( File pom , String relativePath , String profileId , Log logger ) throws IOException , XmlPullParserException { if ( relativePath == null ) return false ; Model model = getModelFromPOM ( pom , logger ) ; relativePath = relativePath . replace ( "\\" , "/" ) ; if ( profileId != null && ! profileId . isEmpty ( ) ) { Profile p = getProfile ( model , profileId ) ; if ( p != null ) { return p . getModules ( ) . indexOf ( relativePath ) >= 0 ; } } else { return model . getModules ( ) . indexOf ( relativePath ) >= 0 ; } return false ; }

Check whether a module exists in a POM.

@param rootPOM
@param relative
@param log
@return
@throws XmlPullParserException
@throws IOException

Check whether a module exists in a POM .


protected File getArtifactFile(File basedir, String finalName, String classifier) {
        if (classifier == null) {
            classifier = "";
        } else if (classifier.trim().length() > 0 && !classifier.startsWith("-")) {
            classifier = "-" + classifier;
        }

        return new File(basedir, finalName + classifier + getArtifactFileExtension());
    }

protected File getArtifactFile ( File basedir , String finalName , String classifier ) { if ( classifier == null ) { classifier = "" ; } else if ( classifier . trim ( ) . length ( ) > 0 && ! classifier . startsWith ( "-" ) ) { classifier = "-" + classifier ; } return new File ( basedir , finalName + classifier + getArtifactFileExtension ( ) ) ; }

Retrieves the full path of the artifact that will be created.

@param basedir, the directory where the artifact will be created
@param finalName, the name of the artifact, without file extension
@param classifier
@return a {@link File} object with the path of the artifact

Retrieves the full path of the artifact that will be created .


public void execute() throws MojoExecutionException {

		if (this.resources.size() == 0) {
			throw new MojoExecutionException("No resources configured");
		}

		// Prefered to count error instead of failing on the first one.
		int errCount = 0;

		// Iterate on all configured resources.
		for (final XPathResource r : this.resources) {
			try {
				classBytesToBWJavaXPath(r);
			} catch (Exception e) {
				super.getLog().error(e);
				errCount++;
			}
		}
		if (errCount > 0) {
			throw new MojoExecutionException("There was " + errCount
					+ " error(s) during goal execution, check above.");
		}
	}


protected String extractFileContent(final String filename)
			throws IOException {
		final StringBuilder sb = new StringBuilder();
		String temp = "";
		final BufferedReader bufferedReader = new BufferedReader(
				new FileReader(filename));
		try {
			while (temp != null) {
				temp = bufferedReader.readLine();
				if (temp != null) {
					sb.append(temp);
				}
			}
			return sb.toString();
		} finally {
			bufferedReader.close();
		}
	}

protected String extractFileContent ( final String filename ) throws IOException { final StringBuilder sb = new StringBuilder ( ) ; String temp = "" ; final BufferedReader bufferedReader = new BufferedReader ( new FileReader ( filename ) ) ; try { while ( temp != null ) { temp = bufferedReader . readLine ( ) ; if ( temp != null ) { sb . append ( temp ) ; } } return sb . toString ( ) ; } finally { bufferedReader . close ( ) ; } }

Reads the complete content of the javaxpath file.

@param filename
@return
@throws IOException

Reads the complete content of the javaxpath file .


private void updateRepoInstances() {
		RepoInstances repoInstances = application.getRepoInstances();

		RvRepoInstance rvRepoInstance = repoInstances.getRvRepoInstance();
		rvRepoInstance.setDiscoveryTimout(BigInteger.valueOf(repoRvDiscoveryTimeout));
		rvRepoInstance.setTimeout(BigInteger.valueOf(repoRvTimeout));
		rvRepoInstance.setDaemon(repoRvDaemon);
		rvRepoInstance.setService(repoRvService);
		rvRepoInstance.setNetwork(repoRvNetwork);
		rvRepoInstance.setRegionalSubject(repoRvRegionalSubject);
		rvRepoInstance.setOperationRetry(BigInteger.valueOf(repoRvOperationRetry));
		rvRepoInstance.setExtraPropertyFile(repoRvExtraPropertyFile);
		rvRepoInstance.setServer(repoRvServer);
		rvRepoInstance.setUser(repoRvUser);
		rvRepoInstance.setPassword(repoRvPassword);

		HttpRepoInstance httpRepoInstance = repoInstances.getHttpRepoInstance();
		httpRepoInstance.setTimeout(BigInteger.valueOf(repoHttpTimeout));
		httpRepoInstance.setUrl(repoHttpUrl);
		httpRepoInstance.setServer(repoHttpServer);
		httpRepoInstance.setUser(repoHttpUser);
		httpRepoInstance.setPassword(repoHttpPassword);
		httpRepoInstance.setExtraPropertyFile(repoHttpExtraPropertyFile);

		LocalRepoInstance localRepoInstance = repoInstances.getLocalRepoInstance();
		EncodingType encoding;
		try {
			encoding = EncodingType.valueOf(repoLocalEncoding);
		} catch (IllegalArgumentException e) {
			encoding = EncodingType.UTF_8;
		}
		localRepoInstance.setEncoding(encoding);

		repoInstances.setRvRepoInstance(rvRepoInstance);
		repoInstances.setHttpRepoInstance(httpRepoInstance);
		repoInstances.setLocalRepoInstance(localRepoInstance);

		RepoType repoType;
		try {
			repoType = RepoType.valueOf(repoSelectInstance.toUpperCase());
		} catch (IllegalArgumentException e) {
			repoType = RepoType.LOCAL;
		}
		repoInstances.setSelected(repoType);
	}

private void updateRepoInstances ( ) { RepoInstances repoInstances = application . getRepoInstances ( ) ; RvRepoInstance rvRepoInstance = repoInstances . getRvRepoInstance ( ) ; rvRepoInstance . setDiscoveryTimout ( BigInteger . valueOf ( repoRvDiscoveryTimeout ) ) ; rvRepoInstance . setTimeout ( BigInteger . valueOf ( repoRvTimeout ) ) ; rvRepoInstance . setDaemon ( repoRvDaemon ) ; rvRepoInstance . setService ( repoRvService ) ; rvRepoInstance . setNetwork ( repoRvNetwork ) ; rvRepoInstance . setRegionalSubject ( repoRvRegionalSubject ) ; rvRepoInstance . setOperationRetry ( BigInteger . valueOf ( repoRvOperationRetry ) ) ; rvRepoInstance . setExtraPropertyFile ( repoRvExtraPropertyFile ) ; rvRepoInstance . setServer ( repoRvServer ) ; rvRepoInstance . setUser ( repoRvUser ) ; rvRepoInstance . setPassword ( repoRvPassword ) ; HttpRepoInstance httpRepoInstance = repoInstances . getHttpRepoInstance ( ) ; httpRepoInstance . setTimeout ( BigInteger . valueOf ( repoHttpTimeout ) ) ; httpRepoInstance . setUrl ( repoHttpUrl ) ; httpRepoInstance . setServer ( repoHttpServer ) ; httpRepoInstance . setUser ( repoHttpUser ) ; httpRepoInstance . setPassword ( repoHttpPassword ) ; httpRepoInstance . setExtraPropertyFile ( repoHttpExtraPropertyFile ) ; LocalRepoInstance localRepoInstance = repoInstances . getLocalRepoInstance ( ) ; EncodingType encoding ; try { encoding = EncodingType . valueOf ( repoLocalEncoding ) ; } catch ( IllegalArgumentException e ) { encoding = EncodingType . UTF_8 ; } localRepoInstance . setEncoding ( encoding ) ; repoInstances . setRvRepoInstance ( rvRepoInstance ) ; repoInstances . setHttpRepoInstance ( httpRepoInstance ) ; repoInstances . setLocalRepoInstance ( localRepoInstance ) ; RepoType repoType ; try { repoType = RepoType . valueOf ( repoSelectInstance . toUpperCase ( ) ) ; } catch ( IllegalArgumentException e ) { repoType = RepoType . LOCAL ; } repoInstances . setSelected ( repoType ) ; }

This will update the <repoInstances> element.

This will update the &lt ; repoInstances > element .


public List<java.lang.Object> getAny() {
        if (any == null) {
            any = new ArrayList<java.lang.Object>();
        }
        return this.any;
    }

public List < java . lang . Object > getAny ( ) { if ( any == null ) { any = new ArrayList < java . lang . Object > ( ) ; } return this . any ; }

Gets the value of the any property.

This accessor method returns a reference to the live list,
not a snapshot. Therefore any modification you make to the
returned list will be present inside the JAXB object.
This is why there is not a set method for the any property.

For example, to add a new item, do as follows:

getAny().add(newItem);

Objects of the following type(s) are allowed in the list
{@link Element }
{@link java.lang.Object }


private static <T> T newInstance(Class<T> clazz, Object... params) throws SQLException {
        try {
            if (params == null || params.length == 0) {
                return clazz.newInstance();
            } else {
                for (Constructor<?> ctor : clazz.getConstructors()) {
                    if (ctor.getParameterTypes().length != params.length) {
                        continue;
                    }
                    int paramIndex = 0;
                    for (Class<?> paramType : ctor.getParameterTypes()) {
                        if (!paramType.isInstance(params[paramIndex])) {
                            break;
                        }
                        paramIndex++;
                    }
                    if (paramIndex != params.length) {
                        continue;
                    }
                    @SuppressWarnings("unchecked")
                    Constructor<T> theCtor = (Constructor<T>) ctor;
                    return theCtor.newInstance(params);
                }
                throw new SQLException("Constructor not found for " + clazz);
            }
        } catch (ReflectiveOperationException reflectiveOperationException) {
            throw new SQLException(reflectiveOperationException);
        }
    }

private
static
<
T
>
T
newInstance
(
Class
<
T
>
clazz
,
Object
...
params
)
throws
SQLException
{
try
{
if
(
params
==
||
params
.
length
==
0
)
{
return
clazz
.
newInstance
(
)
;
}
else
{
for
(
Constructor
<
>
ctor
:
clazz
.
getConstructors
(
)
)
{
if
(
ctor
.
getParameterTypes
(
)
.
length
!=
params
.
length
)
{
continue
;
}
int
paramIndex
=
0
;
for
(
Class
<
>
paramType
:
ctor
.
getParameterTypes
(
)
)
{
if
(
!
paramType
.
isInstance
(
params
[
paramIndex
]
)
)
{
break
;
}
paramIndex
++
;
}
if
(
paramIndex
!=
params
.
length
)
{
continue
;
}
@
SuppressWarnings
(
"unchecked"
)
Constructor
<
T
>
theCtor
=
(
Constructor
<
T
>
)
ctor
;
return
theCtor
.
newInstance
(
params
)
;
}
throw
new
SQLException
(
"Constructor not found for "
+
clazz
)
;
}
}
catch
(
ReflectiveOperationException
reflectiveOperationException
)
{
throw
new
SQLException
(
reflectiveOperationException
)
;
}
}

Instantiate a new object of type T

@param clazz  Object class
@param params Constructor args
@param <T>    Object type
@return New object


public <T> Class<T> createClass() {
        return (Class<T>) Proxy.getProxyClass(getClassLoader(), getInterfaces());
    }

public < T > Class < T > createClass ( ) { return ( Class < T > ) Proxy . getProxyClass ( getClassLoader ( ) , getInterfaces ( ) ) ; }

Create proxy class
@param <T> Expected proxy type
@return Class of proxy for given classloader and interfaces


public <T> Constructor<T> createConstructor() {
        try {
            return this.<T>createClass().getConstructor(InvocationHandler.class);
        } catch (NoSuchMethodException noSuchMethodException) {
            throw new ProxyException(noSuchMethodException);
        }
    }

public < T > Constructor < T > createConstructor ( ) { try { return this . < T > createClass ( ) . getConstructor ( InvocationHandler . class ) ; } catch ( NoSuchMethodException noSuchMethodException ) { throw new ProxyException ( noSuchMethodException ) ; } }

Create proxy constructor

Create proxy class
@param <T> Expected proxy type
@return Constructor of proxy for given classloader and interfaces


public Timer.Context startStatementExecuteTimer(Query query) {
        ensureSqlId(query);
        String name = metricNamingStrategy.getStatementExecuteTimer(query.getSql(), query.getSqlId());
        return startTimer(name);
    }

public Timer . Context startStatementExecuteTimer ( Query query ) { ensureSqlId ( query ) ; String name = metricNamingStrategy . getStatementExecuteTimer ( query . getSql ( ) , query . getSqlId ( ) ) ; return startTimer ( name ) ; }

Start Timer when statement is executed

@param query SQL query
@return Started timer context or null


public Timer.Context startCallableStatementLifeTimer(Query query) {
        ensureSqlId(query);
        String name = metricNamingStrategy.getCallableStatementLifeTimer(query.getSql(), query.getSqlId());
        return startTimer(name);
    }

public Timer . Context startCallableStatementLifeTimer ( Query query ) { ensureSqlId ( query ) ; String name = metricNamingStrategy . getCallableStatementLifeTimer ( query . getSql ( ) , query . getSqlId ( ) ) ; return startTimer ( name ) ; }

Start Timer when callable statement is created

@return Started timer context or null


public Timer.Context startResultSetLifeTimer(Query query) {
        ensureSqlId(query);
        String name = metricNamingStrategy.getResultSetLifeTimer(query.getSql(), query.getSqlId());
        return startTimer(name);
    }

public Timer . Context startResultSetLifeTimer ( Query query ) { ensureSqlId ( query ) ; String name = metricNamingStrategy . getResultSetLifeTimer ( query . getSql ( ) , query . getSqlId ( ) ) ; return startTimer ( name ) ; }

Start Timer when result set is created

@return Started timer context or null


public void markResultSetRowMeter(Query query) {
        ensureSqlId(query);
        String name = metricNamingStrategy.getResultSetRowMeter(query.getSql(), query.getSqlId());
        markMeter(name);
    }

public void markResultSetRowMeter ( Query query ) { ensureSqlId ( query ) ; String name = metricNamingStrategy . getResultSetRowMeter ( query . getSql ( ) , query . getSqlId ( ) ) ; markMeter ( name ) ; }


private <T> T newProxy(JdbcProxyHandler<T> proxyHandler) {
        return proxyFactory.newProxy(proxyHandler, proxyHandler.getProxyClass());
    }

private < T > T newProxy ( JdbcProxyHandler < T > proxyHandler ) { return proxyFactory . newProxy ( proxyHandler , proxyHandler . getProxyClass ( ) ) ; }

Create a proxy for given JDBC proxy handler
@param <T> Proxy type
@param proxyHandler Proxy handler
@return Proxy


public Connection wrapConnection(Connection wrappedConnection) {
        Timer.Context lifeTimerContext = metricHelper.startConnectionLifeTimer();
        return newProxy(new ConnectionProxyHandler(wrappedConnection, this, lifeTimerContext));
    }

public Connection wrapConnection ( Connection wrappedConnection ) { Timer . Context lifeTimerContext = metricHelper . startConnectionLifeTimer ( ) ; return newProxy ( new ConnectionProxyHandler ( wrappedConnection , this , lifeTimerContext ) ) ; }

Wrap a connection to monitor it.

@param wrappedConnection Connection to wrap
@return Wrapped connection


public Statement wrapStatement(Statement statement) {
        Timer.Context lifeTimerContext = getMetricHelper().startStatementLifeTimer();
        return newProxy(new StatementProxyHandler(statement, this, lifeTimerContext));
    }

public Statement wrapStatement ( Statement statement ) { Timer . Context lifeTimerContext = getMetricHelper ( ) . startStatementLifeTimer ( ) ; return newProxy ( new StatementProxyHandler ( statement , this , lifeTimerContext ) ) ; }

Wrap a simple statement to monitor it.

@param statement Statement to wrap
@return Wrapped statement


public PreparedStatement wrapPreparedStatement(PreparedStatement preparedStatement, String sql) {
        Query query = new Query(sql);
        Timer.Context lifeTimerContext = getMetricHelper().startPreparedStatementLifeTimer(query);
        return newProxy(new PreparedStatementProxyHandler(preparedStatement, this, query, lifeTimerContext));
    }

public PreparedStatement wrapPreparedStatement ( PreparedStatement preparedStatement , String sql ) { Query query = new Query ( sql ) ; Timer . Context lifeTimerContext = getMetricHelper ( ) . startPreparedStatementLifeTimer ( query ) ; return newProxy ( new PreparedStatementProxyHandler ( preparedStatement , this , query , lifeTimerContext ) ) ; }

Wrap a prepared statement to monitor it.

@param preparedStatement Prepared statement to wrap
@param sql SQL
@return Wrapped prepared statement

Wrap a prepared statement to monitor it .


public CallableStatement wrapCallableStatement(CallableStatement callableStatement, String sql) {
        Query query = new Query(sql);
        Timer.Context lifeTimerContext = getMetricHelper().startCallableStatementLifeTimer(query);
        return newProxy(new CallableStatementProxyHandler(callableStatement, this, query, lifeTimerContext));
    }

public CallableStatement wrapCallableStatement ( CallableStatement callableStatement , String sql ) { Query query = new Query ( sql ) ; Timer . Context lifeTimerContext = getMetricHelper ( ) . startCallableStatementLifeTimer ( query ) ; return newProxy ( new CallableStatementProxyHandler ( callableStatement , this , query , lifeTimerContext ) ) ; }

Wrap a callable statement to monitor it.

@param callableStatement Prepared statement to wrap
@param sql SQL
@return Wrapped prepared statement

Wrap a callable statement to monitor it .


private Class<? extends ResultSet> getResultSetType(ResultSet resultSet) {
        Class<? extends ResultSet> resultSetType;
        if (resultSet instanceof RowSet) {
            if (resultSet instanceof CachedRowSet) {
                if (resultSet instanceof WebRowSet) {
                    if (resultSet instanceof FilteredRowSet) {
                        resultSetType = FilteredRowSet.class;
                    } else if (resultSet instanceof JoinRowSet) {
                        resultSetType = JoinRowSet.class;
                    } else {
                        resultSetType = WebRowSet.class;
                    }
                } else {
                    resultSetType = CachedRowSet.class;
                }
            } else if (resultSet instanceof JdbcRowSet) {
                resultSetType = JdbcRowSet.class;
            } else {
                resultSetType = RowSet.class;
            }
        } else {
            resultSetType = ResultSet.class;
        }
        return resultSetType;
    }

private Class < ? extends ResultSet > getResultSetType ( ResultSet resultSet ) { Class < ? extends ResultSet > resultSetType ; if ( resultSet instanceof RowSet ) { if ( resultSet instanceof CachedRowSet ) { if ( resultSet instanceof WebRowSet ) { if ( resultSet instanceof FilteredRowSet ) { resultSetType = FilteredRowSet . class ; } else if ( resultSet instanceof JoinRowSet ) { resultSetType = JoinRowSet . class ; } else { resultSetType = WebRowSet . class ; } } else { resultSetType = CachedRowSet . class ; } } else if ( resultSet instanceof JdbcRowSet ) { resultSetType = JdbcRowSet . class ; } else { resultSetType = RowSet . class ; } } else { resultSetType = ResultSet . class ; } return resultSetType ; }

Determine the interface implemented by this result set

@param resultSet Result set


protected String[] buildArgs() {
		String result[] = new String[0];
		List<String> args = new ArrayList<String>();
		if (lang != null && lang.length() > 0) {
			args.add(flagify(CowsayCli.Opt.LANG.toString()));
			args.add(lang);
		}
		if (html) {
			args.add(flagify(CowsayCli.Opt.HTML.toString()));
		}
		if (alt != null && alt.length() > 0) {
			args.add(flagify(CowsayCli.Opt.ALT.toString()));
			args.add(alt);
		}
		if (wrap != null) {
			args.add(flagify(CowsayCli.Opt.WRAP_AT.toString()));
			args.add(wrap);
		}
		buildFaceArgs(args);
		args.add(message);
		return args.toArray(result);
	}

protected String [ ] buildArgs ( ) { String result [ ] = new String [ 0 ] ; List < String > args = new ArrayList < String > ( ) ; if ( lang != null && lang . length ( ) > 0 ) { args . add ( flagify ( CowsayCli . Opt . LANG . toString ( ) ) ) ; args . add ( lang ) ; } if ( html ) { args . add ( flagify ( CowsayCli . Opt . HTML . toString ( ) ) ) ; } if ( alt != null && alt . length ( ) > 0 ) { args . add ( flagify ( CowsayCli . Opt . ALT . toString ( ) ) ) ; args . add ( alt ) ; } if ( wrap != null ) { args . add ( flagify ( CowsayCli . Opt . WRAP_AT . toString ( ) ) ) ; args . add ( wrap ) ; } buildFaceArgs ( args ) ; args . add ( message ) ; return args . toArray ( result ) ; }

Build an args array that can be passed to cowsay.
@return commandline args

Build an args array that can be passed to cowsay .


private void buildFaceArgs(final List<String> args) {
		if (mode != null && CowFace.isKnownMode(mode)) {
			args.add(flagify(mode));
		} else {
			if (eyes != null) {
				args.add(flagify(CowsayCli.Opt.EYES.toString()));
				args.add(eyes);
			}
			if (tongue != null) {
				args.add(flagify(CowsayCli.Opt.TONGUE.toString()));
				args.add(tongue);
			}
			if (cowfile != null) {
				args.add(flagify(CowsayCli.Opt.COWFILE.toString()));
				args.add(cowfile);
			}
		}
	}

private void buildFaceArgs ( final List < String > args ) { if ( mode != null && CowFace . isKnownMode ( mode ) ) { args . add ( flagify ( mode ) ) ; } else { if ( eyes != null ) { args . add ( flagify ( CowsayCli . Opt . EYES . toString ( ) ) ) ; args . add ( eyes ) ; } if ( tongue != null ) { args . add ( flagify ( CowsayCli . Opt . TONGUE . toString ( ) ) ) ; args . add ( tongue ) ; } if ( cowfile != null ) { args . add ( flagify ( CowsayCli . Opt . COWFILE . toString ( ) ) ) ; args . add ( cowfile ) ; } } }

Face specific flags, either a face mode or face customizations.
@param args The arg line to add to.

Face specific flags either a face mode or face customizations .


public String execute() throws IllegalStateException {
		validate();
		String[] args = buildArgs();
		String result;
		if (think) {
			result = Cowsay.think(args);
		} else {
			result = Cowsay.say(args);
		}
		return result;
	}

public String execute ( ) throws IllegalStateException { validate ( ) ; String [ ] args = buildArgs ( ) ; String result ; if ( think ) { result = Cowsay . think ( args ) ; } else { result = Cowsay . say ( args ) ; } return result ; }

Run cowsay with the provided properties.
@return The formatted cow message.
@throws IllegalStateException If mandatory properties have not been set.

Run cowsay with the provided properties .


@Override
	public void execute() throws BuildException {
		try {
			String moo = executor.execute();
			if (this.property != null && this.property.length() > 0) {
				getProject().setProperty(this.property, moo);
			} else {
				System.out.println(moo);
			}
		} catch (IllegalStateException ex) {
			throw new BuildException(ex.getMessage(), ex);
		}
	}

@ Override public void execute ( ) throws BuildException { try { String moo = executor . execute ( ) ; if ( this . property != null && this . property . length ( ) > 0 ) { getProject ( ) . setProperty ( this . property , moo ) ; } else { System . out . println ( moo ) ; } } catch ( IllegalStateException ex ) { throw new BuildException ( ex . getMessage ( ) , ex ) ; } }

Run cowsay with the provided attributes.
@throws BuildException If something goes wrong during execution.

Run cowsay with the provided attributes .


public static void setLanguage(final String language) {
		currentLocale = new Locale(language);
		messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
	}

public static void setLanguage ( final String language ) { currentLocale = new Locale ( language ) ; messages = ResourceBundle . getBundle ( "MessagesBundle" , currentLocale ) ; }

Set the language.
@param language A BCP47 language, e.g. "en", "fr".


protected static String getMessage(final String key) {
		if (messages == null) {
			setLanguage(DEFAULT_LANG);
		}
		return messages.getString(key);
	}

protected static String getMessage ( final String key ) { if ( messages == null ) { setLanguage ( DEFAULT_LANG ) ; } return messages . getString ( key ) ; }

Get a message in the correct language.
@param key The lookup key for the message.
@return The message in the correct language, if found, otherwise in the default language.


private static String sayOrThink(final String[] args, final boolean think) {
		try {
			boolean isThought = think;

			String wordwrap = null;
			CommandLine commandLine = CowsayCli.parseCmdArgs(args);
			if (commandLine != null) {
				if (commandLine.hasOption(CowsayCli.Opt.HELP.toString())) {
					CowsayCli.showCmdLineHelp();
				}
				else if (commandLine.hasOption(CowsayCli.Opt.LIST_COWS.toString())) {
					String[] files = Cowloader.listAllCowfiles();
					if (files != null) {
						return StringUtils.join(files, System.getProperty("line.separator"));
					}
				}
				else {
					String cowfileSpec = null;
					CowFace cowFace = null;

					if (commandLine.hasOption(CowsayCli.Opt.WRAP_AT.toString())) {
						wordwrap = commandLine.getOptionValue(CowsayCli.Opt.WRAP_AT.toString());
					}
					else if (commandLine.hasOption(CowsayCli.Opt.NOWRAP.toString())) {
						wordwrap = "0";
					}
					cowFace = getCowFaceByMode(commandLine);
					if (cowFace == null) {
						// if we are in here no modes were set
						if (commandLine.hasOption(CowsayCli.Opt.COWFILE.toString())) {
							cowfileSpec = commandLine.getOptionValue(CowsayCli.Opt.COWFILE.toString());
						}
						cowFace = getCowFace(commandLine);
					}

					if (commandLine.hasOption(CowsayCli.Opt.THINK.toString())) {
						isThought = true;
					}

					if (cowfileSpec == null) {
						cowfileSpec = Cowloader.DEFAULT_COW;
					}

					String cowTemplate = Cowloader.load(cowfileSpec);
					if (cowTemplate != null) {
						String moosages[] = commandLine.getArgs();
						String moosage = StringUtils.join(moosages, " ");
						if (moosage != null && moosage.length() > 0) {
							Message message = new Message(moosage, isThought);
							if (wordwrap != null) {
								message.setWordwrap(wordwrap);
							}
							String cow = CowFormatter.formatCow(cowTemplate, cowFace, message);
							cow = formatHtml(commandLine, cow, moosage, isThought);
							return cow;
						}
					}
				}
			}
		}
		catch (CowParseException ex) {
			Logger.getLogger(Cowsay.class.getName()).log(Level.SEVERE, null, ex);
		}
		return "";
	}

private
static
String
sayOrThink
(
final
String
[
]
args
,
final
boolean
think
)
{
try
{
boolean
isThought
=
think
;
String
wordwrap
=
;
CommandLine
commandLine
=
CowsayCli
.
parseCmdArgs
(
args
)
;
if
(
commandLine
!=
)
{
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
HELP
.
toString
(
)
)
)
{
CowsayCli
.
showCmdLineHelp
(
)
;
}
else
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
LIST_COWS
.
toString
(
)
)
)
{
String
[
]
files
=
Cowloader
.
listAllCowfiles
(
)
;
if
(
files
!=
)
{
return
StringUtils
.
join
(
files
,
System
.
getProperty
(
"line.separator"
)
)
;
}
}
else
{
String
cowfileSpec
=
;
CowFace
cowFace
=
;
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
WRAP_AT
.
toString
(
)
)
)
{
wordwrap
=
commandLine
.
getOptionValue
(
CowsayCli
.
Opt
.
WRAP_AT
.
toString
(
)
)
;
}
else
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
NOWRAP
.
toString
(
)
)
)
{
wordwrap
=
"0"
;
}
cowFace
=
getCowFaceByMode
(
commandLine
)
;
if
(
cowFace
==
)
{
// if we are in here no modes were set
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
COWFILE
.
toString
(
)
)
)
{
cowfileSpec
=
commandLine
.
getOptionValue
(
CowsayCli
.
Opt
.
COWFILE
.
toString
(
)
)
;
}
cowFace
=
getCowFace
(
commandLine
)
;
}
if
(
commandLine
.
hasOption
(
CowsayCli
.
Opt
.
THINK
.
toString
(
)
)
)
{
isThought
=
true
;
}
if
(
cowfileSpec
==
)
{
cowfileSpec
=
Cowloader
.
DEFAULT_COW
;
}
String
cowTemplate
=
Cowloader
.
load
(
cowfileSpec
)
;
if
(
cowTemplate
!=
)
{
String
moosages
[
]
=
commandLine
.
getArgs
(
)
;
String
moosage
=
StringUtils
.
join
(
moosages
,
" "
)
;
if
(
moosage
!=
&&
moosage
.
length
(
)
>
0
)
{
Message
message
=
new
Message
(
moosage
,
isThought
)
;
if
(
wordwrap
!=
)
{
message
.
setWordwrap
(
wordwrap
)
;
}
String
cow
=
CowFormatter
.
formatCow
(
cowTemplate
,
cowFace
,
message
)
;
cow
=
formatHtml
(
commandLine
,
cow
,
moosage
,
isThought
)
;
return
cow
;
}
}
}
}
}
catch
(
CowParseException
ex
)
{
Logger
.
getLogger
(
Cowsay
.
class
.
getName
(
)
)
.
log
(
Level
.
SEVERE
,
,
ex
)
;
}
return
""
;
}

Do some cowsaying or cowthinking.
@param args the command line arguments
@param think if true will think instead of say (the --cowthink flag can also invoke thinking)


private static String formatHtml(final CommandLine commandLine, final String plainCow, final String moosage,
									 final boolean isThought) {
		String cow = plainCow;
		if (commandLine.hasOption(CowsayCli.Opt.HTML.toString())) {
			cow = StringEscapeUtils.escapeHtml4(cow);
			cow = "

" + cow + "

";
			String alt;
			if (commandLine.hasOption(CowsayCli.Opt.ALT.toString())) {
				alt = commandLine.getOptionValue(CowsayCli.Opt.ALT.toString());
			}
			else {
				alt = isThought ? I18n.getMessage("altthink") : I18n.getMessage("altsay");

			}
			String escaped = StringEscapeUtils.escapeHtml4(moosage);
			cow += String.format(alt, escaped);
			cow += "

";
		}
		return cow;
	}

May apply HTML markup to the cow, if requested in the command line.
@param commandLine The command line with user options.
@param plainCow The cow formatted in plain text.
@param moosage The message the cow is saying.
@param isThought true if this is cowthink instead of cowsay.
@return Either the plaintext cow or an HTML marked up version, depending on command line.

May apply HTML markup to the cow if requested in the command line .


private static CowFace getCowFaceByMode(final CommandLine commandLine) {
		CowFace cowFace = null;
		Set<String> modes = CowFace.COW_MODES.keySet();
		for (String mode : modes) {
			if (commandLine.hasOption(mode)) {
				cowFace = CowFace.getByMode(mode);
				break;
			}
		}
		return cowFace;
	}

private static CowFace getCowFaceByMode ( final CommandLine commandLine ) { CowFace cowFace = null ; Set < String > modes = CowFace . COW_MODES . keySet ( ) ; for ( String mode : modes ) { if ( commandLine . hasOption ( mode ) ) { cowFace = CowFace . getByMode ( mode ) ; break ; } } return cowFace ; }

If a pre-defined cow mode has been set on the command line then use that face.
@param commandLine The command line with user options.
@return The cowface for the mode selected on the command line or null if no mode set.

If a pre - defined cow mode has been set on the command line then use that face .


private static CowFace getCowFace(final CommandLine commandLine) {
		CowFace cowFace;
		cowFace = new CowFace();
		if (commandLine.hasOption(CowsayCli.Opt.EYES.toString())) {
			cowFace.setEyes(commandLine.getOptionValue(CowsayCli.Opt.EYES.toString()));
		}
		if (commandLine.hasOption(CowsayCli.Opt.TONGUE.toString())) {
			cowFace.setTongue(commandLine.getOptionValue(CowsayCli.Opt.TONGUE.toString()));
		}
		return cowFace;
	}

private static CowFace getCowFace ( final CommandLine commandLine ) { CowFace cowFace ; cowFace = new CowFace ( ) ; if ( commandLine . hasOption ( CowsayCli . Opt . EYES . toString ( ) ) ) { cowFace . setEyes ( commandLine . getOptionValue ( CowsayCli . Opt . EYES . toString ( ) ) ) ; } if ( commandLine . hasOption ( CowsayCli . Opt . TONGUE . toString ( ) ) ) { cowFace . setTongue ( commandLine . getOptionValue ( CowsayCli . Opt . TONGUE . toString ( ) ) ) ; } return cowFace ; }

Get a regular cow face optionally formatted with custom eyes and tongue from the command line.
@param commandLine The command line with user options.
@return A regular cowface, possibly formatted with custom tongue and/or eyes.

Get a regular cow face optionally formatted with custom eyes and tongue from the command line .


private static String extractCowTemplate(final String cow) throws CowParseException {

		Matcher matcher = COWSTART_RE.matcher(cow);
		if (matcher.find(0)) {
			String result = matcher.replaceFirst("");
			return result;
		} else {
			throw new CowParseException("Could not parse cow " + cow);
		}
	}

private
static
String
extractCowTemplate
(
final
String
cow
)
throws
CowParseException
{
Matcher
matcher
=
COWSTART_RE
.
matcher
(
cow
)
;
if
(
matcher
.
find
(
0
)
)
{
String
result
=
matcher
.
replaceFirst
(
""
)
;
return
result
;
}
else
{
throw
new
CowParseException
(
"Could not parse cow "
+
cow
)
;
}
}

Extracts the ascii art part of the cowfile, removing any before or after PERL comments, variable assignments, weird EOC markers etc.
@param cow The raw cowfile content.
@return The ascii art portion of the cowfile.
@throws CowParseException if the cowfile cannot be parsed.

Extracts the ascii art part of the cowfile removing any before or after PERL comments variable assignments weird EOC markers etc .


public static String load(final String cowfileSpec) {
		String effectiveCowfileSpec = (cowfileSpec != null) ? cowfileSpec.trim() : DEFAULT_COW;
		if (effectiveCowfileSpec.length() > 0) {
			if (!effectiveCowfileSpec.endsWith(COWFILE_EXT)) {
				effectiveCowfileSpec += COWFILE_EXT;
			}
			InputStream cowInputStream;
			if (effectiveCowfileSpec.indexOf(File.separatorChar) >= 0) {
				cowInputStream = getCowFromPath(effectiveCowfileSpec);
			} else {
				cowInputStream = getCowFromCowPath(effectiveCowfileSpec);
			}
			if (cowInputStream == null) {
				// Maybe there should be a verbose mode where we log this sort of error instead of silently failing?
				cowInputStream = getCowFromResources(DEFAULT_COW + COWFILE_EXT);
			}
			if (cowInputStream != null) {
				String cow = cowInputStreamToString(cowInputStream);
				return cow;
			}
		}
		return null;  // should never happen
	}

Call this with the provided cowfileSpec - that is the value passed to `-f` on the commandline.

@param cowfileSpec If cowfileSpec contains a filepath separator it is interpreted as relative to CWD
otherwise the COWPATH will be searched. If not found on the COWPATH we will search for a bundled cowfile.
@return The content of the specified cowfile (or default cowfile if cowfileSpec is null or empty).

Call this with the provided cowfileSpec - that is the value passed to - f on the commandline .


private static String cowInputStreamToString(final InputStream cowInputStream) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(cowInputStream));
		StringBuilder sb = new StringBuilder();
		String line;
		try {
			String newLine = System.getProperty("line.separator");
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				sb.append(newLine);
			}
			reader.close();
		} catch (IOException ex) {
			Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
		} finally {
			if (cowInputStream != null) {
				try {
					cowInputStream.close();
				} catch (IOException ex) {
					Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
				}
			}
		}
		return sb.toString();
	}

private static String cowInputStreamToString ( final InputStream cowInputStream ) { BufferedReader reader = new BufferedReader ( new InputStreamReader ( cowInputStream ) ) ; StringBuilder sb = new StringBuilder ( ) ; String line ; try { String newLine = System . getProperty ( "line.separator" ) ; while ( ( line = reader . readLine ( ) ) != null ) { sb . append ( line ) ; sb . append ( newLine ) ; } reader . close ( ) ; } catch ( IOException ex ) { Logger . getLogger ( Cowloader . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } finally { if ( cowInputStream != null ) { try { cowInputStream . close ( ) ; } catch ( IOException ex ) { Logger . getLogger ( Cowloader . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } } } return sb . toString ( ) ; }

Reads a cowfile from an InputStream and returns a string.
@param cowInputStream The InputStream instance to read into a String.
@return A String representing the result of reading the entire InputStream.

Reads a cowfile from an InputStream and returns a string .


private static InputStream getCowFromPath(final String path) {
		String cwd = System.getProperty("user.dir");  // TODO is this really CWD?
		if (cwd != null) {
			File cowfile = new File(cwd, path);
			if (isCowfile(cowfile)) {
				return cowfileToCowInputStream(cowfile);
			}
		}
		// maybe it's an absolute path?
		File cowfile = new File(path);
		if (isCowfile(cowfile)) {
			return cowfileToCowInputStream(cowfile);
		}
		return null;
	}

private
static
InputStream
getCowFromPath
(
final
String
path
)
{
String
cwd
=
System
.
getProperty
(
"user.dir"
)
;
// TODO is this really CWD?
if
(
cwd
!=
)
{
File
cowfile
=
new
File
(
cwd
,
path
)
;
if
(
isCowfile
(
cowfile
)
)
{
return
cowfileToCowInputStream
(
cowfile
)
;
}
}
// maybe it's an absolute path?
File
cowfile
=
new
File
(
path
)
;
if
(
isCowfile
(
cowfile
)
)
{
return
cowfileToCowInputStream
(
cowfile
)
;
}
return
;
}

In the case that the cowfileSpec is a filesystem path call this method to attempt to load the cowfile.
It will attempt to load the cowfile relative to CWD and if that fails it will try as an absolute path.
@param path A path to a cowfile either relative to CWD or an absolute path.
@return An InputStream to the cowfile if it exists.

In the case that the cowfileSpec is a filesystem path call this method to attempt to load the cowfile . It will attempt to load the cowfile relative to CWD and if that fails it will try as an absolute path .


private static InputStream getCowFromCowPath(final String cowName) {
		String cowPath = System.getenv("COWPATH");
		if (cowPath != null) {
			String[] paths = cowPath.split(File.pathSeparator);
			if (paths != null) {
				for (String path : paths) {
					File cowfile = getCowfile(path, cowName);
					if (cowfile != null) {
						return cowfileToCowInputStream(cowfile);
					}
				}
			}
		}
		return getCowFromResources(cowName);
	}

private static InputStream getCowFromCowPath ( final String cowName ) { String cowPath = System . getenv ( "COWPATH" ) ; if ( cowPath != null ) { String [ ] paths = cowPath . split ( File . pathSeparator ) ; if ( paths != null ) { for ( String path : paths ) { File cowfile = getCowfile ( path , cowName ) ; if ( cowfile != null ) { return cowfileToCowInputStream ( cowfile ) ; } } } } return getCowFromResources ( cowName ) ; }

This will attempt to load a cowfile, by name, from the COWPATH environment variable or bundled cowfiles.
Note that bundled cowfiles are considered part of the COWPATH since this is how to original `cowsay` worked.
COWPATH takes precedence and bundled cowfiles are only considered after searching the COWPATH.

@param cowName The name of a cowfile, e.g. "sheep" or "sheep.cow".
@return An InputStream to the first matching cowfile found.

This will attempt to load a cowfile by name from the COWPATH environment variable or bundled cowfiles . Note that bundled cowfiles are considered part of the COWPATH since this is how to original cowsay worked . COWPATH takes precedence and bundled cowfiles are only considered after searching the COWPATH .


private static boolean isCowfile(final File cowfile) {
		if (cowfile != null && cowfile.exists()) {
			return cowfile.getName().endsWith(COWFILE_EXT);
		}
		return false;
	}

private static boolean isCowfile ( final File cowfile ) { if ( cowfile != null && cowfile . exists ( ) ) { return cowfile . getName ( ) . endsWith ( COWFILE_EXT ) ; } return false ; }

Determine if this File appears to be a genuine cowfile.
This is not a deep check, more rigor will be applied later.
@param cowfile A potential cowfile.
@return true if this File seems to be a cowfile.

Determine if this File appears to be a genuine cowfile . This is not a deep check more rigor will be applied later .


private static InputStream cowfileToCowInputStream(final File cowfile) {
		InputStream cowInputStream = null;
		try {
			cowInputStream = new FileInputStream(cowfile);
		} catch (FileNotFoundException ex) {
			Logger.getLogger(Cowloader.class.getName()).log(Level.SEVERE, null, ex);
		}
		return cowInputStream;
	}

private static InputStream cowfileToCowInputStream ( final File cowfile ) { InputStream cowInputStream = null ; try { cowInputStream = new FileInputStream ( cowfile ) ; } catch ( FileNotFoundException ex ) { Logger . getLogger ( Cowloader . class . getName ( ) ) . log ( Level . SEVERE , null , ex ) ; } return cowInputStream ; }

Reads a File to an InputStream.
Not sure why I thought this should be a separate method, I guess it made sense at the time.
@param cowfile The cowfile to read.
@return An InputStream which can be used to read the File.

Reads a File to an InputStream . Not sure why I thought this should be a separate method I guess it made sense at the time .


private static File getCowfile(final String folder, final String cowName) {
		File[] cowfiles = getCowFiles(folder);
		for (File cowfile : cowfiles) {
			if (cowfile.getName().equals(cowName)) {
				return cowfile;
			}
		}
		return null;
	}

private static File getCowfile ( final String folder , final String cowName ) { File [ ] cowfiles = getCowFiles ( folder ) ; for ( File cowfile : cowfiles ) { if ( cowfile . getName ( ) . equals ( cowName ) ) { return cowfile ; } } return null ; }

Get a cowfile, by name, from the given directory.
@param folder The absolute path to the filesystem folder.
@param cowName The name of the cowfile to load (without the ".cow" extension).
@return A File if the cowfile is found in this directory otherwise null.

Get a cowfile by name from the given directory .


private static File[] getCowFiles(final String folder) {
		File dir = new File(folder);
		File[] files;
		files = dir.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(final File dir, final String name) {
				return name.endsWith(".cow");
			}
		});
		return files;
	}

private static File [ ] getCowFiles ( final String folder ) { File dir = new File ( folder ) ; File [ ] files ; files = dir . listFiles ( new FilenameFilter ( ) { @ Override public boolean accept ( final File dir , final String name ) { return name . endsWith ( ".cow" ) ; } } ) ; return files ; }

Gets all cowfiles found in the given directory.
@param folder The absolute path to the filesystem folder.
@return A list of all cowfiles found in this directory.

Gets all cowfiles found in the given directory .


protected static CowFace getByMode(final String mode) {
		if (mode != null) {
			return COW_MODES.get(mode);
		}
		return null;
	}

protected static CowFace getByMode ( final String mode ) { if ( mode != null ) { return COW_MODES . get ( mode ) ; } return null ; }

Get cow args by mode.
@param mode A mode key, "b" for Borg, "d" for dead, "g" for greedy etc
@return The CowArgs for the given mode or null if not found


public final void setEyes(final String eyes) {
		if (eyes != null && eyes.length() > 0) {
			if (eyes.length() > 2) {
				this.eyes = eyes.substring(0, 2);
			} else {
				this.eyes = eyes;
			}
		}
	}

public final void setEyes ( final String eyes ) { if ( eyes != null && eyes . length ( ) > 0 ) { if ( eyes . length ( ) > 2 ) { this . eyes = eyes . substring ( 0 , 2 ) ; } else { this . eyes = eyes ; } } }

Set custom cow eyes.
@param eyes The eyes to use - if more than two characters long the first two will be used.


public final void setTongue(final String tongue) {
		if (tongue != null && tongue.length() > 0) {
			if (tongue.length() > 2) {
				this.tongue = tongue.substring(0, 2);
			} else {
				this.tongue = tongue;
			}
		}
	}

public final void setTongue ( final String tongue ) { if ( tongue != null && tongue . length ( ) > 0 ) { if ( tongue . length ( ) > 2 ) { this . tongue = tongue . substring ( 0 , 2 ) ; } else { this . tongue = tongue ; } } }

Set custom cow tongue.
@param tongue The tongue to use - if more than two characters long the first two will be used.


public static final boolean isKnownMode(final String mode) {
		Set<String> modes = COW_MODES.keySet();
		return modes.contains(mode);
	}

public static final boolean isKnownMode ( final String mode ) { Set < String > modes = COW_MODES . keySet ( ) ; return modes . contains ( mode ) ; }

Determine if the given mode flag is known and mapped to a particular cow face.
@param mode The key to the mode, generally a single character, e.g. "b" for "Borg" mode.
@return true if this is a known mode.

Determine if the given mode flag is known and mapped to a particular cow face .


public static CommandLine parseCmdArgs(final String[] argv) {
		final CommandLineParser cmdLineParser = new DefaultParser();

		try {
			CommandLine parsed = cmdLineParser.parse(options, argv, true);
			if (parsed.hasOption(Opt.LANG.text)) {
				String language = parsed.getOptionValue(Opt.LANG.text);
				if (language != null) {
					I18n.setLanguage(language);
				}
			}
			return parsed;
		}
		catch (MissingArgumentException ex) {
			Option option = ex.getOption();
			String flag = option.getOpt();
			if (flag == null) {
				flag = option.getLongOpt();
			}
			Logger.getLogger(CowsayCli.class.getName()).log(Level.INFO, I18n.getMessage("missingarg"), flag);
		}
		catch (ParseException ex) {
			Logger.getLogger(CowsayCli.class.getName()).log(Level.FINEST, null, ex);
		}
		return null;
	}

public static CommandLine parseCmdArgs ( final String [ ] argv ) { final CommandLineParser cmdLineParser = new DefaultParser ( ) ; try { CommandLine parsed = cmdLineParser . parse ( options , argv , true ) ; if ( parsed . hasOption ( Opt . LANG . text ) ) { String language = parsed . getOptionValue ( Opt . LANG . text ) ; if ( language != null ) { I18n . setLanguage ( language ) ; } } return parsed ; } catch ( MissingArgumentException ex ) { Option option = ex . getOption ( ) ; String flag = option . getOpt ( ) ; if ( flag == null ) { flag = option . getLongOpt ( ) ; } Logger . getLogger ( CowsayCli . class . getName ( ) ) . log ( Level . INFO , I18n . getMessage ( "missingarg" ) , flag ) ; } catch ( ParseException ex ) { Logger . getLogger ( CowsayCli . class . getName ( ) ) . log ( Level . FINEST , null , ex ) ; } return null ; }

Parses an array of arguments.
@param argv Arguments array.
@return The parsed arguments.


public static void showCmdLineHelp() {
		HelpFormatter formatter = new HelpFormatter();
		updateOptionDescriptions();
		formatter.printHelp(I18n.getMessage("usage"), options);
	}

public static void showCmdLineHelp ( ) { HelpFormatter formatter = new HelpFormatter ( ) ; updateOptionDescriptions ( ) ; formatter . printHelp ( I18n . getMessage ( "usage" ) , options ) ; }


private static String formatBubble(final BubbleWrap bubble, final String message, final int longestLine) {
		String newLine = System.getProperty("line.separator");
		String[] lines = message.split(newLine);
		StringBuilder sb = new StringBuilder();
		sb.append(bubble.buildTop(longestLine));
		if (lines.length > 1) {
			sb.append(bubble.formatMultiOpen(lines[0], longestLine));
			for (int i = 1; i < (lines.length - 1); i++) {
				sb.append(bubble.formatMultiMid(lines[i], longestLine));
			}
			sb.append(bubble.formatMultiEnd(lines[(lines.length - 1)], longestLine));
		} else {
			sb.append(bubble.formatSingle(lines[0]));
		}
		sb.append(bubble.buildBottom(longestLine));
		return sb.toString();
	}

private static String formatBubble ( final BubbleWrap bubble , final String message , final int longestLine ) { String newLine = System . getProperty ( "line.separator" ) ; String [ ] lines = message . split ( newLine ) ; StringBuilder sb = new StringBuilder ( ) ; sb . append ( bubble . buildTop ( longestLine ) ) ; if ( lines . length > 1 ) { sb . append ( bubble . formatMultiOpen ( lines [ 0 ] , longestLine ) ) ; for ( int i = 1 ; i < ( lines . length - 1 ) ; i ++ ) { sb . append ( bubble . formatMultiMid ( lines [ i ] , longestLine ) ) ; } sb . append ( bubble . formatMultiEnd ( lines [ ( lines . length - 1 ) ] , longestLine ) ) ; } else { sb . append ( bubble . formatSingle ( lines [ 0 ] ) ) ; } sb . append ( bubble . buildBottom ( longestLine ) ) ; return sb . toString ( ) ; }

Draws a complete bubble around a line-wrapped message.
@param bubble The BubbleWrap to use (e.g. SPEECH_BUBBLE or THOUGHT_BUBBLE)
@param message The message to wrap, it should already be line-wrapped if appropriate.
@param longestLine The length of the longest line in the message.
@return The message, wrapped in a bubble.

Draws a complete bubble around a line - wrapped message .


private String wrapMessage(final String message) {
		// Note that the original cowsay wraps lines mid-word.
		// This version differs in that it wraps between words if possible.
		int wrap = getWordwrap();
		if (wrap <= 0) {
			return message;
		}
		final List<String> result = new ArrayList<String>();
		String newLine = System.getProperty("line.separator");
		String[] lines = message.split(newLine);
		for (String line : lines) {
			result.add(WordUtils.wrap(line, wrap, null, true));
		}
		return StringUtils.join(result, newLine);
	}

Applies word wrapping to the message to handle long lines.
@param message The raw input message.
@return The message with long lines wrapped.

Applies word wrapping to the message to handle long lines .


private String formatMessage(final String message) {
		String result;
		if (message != null) {
			result = wrapMessage(message);
			int longestLine = getLongestLineLen(result);
			if (!isThought) {
				result = Bubble.formatSpeech(result, longestLine);
			} else {
				result = Bubble.formatThought(result, longestLine);
			}
			return result;
		}
		return "";
	}

private String formatMessage ( final String message ) { String result ; if ( message != null ) { result = wrapMessage ( message ) ; int longestLine = getLongestLineLen ( result ) ; if ( ! isThought ) { result = Bubble . formatSpeech ( result , longestLine ) ; } else { result = Bubble . formatThought ( result , longestLine ) ; } return result ; } return "" ; }

Builds the bubble around the message.
@param message The plain message as provided by the user.
@return The message, line-wrapped and bubble-wrapped.


public void setWordwrap(final String wordwrap) {
		try {
			int ww = Integer.parseInt(wordwrap);
			if (ww >= 0) {
				this.wordwrap = ww;
			}
		} catch(Throwable ignore) {
			// ignore
		}
	}

public
void
setWordwrap
(
final
String
wordwrap
)
{
try
{
int
ww
=
Integer
.
parseInt
(
wordwrap
)
;
if
(
ww
>=
0
)
{
this
.
wordwrap
=
ww
;
}
}
catch
(
Throwable
ignore
)
{
// ignore
}
}

Set the length of the wordwrap, default is "40", zero disables line-wrap.
@param wordwrap A number indicating where (approximately) to line-wrap the message.

Set the length of the wordwrap default is 40 zero disables line - wrap .