pax_global_header00006660000000000000000000000064135656046170014527gustar00rootroot0000000000000052 comment=d194911d16ef58d6b14db8c136592e3d6ea59845 jboss-logging-tools-2.2.1.Final/000077500000000000000000000000001356560461700164635ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/.gitignore000066400000000000000000000003761356560461700204610ustar00rootroot00000000000000#Ignore Maven target folder target/ #Ignore Eclipse files .settings/ .classpath .project #Ignore Intellij files *.iml *.iws *.ipr .idea/ #Ignore Mac files .DS_Store /core/target/ /base/target/ nb-configuration.xml /processor/target/ /generator/target/jboss-logging-tools-2.2.1.Final/README.adoc000066400000000000000000000007511356560461700202530ustar00rootroot00000000000000= JBoss Logging Tools The JBoss logging tools are used to create internationalized log statements and exceptions. For user documentation see https://jboss-logging.github.io/jboss-logging-tools/. For annotation JavaDoc's see https://jboss-logging.github.io/jboss-logging-tools/apidocs/. == Building Standard Maven build: mvn clean install To generate the site use the `-Pgenerate-site` profile or `-Dgenerate-site` system property when building. mvn clean install -Dgenerate-site jboss-logging-tools-2.2.1.Final/annotations/000077500000000000000000000000001356560461700210205ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/pom.xml000066400000000000000000000034701356560461700223410ustar00rootroot00000000000000 4.0.0 org.jboss.logging jboss-logging-tools-parent 2.2.1.Final ../pom.xml jboss-logging-annotations jar JBoss Logging I18n Annotations Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo org.jboss.logging jboss-logging provided jboss-logging-tools-2.2.1.Final/annotations/src/000077500000000000000000000000001356560461700216075ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/000077500000000000000000000000001356560461700225335ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/000077500000000000000000000000001356560461700234545ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/000077500000000000000000000000001356560461700242435ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/000077500000000000000000000000001356560461700253635ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/000077500000000000000000000000001356560461700270115ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/000077500000000000000000000000001356560461700313465ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/BaseUrl.java000066400000000000000000000040251356560461700335470ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Messages on reports can have a link to a {@linkplain ResolutionDoc resolution document}. This annotation can be used * to provide a base URL for these documents. *

* Expressions in the form of {@code ${property.key:default-value}} can be used for the values. If the property key is * prefixed with {@code sys.} a {@linkplain System#getProperty(String) system property} will be used. If the key is * prefixed with {@code env.} an {@linkplain System#getenv(String) environment variable} will be used. In all other cases * the {@code org.jboss.logging.tools.expressionProperties} processor argument is used to specify the path the properties * file which contains the values for the expressions. *

* * @author James R. Perkins * @since 1.2 */ @Target(TYPE) @Retention(CLASS) @Documented public @interface BaseUrl { /** * The base URL used for links to resolution documentation on reports. This can be a fully qualified URL or a * relative URL. * * @return the base URL */ String value(); } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Cause.java000066400000000000000000000023361356560461700332550ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Mark a parameter as being the "exception cause" parameter rather than a positional format parameter. * * @author David M. Lloyd */ @Retention(CLASS) @Target(PARAMETER) @Documented public @interface Cause { } ConstructType.java000066400000000000000000000031251356560461700347610ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicates the value of this annotation should be constructed and returned. This does not change the return type of * the method. *

* This annotation is only allowed on bundle messages that have a throwable return type. The value must be assignable * to the return type. *

* * @author James R. Perkins * @since 2.0.0 */ @Retention(CLASS) @Target(METHOD) @Documented public @interface ConstructType { /** * The actual type that should be constructed for the return type. * * @return the class to construct */ Class value(); } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Field.java000066400000000000000000000073271356560461700332450ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicate that a method parameter value should be applied to a field on the resultant exception object. *

* If this annotation is placed on a method the {@linkplain #name() name} attribute becomes a required parameter and one * default attribute needs to be set. The value of the default attribute is used to set the filed on the resultant * exception object. *

* * @author David M. Lloyd * @author James R. Perkins */ @Retention(CLASS) @Target({PARAMETER, METHOD}) @Repeatable(Fields.class) @Documented public @interface Field { /** * The field name. If not specified, the parameter name is assumed to be the field name. *

* This becomes a required attrubyte if this annotation is present on a method. *

* * @return the field name */ String name() default ""; /** * The default {@code boolean} value if this annotation is used on a method. * * @return the default value to use */ boolean booleanValue() default false; /** * The default boolean value if this annotation is used on a method. * * @return the default value to use */ byte byteValue() default 0x00; /** * The default {@code byte} value if this annotation is used on a method. * * @return the default value to use */ char charValue() default 0x00; /** * The default {@link Class} value if this annotation is used on a method. * * @return the default value to use */ Class classValue() default Object.class; /** * The default {@code double} value if this annotation is used on a method. * * @return the default value to use */ double doubleValue() default 0.0d; /** * The default {@code float} value if this annotation is used on a method. * * @return the default value to use */ float floatValue() default 0.0f; /** * The default {@code int} value if this annotation is used on a method. * * @return the default value to use */ int intValue() default 0; /** * The default {@code long} value if this annotation is used on a method. * * @return the default value to use */ long longValue() default 0L; /** * The default {@code short} value if this annotation is used on a method. * * @return the default value to use */ short shortValue() default 0; /** * The default {@link String} value if this annotation is used on a method. * * @return the default value to use */ String stringValue() default ""; } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Fields.java000066400000000000000000000026421356560461700334230ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Defines the default field properties to use on the resultant exception object. * * @author James R. Perkins */ @Retention(CLASS) @Target(METHOD) @Documented public @interface Fields { /** * The fields to use on the resultant exception object. Note that the {@link Field#name() name} attribute is * required for these annotations. * * @return the fields */ Field[] value(); } FormatWith.java000066400000000000000000000034171356560461700342230ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicate that the given parameter should be wrapped with a formatting object of the given class. The class * must have a one-argument constructor which unambiguously accepts a value of this parameter's type. The resultant * object will be passed in as a parameter to the underlying format type; thus its {@link Object#toString() toString()} * method will be invoked (or, if the format style is {@link Message.Format#PRINTF PRINTF}, the object may implement * {@link java.util.Formattable Formattable} to get extra functionality). * * @author David M. Lloyd */ @Target(PARAMETER) @Retention(CLASS) @Documented public @interface FormatWith { /** * The class of the formatting object to use. * * @return the class */ Class value(); } LogMessage.java000066400000000000000000000032511356560461700341610ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.jboss.logging.Logger; /** * A typed logger method. Indicates that this method will log the associated {@link Message} to the logger system, as * opposed to being a simple message lookup. * * @author David M. Lloyd */ @Retention(CLASS) @Target(METHOD) @Documented public @interface LogMessage { /** * The log level at which this message should be logged. Defaults to {@code INFO}. * * @return the log level */ Logger.Level level() default Logger.Level.INFO; /** * The logging class name to use for this message, if any. * * @return the logging class name */ Class loggingClass() default Void.class; } LoggingClass.java000066400000000000000000000023711356560461700345110ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Mark a parameter as specifying the name of the logging class to use. The parameter * may have a type of {@link Class}. * * @author David M. Lloyd */ @Retention(CLASS) @Target(PARAMETER) @Documented public @interface LoggingClass { } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Message.java000066400000000000000000000056321356560461700336030ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Assigns a message string to a resource method. The method arguments are used to supply the positional parameter * values for the method. * * @author David M. Lloyd */ @Target(METHOD) @Retention(CLASS) @Documented public @interface Message { /** * Indicates that this message has no ID. */ int NONE = 0; /** * Indicates that this message should inherit the ID from another message with the same name. */ int INHERIT = -1; /** * The message ID number. Only one message with a given name may specify an ID other than {@link #INHERIT}. * * @return the message ID number */ int id() default INHERIT; /** * The default format string of this message. *

* Expressions in the form of {@code ${property.key:default-value}} can be used for the value. If the property key is * prefixed with {@code sys.} a {@linkplain System#getProperty(String) system property} will be used. If the key is * prefixed with {@code env.} an {@linkplain System#getenv(String) environment variable} will be used. In all other cases * the {@code org.jboss.logging.tools.expressionProperties} processor argument is used to specify the path the properties * file which contains the values for the expressions. *

* * @return the format string */ String value(); /** * The format type of this method (defaults to {@link Format#PRINTF}). * * @return the format type */ Format format() default Format.PRINTF; /** * The possible format types. */ enum Format { /** * A {@link java.util.Formatter}-type format string. */ PRINTF, /** * A {@link java.text.MessageFormat}-type format string. */ MESSAGE_FORMAT, /** * Indicates the message should not be formatted. */ NO_FORMAT, } } MessageBundle.java000066400000000000000000000050601356560461700346510ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Locale; /** * Signify that an interface is a message bundle interface. * * @author David M. Lloyd */ @Target(TYPE) @Retention(CLASS) @Documented public @interface MessageBundle { /** * Get the project code for messages that have an associated code. If no project code is associated * with this bundle, specify {@code ""} (the empty string). * * @return the project code */ String projectCode(); /** * The length of the padding used for each id in the message bundle. For example given the default padding length * of 6 and a message with an id of 100 would result would be {@code "000100"}. *

* Valid values a range of 3 to 8. Any value less than 0 turns off padding. Any other value will result in an error * being produced. * * @return the length the id should be padded */ int length() default 6; /** * Specifies the {@linkplain Locale locale} for formatting bundle messages. This is only used in the super * implementation. Subclasses will define their own locale to use based on the name of the resource bundle at * compile time. *

* An empty string will default to {@link Locale#ROOT}. *

*

* A non-empty string will be parsed by the {@link Locale#forLanguageTag(String)}. This uses the * IETF BCP 47 format. *

* * @return the default locale message bundles should use for formatting messages */ String rootLocale() default ""; } MessageLogger.java000066400000000000000000000054361356560461700346660ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import java.util.Locale; /** * Signify that an interface is a typed logger interface. A message logger interface may optionally extend other * message logger interfaces and message bundle interfaces (see {@link org.jboss.logging.annotations.MessageBundle}, as * well as the {@link org.jboss.logging.BasicLogger} interface. * * @author David M. Lloyd */ @Retention(CLASS) @Target(TYPE) @Documented public @interface MessageLogger { /** * Get the project code for messages that have an associated code. If no project code is associated * with this logger, specify {@code ""} (the empty string). * * @return the project code */ String projectCode(); /** * The length of the padding used for each id in the message bundle. For example given the default padding length * of 6 and a message with an id of 100 would result would be {@code "000100"}. *

* Valid values a range of 3 to 8. Any value less than 0 turns off padding. Any other value will result in an error * being produced. * * @return the length the id should be padded */ int length() default 6; /** * Specifies the {@linkplain Locale locale} for formatting bundle messages. This is only used in the super * implementation. Subclasses will define their own locale to use based on the name of the resource bundle at * compile time. *

* An empty string will default to {@link Locale#ROOT}. *

*

* A non-empty string will be parsed by the {@link Locale#forLanguageTag(String)}. This uses the * IETF BCP 47 format. *

* * @return the default locale message bundles should use for formatting messages */ String rootLocale() default ""; } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Once.java000066400000000000000000000026741356560461700331060ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicates a message should only be logged once. *

* Methods that use this annotation must be {@linkplain org.jboss.logging.annotations.LogMessage logger methods}. Overloaded * methods also annotated with {@code @Once} will inherit the same check only logging the message from the first * overloaded method invoked. *

* * @author James R. Perkins */ @Target(METHOD) @Retention(CLASS) @Documented public @interface Once { } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Param.java000066400000000000000000000034541356560461700332570ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Identifies a parameter is to be used for constructing an exception and excluded from the formatting of the message. *

* Parameters will be order-matched first, then type-matched to resolve ambiguity. If a match fails an error should * occur. *

* The {@link #value()} option will allow an optional class to be specified which will have to match the exact type of * the parameter in question, to enable unambiguous resolution. The value must be the fully qualified class name. * * @author James R. Perkins */ @Target(PARAMETER) @Retention(CLASS) @Documented public @interface Param { /** * Defines an exact class the parameter must match for unambiguous resolution. * * @return the class the parameter must match. */ Class value() default Object.class; } jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/Pos.java000066400000000000000000000027301356560461700327540ustar00rootroot00000000000000/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @author James R. Perkins * @since 1.1.0 */ @Retention(CLASS) @Target(PARAMETER) @Documented public @interface Pos { /** * The positions the value should be used at. * * @return an array of the positions for the parameter */ int[] value(); /** * The transform types used on the parameter. * * @return an array of the transformer types * * @see Transform */ Transform[] transform() default {}; } Producer.java000066400000000000000000000053261356560461700337230ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Identifies a parameter has the ability to produce a {@link Throwable} or a super type of a {@code Throwable}. The * parameter type must be a {@link java.util.function.Function} or a {@link java.util.function.BiFunction}. *

* For a {@link java.util.function.Function} the input parameter must be a {@link String} which will be the message * associated with the method. The result type must {@link Throwable} or a super type of a {@code Throwable}. *

* *

* For a {@link java.util.function.BiFunction} one of the input parameters must be a {@link String} which will be the * message associated with the method. The other input parameter must be a {@link Throwable} or a super type of a * {@code Throwable} and must be assignable from the parameter annotated with {@link Cause}. The result type must * {@link Throwable} or a super type of a {@code Throwable}. *

* *

* Example * *

 * @Message("The operation failed due to %s")
 *  T operationFailed(@Producer Function function, String op);
 *
 * @Message("The operation failed due to %s")
 *  T operationFailed(@Producer BiFunction function, @Cause Throwable cause, String op);
 *
 * 
* *

* *

* Example Usage * *

 * throw Bundle.MESSAGES.operationFailed(IllegalArgumentException::new, "start");
 *
 * throw Bundle.MESSAGES.operationFailed(IllegalStateException::new, cause, "start");
 *
 * 
* *

* * @author James R. Perkins */ @Target(PARAMETER) @Retention(CLASS) @Documented public @interface Producer { } Properties.java000066400000000000000000000026561356560461700342770ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Defines the default properties to use on the resultant exception object. * * @author James R. Perkins */ @Retention(CLASS) @Target(METHOD) @Documented public @interface Properties { /** * The properties to use on the resultant exception object. Note that the {@link Property#name() name} attribute is * required for these annotations. * * @return the properties */ Property[] value(); } Property.java000066400000000000000000000074101356560461700337600ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicate that a method parameter value should be applied to a property (with a setter method) on the resultant * exception object. *

* If this annotation is placed on a method the {@linkplain #name() name} attribute becomes a required parameter and one * default attribute needs to be set. The value of the default attribute is used to set the property on the resultant * exception object. *

* * @author David M. Lloyd * @author James R. Perkins */ @Retention(CLASS) @Target({PARAMETER, METHOD}) @Repeatable(Properties.class) @Documented public @interface Property { /** * The property name. If not specified, the parameter name is assumed to be the property name. *

* This becomes a required attribute if this annotation is present on a method. *

* * @return the property name */ String name() default ""; /** * The default {@code boolean} value if this annotation is used on a method. * * @return the default value to use */ boolean booleanValue() default false; /** * The default boolean value if this annotation is used on a method. * * @return the default value to use */ byte byteValue() default 0x00; /** * The default {@code byte} value if this annotation is used on a method. * * @return the default value to use */ char charValue() default 0x00; /** * The default {@link Class} value if this annotation is used on a method. * * @return the default value to use */ Class classValue() default Object.class; /** * The default {@code double} value if this annotation is used on a method. * * @return the default value to use */ double doubleValue() default 0.0d; /** * The default {@code float} value if this annotation is used on a method. * * @return the default value to use */ float floatValue() default 0.0f; /** * The default {@code int} value if this annotation is used on a method. * * @return the default value to use */ int intValue() default 0; /** * The default {@code long} value if this annotation is used on a method. * * @return the default value to use */ long longValue() default 0L; /** * The default {@code short} value if this annotation is used on a method. * * @return the default value to use */ short shortValue() default 0; /** * The default {@link String} value if this annotation is used on a method. * * @return the default value to use */ String stringValue() default ""; } ResolutionDoc.java000066400000000000000000000103551356560461700347270ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Allows a link to be created for messages on a report which contain a possible resolution to the issue reported . If * the method does not include an {@linkplain Message#id() id} no link will be created for the report unless a * {@link #path()} is defined. * *

* The rules for building the URL are as follows: *

*

* *

* If placed on a type links will be created for all methods on the type. *

* *

* Do note that the processor does not validate the resolution document exists. It simply attempts to create links to * the resolution document. *

*

* Expressions in the form of {@code ${property.key:default-value}} can be used for the values with the exception of the * {@link #skip() skip} attribute. If the property key is prefixed with {@code sys.} a * {@linkplain System#getProperty(String) system property} will be used. If the key is prefixed with {@code env.} an * {@linkplain System#getenv(String) environment variable} will be used. In all other cases the * {@code org.jboss.logging.tools.expressionProperties} processor argument is used to specify the path the properties * file which contains the values for the expressions. *

* * @author James R. Perkins * @since 1.2 */ @Target({METHOD, TYPE}) @Retention(CLASS) @Documented public @interface ResolutionDoc { /** * The URL, fully qualified or relative, to use for the resolution document. If defined this will override the value * of the {@link BaseUrl} if the annotation is used. * * @return the URL or an empty string */ String url() default ""; /** * The path to the resolution document. If left undefined this will default to the message id. * * @return the path to the resolution document */ String path() default ""; /** * The suffix to append to the path. If left undefined this will default to the extension for the report type. For * example if the report type is {@code xml} the default suffix would be {@code .xml}. * * @return the suffix for the resolution document */ String suffix() default ""; /** * Allows the creation of a link to be skipped. * * @return {@code true} if creating the link should be skipped */ boolean skip() default false; } Signature.java000066400000000000000000000066751356560461700341110ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Specifies the exact signature to use when creating a {@link Throwable} return type. * *

* Given the following exception and message bundle interface method the {@code InvalidIntValueException(final RuntimeException cause, final String msg, final int value)} * constructor would be used. * * *

 * public class InvalidIntValueException extends RuntimeException {
 *     private final RuntimeException causeAsRuntime;
 *     private final int value;
 *     public InvalidIntValueException(final Throwable cause, final String msg, final int value) {
 *         super(msg, cause);
 *         causeAsRuntime = new RuntimeException(cause);
 *         this.value = value;
 *     }
 *
 *     public InvalidIntValueException(final RuntimeException cause, final String msg, final int value) {
 *         super(msg, cause);
 *         causeAsRuntime = cause;
 *         this.value = value;
 *     }
 *     public InvalidIntValueException(final RuntimeException cause, final String msg, final Integer value) {
 *         super(msg, cause);
 *         causeAsRuntime = cause;
 *         this.value = value;
 *     }
 * }
 * 
* * * *
 * @Message("Invalid value %d")
 * @Signature(causeIndex = 0, messageIndex = 1, value = {RuntimeException.class, String.class, int.class}
 * InvalidIntValueException invalidValue(@Cause RuntimeException cause, @Param int value);
 * 
*
*

* * @author James R. Perkins */ @Retention(CLASS) @Target(METHOD) @Documented public @interface Signature { /** * An array of types matching the exact signature to use for the exception being created. * * @return an array of types used to find the signature */ Class[] value(); /** * The index for the {@linkplain Cause cause} of the exception being created. A value of less than zero assumes * there is no cause parameter in the constructor. A {@link Cause} annotation can still be used and the * {@link Throwable#initCause(Throwable)} will be used to initialize the cause of the exception. * * @return the index for the cause parameter */ int causeIndex() default -1; /** * The index for the message. This is the formatted messaged from the {@link Message#value()}. This is a required * value defaulting to 0 which would be the first parameter. * * @return the index for the message parameter */ int messageIndex() default 0; } Suppressed.java000066400000000000000000000031601356560461700342670ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2016 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicates the parameter should be added as a {@linkplain Throwable#addSuppressed(Throwable) suppressed} exception to * the returned exception. *

* The annotated parameter can be a single {@linkplain Throwable throwable type}, an array of * {@linkplain Throwable throwable types} or a {@linkplain java.util.Collection collection} of * {@linkplain Throwable throwable types}. Note this is only allowed on message bundle methods that return a * {@linkplain Throwable throwable type}. *

* * @author James R. Perkins */ @Retention(CLASS) @Target(PARAMETER) @Documented public @interface Suppressed { } Transform.java000066400000000000000000000055741356560461700341200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Indicate the given parameter should be transformed in each of the {@link org.jboss.logging.annotations.Transform.TransformType transform types} * provided. The parameter cannot be a primitive type. *

* For the {@link TransformType#SIZE} type, the object must be a {@link String}, a {@link java.util.Collection}, a * {@link java.util.Map} or an array. *

* The type {@link TransformType#GET_CLASS} can be used with {@link TransformType#HASH_CODE} or {@link * TransformType#IDENTITY_HASH_CODE}. The type {@link TransformType#SIZE} must be used on it's own. * * @author James R. Perkins * @since 1.1.0 */ @Retention(CLASS) @Target(PARAMETER) @Documented public @interface Transform { /** * The transform type */ public enum TransformType { /** * Gets the class of the object object passed, {@link Object#getClass()}. */ GET_CLASS, /** * Gets the hash code of the object, {@link Object#hashCode()}. */ HASH_CODE, /** * Gets the identity hash code of the object, {@link System#identityHashCode(Object)}. */ IDENTITY_HASH_CODE, /** * Gets the size or length of a {@link String}, {@link java.util.Collection}, {@link java.util.Map} or array. */ SIZE, } /** * The transform types used on the parameter. *

* Valid combinations: *

* * @return an array of the transform types */ TransformType[] value(); } ValidIdRange.java000066400000000000000000000045651356560461700344350ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Sets a range of valid id's allowed on the {@link org.jboss.logging.annotations.Message#id() message id}. Both {@link * Message#INHERIT} and {@link Message#NONE} are ignored when validating. *

* Note: Message id's from inherited interfaces are not validated within the range provided. Super interfaces * would need their own annotation for range validation. *

* *

 *          @MessageLogger(projectCode = "EXAMPLE")
 *          @ValidIdRange(min = 100, max = 200)
 *          public interface ExampleLogger {
 *
 *              @LogMessage
 *              @Message(id = 100, value = "Example message")
 *              void example();
 *          }
 * 
* * * @author James R. Perkins */ @Target(TYPE) @Retention(CLASS) @Documented public @interface ValidIdRange { /** * The minimum id allowed in the {@link org.jboss.logging.annotations.Message#id() message id}. Both {@link * Message#INHERIT} and {@link Message#NONE} are ignored when validating. * * @return the minimum id allowed */ int min() default 1; /** * The maximum id allowed in the {@link org.jboss.logging.annotations.Message#id() message id}. Both {@link * Message#INHERIT} and {@link Message#NONE} are ignored when validating. * * @return the maximum id allowed */ int max() default 999999; } ValidIdRanges.java000066400000000000000000000023631356560461700346120ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/java/org/jboss/logging/annotations/* * JBoss, Home of Professional Open Source. * * Copyright 2015 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.annotations; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.CLASS; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * @author James R. Perkins */ @Target(TYPE) @Retention(CLASS) @Documented public @interface ValidIdRanges { /** * An array of valid id ranges. * * @return an array of valid id ranges */ ValidIdRange[] value(); } jboss-logging-tools-2.2.1.Final/annotations/src/main/resources/000077500000000000000000000000001356560461700245455ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/resources/META-INF/000077500000000000000000000000001356560461700257055ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/annotations/src/main/resources/META-INF/LICENSE.txt000066400000000000000000000261351356560461700275370ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.jboss-logging-tools-2.2.1.Final/docs/000077500000000000000000000000001356560461700174135ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/000077500000000000000000000000001356560461700210355ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/allclasses-frame.html000066400000000000000000000103651356560461700251460ustar00rootroot00000000000000 All Classes (JBoss Logging I18n Documentation 2.2.1.Final API)

All Classes

jboss-logging-tools-2.2.1.Final/docs/apidocs/allclasses-noframe.html000066400000000000000000000074011356560461700255000ustar00rootroot00000000000000 All Classes (JBoss Logging I18n Documentation 2.2.1.Final API)

All Classes

jboss-logging-tools-2.2.1.Final/docs/apidocs/constant-values.html000066400000000000000000000124221356560461700250520ustar00rootroot00000000000000 Constant Field Values (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Constant Field Values

Contents

org.jboss.*

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/deprecated-list.html000066400000000000000000000075631356560461700250070ustar00rootroot00000000000000 Deprecated List (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Deprecated API

Contents

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/help-doc.html000066400000000000000000000213421356560461700234200ustar00rootroot00000000000000 API Help (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

How This API Document Is Organized

This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.
This help file applies to API documentation generated using the standard doclet.
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/index-all.html000066400000000000000000000441061356560461700236050ustar00rootroot00000000000000 Index (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
B C F I L M N O P R S T V 

B

BaseUrl - Annotation Type in org.jboss.logging.annotations
Messages on reports can have a link to a resolution document.

C

Cause - Annotation Type in org.jboss.logging.annotations
Mark a parameter as being the "exception cause" parameter rather than a positional format parameter.
ConstructType - Annotation Type in org.jboss.logging.annotations
Indicates the value of this annotation should be constructed and returned.

F

Field - Annotation Type in org.jboss.logging.annotations
Indicate that a method parameter value should be applied to a field on the resultant exception object.
Fields - Annotation Type in org.jboss.logging.annotations
Defines the default field properties to use on the resultant exception object.
FormatWith - Annotation Type in org.jboss.logging.annotations
Indicate that the given parameter should be wrapped with a formatting object of the given class.

I

INHERIT - Static variable in annotation type org.jboss.logging.annotations.Message
Indicates that this message should inherit the ID from another message with the same name.

L

LoggingClass - Annotation Type in org.jboss.logging.annotations
Mark a parameter as specifying the name of the logging class to use.
LogMessage - Annotation Type in org.jboss.logging.annotations
A typed logger method.

M

Message - Annotation Type in org.jboss.logging.annotations
Assigns a message string to a resource method.
Message.Format - Enum in org.jboss.logging.annotations
The possible format types.
MessageBundle - Annotation Type in org.jboss.logging.annotations
Signify that an interface is a message bundle interface.
MessageLogger - Annotation Type in org.jboss.logging.annotations
Signify that an interface is a typed logger interface.

N

NONE - Static variable in annotation type org.jboss.logging.annotations.Message
Indicates that this message has no ID.

O

Once - Annotation Type in org.jboss.logging.annotations
Indicates a message should only be logged once.
org.jboss.logging.annotations - package org.jboss.logging.annotations
 

P

Param - Annotation Type in org.jboss.logging.annotations
Identifies a parameter is to be used for constructing an exception and excluded from the formatting of the message.
Pos - Annotation Type in org.jboss.logging.annotations
 
Producer - Annotation Type in org.jboss.logging.annotations
Identifies a parameter has the ability to produce a Throwable or a super type of a Throwable.
Properties - Annotation Type in org.jboss.logging.annotations
Defines the default properties to use on the resultant exception object.
Property - Annotation Type in org.jboss.logging.annotations
Indicate that a method parameter value should be applied to a property (with a setter method) on the resultant exception object.

R

ResolutionDoc - Annotation Type in org.jboss.logging.annotations
Allows a link to be created for messages on a report which contain a possible resolution to the issue reported .

S

Signature - Annotation Type in org.jboss.logging.annotations
Specifies the exact signature to use when creating a Throwable return type.
Suppressed - Annotation Type in org.jboss.logging.annotations
Indicates the parameter should be added as a suppressed exception to the returned exception.

T

Transform - Annotation Type in org.jboss.logging.annotations
Indicate the given parameter should be transformed in each of the transform types provided.
Transform.TransformType - Enum in org.jboss.logging.annotations
The transform type

V

ValidIdRange - Annotation Type in org.jboss.logging.annotations
Sets a range of valid id's allowed on the message id.
ValidIdRanges - Annotation Type in org.jboss.logging.annotations
 
valueOf(String) - Static method in enum org.jboss.logging.annotations.Message.Format
Returns the enum constant of this type with the specified name.
valueOf(String) - Static method in enum org.jboss.logging.annotations.Transform.TransformType
Returns the enum constant of this type with the specified name.
values() - Static method in enum org.jboss.logging.annotations.Message.Format
Returns an array containing the constants of this enum type, in the order they are declared.
values() - Static method in enum org.jboss.logging.annotations.Transform.TransformType
Returns an array containing the constants of this enum type, in the order they are declared.
B C F I L M N O P R S T V 
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/index.html000066400000000000000000000054501356560461700230360ustar00rootroot00000000000000 JBoss Logging I18n Documentation 2.2.1.Final API <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <h2>Frame Alert</h2> <p>This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to <a href="org/jboss/logging/annotations/package-summary.html">Non-frame version</a>.</p> jboss-logging-tools-2.2.1.Final/docs/apidocs/org/000077500000000000000000000000001356560461700216245ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/000077500000000000000000000000001356560461700227445ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/000077500000000000000000000000001356560461700243725ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/000077500000000000000000000000001356560461700267275ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/BaseUrl.html000066400000000000000000000235501356560461700311570ustar00rootroot00000000000000 BaseUrl (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type BaseUrl

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Cause.html000066400000000000000000000160151356560461700306600ustar00rootroot00000000000000 Cause (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Cause

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/ConstructType.html000066400000000000000000000233441356560461700324510ustar00rootroot00000000000000 ConstructType (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type ConstructType

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Field.html000066400000000000000000000462471356560461700306550ustar00rootroot00000000000000 Field (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Field

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Fields.html000066400000000000000000000222441356560461700310270ustar00rootroot00000000000000 Fields (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Fields

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/FormatWith.html000066400000000000000000000235431356560461700317100ustar00rootroot00000000000000 FormatWith (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type FormatWith

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/LogMessage.html000066400000000000000000000243761356560461700316570ustar00rootroot00000000000000 LogMessage (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type LogMessage

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/LoggingClass.html000066400000000000000000000163671356560461700322060ustar00rootroot00000000000000 LoggingClass (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type LoggingClass

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Message.Format.html000066400000000000000000000443741356560461700324440ustar00rootroot00000000000000 Message.Format (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Enum Message.Format

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Message.html000066400000000000000000000354541356560461700312140ustar00rootroot00000000000000 Message (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Message

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/MessageBundle.html000066400000000000000000000321301356560461700323320ustar00rootroot00000000000000 MessageBundle (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type MessageBundle

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/MessageLogger.html000066400000000000000000000326231356560461700323470ustar00rootroot00000000000000 MessageLogger (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type MessageLogger

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Once.html000066400000000000000000000164361356560461700305130ustar00rootroot00000000000000 Once (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Once

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Param.html000066400000000000000000000232051356560461700306570ustar00rootroot00000000000000 Param (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Param

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Pos.html000066400000000000000000000252701356560461700303640ustar00rootroot00000000000000 Pos (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Pos

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Producer.html000066400000000000000000000237451356560461700314130ustar00rootroot00000000000000 Producer (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Producer

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Properties.html000066400000000000000000000223531356560461700317560ustar00rootroot00000000000000 Properties (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Properties

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Property.html000066400000000000000000000464461356560461700314570ustar00rootroot00000000000000 Property (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Property

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/ResolutionDoc.html000066400000000000000000000402641356560461700324140ustar00rootroot00000000000000 ResolutionDoc (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type ResolutionDoc

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Signature.html000066400000000000000000000335351356560461700315670ustar00rootroot00000000000000 Signature (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Signature

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Suppressed.html000066400000000000000000000201611356560461700317520ustar00rootroot00000000000000 Suppressed (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Suppressed

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

Transform.TransformType.html000066400000000000000000000512671356560461700343400ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations Transform.TransformType (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Enum Transform.TransformType

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/Transform.html000066400000000000000000000276431356560461700316040ustar00rootroot00000000000000 Transform (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type Transform

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/ValidIdRange.html000066400000000000000000000262711356560461700321160ustar00rootroot00000000000000 ValidIdRange (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type ValidIdRange

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/ValidIdRanges.html000066400000000000000000000213031356560461700322700ustar00rootroot00000000000000 ValidIdRanges (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final
org.jboss.logging.annotations

Annotation Type ValidIdRanges

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/000077500000000000000000000000001356560461700306265ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/BaseUrl.html000066400000000000000000000111061356560461700330500ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.BaseUrl (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.BaseUrl

No usage of org.jboss.logging.annotations.BaseUrl
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Cause.html000066400000000000000000000110601356560461700325520ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Cause (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Cause

No usage of org.jboss.logging.annotations.Cause
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

ConstructType.html000066400000000000000000000112101356560461700342560ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.ConstructType (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.ConstructType

No usage of org.jboss.logging.annotations.ConstructType
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Field.html000066400000000000000000000110601356560461700325350ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Field (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Field

No usage of org.jboss.logging.annotations.Field
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Fields.html000066400000000000000000000110731356560461700327240ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Fields (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Fields

No usage of org.jboss.logging.annotations.Fields
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/FormatWith.html000066400000000000000000000111471356560461700336040ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.FormatWith (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.FormatWith

No usage of org.jboss.logging.annotations.FormatWith
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/LogMessage.html000066400000000000000000000111471356560461700335460ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.LogMessage (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.LogMessage

No usage of org.jboss.logging.annotations.LogMessage
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

LoggingClass.html000066400000000000000000000111751356560461700340160ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.LoggingClass (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.LoggingClass

No usage of org.jboss.logging.annotations.LoggingClass
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

Message.Format.html000066400000000000000000000155271356560461700342620ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.Message.Format (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Message.Format

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Message.html000066400000000000000000000111061356560461700330770ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Message (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Message

No usage of org.jboss.logging.annotations.Message
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

MessageBundle.html000066400000000000000000000112101356560461700341460ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.MessageBundle (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.MessageBundle

No usage of org.jboss.logging.annotations.MessageBundle
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

MessageLogger.html000066400000000000000000000112101356560461700341540ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.MessageLogger (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.MessageLogger

No usage of org.jboss.logging.annotations.MessageLogger
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Once.html000066400000000000000000000110451356560461700324010ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Once (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Once

No usage of org.jboss.logging.annotations.Once
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Param.html000066400000000000000000000110601356560461700325520ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Param (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Param

No usage of org.jboss.logging.annotations.Param
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Pos.html000066400000000000000000000110321356560461700322520ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Pos (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Pos

No usage of org.jboss.logging.annotations.Pos
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Producer.html000066400000000000000000000111211356560461700332730ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Producer (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Producer

No usage of org.jboss.logging.annotations.Producer
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Properties.html000066400000000000000000000111471356560461700336540ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Properties (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Properties

No usage of org.jboss.logging.annotations.Properties
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Property.html000066400000000000000000000111211356560461700333340ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Property (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Property

No usage of org.jboss.logging.annotations.Property
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

ResolutionDoc.html000066400000000000000000000112101356560461700342210ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.ResolutionDoc (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.ResolutionDoc

No usage of org.jboss.logging.annotations.ResolutionDoc
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Signature.html000066400000000000000000000111341356560461700334550ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Signature (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Signature

No usage of org.jboss.logging.annotations.Signature
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Suppressed.html000066400000000000000000000111471356560461700336550ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Suppressed (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Suppressed

No usage of org.jboss.logging.annotations.Suppressed
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

Transform.TransformType.html000066400000000000000000000160351356560461700362310ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.Transform.TransformType (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Transform.TransformType

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use/Transform.html000066400000000000000000000111341356560461700334670ustar00rootroot00000000000000 Uses of Class org.jboss.logging.annotations.Transform (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.Transform

No usage of org.jboss.logging.annotations.Transform
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

ValidIdRange.html000066400000000000000000000111751356560461700337330ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.ValidIdRange (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.ValidIdRange

No usage of org.jboss.logging.annotations.ValidIdRange
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

ValidIdRanges.html000066400000000000000000000112101356560461700341040ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/class-use Uses of Class org.jboss.logging.annotations.ValidIdRanges (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Class
org.jboss.logging.annotations.ValidIdRanges

No usage of org.jboss.logging.annotations.ValidIdRanges
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/package-frame.html000066400000000000000000000074411356560461700323060ustar00rootroot00000000000000 org.jboss.logging.annotations (JBoss Logging I18n Documentation 2.2.1.Final API)

org.jboss.logging.annotations

Enums

Annotation Types

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/package-summary.html000066400000000000000000000325101356560461700327040ustar00rootroot00000000000000 org.jboss.logging.annotations (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Package org.jboss.logging.annotations

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/package-tree.html000066400000000000000000000360241356560461700321520ustar00rootroot00000000000000 org.jboss.logging.annotations Class Hierarchy (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Hierarchy For Package org.jboss.logging.annotations

Annotation Type Hierarchy

Enum Hierarchy

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/org/jboss/logging/annotations/package-use.html000066400000000000000000000124561356560461700320120ustar00rootroot00000000000000 Uses of Package org.jboss.logging.annotations (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Uses of Package
org.jboss.logging.annotations

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/overview-tree.html000066400000000000000000000351661356560461700245410ustar00rootroot00000000000000 Class Hierarchy (JBoss Logging I18n Documentation 2.2.1.Final API)
Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Hierarchy For All Packages

Package Hierarchies:

Annotation Type Hierarchy

Enum Hierarchy

Skip navigation links
JBoss Logging Tools, 2.2.1.Final

Copyright © 2019 JBoss by Red Hat. All rights reserved.

jboss-logging-tools-2.2.1.Final/docs/apidocs/package-list000066400000000000000000000000361356560461700233230ustar00rootroot00000000000000org.jboss.logging.annotations jboss-logging-tools-2.2.1.Final/docs/apidocs/script.js000066400000000000000000000014731356560461700227040ustar00rootroot00000000000000function show(type) { count = 0; for (var key in methods) { var row = document.getElementById(key); if ((methods[key] & type) != 0) { row.style.display = ''; row.className = (count++ % 2) ? rowColor : altColor; } else row.style.display = 'none'; } updateTabs(type); } function updateTabs(type) { for (var value in tabs) { var sNode = document.getElementById(tabs[value][0]); var spanNode = sNode.firstChild; if (value == type) { sNode.className = activeTableTab; spanNode.innerHTML = tabs[value][1]; } else { sNode.className = tableTab; spanNode.innerHTML = "" + tabs[value][1] + ""; } } } jboss-logging-tools-2.2.1.Final/docs/apidocs/stylesheet.css000066400000000000000000000310521356560461700237410ustar00rootroot00000000000000/* Javadoc style sheet */ /* Overall document style */ @import url('resources/fonts/dejavu.css'); body { background-color:#ffffff; color:#353833; font-family:'DejaVu Sans', Arial, Helvetica, sans-serif; font-size:14px; margin:0; } a:link, a:visited { text-decoration:none; color:#4A6782; } a:hover, a:focus { text-decoration:none; color:#bb7a2a; } a:active { text-decoration:none; color:#4A6782; } a[name] { color:#353833; } a[name]:hover { text-decoration:none; color:#353833; } pre { font-family:'DejaVu Sans Mono', monospace; font-size:14px; } h1 { font-size:20px; } h2 { font-size:18px; } h3 { font-size:16px; font-style:italic; } h4 { font-size:13px; } h5 { font-size:12px; } h6 { font-size:11px; } ul { list-style-type:disc; } code, tt { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; margin-top:8px; line-height:1.4em; } dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; padding-top:4px; } table tr td dt code { font-family:'DejaVu Sans Mono', monospace; font-size:14px; vertical-align:top; padding-top:4px; } sup { font-size:8px; } /* Document title and Copyright styles */ .clear { clear:both; height:0px; overflow:hidden; } .aboutLanguage { float:right; padding:0px 21px; font-size:11px; z-index:200; margin-top:-9px; } .legalCopy { margin-left:.5em; } .bar a, .bar a:link, .bar a:visited, .bar a:active { color:#FFFFFF; text-decoration:none; } .bar a:hover, .bar a:focus { color:#bb7a2a; } .tab { background-color:#0066FF; color:#ffffff; padding:8px; width:5em; font-weight:bold; } /* Navigation bar styles */ .bar { background-color:#4D7A97; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ font-size:11px; margin:0; } .topNav { background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .bottomNav { margin-top:10px; background-color:#4D7A97; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; font-size:12px; } .subNav { background-color:#dee3e9; float:left; width:100%; overflow:hidden; font-size:12px; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; text-transform:uppercase; } ul.navList, ul.subNavList { float:left; margin:0 25px 0 0; padding:0; } ul.navList li{ list-style:none; float:left; padding: 5px 6px; text-transform:uppercase; } ul.subNavList li{ list-style:none; float:left; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; text-transform:uppercase; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; text-transform:uppercase; } .navBarCell1Rev { background-color:#F8981D; color:#253441; margin: auto 5px; } .skipNav { position:absolute; top:auto; left:-9999px; overflow:hidden; } /* Page header and footer styles */ .header, .footer { clear:both; margin:0 20px; padding:5px 0 0 0; } .indexHeader { margin:10px; position:relative; } .indexHeader span{ margin-right:15px; } .indexHeader h1 { font-size:13px; } .title { color:#2c4557; margin:10px 0; } .subTitle { margin:5px 0 0 0; } .header ul { margin:0 0 15px 0; padding:0; } .footer ul { margin:20px 0 5px 0; } .header ul li, .footer ul li { list-style:none; font-size:13px; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; border:1px solid #d0d9e0; margin:0 0 6px -8px; padding:7px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; margin:15px 0; } ul.blockList li.blockList h2 { padding:0px 0 20px 0; } /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { clear:both; padding:10px 20px; position:relative; } .indexContainer { margin:10px; position:relative; font-size:12px; } .indexContainer h2 { font-size:13px; padding:0 0 3px 0; } .indexContainer ul { margin:0; padding:0; } .indexContainer ul li { list-style:none; padding-top:2px; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { font-size:12px; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { margin:5px 0 10px 0px; font-size:14px; font-family:'DejaVu Sans Mono',monospace; } .serializedFormContainer dl.nameValue dt { margin-left:1px; font-size:1.1em; display:inline; font-weight:bold; } .serializedFormContainer dl.nameValue dd { margin:0 0 0 1px; font-size:1.1em; display:inline; } /* List styles */ ul.horizontal li { display:inline; font-size:0.9em; } ul.inheritance { margin:0; padding:0; } ul.inheritance li { display:inline; list-style:none; } ul.inheritance li ul.inheritance { margin-left:15px; padding-left:15px; padding-top:1px; } ul.blockList, ul.blockListLast { margin:10px 0 10px 0; padding:0; } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; margin-bottom:15px; line-height:1.4; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; border:1px solid #ededed; background-color:#f8f8f8; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px; border:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; border-bottom:none; padding-bottom:0; } table tr td dl, table tr td dl dt, table tr td dl dd { margin-top:0; margin-bottom:1px; } /* Table styles */ .overviewSummary, .memberSummary, .typeSummary, .useSummary, .constantsSummary, .deprecatedSummary { width:100%; border-left:1px solid #EEE; border-right:1px solid #EEE; border-bottom:1px solid #EEE; } .overviewSummary, .memberSummary { padding:0px; } .overviewSummary caption, .memberSummary caption, .typeSummary caption, .useSummary caption, .constantsSummary caption, .deprecatedSummary caption { position:relative; text-align:left; background-repeat:no-repeat; color:#253441; font-weight:bold; clear:none; overflow:hidden; padding:0px; padding-top:10px; padding-left:1px; margin:0px; white-space:pre; } .overviewSummary caption a:link, .memberSummary caption a:link, .typeSummary caption a:link, .useSummary caption a:link, .constantsSummary caption a:link, .deprecatedSummary caption a:link, .overviewSummary caption a:hover, .memberSummary caption a:hover, .typeSummary caption a:hover, .useSummary caption a:hover, .constantsSummary caption a:hover, .deprecatedSummary caption a:hover, .overviewSummary caption a:active, .memberSummary caption a:active, .typeSummary caption a:active, .useSummary caption a:active, .constantsSummary caption a:active, .deprecatedSummary caption a:active, .overviewSummary caption a:visited, .memberSummary caption a:visited, .typeSummary caption a:visited, .useSummary caption a:visited, .constantsSummary caption a:visited, .deprecatedSummary caption a:visited { color:#FFFFFF; } .overviewSummary caption span, .memberSummary caption span, .typeSummary caption span, .useSummary caption span, .constantsSummary caption span, .deprecatedSummary caption span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; padding-bottom:7px; display:inline-block; float:left; background-color:#F8981D; border: none; height:16px; } .memberSummary caption span.activeTableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#F8981D; height:16px; } .memberSummary caption span.tableTab span { white-space:nowrap; padding-top:5px; padding-left:12px; padding-right:12px; margin-right:3px; display:inline-block; float:left; background-color:#4D7A97; height:16px; } .memberSummary caption span.tableTab, .memberSummary caption span.activeTableTab { padding-top:0px; padding-left:0px; padding-right:0px; background-image:none; float:none; display:inline; } .overviewSummary .tabEnd, .memberSummary .tabEnd, .typeSummary .tabEnd, .useSummary .tabEnd, .constantsSummary .tabEnd, .deprecatedSummary .tabEnd { display:none; width:5px; position:relative; float:left; background-color:#F8981D; } .memberSummary .activeTableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; float:left; background-color:#F8981D; } .memberSummary .tableTab .tabEnd { display:none; width:5px; margin-right:3px; position:relative; background-color:#4D7A97; float:left; } .overviewSummary td, .memberSummary td, .typeSummary td, .useSummary td, .constantsSummary td, .deprecatedSummary td { text-align:left; padding:0px 0px 12px 10px; } th.colOne, th.colFirst, th.colLast, .useSummary th, .constantsSummary th, td.colOne, td.colFirst, td.colLast, .useSummary td, .constantsSummary td{ vertical-align:top; padding-right:0px; padding-top:8px; padding-bottom:3px; } th.colFirst, th.colLast, th.colOne, .constantsSummary th { background:#dee3e9; text-align:left; padding:8px 3px 3px 7px; } td.colFirst, th.colFirst { white-space:nowrap; font-size:13px; } td.colLast, th.colLast { font-size:13px; } td.colOne, th.colOne { font-size:13px; } .overviewSummary td.colFirst, .overviewSummary th.colFirst, .useSummary td.colFirst, .useSummary th.colFirst, .overviewSummary td.colOne, .overviewSummary th.colOne, .memberSummary td.colFirst, .memberSummary th.colFirst, .memberSummary td.colOne, .memberSummary th.colOne, .typeSummary td.colFirst{ width:25%; vertical-align:top; } td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { font-weight:bold; } .tableSubHeadingColor { background-color:#EEEEFF; } .altColor { background-color:#FFFFFF; } .rowColor { background-color:#EEEEEF; } /* Content styles */ .description pre { margin-top:0; } .deprecatedContent { margin:0; padding:10px 0; } .docSummary { padding:0; } ul.blockList ul.blockList ul.blockList li.blockList h3 { font-style:normal; } div.block { font-size:14px; font-family:'DejaVu Serif', Georgia, "Times New Roman", Times, serif; } td.colLast div { padding-top:0px; } td.colLast a { padding-bottom:3px; } /* Formatting effect styles */ .sourceLineNo { color:green; padding:0 30px 0 0; } h1.hidden { visibility:hidden; overflow:hidden; font-size:10px; } .block { display:block; margin:3px 10px 2px 0px; color:#474747; } .deprecatedLabel, .descfrmTypeLabel, .memberNameLabel, .memberNameLink, .overrideSpecifyLabel, .packageHierarchyLabel, .paramLabel, .returnLabel, .seeLabel, .simpleTagLabel, .throwsLabel, .typeNameLabel, .typeNameLink { font-weight:bold; } .deprecationComment, .emphasizedPhrase, .interfaceName { font-style:italic; } div.block div.block span.deprecationComment, div.block div.block span.emphasizedPhrase, div.block div.block span.interfaceName { font-style:normal; } div.contentContainer ul.blockList li.blockList h2{ padding-bottom:0px; } jboss-logging-tools-2.2.1.Final/docs/default-notes.html000066400000000000000000001047031356560461700230600ustar00rootroot00000000000000 Untitled
A message is inheritable if the two methods have the same name and same number of format parameters.
A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; @FormatWith, @Pos or @Transform.
jboss-logging-tools-2.2.1.Final/docs/examples.html000066400000000000000000001200201356560461700221120ustar00rootroot00000000000000 Example Use Cases

Example Use Cases

Below are some example use case snippets from the examples.

/**
 * Writes the value of the object to the file.
 *
 * @param value the value to write, cannot be {@code null}
 *
 * @throws UncheckedIOException if an error occurs writing the data
 */
public void write(final Object value) {
    AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1"); (1)
    Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")); (2)
    write(Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).toString());
}

/**
 * Writes the value to the file.
 *
 * @param value the value to write, cannot be {@code null} or an {@linkplain String#isEmpty() empty string}.
 *
 * @throws UncheckedIOException if an error occurs writing the data
 */
public void write(final String value) {
    AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1");
    if (Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).isEmpty()) {
        throw ErrorMessages.MESSAGES.invalidValue(value); (3)
    }
    try {
        synchronized (outputLock) {
            writer.write(value);
            writer.newLine();
            if (autoFlush) {
                flush();
            }
        }
    } catch (IOException e) {
        throw ErrorMessages.MESSAGES.operationFailed(UncheckedIOException::new, e, "write"); (4)
    }
}

@Override
public void close() {
    try {
        synchronized (outputLock) {
            writer.close();
        }
        AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
    } catch (Exception e) {
        throw ErrorMessages.MESSAGES.closeFailure(e, this);
    }
}

/**
 * Safely close this writer logging any errors that occur during closing.
 */
public void safeClose() {
    try {
        synchronized (outputLock) {
            writer.close();
        }
        AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
    } catch (Exception e) {
        AppLogger.LOGGER.closeFailure(e, this); (5)
    }
}
1 Logs the application version. Note this uses the @Once annotation to indicate this should only be logged once regardless of which write method is used.
2 The ErrorMessages.nullParam() returns a java.lang.function.Supplier. This allows the message to be lazily formatted only if the value is null.
3 Throws a message if the value is an empty string.
4 Uses a java.lang.function.BiFunction to create a new UncheckedIOException with the caught exception set as the cause.
5 Logs the caught exception instead of throwing a new exception.
jboss-logging-tools-2.2.1.Final/docs/examples/000077500000000000000000000000001356560461700212315ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/examples/AppLogger.html000066400000000000000000001077311356560461700240100ustar00rootroot00000000000000 Example Messages
Table 1. org.jboss.logging.tools.examples.AppLogger
Message Id Message Log Level Return Type

 — 

%s version %d.%d.%d.%s

INFO

void

CW000100

Failure while closing %s

ERROR

void

CW000101

Encoding %s could not be found. Defaulting to %s.

WARN

void

CW000102

Cache size changed to %d

INFO

void

jboss-logging-tools-2.2.1.Final/docs/examples/ErrorMessages.html000066400000000000000000001107421356560461700247050ustar00rootroot00000000000000 Example Messages
Table 1. org.jboss.logging.tools.examples.ErrorMessages
Message Id Message Log Level Return Type

 — 

Version %d.%d.%d.%s

 — 

java.lang.String

CW000001

Value %s is invalid

 — 

java.lang.IllegalArgumentException

CW000002

Failure closing %s

 — 

org.jboss.logging.tools.examples.CloseException

CW000003

Parameter %s cannot be null

 — 

java.util.function.Supplier

CW000004

Operation %s failed.

 — 

java.lang.RuntimeException

jboss-logging-tools-2.2.1.Final/docs/examples/errors/000077500000000000000000000000001356560461700225455ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/examples/errors/CW000003.html000066400000000000000000001041741356560461700244160ustar00rootroot00000000000000 CW000003: Null Parameter

CW000003: Null Parameter

This error indicates you’ve passed a null parameter where a non-null value is required.

jboss-logging-tools-2.2.1.Final/docs/examples/errors/CW000100.html000066400000000000000000001042011356560461700244030ustar00rootroot00000000000000 CW000100: Close Failure

CW000100: Close Failure

This error indicates there was a failure closing a resource. Please see previous error messages and contact support if required.

jboss-logging-tools-2.2.1.Final/docs/examples/errors/CW000101.html000066400000000000000000001042501356560461700244100ustar00rootroot00000000000000 CW000101: Encoding Error

CW000101: Encoding Error

This error indicates an invalid encoding is attempting to be used and a default encoding of UTF-8 will be used. You can fix this by setting a valid encoding value.

jboss-logging-tools-2.2.1.Final/docs/expressions.html000066400000000000000000001051651356560461700226730ustar00rootroot00000000000000 Untitled
Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.
jboss-logging-tools-2.2.1.Final/docs/getting-started.html000066400000000000000000001133741356560461700234170ustar00rootroot00000000000000 Getting Started

Getting Started

To get started you need to include three dependencies in your project.

JBoss Logging

Required at compile time and runtime.

JBoss Logging Annotations

Required at compile time only.

JBoss Logging Processor

Required at compile time only.

If you’re using maven here is an example pom.xml snippet:

<dependencies>
    <!-- Required by the annotation processor and will be used at runtime -->
    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging-annotations</artifactId>
        <version>2.2.1.Final</version>
        <!-- This is a compile-time dependency of this project, but is not needed at compile or runtime by other
              projects that depend on this project.-->
        <scope>provided</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging-processor</artifactId>
        <version>2.2.1.Final</version>
        <!-- This is a compile-time dependency of this project, but is not needed at compile or runtime by other
              projects that depend on this project.-->
        <scope>provided</scope>
        <optional>true</optional>
    </dependency>
</dependencies>

Once your project is configured you can create either a message bundle interface or a message logger interface. For detailed information see the JavaDocs for the annotations.

jboss-logging-tools-2.2.1.Final/docs/index.html000066400000000000000000002151741356560461700214220ustar00rootroot00000000000000 JBoss Logging Tools

Introduction

The JBoss logging tools are used to create internationalized log statements and exceptions.

Getting Started

To get started you need to include three dependencies in your project.

JBoss Logging

Required at compile time and runtime.

JBoss Logging Annotations

Required at compile time only.

JBoss Logging Processor

Required at compile time only.

If you’re using maven here is an example pom.xml snippet:

<dependencies>
    <!-- Required by the annotation processor and will be used at runtime -->
    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging</artifactId>
    </dependency>

    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging-annotations</artifactId>
        <version>2.2.1.Final</version>
        <!-- This is a compile-time dependency of this project, but is not needed at compile or runtime by other
              projects that depend on this project.-->
        <scope>provided</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.jboss.logging</groupId>
        <artifactId>jboss-logging-processor</artifactId>
        <version>2.2.1.Final</version>
        <!-- This is a compile-time dependency of this project, but is not needed at compile or runtime by other
              projects that depend on this project.-->
        <scope>provided</scope>
        <optional>true</optional>
    </dependency>
</dependencies>

Once your project is configured you can create either a message bundle interface or a message logger interface. For detailed information see the JavaDocs for the annotations.

Message Bundle Interfaces

Message bundle interfaces provide a way to internationalize exceptions or strings. A message bundle interface is annotated with @MessageBundle. Each method in must be annotated with @Message which will be used to determine the String used for either the return type or the message for the exception being returned.

The value for a @Message may contain an expression.

Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

The following constraints are placed on methods in a message bundle:

  • The return type must be one of the follow

    • A java.lang.String

    • A java.lang.Throwable or a subtype of java.lang.Throwable

    • A java.lang.function.Supplier who’s return type fits one of the other two constraints above.

  • The method must be annotated with @Message or a message must be inheritable.

  • A method can have only one @Cause parameter.

  • A method can only have one @Producer parameter.

A message is inheritable if the two methods have the same name and same number of format parameters.
A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; @FormatWith, @Pos or @Transform.

Example Message Bundle

@MessageBundle(projectCode = "CW") (1)
public interface ErrorMessages {
    ErrorMessages MESSAGES = Messages.getBundle(ErrorMessages.class);

    @Message("Version %d.%d.%d.%s") (2)
    String version(int major, int minor, int macro, String rel);

    @Message(id = 1, value = "Value '%s' is invalid")
    IllegalArgumentException invalidValue(Object value);

    @Message(id = 2, value = "Failure closing %s") (3)
    CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c);

    CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c, @Suppressed Throwable... errors);

    @Message(id = 3, value = "Parameter %s cannot be null")
    Supplier<String> nullParam(String name);

    @Message(id = 4, value = "Operation %s failed.")
    <T extends RuntimeException> T operationFailed(@Producer Function<String, T> fn, String name); (4)

    <T extends RuntimeException> T operationFailed(@Producer BiFunction<String, IOException, T> fn, @Cause IOException cause, String name);
}
1 The projectCode will be prepended to messages which have an id specified. For example with id = 1 the message will be prepended with CW000001. You can control the number padding with the length property on the annotation.
2 No id is specified for this message which means no id will be prepended on this message.
3 The @Param annotation tells the generator that the parameter should be used to construct the CloseException. The @Pos(1) annotation indicates the parameter should also be used when formatting the message.
4 The @Producer annotation indicates that the Function should be used to create the exception being returned.
Message bundle interfaces can also contain valid message logger methods.

Message Logger Interfaces

Logger interfaces provide a way to internationalize log messages. A logger interface is an interface annotated with @MessageLogger. Each method in must be annotated with @Message which will be used to determine the message to be logged.

The value for a @Message may contain an expression.

Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

The following constraints are placed on methods in a message logger:

  • The method must have a void return type

  • The method must be annotated with @LogMessage

  • The method must be annotated with @Message or a message must be inheritable.

  • A method can have only one @Cause parameter.

A message is inheritable if the two methods have the same name and same number of format parameters.
A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; @FormatWith, @Pos or @Transform.

A message logger interface may also extend the org.jboss.logging.BasicLogger. This allows the logging interface to be usable for standard logging. For example AppLogger.LOGGER.debugf("Initializing %s", this);

Example Message Logger

@MessageLogger(projectCode = "CW") (1)
public interface AppLogger extends BasicLogger {

    AppLogger LOGGER = Logger.getMessageLogger(AppLogger.class, AppLogger.class.getPackage().getName());

    @LogMessage
    @Once (2)
    @Message("%s version %d.%d.%d.%s") (3)
    void appVersion(CharSequence name, int major, int minor, int macro, String rel);

    @LogMessage(level = Logger.Level.ERROR) (4)
    @Message(id = 100, value = "Failure while closing %s")
    void closeFailure(@Cause Throwable cause, Object obj);

    @LogMessage(level = Logger.Level.WARN)
    @Message(id = 101, value = "Encoding %s could not be found. Defaulting to %s.")
    void encodingNotFound(String encoding, Charset dft);

    @LogMessage
    @Message(id = 102, value = "Cache size changed to '%d'")
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Collection<String> c);

    @LogMessage
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) String... array);

    @LogMessage
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Map<String, Object> map);
}
1 The projectCode will be prepended to messages which have an id specified. For example with id = 100 the message will be prepended with CW000100. You can control the number padding with the length property on the annotation.
2 Ensures the log message is only written once.
3 No id is specified for this message which means no id will be prepended on this message.
4 Overrides the default level to ERROR to indicate an error message should be logged.

Reports

There are currently two types of reports that can be generated. The options are adoc or asciidoc for asciidoc and xml for XML.

The reports contain the following data:

  • The formatted message id.

  • A possible link to a resolution document for the error.

  • The unformatted message.

  • The log level, if applicable.

  • The return type, if applicable.

Annotations

Two annotations can be used to assist withing linking resolution documents for messages.

  • @BaseUrl

    • This annotation can be used on a type to define the base URL for linking resolution documents. This annotation is not required for links to be created on reports.

  • @ResolutionDoc

    • This annotation is used to define information about the resolution document for creating links. If placed on an interface all methods that have a defined id will have a link generated. This can also be placed individually on the method to only generate links for specific id’s.

Example Use Cases

Below are some example use case snippets from the examples.

/**
 * Writes the value of the object to the file.
 *
 * @param value the value to write, cannot be {@code null}
 *
 * @throws UncheckedIOException if an error occurs writing the data
 */
public void write(final Object value) {
    AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1"); (1)
    Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")); (2)
    write(Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).toString());
}

/**
 * Writes the value to the file.
 *
 * @param value the value to write, cannot be {@code null} or an {@linkplain String#isEmpty() empty string}.
 *
 * @throws UncheckedIOException if an error occurs writing the data
 */
public void write(final String value) {
    AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1");
    if (Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).isEmpty()) {
        throw ErrorMessages.MESSAGES.invalidValue(value); (3)
    }
    try {
        synchronized (outputLock) {
            writer.write(value);
            writer.newLine();
            if (autoFlush) {
                flush();
            }
        }
    } catch (IOException e) {
        throw ErrorMessages.MESSAGES.operationFailed(UncheckedIOException::new, e, "write"); (4)
    }
}

@Override
public void close() {
    try {
        synchronized (outputLock) {
            writer.close();
        }
        AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
    } catch (Exception e) {
        throw ErrorMessages.MESSAGES.closeFailure(e, this);
    }
}

/**
 * Safely close this writer logging any errors that occur during closing.
 */
public void safeClose() {
    try {
        synchronized (outputLock) {
            writer.close();
        }
        AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this);
    } catch (Exception e) {
        AppLogger.LOGGER.closeFailure(e, this); (5)
    }
}
1 Logs the application version. Note this uses the @Once annotation to indicate this should only be logged once regardless of which write method is used.
2 The ErrorMessages.nullParam() returns a java.lang.function.Supplier. This allows the message to be lazily formatted only if the value is null.
3 Throws a message if the value is an empty string.
4 Uses a java.lang.function.BiFunction to create a new UncheckedIOException with the caught exception set as the cause.
5 Logs the caught exception instead of throwing a new exception.

Translation Property Files

The translation properties files must exist in the same directory structure as the interface. The name of the properties file InterfaceName.i18n_language_country_variant.properties. For example if you have a class named org.jboss.logging.tools.examples.ErrorMessages and you want to translate this into French you create a properties file called ErrorMessages.i18n_fr.properties in a directory org/jboss/logging/tools/examples.

Annotation Processor Options

You can pass options to an annotation processor with the -A compiler option. For example to disable generating the @Generated annotation from being placed on the generated source files you would pass -Aorg.jboss.logging.tools.addGeneratedAnnotation=false to the compiler command.

General

Option Description

debug

This option turns on debug logging for the processor

org.jboss.logging.tools.expressionProperties

This option allows you to define a path where, at compile-time, expressions in messages can be resolved.

org.jboss.logging.tools.addGeneratedAnnotation

If set to false the @Generated annotation will not be placed on the generated source files. The default is true.

In Java 9 the @javax.annotation.Generated was moved to @javax.annotation.processor.Generated. The processor attempts to determine which annotation to use by attempting to find the @javax.annotation.Generated first. If it fails the @javax.annotation.processor.Generated is attempted. If neither can be found no annotation will be placed on the generated implementations.
Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

Translation Options

Option Description

translationsFilesPath

The base path for the translated properties files. This defaults to the location where new class files are placed.

skipTranslations

If set to true source files with the translated tet will not be generated. The default is false.

generatedTranslationFilesPath

If defined this indicates the path a skeleton file should be generated for the interface. The generated skeleton file will be placed in a directory that matches the package with a name that matches the interface with a .i18n_locale_COUNTRY_VARIANT.properties suffix.

org.jboss.logging.tools.level

Sets the maximum level to include in the generated skeleton files. For example if set to INFO the skeleton files will not contain any properties where the log level was set to DEBUG or TRACE.

org.jboss.logging.tools.generated.skip.index

By default when generating a skeleton translation file an index will be appended to the format pattern. For example Example %s and %d becomes Example %1$s and %2$d. This option allows this behavior to be disabled.

Report Options

Option Description

org.jboss.logging.tools.report.type

Indicates the type of report that should be generated. The current report types are adoc for asciidoc or xml for XML.

org.jboss.logging.tools.report.path

The path where the generated reports should be placed. This defaults to the location where new class files are placed.

org.jboss.logging.tools.report.title

An optional title for the report. For asciidoc this defaults to Messages. For XML the <title> element is left off.

jboss-logging-tools-2.2.1.Final/docs/js/000077500000000000000000000000001356560461700200275ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/js/links.js000066400000000000000000000004721356560461700215100ustar00rootroot00000000000000function annotationLinks() { var links = document.getElementsByTagName("a"); for(var i = 0, max = links.length; i < max; i++) { var l = links[i]; if (l.text.startsWith("@")) { l.href = l.href + "/org/jboss/logging/annotations/" + l.text.substring(1) + ".html"; } } }jboss-logging-tools-2.2.1.Final/docs/message-bundle.html000066400000000000000000001237301356560461700232020ustar00rootroot00000000000000 Message Bundle Interfaces

Message Bundle Interfaces

Message bundle interfaces provide a way to internationalize exceptions or strings. A message bundle interface is annotated with @MessageBundle. Each method in must be annotated with @Message which will be used to determine the String used for either the return type or the message for the exception being returned.

The value for a @Message may contain an expression.

Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

The following constraints are placed on methods in a message bundle:

  • The return type must be one of the follow

    • A java.lang.String

    • A java.lang.Throwable or a subtype of java.lang.Throwable

    • A java.lang.function.Supplier who’s return type fits one of the other two constraints above.

  • The method must be annotated with @Message or a message must be inheritable.

  • A method can have only one @Cause parameter.

  • A method can only have one @Producer parameter.

A message is inheritable if the two methods have the same name and same number of format parameters.
A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; @FormatWith, @Pos or @Transform.

Example Message Bundle

@MessageBundle(projectCode = "CW") (1)
public interface ErrorMessages {
    ErrorMessages MESSAGES = Messages.getBundle(ErrorMessages.class);

    @Message("Version %d.%d.%d.%s") (2)
    String version(int major, int minor, int macro, String rel);

    @Message(id = 1, value = "Value '%s' is invalid")
    IllegalArgumentException invalidValue(Object value);

    @Message(id = 2, value = "Failure closing %s") (3)
    CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c);

    CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c, @Suppressed Throwable... errors);

    @Message(id = 3, value = "Parameter %s cannot be null")
    Supplier<String> nullParam(String name);

    @Message(id = 4, value = "Operation %s failed.")
    <T extends RuntimeException> T operationFailed(@Producer Function<String, T> fn, String name); (4)

    <T extends RuntimeException> T operationFailed(@Producer BiFunction<String, IOException, T> fn, @Cause IOException cause, String name);
}
1 The projectCode will be prepended to messages which have an id specified. For example with id = 1 the message will be prepended with CW000001. You can control the number padding with the length property on the annotation.
2 No id is specified for this message which means no id will be prepended on this message.
3 The @Param annotation tells the generator that the parameter should be used to construct the CloseException. The @Pos(1) annotation indicates the parameter should also be used when formatting the message.
4 The @Producer annotation indicates that the Function should be used to create the exception being returned.
Message bundle interfaces can also contain valid message logger methods.
jboss-logging-tools-2.2.1.Final/docs/message-logger.html000066400000000000000000001223031356560461700232030ustar00rootroot00000000000000 Message Logger Interfaces

Message Logger Interfaces

Logger interfaces provide a way to internationalize log messages. A logger interface is an interface annotated with @MessageLogger. Each method in must be annotated with @Message which will be used to determine the message to be logged.

The value for a @Message may contain an expression.

Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

The following constraints are placed on methods in a message logger:

  • The method must have a void return type

  • The method must be annotated with @LogMessage

  • The method must be annotated with @Message or a message must be inheritable.

  • A method can have only one @Cause parameter.

A message is inheritable if the two methods have the same name and same number of format parameters.
A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; @FormatWith, @Pos or @Transform.

A message logger interface may also extend the org.jboss.logging.BasicLogger. This allows the logging interface to be usable for standard logging. For example AppLogger.LOGGER.debugf("Initializing %s", this);

Example Message Logger

@MessageLogger(projectCode = "CW") (1)
public interface AppLogger extends BasicLogger {

    AppLogger LOGGER = Logger.getMessageLogger(AppLogger.class, AppLogger.class.getPackage().getName());

    @LogMessage
    @Once (2)
    @Message("%s version %d.%d.%d.%s") (3)
    void appVersion(CharSequence name, int major, int minor, int macro, String rel);

    @LogMessage(level = Logger.Level.ERROR) (4)
    @Message(id = 100, value = "Failure while closing %s")
    void closeFailure(@Cause Throwable cause, Object obj);

    @LogMessage(level = Logger.Level.WARN)
    @Message(id = 101, value = "Encoding %s could not be found. Defaulting to %s.")
    void encodingNotFound(String encoding, Charset dft);

    @LogMessage
    @Message(id = 102, value = "Cache size changed to '%d'")
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Collection<String> c);

    @LogMessage
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) String... array);

    @LogMessage
    void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Map<String, Object> map);
}
1 The projectCode will be prepended to messages which have an id specified. For example with id = 100 the message will be prepended with CW000100. You can control the number padding with the length property on the annotation.
2 Ensures the log message is only written once.
3 No id is specified for this message which means no id will be prepended on this message.
4 Overrides the default level to ERROR to indicate an error message should be logged.
jboss-logging-tools-2.2.1.Final/docs/pom.xml000066400000000000000000000230461356560461700207350ustar00rootroot00000000000000 4.0.0 org.jboss.logging jboss-logging-tools-parent 2.2.1.Final ../pom.xml jboss-logging-tools-docs jar JBoss Logging I18n Documentation Apache License, version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo 1.6.0 apidocs ${project.build.directory}/site/${java.docs.dir} org.jboss.logging jboss-logging provided org.jboss.logging jboss-logging-annotations ${project.version} provided true org.jboss.logging jboss-logging-processor ${project.version} provided true generate-site generate-site maven-clean-plugin ${java.docs.dir}/ examples/ ${project.basedir} *.html org.apache.maven.plugins maven-compiler-plugin -Aorg.jboss.logging.tools.report.type=adoc -Aorg.jboss.logging.tools.report.path=${project.reporting.outputDirectory}/adoc -Aorg.jboss.logging.tools.report.title=Example Messages maven-javadoc-plugin create-javadoc generate-resources javadoc true ${project.reporting.outputDirectory}/${java.docs.dir} *.examples.* true org.jboss.logging:jboss-logging-annotations:* true maven-resources-plugin copy-javadoc process-resources copy-resources ${project.basedir}/${java.docs.dir} ${project.reporting.outputDirectory}/${java.docs.dir} org.asciidoctor asciidoctor-maven-plugin ${version.asciidoctor} html5 coderay font true - true ${java.docs.dir} ${project.version} ${project.version} ${project.organization.name} ${project.basedir} output-html generate-resources process-asciidoc true output-report-html process-classes process-asciidoc ${project.reporting.outputDirectory}/adoc/ ${project.basedir}/examples/ jboss-logging-tools-2.2.1.Final/docs/processor-options.html000066400000000000000000001216241356560461700240170ustar00rootroot00000000000000 Annotation Processor Options

Annotation Processor Options

You can pass options to an annotation processor with the -A compiler option. For example to disable generating the @Generated annotation from being placed on the generated source files you would pass -Aorg.jboss.logging.tools.addGeneratedAnnotation=false to the compiler command.

General

Option Description

debug

This option turns on debug logging for the processor

org.jboss.logging.tools.expressionProperties

This option allows you to define a path where, at compile-time, expressions in messages can be resolved.

org.jboss.logging.tools.addGeneratedAnnotation

If set to false the @Generated annotation will not be placed on the generated source files. The default is true.

In Java 9 the @javax.annotation.Generated was moved to @javax.annotation.processor.Generated. The processor attempts to determine which annotation to use by attempting to find the @javax.annotation.Generated first. If it fails the @javax.annotation.processor.Generated is attempted. If neither can be found no annotation will be placed on the generated implementations.
Expressions are in the form of ${key:defaultValue}. If the key is prefixed with sys. a system property is used. If the key is prefixed with env. an environment variable is used. In all other cases the properties are resolved from the org.jboss.logging.tools.expressionProperties path. If the key is not found in the properties the default value will be used.
Expressions are processed at compile time. The values will be hard-coded in the generated source files.

Translation Options

Option Description

translationsFilesPath

The base path for the translated properties files. This defaults to the location where new class files are placed.

skipTranslations

If set to true source files with the translated tet will not be generated. The default is false.

generatedTranslationFilesPath

If defined this indicates the path a skeleton file should be generated for the interface. The generated skeleton file will be placed in a directory that matches the package with a name that matches the interface with a .i18n_locale_COUNTRY_VARIANT.properties suffix.

org.jboss.logging.tools.level

Sets the maximum level to include in the generated skeleton files. For example if set to INFO the skeleton files will not contain any properties where the log level was set to DEBUG or TRACE.

org.jboss.logging.tools.generated.skip.index

By default when generating a skeleton translation file an index will be appended to the format pattern. For example Example %s and %d becomes Example %1$s and %2$d. This option allows this behavior to be disabled.

Report Options

Option Description

org.jboss.logging.tools.report.type

Indicates the type of report that should be generated. The current report types are adoc for asciidoc or xml for XML.

org.jboss.logging.tools.report.path

The path where the generated reports should be placed. This defaults to the location where new class files are placed.

org.jboss.logging.tools.report.title

An optional title for the report. For asciidoc this defaults to Messages. For XML the <title> element is left off.

jboss-logging-tools-2.2.1.Final/docs/reports.html000066400000000000000000001066401356560461700220060ustar00rootroot00000000000000 Reports

Reports

There are currently two types of reports that can be generated. The options are adoc or asciidoc for asciidoc and xml for XML.

The reports contain the following data:

  • The formatted message id.

  • A possible link to a resolution document for the error.

  • The unformatted message.

  • The log level, if applicable.

  • The return type, if applicable.

Annotations

Two annotations can be used to assist withing linking resolution documents for messages.

  • @BaseUrl

    • This annotation can be used on a type to define the base URL for linking resolution documents. This annotation is not required for links to be created on reports.

  • @ResolutionDoc

    • This annotation is used to define information about the resolution document for creating links. If placed on an interface all methods that have a defined id will have a link generated. This can also be placed individually on the method to only generate links for specific id’s.

jboss-logging-tools-2.2.1.Final/docs/src/000077500000000000000000000000001356560461700202025ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/000077500000000000000000000000001356560461700211265ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/000077500000000000000000000000001356560461700227045ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/default-notes.adoc000066400000000000000000000005051356560461700263060ustar00rootroot00000000000000NOTE: A message is inheritable if the two methods have the same name and same number of format parameters. NOTE: A format parameter is a parameter that has no annotations or is annotated with one of the following annotations; link:{javadocsdir}[`@FormatWith`], link:{javadocsdir}[`@Pos`] or link:{javadocsdir}[`@Transform`].jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/docinfo-footer.html000066400000000000000000000001311356560461700265020ustar00rootroot00000000000000 jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples.adoc000066400000000000000000000016311356560461700253530ustar00rootroot00000000000000 :sourcedir: java/org/jboss/logging/tools/examples :projecturl: https://github.com/jboss-logging/jboss-logging-tools/docs/src/main == Example Use Cases Below are some example use case snippets from the link:{projecturl}/{sourcedir}[examples]. [source,java,indent=0] ---- include::../{sourcedir}/ContentWriter.java[tags=write;close] ---- <1> Logs the application version. Note this uses the link:{javadocsdir}[@Once] annotation to indicate this should only be logged once regardless of which `write` method is used. <2> The `ErrorMessages.nullParam()` returns a `java.lang.function.Supplier`. This allows the message to be lazily formatted only if the `value` is `null`. <3> Throws a message if the `value` is an empty string. <4> Uses a `java.lang.function.BiFunction` to create a new `UncheckedIOException` with the caught exception set as the cause. <5> Logs the caught exception instead of throwing a new exception.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples/000077500000000000000000000000001356560461700245225ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples/errors/000077500000000000000000000000001356560461700260365ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples/errors/CW000003.adoc000066400000000000000000000001701356560461700276400ustar00rootroot00000000000000== CW000003: Null Parameter This error indicates you've passed a `null` parameter where a `non-null` value is required.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples/errors/CW000100.adoc000066400000000000000000000002341356560461700276370ustar00rootroot00000000000000== CW000100: Close Failure This error indicates there was a failure closing a resource. Please see previous error messages and contact support if required.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/examples/errors/CW000101.adoc000066400000000000000000000003001356560461700276320ustar00rootroot00000000000000== CW000101: Encoding Error This error indicates an invalid encoding is attempting to be used and a default encoding of UTF-8 will be used. You can fix this by setting a valid encoding value.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/expressions.adoc000066400000000000000000000007511356560461700261210ustar00rootroot00000000000000 NOTE: Expressions are in the form of `${key:defaultValue}`. If the key is prefixed with `sys.` a system property is used. If the key is prefixed with `env.` an environment variable is used. In all other cases the properties are resolved from the `org.jboss.logging.tools.expressionProperties` path. If the key is not found in the properties the default value will be used. IMPORTANT: Expressions are processed at compile time. The values will be hard-coded in the generated source files.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/getting-started.adoc000066400000000000000000000036011356560461700266410ustar00rootroot00000000000000:repourl: https://repository.jboss.org/org/jboss/logging == Getting Started To get started you need to include three dependencies in your project. [frame=none,grid=none,options="noheader"] |=== | link:{repourl}/jboss-logging/[JBoss Logging] | Required at compile time and runtime. | link:{repourl}/jboss-logging-annotations/[JBoss Logging Annotations] | Required at compile time only. | link:{repourl}/jboss-logging-processor/[JBoss Logging Processor] | Required at compile time only. |=== If you're using maven here is an example `pom.xml` snippet: [source,xml,subs="attributes+"] ---- org.jboss.logging jboss-logging org.jboss.logging jboss-logging-annotations {version} provided true org.jboss.logging jboss-logging-processor {version} provided true ---- Once your project is configured you can create either a <> or a <>. For detailed information see the link:{javadocsdir}/index.html[JavaDocs] for the annotations.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/index.adoc000066400000000000000000000007441356560461700246500ustar00rootroot00000000000000= JBoss Logging Tools :Author: James R. Perkins :Email: :docinfo: shared :toc: left :scriptsdir: ./js == Introduction The JBoss logging tools are used to create internationalized log statements and exceptions. include::getting-started.adoc[] include::message-bundle.adoc[] include::message-logger.adoc[] include::reports.adoc[] include::examples.adoc[] include::translation-property-files.adoc[] include::processor-options.adoc[]jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/js/000077500000000000000000000000001356560461700233205ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/js/links.js000066400000000000000000000004721356560461700250010ustar00rootroot00000000000000function annotationLinks() { var links = document.getElementsByTagName("a"); for(var i = 0, max = links.length; i < max; i++) { var l = links[i]; if (l.text.startsWith("@")) { l.href = l.href + "/org/jboss/logging/annotations/" + l.text.substring(1) + ".html"; } } }jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/message-bundle.adoc000066400000000000000000000055511356560461700264350ustar00rootroot00000000000000 == Message Bundle Interfaces Message bundle interfaces provide a way to internationalize exceptions or strings. A message bundle interface is annotated with link:{javadocsdir}[`@MessageBundle`]. Each method in must be annotated with link:{javadocsdir}[`@Message`] which will be used to determine the String used for either the return type or the message for the exception being returned. The value for a link:{javadocsdir}[`@Message`] may contain an expression. include::expressions.adoc[] The following constraints are placed on methods in a message bundle: - The return type must be one of the follow * A `java.lang.String` * A `java.lang.Throwable` or a subtype of `java.lang.Throwable` * A `java.lang.function.Supplier` who's return type fits one of the other two constraints above. - The method must be annotated with link:{javadocsdir}[`@Message`] or a message must be inheritable. - A method can have only one link:{javadocsdir}[`@Cause`] parameter. - A method can only have one link:{javadocsdir}[`@Producer`] parameter. include::default-notes.adoc[] === Example Message Bundle [source,java] ---- @MessageBundle(projectCode = "CW") <1> public interface ErrorMessages { ErrorMessages MESSAGES = Messages.getBundle(ErrorMessages.class); @Message("Version %d.%d.%d.%s") <2> String version(int major, int minor, int macro, String rel); @Message(id = 1, value = "Value '%s' is invalid") IllegalArgumentException invalidValue(Object value); @Message(id = 2, value = "Failure closing %s") <3> CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c); CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c, @Suppressed Throwable... errors); @Message(id = 3, value = "Parameter %s cannot be null") Supplier nullParam(String name); @Message(id = 4, value = "Operation %s failed.") T operationFailed(@Producer Function fn, String name); <4> T operationFailed(@Producer BiFunction fn, @Cause IOException cause, String name); } ---- <1> The `projectCode` will be prepended to messages which have an `id` specified. For example with `id = 1` the message will be prepended with `CW000001`. You can control the number padding with the `length` property on the annotation. <2> No `id` is specified for this message which means no id will be prepended on this message. <3> The `@Param` annotation tells the generator that the parameter should be used to construct the `CloseException`. The `@Pos(1)` annotation indicates the parameter should also be used when formatting the message. <4> The `@Producer` annotation indicates that the `Function` should be used to create the exception being returned. TIP: Message bundle interfaces can also contain valid <>.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/message-logger.adoc000066400000000000000000000051041356560461700264350ustar00rootroot00000000000000 == Message Logger Interfaces Logger interfaces provide a way to internationalize log messages. A logger interface is an interface annotated with link:{javadocsdir}[`@MessageLogger`]. Each method in must be annotated with link:{javadocsdir}[`@Message`] which will be used to determine the message to be logged. The value for a link:{javadocsdir}[`@Message`] may contain an expression. include::expressions.adoc[] The following constraints are placed on methods in a message logger: - The method must have a `void` return type - The method must be annotated with link:{javadocsdir}[`@LogMessage`] - The method must be annotated with link:{javadocsdir}[`@Message`] or a message must be inheritable. - A method can have only one link:{javadocsdir}[`@Cause`] parameter. include::default-notes.adoc[] A message logger interface may also extend the `org.jboss.logging.BasicLogger`. This allows the logging interface to be usable for standard logging. For example `AppLogger.LOGGER.debugf("Initializing %s", this);` === Example Message Logger [source,java] ---- @MessageLogger(projectCode = "CW") <1> public interface AppLogger extends BasicLogger { AppLogger LOGGER = Logger.getMessageLogger(AppLogger.class, AppLogger.class.getPackage().getName()); @LogMessage @Once <2> @Message("%s version %d.%d.%d.%s") <3> void appVersion(CharSequence name, int major, int minor, int macro, String rel); @LogMessage(level = Logger.Level.ERROR) <4> @Message(id = 100, value = "Failure while closing %s") void closeFailure(@Cause Throwable cause, Object obj); @LogMessage(level = Logger.Level.WARN) @Message(id = 101, value = "Encoding %s could not be found. Defaulting to %s.") void encodingNotFound(String encoding, Charset dft); @LogMessage @Message(id = 102, value = "Cache size changed to '%d'") void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Collection c); @LogMessage void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) String... array); @LogMessage void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Map map); } ---- <1> The `projectCode` will be prepended to messages which have an `id` specified. For example with `id = 100` the message will be prepended with `CW000100`. You can control the number padding with the `length` property on the annotation. <2> Ensures the log message is only written once. <3> No `id` is specified for this message which means no id will be prepended on this message. <4> Overrides the default level to `ERROR` to indicate an error message should be logged.jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/processor-options.adoc000066400000000000000000000055521356560461700272530ustar00rootroot00000000000000 == Annotation Processor Options You can pass options to an annotation processor with the `-A` compiler option. For example to disable generating the `@Generated` annotation from being placed on the generated source files you would pass `-Aorg.jboss.logging.tools.addGeneratedAnnotation=false` to the compiler command. === General [frame=none,grid=none] |=== | Option | Description | `debug` | This option turns on debug logging for the processor | `org.jboss.logging.tools.expressionProperties` | This option allows you to define a path where, at compile-time, expressions in messages can be resolved. | `org.jboss.logging.tools.addGeneratedAnnotation` | If set to `false` the `@Generated` annotation will not be placed on the generated source files. The default is `true`. |=== NOTE: In Java 9 the `@javax.annotation.Generated` was moved to `@javax.annotation.processor.Generated`. The processor attempts to determine which annotation to use by attempting to find the `@javax.annotation.Generated` first. If it fails the `@javax.annotation.processor.Generated` is attempted. If neither can be found no annotation will be placed on the generated implementations. include::expressions.adoc[] === Translation Options [frame=none,grid=none] |=== | Option | Description | `translationsFilesPath` | The base path for the translated properties files. This defaults to the location where new class files are placed. | `skipTranslations` | If set to `true` source files with the translated tet will not be generated. The default is `false`. | `generatedTranslationFilesPath` | If defined this indicates the path a skeleton file should be generated for the interface. The generated skeleton file will be placed in a directory that matches the package with a name that matches the interface with a `.i18n_locale_COUNTRY_VARIANT.properties` suffix. | `org.jboss.logging.tools.level` | Sets the maximum level to include in the generated skeleton files. For example if set to `INFO` the skeleton files will not contain any properties where the log level was set to `DEBUG` or `TRACE`. | `org.jboss.logging.tools.generated.skip.index` | By default when generating a skeleton translation file an index will be appended to the format pattern. For example `Example %s and %d` becomes `Example %1$s and %2$d`. This option allows this behavior to be disabled. |=== === Report Options [frame=none,grid=none] |=== | Option | Description | `org.jboss.logging.tools.report.type` | Indicates the type of report that should be generated. The current report types are `adoc` for asciidoc or `xml` for XML. | `org.jboss.logging.tools.report.path` | The path where the generated reports should be placed. This defaults to the location where new class files are placed. | `org.jboss.logging.tools.report.title` | An optional title for the report. For asciidoc this defaults to `Messages`. For XML the `` element is left off. |===������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/reports.adoc���������������������������������0000664�0000000�0000000�00000001757�13565604617�0025244�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ == Reports There are currently two types of reports that can be generated. The options are `adoc` or `asciidoc` for asciidoc and `xml` for XML. The reports contain the following data: * The formatted message id. * A possible link to a resolution document for the error. * The unformatted message. * The log level, if applicable. * The return type, if applicable. === Annotations Two annotations can be used to assist withing linking resolution documents for messages. * link:{javadocsdir}[`@BaseUrl`] - This annotation can be used on a type to define the base URL for linking resolution documents. This annotation is not required for links to be created on reports. * link:{javadocsdir}[`@ResolutionDoc`] - This annotation is used to define information about the resolution document for creating links. If placed on an interface all methods that have a defined id will have a link generated. This can also be placed individually on the method to only generate links for specific id's.�����������������jboss-logging-tools-2.2.1.Final/docs/src/main/asciidoc/translation-property-files.adoc��������������0000664�0000000�0000000�00000000723�13565604617�0031056�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������ == Translation Property Files The translation properties files must exist in the same directory structure as the interface. The name of the properties file `InterfaceName.i18n_language_country_variant.properties`. For example if you have a class named `org.jboss.logging.tools.examples.ErrorMessages` and you want to translate this into French you create a properties file called `ErrorMessages.i18n_fr.properties` in a directory `org/jboss/logging/tools/examples`.���������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/�������������������������������������������������0000775�0000000�0000000�00000000000�13565604617�0022047�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/���������������������������������������������0000775�0000000�0000000�00000000000�13565604617�0022636�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/���������������������������������������0000775�0000000�0000000�00000000000�13565604617�0023756�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/�������������������������������0000775�0000000�0000000�00000000000�13565604617�0025404�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/�������������������������0000775�0000000�0000000�00000000000�13565604617�0026544�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples/����������������0000775�0000000�0000000�00000000000�13565604617�0030362�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples/AppLogger.java��0000664�0000000�0000000�00000007463�13565604617�0033117�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.tools.examples; import java.nio.charset.Charset; import java.util.Collection; import java.util.Map; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Once; import org.jboss.logging.annotations.ResolutionDoc; import org.jboss.logging.annotations.Transform; /** * A common logger for the application. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings({"unused", "SameParameterValue"}) @MessageLogger(projectCode = "CW") @ResolutionDoc(url = "errors", suffix = ".html") public interface AppLogger extends BasicLogger { AppLogger LOGGER = Logger.getMessageLogger(AppLogger.class, AppLogger.class.getPackage().getName()); /** * Logs an informational message, once, indicating the applications version. * * @param name the name of the application * @param major the major version * @param minor the minor version * @param macro the macro version * @param rel the release suffix, e.g. {@code Beta1}, {@code Final} */ @LogMessage @Once @Message("%s version %d.%d.%d.%s") void appVersion(CharSequence name, int major, int minor, int macro, String rel); /** * Logs an error message indicating a failure to close the object. * * @param cause the cause of the error * @param obj the object that failed closing */ @LogMessage(level = Logger.Level.ERROR) @Message(id = 100, value = "Failure while closing %s") void closeFailure(@Cause Throwable cause, Object obj); /** * Logs a warning message indicating the encoding is invalid and a default encoding will be used. * * @param encoding the invalid encoding * @param dft the default encoding */ @LogMessage(level = Logger.Level.WARN) @Message(id = 101, value = "Encoding %s could not be found. Defaulting to %s.") void encodingNotFound(String encoding, Charset dft); /** * Logs an informational message indicating the cache size has changed and the size the cache is now. * * @param c the collection holding the cache */ @LogMessage @Message(id = 102, value = "Cache size changed to '%d'") @ResolutionDoc(skip = true) void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Collection<String> c); /** * Logs an informational message indicating the cache size has changed and the size the cache is now. * * @param array the cache arracy */ @LogMessage @ResolutionDoc(skip = true) void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) String... array); /** * Logs an informational message indicating the cache size has changed and the size the cache is now. * * @param map the map holding the cache */ @LogMessage @ResolutionDoc(skip = true) void cacheSizeChanged(@Transform(Transform.TransformType.SIZE) Map<String, Object> map); } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������CloseException.java���������������������������������������������������������������������������������0000664�0000000�0000000�00000003473�13565604617�0034101�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000�jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples������������������������������������������������������������������������������������/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.tools.examples; import java.io.Closeable; /** * An error with access to the failing {@link Closeable}. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings("unused") public class CloseException extends RuntimeException { private final Closeable closeable; /** * Creates a new error. * * @param msg the message for the error * @param closeable the failed closeable */ public CloseException(final String msg, final Closeable closeable) { super(msg); this.closeable = closeable; } /** * Creates a new error. * * @param msg the message for the error * @param cause the cause of the error * @param closeable the failed closeable */ public CloseException(final String msg, final Throwable cause, final Closeable closeable) { super(msg, cause); this.closeable = closeable; } /** * Returns the failed closeable. * * @return the failed closeable */ public Closeable getCloseable() { return closeable; } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ContentWriter.java����������������������������������������������������������������������������������0000664�0000000�0000000�00000012231�13565604617�0033754�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000�jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples������������������������������������������������������������������������������������/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.tools.examples; import java.io.BufferedWriter; import java.io.Closeable; import java.io.Flushable; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.Objects; /** * A writer for writing content to a file. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings({"unused", "WeakerAccess"}) public class ContentWriter implements Closeable, Flushable { private final Object outputLock = new Object(); private final Path contentPath; private final BufferedWriter writer; private volatile boolean autoFlush = true; ContentWriter(final Path contentPath, final BufferedWriter writer) { this.contentPath = Objects.requireNonNull(contentPath, ErrorMessages.MESSAGES.nullParam("contentPath")); this.writer = Objects.requireNonNull(writer, ErrorMessages.MESSAGES.nullParam("writer")); } // tag::write[] /** * Writes the value of the object to the file. * * @param value the value to write, cannot be {@code null} * * @throws UncheckedIOException if an error occurs writing the data */ public void write(final Object value) { AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1"); // <1> Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")); // <2> write(Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).toString()); } /** * Writes the value to the file. * * @param value the value to write, cannot be {@code null} or an {@linkplain String#isEmpty() empty string}. * * @throws UncheckedIOException if an error occurs writing the data */ public void write(final String value) { AppLogger.LOGGER.appVersion("ContentWriter", 1, 0, 0, "Beta1"); if (Objects.requireNonNull(value, ErrorMessages.MESSAGES.nullParam("value")).isEmpty()) { throw ErrorMessages.MESSAGES.invalidValue(value); // <3> } try { synchronized (outputLock) { writer.write(value); writer.newLine(); if (autoFlush) { flush(); } } } catch (IOException e) { throw ErrorMessages.MESSAGES.operationFailed(UncheckedIOException::new, e, "write"); // <4> } } // end::write[] /** * Set the value to {@code false} if the buffer should not automatically {@linkplain #flush() flush} on each write. * <p> * Defaults to {@code true}. * </p> * * @param autoFlush {@code true} to {@linkplain #flush() flush} on each write, otherwise {@code false} to flush * when the buffer determines it should be flushed */ public void setAutoFlush(final boolean autoFlush) { this.autoFlush = autoFlush; } // tag::close[] @Override public void close() { try { synchronized (outputLock) { writer.close(); } AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this); } catch (Exception e) { throw ErrorMessages.MESSAGES.closeFailure(e, this); } } /** * Safely close this writer logging any errors that occur during closing. */ public void safeClose() { try { synchronized (outputLock) { writer.close(); } AppLogger.LOGGER.tracef("ContentWriter %s was successfully closed.", this); } catch (Exception e) { AppLogger.LOGGER.closeFailure(e, this); // <5> } } // end::close[] @Override public void flush() { try { synchronized (outputLock) { writer.flush(); } } catch (IOException e) { throw ErrorMessages.MESSAGES.operationFailed(UncheckedIOException::new, e, "flush"); } } @Override public int hashCode() { return Objects.hash(contentPath); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof ContentWriter)) { return false; } final ContentWriter other = (ContentWriter) obj; return Objects.equals(contentPath, other.contentPath); } @Override public String toString() { return "ContentWriter[" + contentPath.toAbsolutePath() + "]"; } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ContentWriterBuilder.java���������������������������������������������������������������������������0000664�0000000�0000000�00000007133�13565604617�0035270�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000�jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples������������������������������������������������������������������������������������/* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.tools.examples; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Objects; /** * Builds a {@link ContentWriter}. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings("unused") public class ContentWriterBuilder { private final Path path; private boolean append = true; private String encoding = null; private ContentWriterBuilder(final Path path) { this.path = path; } /** * Creates a new builder. * * @param path the path where the content should be written to, cannot be {@code null} * * @return the new content writer */ public static ContentWriterBuilder of(final Path path) { Objects.requireNonNull(path, ErrorMessages.MESSAGES.nullParam("path")); return new ContentWriterBuilder(path); } /** * Set the encoding of for the content. If the encoding is not a valid {@link Charset} a default encoding of * {@link StandardCharsets#UTF_8} will be used. * * @param encoding the encoding to use * * @return this builder */ public ContentWriterBuilder setEncoding(final String encoding) { this.encoding = encoding; return this; } /** * Indicates whether or not the content should be appended to any previous content already written. The default * value is {@link true}. * * @param append {@code false} if the created writer should overwrite previously written content, otherwise * {@code true} * * @return this builder */ public ContentWriterBuilder setAppend(final boolean append) { this.append = append; return this; } /** * Creates the {@link ContentWriter}. * * @return the created writer * * @throws IOException if a failure creating the writer occurs */ public ContentWriter build() throws IOException { final OpenOption[] options; if (append) { options = new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.APPEND}; } else { options = new OpenOption[] {StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING}; } Charset charset = StandardCharsets.UTF_8; if (encoding != null) { try { charset = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { AppLogger.LOGGER.encodingNotFound(encoding, charset); } } final BufferedWriter writer = Files.newBufferedWriter(path, charset, options); return new ContentWriter(path, writer); } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ErrorMessages.java����������������������������������������������������������������������������������0000664�0000000�0000000�00000012445�13565604617�0033735�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000�jboss-logging-tools-2.2.1.Final/docs/src/main/java/org/jboss/logging/tools/examples������������������������������������������������������������������������������������ /* * JBoss, Home of Professional Open Source. * * Copyright 2017 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.logging.tools.examples; import java.io.Closeable; import java.io.IOException; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import org.jboss.logging.Messages; import org.jboss.logging.annotations.BaseUrl; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Producer; import org.jboss.logging.annotations.ResolutionDoc; import org.jboss.logging.annotations.Suppressed; /** * Common error messages for the application. * * @author <a href="mailto:jperkins@redhat.com">James R. Perkins</a> */ @SuppressWarnings("unused") @MessageBundle(projectCode = "CW") @BaseUrl("errors/") public interface ErrorMessages { /** * The static message instance. */ ErrorMessages MESSAGES = Messages.getBundle(ErrorMessages.class); /** * Returns the internationalized version message. * * @param major the major version * @param minor the minor version * @param macro the macro version * @param rel the release suffix, e.g. {@code Beta1}, {@code Final} * * @return the formatted version */ @Message("Version %d.%d.%d.%s") String version(int major, int minor, int macro, String rel); /** * Creates an exception indicating the value is invalid. * * @param value the invalid value * * @return an {@link IllegalStateException} for the error */ @Message(id = 1, value = "Value '%s' is invalid") IllegalArgumentException invalidValue(Object value); /** * Creates an exception indicating a failure to close the {@link Closeable} * * @param cause the cause of the error * @param c the closeable that failed * * @return a {@link CloseException} for the error */ @Message(id = 2, value = "Failure closing %s") CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c); /** * Creates an exception indicating a failure to close the {@link Closeable} * * @param cause the cause of the error * @param c the closeable that failed * @param errors errors that should be added as {@linkplain Throwable#getSuppressed() suppressed exceptions}. * * @return a {@link CloseException} for the error */ CloseException closeFailure(@Cause Throwable cause, @Param @Pos(1) Closeable c, @Suppressed Throwable... errors); /** * Creates a message indicating the parameter is {@code null}. * <p> * This can be used to lazily format the message for {@code null} checks like * {@link java.util.Objects#requireNonNull(Object, Supplier)}. * </p> * * @param name the name of the parameter * * @return a supplier for the message */ @Message(id = 3, value = "Parameter %s cannot be null") @ResolutionDoc(suffix = ".html") Supplier<String> nullParam(String name); /** * Uses the producer function to create the returned exception indicating the operation has failed. * <p> * The formatted value of the message will be the parameter for the functions * {@linkplain Function#apply(Object) apply} method. * </p> * * @param fn the function to produce the returned exception * @param name the name of the operation that failed * @param <T> the type of the exception to return, must be assignable to a {@link RuntimeException} * * @return the produced exception for the error */ @Message(id = 4, value = "Operation %s failed.") <T extends RuntimeException> T operationFailed(@Producer Function<String, T> fn, String name); /** * Uses the producer function to create the returned exception indicating the operation has failed. * <p> * The formatted value of the message will be the first parameter for the functions * {@linkplain BiFunction#apply(Object, Object)} apply} method. The second parameter will be the cause. * </p> * * @param fn the function to produce the returned exception * @param cause the cause of the exception to pass to the function * @param name the name of the operation that failed * @param <T> the type of the exception to return, must be assignable to a {@link RuntimeException} * * @return the produced exception for the error */ <T extends RuntimeException> T operationFailed(@Producer BiFunction<String, IOException, T> fn, @Cause IOException cause, String name); } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������jboss-logging-tools-2.2.1.Final/docs/translation-property-files.html��������������������������������0000664�0000000�0000000�00000104756�13565604617�0025636�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <!--[if IE]><meta http-equiv="X-UA-Compatible" content="IE=edge"><![endif]--> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="Asciidoctor 1.5.8"> <title>Translation Property Files

Translation Property Files

The translation properties files must exist in the same directory structure as the interface. The name of the properties file InterfaceName.i18n_language_country_variant.properties. For example if you have a class named org.jboss.logging.tools.examples.ErrorMessages and you want to translate this into French you create a properties file called ErrorMessages.i18n_fr.properties in a directory org/jboss/logging/tools/examples.

jboss-logging-tools-2.2.1.Final/pom.xml000066400000000000000000000127071356560461700200070ustar00rootroot00000000000000 4.0.0 org.jboss jboss-parent 34 org.jboss.logging jboss-logging-tools-parent 2.2.1.Final pom JBoss Logging Tools Parent James R. Perkins jperkins@redhat.com Kevin Pollet kevin.pollet@serli.com scm:git:git@github.com:jboss-logging/jboss-logging-tools.git scm:git:git@github.com:jboss-logging/jboss-logging-tools.git http://github.com/jboss-logging/jboss-logging-tools UTF-8 2.0.3.Final 3.4.0.Final 2.1.9.Final 2.20.8.Final 4.12 lgpl http://repository.jboss.org/licenses/lgpl-2.1.txt repo org.jboss.logging jboss-logging-annotations ${project.version} org.jboss.logging jboss-logging ${version.org.jboss.logging} org.jboss.jdeparser jdeparser ${version.org.jboss.jdeparser} org.jboss.logmanager jboss-logmanager ${version.org.jboss.logmanager} org.jboss.forge.roaster roaster-api ${verion.org.jboss.forge.roaster} org.jboss.forge.roaster roaster-jdt ${verion.org.jboss.forge.roaster} junit junit ${version.junit} test maven-javadoc-plugin http://docs.oracle.com/javase/8/docs/api public
JBoss Logging Tools, ${project.version}
JBoss Logging Tools, ${project.version}
JBoss Logging Tools, ${project.version}
annotations processor docs
jboss-logging-tools-2.2.1.Final/processor/000077500000000000000000000000001356560461700205025ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/pom.xml000066400000000000000000000156661356560461700220350ustar00rootroot00000000000000 4.0.0 org.jboss.logging jboss-logging-tools-parent 2.2.1.Final ../pom.xml jboss-logging-processor jar JBoss Logging I18n Annotation Processor ${project.build.testOutputDirectory} ${basedir}/src/test/resources/expression.properties org.jboss.logging jboss-logging-annotations org.jboss.logging jboss-logging provided org.jboss.jdeparser jdeparser org.jboss.logmanager jboss-logmanager test org.jboss.forge.roaster roaster-api test org.jboss.forge.roaster roaster-jdt test junit junit test org.apache.maven.plugins maven-compiler-plugin default-compile compile compile -proc:none test-compile-adoc test-compile testCompile -Aorg.jboss.logging.tools.report.type=adoc -Aorg.jboss.logging.tools.report.path=${test.report.path} -Aorg.jboss.logging.tools.report.title=Test Title -Aorg.jboss.logging.tools.expressionProperties=${expression.properties.path} test-compile-xml test-compile testCompile -Aorg.jboss.logging.tools.report.type=xml -Aorg.jboss.logging.tools.report.path=${test.report.path} -Aorg.jboss.logging.tools.report.title=Test Title -Aorg.jboss.logging.tools.expressionProperties=${expression.properties.path} org.apache.maven.plugins maven-surefire-plugin envValue org.jboss.logmanager.LogManager ${project.build.testSourceDirectory} ${project.build.directory}/generated-test-sources/test-annotations ${test.report.path} sysValue ${project.build.testOutputDirectory} ${expression.properties.path} jboss-logging-tools-2.2.1.Final/processor/src/000077500000000000000000000000001356560461700212715ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/000077500000000000000000000000001356560461700222155ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/000077500000000000000000000000001356560461700231365ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/000077500000000000000000000000001356560461700237255ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/000077500000000000000000000000001356560461700250455ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/000077500000000000000000000000001356560461700264735ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/000077500000000000000000000000001356560461700305125ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/000077500000000000000000000000001356560461700312765ustar00rootroot00000000000000AbstractClassType.java000066400000000000000000000060571356560461700354650ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import org.jboss.logging.processor.model.ClassType; import org.jboss.logging.processor.util.ElementHelper; /** * @author James R. Perkins */ abstract class AbstractClassType implements ClassType { protected final ProcessingEnvironment processingEnv; protected final Elements elements; protected final Types types; protected final TypeMirror typeMirror; AbstractClassType(final ProcessingEnvironment processingEnv, final TypeMirror typeMirror) { this.processingEnv = processingEnv; this.elements = processingEnv.getElementUtils(); this.types = processingEnv.getTypeUtils(); this.typeMirror = typeMirror; } AbstractClassType(final ProcessingEnvironment processingEnv, final Element element) { this.processingEnv = processingEnv; this.elements = processingEnv.getElementUtils(); this.types = processingEnv.getTypeUtils(); this.typeMirror = element.asType(); } @Override public final boolean isAssignableFrom(final Class type) { return types.isAssignable(types.erasure(toType(type)), types.erasure(this.typeMirror)); } @Override public final boolean isSubtypeOf(final Class type) { return types.isSubtype(types.erasure(this.typeMirror), toType(type)); } @Override public final boolean isSameAs(final Class type) { return types.isSameType(types.erasure(this.typeMirror), toType(type)); } /** * Creates a {@link TypeMirror} from a class type. * * @param type the type to create the {@link TypeMirror} for * * @return the {@code TypeMirror} to represent the type */ private TypeMirror toType(final Class type) { return types.erasure(ElementHelper.toType(elements, type)); } } AbstractGenerator.java000066400000000000000000000073251356560461700355030ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import java.io.Writer; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.SupportedOptions; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import org.jboss.logging.processor.model.DelegatingElement; import org.jboss.logging.processor.model.DelegatingTypeElement; import org.jboss.logging.processor.model.MessageInterface; /** * An abstract processor used process annotations. * * @author James R. Perkins * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ public abstract class AbstractGenerator { private final ToolLogger logger; final ProcessingEnvironment processingEnv; /** * Constructs a new processor. * * @param processingEnv the processing environment. */ AbstractGenerator(final ProcessingEnvironment processingEnv) { this.logger = ToolLogger.getLogger(processingEnv); this.processingEnv = processingEnv; } /** * Processes a type element. * * @param annotation the annotation who trigger the processing * @param element the element that contains the methods. * @param messageInterface the message interface to implement. */ public abstract void processTypeElement(final TypeElement annotation, final TypeElement element, final MessageInterface messageInterface); /** * Returns the logger to log messages with. * * @return the logger to log messages with. */ final ToolLogger logger() { return logger; } /** * Returns the name of the processor. * * @return the name of the processor. */ public final String getName() { return this.getClass().getSimpleName(); } /** * Returns the supported options set. * * @return the supported options set or empty set if none */ public final Set getSupportedOptions() { SupportedOptions options = this.getClass().getAnnotation(SupportedOptions.class); if (options != null) { return new HashSet<>(Arrays.asList(options.value())); } return Collections.emptySet(); } } ImplementationClassGenerator.java000066400000000000000000000051231356560461700377050ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import java.io.IOException; import java.util.Map; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import org.jboss.logging.processor.generator.model.ClassModel; import org.jboss.logging.processor.generator.model.ClassModelFactory; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.util.VersionComparator; /** * A generator for creating implementations of message bundle and logging * interfaces. * * @author James R. Perkins */ final class ImplementationClassGenerator extends AbstractGenerator { private static final String LOGGING_VERSION = "loggingVersion"; /** * @param processingEnv the processing environment. */ public ImplementationClassGenerator(ProcessingEnvironment processingEnv) { super(processingEnv); final Map options = processingEnv.getOptions(); if (options.containsKey(LOGGING_VERSION)) { logger().warn(null, "The option %s has been deprecated and is no longer used.", LOGGING_VERSION); } } @Override public void processTypeElement(final TypeElement annotation, final TypeElement element, final MessageInterface messageInterface) { try { final ClassModel classModel = ClassModelFactory.implementation(processingEnv, messageInterface); classModel.generateAndWrite(); } catch (IllegalStateException | IOException e) { logger().error(element, e); } } } LoggingToolsProcessor.java000066400000000000000000000254011356560461700363730ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static javax.lang.model.util.ElementFilter.typesIn; import java.io.BufferedReader; import java.io.IOException; import java.lang.annotation.Annotation; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.annotation.processing.SupportedOptions; import javax.lang.model.SourceVersion; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.tools.Diagnostic; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.ConstructType; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.FormatWith; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.LoggingClass; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Once; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Property; import org.jboss.logging.annotations.Signature; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.annotations.ValidIdRanges; import org.jboss.logging.processor.model.DelegatingElement; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.validation.ValidationMessage; import org.jboss.logging.processor.validation.Validator; /** * The main annotation processor for JBoss Logging Tooling. * * @author James R. Perkins * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ @SupportedOptions({ LoggingToolsProcessor.DEBUG_OPTION, LoggingToolsProcessor.EXPRESSION_PROPERTIES, LoggingToolsProcessor.ADD_GENERATED_ANNOTATION, }) public class LoggingToolsProcessor extends AbstractProcessor { public static final String DEBUG_OPTION = "debug"; static final String EXPRESSION_PROPERTIES = "org.jboss.logging.tools.expressionProperties"; static final String ADD_GENERATED_ANNOTATION = "org.jboss.logging.tools.addGeneratedAnnotation"; private final List interfaceAnnotations = Arrays.asList(MessageBundle.class.getName(), MessageLogger.class.getName()); private final List generators; private final Set supportedAnnotations; private ToolLogger logger; /** * Default constructor. */ public LoggingToolsProcessor() { this.generators = new ArrayList<>(); this.supportedAnnotations = createSupportedAnnotations( Cause.class, ConstructType.class, Field.class, FormatWith.class, LoggingClass.class, LogMessage.class, Message.class, MessageBundle.class, MessageLogger.class, Once.class, Param.class, Pos.class, Property.class, Signature.class, Transform.class, ValidIdRange.class, ValidIdRanges.class ); } @Override public Set getSupportedOptions() { Set supportedOptions = new HashSet<>(); //Add global options SupportedOptions globalOptions = this.getClass().getAnnotation(SupportedOptions.class); if (globalOptions != null) { supportedOptions.addAll(Arrays.asList(globalOptions.value())); } //Add tool processors options for (AbstractGenerator generator : generators) { supportedOptions.addAll(generator.getSupportedOptions()); } return supportedOptions; } @Override public Set getSupportedAnnotationTypes() { return supportedAnnotations; } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latest(); } @Override public synchronized void init(final ProcessingEnvironment processingEnv) { super.init(processingEnv); logger = ToolLogger.getLogger(processingEnv); //Tools generator - Note the order these are executed in. generators.add(new ImplementationClassGenerator(processingEnv)); generators.add(new TranslationClassGenerator(processingEnv)); generators.add(new TranslationFileGenerator(processingEnv)); generators.add(new ReportFileGenerator(processingEnv)); } @Override public boolean process(final Set annotations, final RoundEnvironment roundEnv) { if (!roundEnv.processingOver() && !annotations.isEmpty()) { doProcess(annotations, roundEnv); } return true; } private void doProcess(final Set annotations, final RoundEnvironment roundEnv) { final String propertiesPath = processingEnv.getOptions().getOrDefault(EXPRESSION_PROPERTIES, ""); final Properties expressionProperties = new Properties(); if (!propertiesPath.isEmpty()) { final Path path = Paths.get(propertiesPath); if (Files.notExists(path)) { logger.error("Expression properties file %s does not exist.", propertiesPath); return; } else { try (final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { expressionProperties.load(reader); } catch (IOException e) { logger.error(e, "Error reading expression properties file %s", propertiesPath); return; } } } final boolean addGeneratedAnnotation = Boolean.parseBoolean(processingEnv.getOptions().getOrDefault(ADD_GENERATED_ANNOTATION, "true")); boolean generate = true; final Validator validator = new Validator(processingEnv); //Call jboss logging tools for (TypeElement annotation : annotations) { // We only want to process the interface annotations if (interfaceAnnotations.contains(annotation.getQualifiedName().toString())) { try { final Set interfaces = typesIn(roundEnv.getElementsAnnotatedWith(annotation)); for (TypeElement interfaceElement : interfaces) { try { final MessageInterface messageInterface = MessageInterfaceFactory.of(processingEnv, interfaceElement, expressionProperties, addGeneratedAnnotation); final Collection validationMessages = validator.validate(messageInterface); for (ValidationMessage message : validationMessages) { if (message.printMessage(processingEnv.getMessager())) { generate = false; } } if (generate) { if (interfaceElement.getKind().isInterface() && !interfaceElement.getModifiers().contains(Modifier.PRIVATE)) { for (AbstractGenerator processor : generators) { logger.debug("Executing processor %s", processor.getName()); processor.processTypeElement(annotation, interfaceElement, messageInterface); } } } } catch (ProcessingException e) { final AnnotationMirror a = e.getAnnotation(); final AnnotationValue value = e.getAnnotationValue(); final Element element = resolveElement(e.getElement()); if (a == null) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element); } else if (value == null) { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element, a); } else { processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), element, a, value); } } } } catch (Throwable t) { logger.error(annotation, t); } } } } @SafeVarargs private static Set createSupportedAnnotations(final Class... annotations) { final Set supportedAnnotations = new HashSet<>(annotations.length); for (Class c : annotations) { supportedAnnotations.add(c.getName()); } return Collections.unmodifiableSet(supportedAnnotations); } private static Element resolveElement(final Element element) { if (element instanceof DelegatingElement) { return ((DelegatingElement) element).getDelegate(); } return element; } } MessageInterfaceFactory.java000066400000000000000000000347551356560461700366350ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.ToStringBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Types; import org.jboss.logging.BasicLogger; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.annotations.ValidIdRanges; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.util.ElementHelper; /** * A factory to create a {@link org.jboss.logging.processor.model.MessageInterface} for annotation processors. * * @author James R. Perkins */ public final class MessageInterfaceFactory { private static final Object LOCK = new Object(); private static volatile LoggerInterface LOGGER_INTERFACE; /** * Private constructor for factory. */ private MessageInterfaceFactory() { } /** * Creates a message interface from the {@link javax.lang.model.element.TypeElement} specified by the {@code * interfaceElement} parameter. * * @param processingEnv the annotation processing environment. * @param interfaceElement the interface element to parse. * @param expressionProperties the properties used to resolve expressions * * @return a message interface for the interface element. */ public static MessageInterface of(final ProcessingEnvironment processingEnv, final TypeElement interfaceElement, final Properties expressionProperties, final boolean addGeneratedAnnotation) { final Types types = processingEnv.getTypeUtils(); if (types.isSameType(interfaceElement.asType(), ElementHelper.toType(processingEnv.getElementUtils(), BasicLogger.class))) { MessageInterface result = LOGGER_INTERFACE; if (result == null) { synchronized (LOCK) { result = LOGGER_INTERFACE; if (result == null) { LOGGER_INTERFACE = LoggerInterface.of(processingEnv); result = LOGGER_INTERFACE; } } } return result; } final AptMessageInterface result = new AptMessageInterface(interfaceElement, processingEnv, expressionProperties, addGeneratedAnnotation); result.init(); for (TypeMirror typeMirror : interfaceElement.getInterfaces()) { final MessageInterface extended = MessageInterfaceFactory.of(processingEnv, (TypeElement) types.asElement(typeMirror), expressionProperties, addGeneratedAnnotation); result.extendedInterfaces.add(extended); result.extendedInterfaces.addAll(extended.extendedInterfaces()); } return result; } /** * Message interface implementation. */ private static class AptMessageInterface extends AbstractClassType implements MessageInterface { private final TypeElement interfaceElement; private final Set extendedInterfaces; private final List messageMethods; private final List validIdRanges; private final Properties expressionProperties; private final TypeElement generatedAnnotation; private String projectCode; private String packageName; private String simpleName; private String qualifiedName; private String fqcn; private int idLen; private AptMessageInterface(final TypeElement interfaceElement, final ProcessingEnvironment processingEnv, final Properties expressionProperties, final boolean addGeneratedAnnotation) { super(processingEnv, interfaceElement); this.interfaceElement = interfaceElement; this.expressionProperties = expressionProperties; this.messageMethods = new LinkedList<>(); this.extendedInterfaces = new LinkedHashSet<>(); if (ElementHelper.isAnnotatedWith(interfaceElement, ValidIdRanges.class)) { validIdRanges = Arrays.asList(interfaceElement.getAnnotation(ValidIdRanges.class).value()); } else if (ElementHelper.isAnnotatedWith(interfaceElement, ValidIdRange.class)) { validIdRanges = Collections.singletonList(interfaceElement.getAnnotation(ValidIdRange.class)); } else { validIdRanges = Collections.emptyList(); } // Determine the type for the generated annotation TypeElement generatedAnnotation = null; if (addGeneratedAnnotation) { generatedAnnotation = processingEnv.getElementUtils().getTypeElement("javax.annotation.Generated"); if (generatedAnnotation == null) { // As of Java 9 the annotation has been moved to the javax.annotation.processing package generatedAnnotation = processingEnv.getElementUtils().getTypeElement("javax.annotation.processing.Generated"); } } this.generatedAnnotation = generatedAnnotation; } @Override public boolean extendsLoggerInterface() { return LOGGER_INTERFACE != null && extendedInterfaces.contains(LOGGER_INTERFACE); } @Override public String name() { return qualifiedName; } @Override public Set extendedInterfaces() { return Collections.unmodifiableSet(extendedInterfaces); } @Override public int hashCode() { return Objects.hash(qualifiedName); } @Override public Collection methods() { return messageMethods; } @Override public int compareTo(final MessageInterface o) { return this.name().compareTo(o.name()); } @Override public String projectCode() { return projectCode; } private void init() { final MessageMethodBuilder builder = MessageMethodBuilder.create(processingEnv, expressionProperties) .add(getMessageMethods(interfaceElement)); final Collection m = builder.build(); this.messageMethods.addAll(m); final MessageBundle messageBundle = interfaceElement.getAnnotation(MessageBundle.class); final MessageLogger messageLogger = interfaceElement.getAnnotation(MessageLogger.class); if (messageBundle != null) { projectCode = messageBundle.projectCode(); idLen = messageBundle.length(); } else if (messageLogger != null) { projectCode = messageLogger.projectCode(); idLen = messageLogger.length(); } else { throw new ProcessingException(interfaceElement, "Interface is not annotated with @MessageBundle or @MessageLogger"); } qualifiedName = elements.getBinaryName(interfaceElement).toString(); final int lastDot = qualifiedName.lastIndexOf("."); if (lastDot > 0) { packageName = qualifiedName.substring(0, lastDot); simpleName = qualifiedName.substring(lastDot + 1); } else { packageName = null; simpleName = qualifiedName; } // Get the FQCN final TypeElement loggingClass = ElementHelper.getClassAnnotationValue(interfaceElement, MessageLogger.class, "loggingClass"); if (loggingClass != null) { final String value = loggingClass.getQualifiedName().toString(); if (!value.equals(Void.class.getName())) { fqcn = value; } } } @Override public String packageName() { return packageName; } @Override public String getComment() { return elements.getDocComment(interfaceElement); } @Override public String simpleName() { return simpleName; } @Override public String loggingFQCN() { return fqcn; } @Override public List validIdRanges() { return validIdRanges; } @Override public int getIdLength() { return idLen; } @Override public TypeElement getDelegate() { return interfaceElement; } @Override public TypeElement generatedAnnotation() { return generatedAnnotation; } @Override public Properties expressionProperties() { return expressionProperties; } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptMessageInterface)) { return false; } final AptMessageInterface other = (AptMessageInterface) obj; return areEqual(name(), other.name()); } @Override public String toString() { return ToStringBuilder.of(this).add(qualifiedName).toString(); } } private static class LoggerInterface extends AbstractClassType implements MessageInterface { private final TypeElement loggerInterface; private final Set messageMethods; private LoggerInterface(final ProcessingEnvironment processingEnv, final TypeElement loggerInterface) { super(processingEnv, loggerInterface.asType()); messageMethods = new LinkedHashSet<>(); this.loggerInterface = loggerInterface; } private void init() { final MessageMethodBuilder builder = MessageMethodBuilder.create(processingEnv) .add(getMessageMethods(loggerInterface)); final Collection m = builder.build(); this.messageMethods.addAll(m); } static LoggerInterface of(final ProcessingEnvironment processingEnv) { final LoggerInterface result = new LoggerInterface(processingEnv, ElementHelper.toTypeElement(processingEnv, BasicLogger.class)); result.init(); return result; } @Override public boolean extendsLoggerInterface() { return false; } @Override public Set extendedInterfaces() { return Collections.emptySet(); } @Override public Collection methods() { return messageMethods; } @Override public String projectCode() { return null; } @Override public String name() { return BasicLogger.class.getName(); } @Override public String packageName() { return BasicLogger.class.getPackage().getName(); } @Override public String simpleName() { return BasicLogger.class.getSimpleName(); } @Override public String loggingFQCN() { return null; } @Override public List validIdRanges() { return Collections.emptyList(); } @Override public int getIdLength() { return -1; } @Override public int hashCode() { return HashCodeBuilder.builder().add(name()).toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptMessageInterface)) { return false; } final AptMessageInterface other = (AptMessageInterface) obj; return areEqual(name(), other.name()); } @Override public int compareTo(final MessageInterface o) { return this.name().compareTo(o.name()); } @Override public String toString() { return ToStringBuilder.of(this).add(name()).toString(); } @Override public String getComment() { return elements.getDocComment(loggerInterface); } @Override public TypeElement getDelegate() { return loggerInterface; } } private static Collection getMessageMethods(final TypeElement intf) { return ElementFilter.methodsIn(intf.getEnclosedElements()) .stream() .filter(method -> !method.isDefault() && !method.getModifiers().contains(Modifier.STATIC)) .collect(Collectors.toList()); } } MessageMethodBuilder.java000066400000000000000000000506311356560461700361230ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.ElementHelper.isAnnotatedWith; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.ToStringBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Property; import org.jboss.logging.annotations.Suppressed; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.model.ReturnType; import org.jboss.logging.processor.model.ThrowableType; import org.jboss.logging.processor.util.Comparison; import org.jboss.logging.processor.util.ElementHelper; import org.jboss.logging.processor.util.Expressions; /** * Date: 29.07.2011 * * @author James R. Perkins */ final class MessageMethodBuilder { private static final String MESSAGE_METHOD_SUFFIX = "$str"; private final List methods; private final ProcessingEnvironment processingEnv; private final Properties expressionProperties; private MessageMethodBuilder(final ProcessingEnvironment processingEnv, final Properties expressionProperties) { this.processingEnv = processingEnv; this.expressionProperties = expressionProperties; methods = new LinkedList<>(); } MessageMethodBuilder add(final Collection methods) { this.methods.addAll(methods); return this; } Set build() { final Elements elements = processingEnv.getElementUtils(); final Set result = new LinkedHashSet<>(); for (ExecutableElement elementMethod : methods) { final AptMessageMethod resultMethod = new AptMessageMethod(elements, elementMethod); resultMethod.inheritsMessage = inheritsMessage(methods, elementMethod); resultMethod.message = findMessage(methods, elementMethod); resultMethod.isOverloaded = isOverloaded(methods, elementMethod); for (TypeMirror thrownType : elementMethod.getThrownTypes()) { resultMethod.thrownTypes.add(ThrowableTypeFactory.of(processingEnv, thrownType)); } // Create a list of parameters for (Parameter parameter : ParameterFactory.of(processingEnv, resultMethod.method)) { resultMethod.add(parameter); } // Check to see if the method is overloaded if (resultMethod.isOverloaded()) { resultMethod.messageMethodName = resultMethod.name() + resultMethod.formatParameterCount() + MESSAGE_METHOD_SUFFIX; resultMethod.translationKey = resultMethod.name() + "." + resultMethod.formatParameterCount(); } else { resultMethod.messageMethodName = resultMethod.name() + MESSAGE_METHOD_SUFFIX; resultMethod.translationKey = resultMethod.name(); } // Set the return type resultMethod.returnType = ReturnTypeFactory.of(processingEnv, elementMethod.getReturnType(), resultMethod); result.add(resultMethod); } return Collections.unmodifiableSet(result); } private MessageMethod.Message findMessage(final Collection methods, final ExecutableElement method) { AptMessage result = null; Message message = method.getAnnotation(Message.class); if (message != null) { result = new AptMessage(message, expressionProperties); result.hasId = hasMessageId(message); result.inheritsId = message.id() == Message.INHERIT; if (result.inheritsId()) { result.id = findMessageId(methods, method); if (result.id > 0) { result.hasId = true; } } else { result.id = message.id(); } } else { final Collection allMethods = findByName(methods, method); for (ExecutableElement m : allMethods) { message = m.getAnnotation(Message.class); if (message != null) { result = new AptMessage(message, expressionProperties); result.hasId = hasMessageId(message); result.inheritsId = message.id() == Message.INHERIT; if (result.inheritsId()) { result.id = findMessageId(methods, m); if (result.id > 0) { result.hasId = true; } } else { result.id = message.id(); } break; } } } return result; } private int findMessageId(final Collection methods, final ExecutableElement method) { int result = -2; final Collection allMethods = findByName(methods, method.getSimpleName()); for (ExecutableElement m : allMethods) { final Message message = m.getAnnotation(Message.class); if (message != null) { if (message.id() != Message.INHERIT) { result = message.id(); } } } return result; } private boolean hasMessageId(final Message message) { return message != null && (message.id() != Message.NONE && message.id() != Message.INHERIT); } private Collection findByName(final Collection methods, final ExecutableElement method) { final Name methodName = method.getSimpleName(); final List result = new ArrayList<>(); final int paramCount = parameterCount(method.getParameters()); for (ExecutableElement m : methods) { if (methodName.equals(m.getSimpleName()) && parameterCount(m.getParameters()) == paramCount) { result.add(m); } } return result; } /** * Returns a collection of methods with the same name. * * @param methods the methods to process. * @param methodName the method name to findByName. * * @return a collection of methods with the same name. */ private Collection findByName(final Collection methods, final Name methodName) { final List result = new ArrayList<>(); for (ExecutableElement method : methods) { if (methodName.equals(method.getSimpleName())) { result.add(method); } } return result; } /** * Checks to see if the method has or inherits a {@link org.jboss.logging.annotations.Message} * annotation. * * @param methods the method to search. * @param method the method to check. * * @return {@code true} if the method has or inherits a message annotation, otherwise {@code false}. */ private boolean inheritsMessage(final Collection methods, final ExecutableElement method) { if (isAnnotatedWith(method, Message.class)) { return false; } final Collection allMethods = findByName(methods, method.getSimpleName()); for (ExecutableElement m : allMethods) { if (isAnnotatedWith(m, Message.class)) { return true; } } return false; } /** * Checks to see if the method is overloaded. An overloaded method has a different parameter count based on the * format parameters only. Parameters annotated with {@link org.jboss.logging.annotations.Cause} or * {@link org.jboss.logging.annotations.Param} * are not counted. * * @param methods the method to search. * @param method the method to check. * * @return {@code true} if the method is overloaded, otherwise {@code false}. */ private boolean isOverloaded(final Collection methods, final ExecutableElement method) { final Collection allMethods = findByName(methods, method.getSimpleName()); for (ExecutableElement m : allMethods) { if (method.getSimpleName().equals(m.getSimpleName()) && parameterCount(method.getParameters()) != parameterCount(m.getParameters())) { return true; } } return false; } /** * Returns the number of parameters excluding the {@link org.jboss.logging.annotations.Cause} parameter * and any {@link org.jboss.logging.annotations.Param} parameters if found. * * @param params the parameters to get the count for. * * @return the number of parameters. */ private int parameterCount(final Collection params) { int result = params.size(); boolean hasCause = false; for (VariableElement param : params) { if (isAnnotatedWith(param, Param.class) || isAnnotatedWith(param, Field.class) || isAnnotatedWith(param, Property.class) || isAnnotatedWith(param, Suppressed.class)) { --result; } if (isAnnotatedWith(param, Cause.class)) { hasCause = true; } } return (result - (hasCause ? 1 : 0)); } static MessageMethodBuilder create(final ProcessingEnvironment processingEnv) { return create(processingEnv, new Properties()); } static MessageMethodBuilder create(final ProcessingEnvironment processingEnv, final Properties expressionProperties) { return new MessageMethodBuilder(processingEnv, expressionProperties); } /** * An implementation for the MessageMethod interface. */ private static class AptMessageMethod implements MessageMethod { private final Elements elements; private final Map> parameters; private final Set thrownTypes; private final ExecutableElement method; private ReturnType returnType; private Parameter cause; private boolean inheritsMessage; private boolean isOverloaded; private Message message; private String messageMethodName; private String translationKey; private int formatParameterCount; /** * Private constructor for the * * @param elements the elements utility. * @param method the method to describe. */ AptMessageMethod(final Elements elements, final ExecutableElement method) { this.elements = elements; this.method = method; inheritsMessage = false; isOverloaded = false; parameters = new HashMap<>(); thrownTypes = new LinkedHashSet<>(); formatParameterCount = 0; } void add(final Parameter parameter) { if (parameter.isFormatParameter()) { if (parameter.isAnnotatedWith(Pos.class)) { formatParameterCount += parameter.getAnnotation(Pos.class).value().length; } else { formatParameterCount++; } } if (parameters.containsKey(null)) { parameters.get(null).add(parameter); } else { final Set any = new LinkedHashSet<>(); any.add(parameter); parameters.put(null, any); } for (AnnotationMirror a : parameter.getAnnotationMirrors()) { if (parameters.containsKey(a.getAnnotationType())) { parameters.get(a.getAnnotationType()).add(parameter); } else { final Set set = new LinkedHashSet<>(); set.add(parameter); parameters.put(a.getAnnotationType(), set); } } if (parameter.isAnnotatedWith(Cause.class)) { cause = parameter; } } @Override public String name() { return method.getSimpleName().toString(); } @Override public Set parameters() { if (parameters.containsKey(null)) { return Collections.unmodifiableSet(parameters.get(null)); } return Collections.emptySet(); } @Override public Set parametersAnnotatedWith(final Class annotation) { final TypeElement type = ElementHelper.toTypeElement(elements, annotation); return parameters.containsKey(type.asType()) ? Collections.unmodifiableSet(parameters.get(type.asType())) : Collections.emptySet(); } @Override public ReturnType returnType() { return returnType; } @Override public Set thrownTypes() { return Collections.unmodifiableSet(thrownTypes); } @Override public Message message() { return message; } @Override public boolean inheritsMessage() { return inheritsMessage; } @Override public String messageMethodName() { return messageMethodName; } @Override public String translationKey() { return translationKey; } @Override public boolean hasCause() { return cause != null; } @Override public boolean isOverloaded() { return isOverloaded; } @Override public Parameter cause() { return cause; } @Override public String loggerMethod() { switch (message.format()) { case MESSAGE_FORMAT: return "logv"; case NO_FORMAT: return "log"; case PRINTF: return "logf"; default: // Should never be hit return "log"; } } @Override public String logLevel() { final LogMessage logMessage = method.getAnnotation(LogMessage.class); return (logMessage.level() == null ? Logger.Level.INFO.name() : logMessage.level().name()); } @Override public int formatParameterCount() { return formatParameterCount; } @Override public boolean isLoggerMethod() { return isAnnotatedWith(LogMessage.class); } @Override public int hashCode() { return HashCodeBuilder.builder() .add(name()) .add(parameters()) .add(returnType()).toHashCode(); } @Override public ExecutableElement getDelegate() { return method; } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptMessageMethod)) { return false; } final AptMessageMethod other = (AptMessageMethod) obj; return areEqual(name(), other.name()) && areEqual(parameters, parameters) && areEqual(returnType, other.returnType); } @Override public String toString() { return ToStringBuilder.of(this) .add("name", name()) .add("returnType", returnType()) .add("parameters", parameters()) .add("loggerMethod", loggerMethod()).toString(); } @Override public int compareTo(final MessageMethod o) { int result = name().compareTo(o.name()); result = (result != Comparison.EQUAL) ? result : returnType.name().compareTo(o.returnType().name()); // Size does matter result = (result != Comparison.EQUAL) ? result : parameters().size() - o.parameters().size(); if (result == Comparison.EQUAL) { // Check element by element final Iterator params1 = parameters().iterator(); final Iterator params2 = o.parameters().iterator(); while (params1.hasNext()) { if (params2.hasNext()) { final Parameter param1 = params1.next(); final Parameter param2 = params2.next(); result = param1.compareTo(param2); } else { result = Comparison.GREATER; } // Short circuit if (result != Comparison.EQUAL) break; } } return result; } @Override public String getComment() { return elements.getDocComment(method); } } private static class AptMessage implements MessageMethod.Message { private final Message message; private final String messageValue; private int id; private boolean hasId; private boolean inheritsId; private AptMessage(final Message message, final Properties expressionProperties) { this.message = message; if (expressionProperties.isEmpty()) { this.messageValue = message.value(); } else { this.messageValue = Expressions.resolve(expressionProperties, message.value()); } } @Override public int id() { return id; } @Override public boolean hasId() { return hasId; } @Override public boolean inheritsId() { return inheritsId; } @Override public String value() { return messageValue; } @Override public Format format() { return message.format(); } @Override public String toString() { return ToStringBuilder.of(this) .add("hasId", hasId) .add("id", id()) .add("inheritsId", inheritsId) .add("value", value()) .add("formatType", format()).toString(); } } } ParameterFactory.java000066400000000000000000000253521356560461700353410ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.ToStringBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import java.util.LinkedHashSet; import java.util.List; import java.util.Objects; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.util.Types; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.FormatWith; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Property; import org.jboss.logging.annotations.Transform; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.util.Comparison; import org.jboss.logging.processor.util.ElementHelper; /** * @author James R. Perkins - 20.Feb.2011 */ final class ParameterFactory { /** * Private constructor for factory. */ private ParameterFactory() { } public static Set of(final ProcessingEnvironment processingEnv, final ExecutableElement method) { final Types types = processingEnv.getTypeUtils(); final Set result = new LinkedHashSet<>(); final List params = method.getParameters(); int index = 0; for (VariableElement param : params) { final TypeElement formatClassType = ElementHelper.getClassAnnotationValue(param, FormatWith.class); final String formatClass = formatClassType == null ? null : formatClassType.getQualifiedName().toString(); final String qualifiedType; if (param.asType().getKind().isPrimitive()) { qualifiedType = param.asType().toString(); } else { switch ((param.asType().getKind())) { case ARRAY: qualifiedType = param.asType().toString().replace("[]", ""); break; default: qualifiedType = types.asElement(param.asType()).toString(); break; } } if (method.isVarArgs()) { result.add(new AptParameter(processingEnv, qualifiedType, param, formatClass, (++index == params.size()))); } else { result.add(new AptParameter(processingEnv, qualifiedType, param, formatClass, false)); } } return result; } public static Parameter forMessageMethod(final MessageMethod messageMethod) { return new MessageMethodParameter(messageMethod); } private static class AptParameter extends AbstractClassType implements Parameter { private final VariableElement param; private final String qualifiedType; private final String formatterClass; private final boolean isVarArgs; private final boolean isFormatArg; /** * Only allow construction from within the parent class. * * @param processingEnv the annotation processing environment. * @param qualifiedType the qualified type name of the parameter. * @param param the parameter. * @param formatterClass the formatter class, or {@code null} if none * @param isVarArgs {@code true} if this is a vararg parameter, otherwise {@code false}. */ AptParameter(final ProcessingEnvironment processingEnv, final String qualifiedType, final VariableElement param, final String formatterClass, final boolean isVarArgs) { super(processingEnv, param); this.qualifiedType = qualifiedType; this.param = param; this.formatterClass = formatterClass; this.isVarArgs = isVarArgs; isFormatArg = param.getAnnotationMirrors().isEmpty() || ElementHelper.isAnnotatedWith(param, FormatWith.class) || ElementHelper.isAnnotatedWith(param, Transform.class) || ElementHelper.isAnnotatedWith(param, Pos.class); } @Override public String formatterClass() { return formatterClass; } @Override public String name() { return param.getSimpleName().toString(); } @Override public boolean isArray() { return param.asType().getKind() == TypeKind.ARRAY; } @Override public boolean isPrimitive() { return param.asType().getKind().isPrimitive(); } @Override public boolean isVarArgs() { return isVarArgs; } @Override public boolean isFormatParameter() { return isFormatArg; } @Override public String targetName() { String result = ""; final Field field = param.getAnnotation(Field.class); final Property property = param.getAnnotation(Property.class); if (field != null) { final String name = field.name(); if (name.isEmpty()) { result = param.getSimpleName().toString(); } else { result = name; } } else if (property != null) { final String name = property.name(); if (name.isEmpty()) { result = param.getSimpleName().toString(); } else { result = name; } result = "set" + Character.toUpperCase(result.charAt(0)) + result.substring(1); } return result; } @Override public int hashCode() { return HashCodeBuilder.builder() .add(qualifiedType) .add(param).toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptParameter)) { return false; } final AptParameter other = (AptParameter) obj; return areEqual(this.param, other.param) && areEqual(this.qualifiedType, other.qualifiedType); } @Override public int compareTo(final Parameter other) { return Comparison.begin() .compare(asType().toString(), other.asType().toString()) .compare(this.name(), other.name()).result(); } @Override public String toString() { return ToStringBuilder.of(this) .add("name", name()) .add("type", asType()).toString(); } @Override public Element getDelegate() { return param; } } private static class MessageMethodParameter implements Parameter { private final MessageMethod messageMethod; private MessageMethodParameter(final MessageMethod messageMethod) { this.messageMethod = messageMethod; } @Override public Element getDelegate() { return messageMethod; } @Override public String formatterClass() { return null; } @Override public String targetName() { return ""; } @Override public String name() { return messageMethod.messageMethodName(); } @Override public boolean isArray() { return false; } @Override public boolean isPrimitive() { return false; } @Override public boolean isVarArgs() { return false; } @Override public boolean isMessageMethod() { return true; } @Override public int hashCode() { return Objects.hash(messageMethod); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof MessageMethodParameter)) { return false; } final MessageMethodParameter other = (MessageMethodParameter) obj; return Objects.equals(messageMethod, other.messageMethod); } @Override public int compareTo(final Parameter other) { if (other instanceof MessageMethodParameter) { final MessageMethodParameter otherParameter = (MessageMethodParameter) other; return messageMethod.compareTo(otherParameter.messageMethod); } // A little odd, but some kind of comparison should be done by default return Comparison.begin() .compare(asType().toString(), other.asType().toString()) .compare(name(), other.name()) .result(); } @Override public String toString() { return ToStringBuilder.of(this) .add("name", name()) .add("type", asType()).toString(); } @Override public boolean isAssignableFrom(final Class type) { return false; } @Override public boolean isSubtypeOf(final Class type) { return false; } @Override public boolean isSameAs(final Class type) { return false; } } } ProcessingException.java000066400000000000000000000115051356560461700360570ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; /** * An exception that can be used to log which element caused the error. * * @author James R. Perkins */ public class ProcessingException extends RuntimeException { private final Element element; private final AnnotationMirror annotation; private final AnnotationValue annotationValue; /** * Creates a new exception. * * @param element the element the error occurs on * @param message the message */ public ProcessingException(final Element element, final String message) { this(element, null, null, message); } /** * Creates a new exception. * * @param element the element the error occurs on * @param annotation the annotation the error occurred on * @param message the message */ public ProcessingException(final Element element, final AnnotationMirror annotation, final String message) { this(element, annotation, null, message); } /** * Creates a new exception. * * @param element the element the error occurs on * @param annotation the annotation the error occurred on * @param annotationValue the annotation value * @param message the message */ public ProcessingException(final Element element, final AnnotationMirror annotation, final AnnotationValue annotationValue, final String message) { super(message); this.element = element; this.annotation = annotation; this.annotationValue = annotationValue; } /** * Creates a new exception. * * @param element the element the error occurs on * @param format the format for the message * @param args the arguments for the format */ public ProcessingException(final Element element, final String format, final Object... args) { this(element, null, null, format, args); } /** * Creates a new exception. * * @param element the element the error occurs on * @param annotation the annotation the error occurred on * @param format the format for the message * @param args the arguments for the format */ public ProcessingException(final Element element, final AnnotationMirror annotation, final String format, final Object... args) { this(element, annotation, null, format, args); } /** * Creates a new exception. * * @param element the element the error occurs on * @param annotation the annotation the error occurred on * @param annotationValue the annotation value * @param format the format for the message * @param args the arguments for the format */ public ProcessingException(final Element element, final AnnotationMirror annotation, final AnnotationValue annotationValue, final String format, final Object... args) { super(String.format(format, args)); this.element = element; this.annotation = annotation; this.annotationValue = annotationValue; } /** * The element the error occurred on. * * @return the element */ public Element getElement() { return element; } /** * The annotation where the error occurred. * * @return the annotation or {@code null} if the error did not occur on an annotation */ public AnnotationMirror getAnnotation() { return annotation; } /** * The value for the annotation that is invalid. * * @return the annotation value or {@code null} */ public AnnotationValue getAnnotationValue() { return annotationValue; } } ReportFileGenerator.java000066400000000000000000000151201356560461700360030ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Collection; import java.util.Comparator; import java.util.Locale; import java.util.Map; import java.util.TreeSet; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.SupportedOptions; import javax.lang.model.element.TypeElement; import javax.tools.StandardLocation; import org.jboss.logging.processor.apt.report.ReportType; import org.jboss.logging.processor.apt.report.ReportWriter; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * Generates reports for logging interfaces and message bundles. * * @author James R. Perkins */ @SupportedOptions({ ReportFileGenerator.REPORT_TYPE, ReportFileGenerator.REPORT_PATH, ReportFileGenerator.REPORT_TITLE }) public class ReportFileGenerator extends AbstractGenerator { static final String REPORT_TYPE = "org.jboss.logging.tools.report.type"; static final String REPORT_PATH = "org.jboss.logging.tools.report.path"; static final String REPORT_TITLE = "org.jboss.logging.tools.report.title"; private final ReportType reportType; private final String reportPath; private final String reportTitle; ReportFileGenerator(final ProcessingEnvironment processingEnv) { super(processingEnv); Map options = processingEnv.getOptions(); final String reportType = options.get(REPORT_TYPE); reportPath = options.get(REPORT_PATH); reportTitle = options.get(REPORT_TITLE); if (reportType == null) { this.reportType = null; } else { final String s = reportType.toLowerCase(Locale.ROOT); if ("adoc".equals(s) || "asciidoc".equals(s)) { this.reportType = ReportType.ASCIIDOC; } else if ("xml".equals(s)) { this.reportType = ReportType.XML; } else { this.reportType = null; logger().warn(null, "Report type %s is invalid. No reports will be generated.", reportType); } } } @Override public void processTypeElement(final TypeElement annotation, final TypeElement element, final MessageInterface messageInterface) { if (reportType != null) { try { // Don't generate empty interfaces if (messageInterface.methods().isEmpty()) { logger().debug(element, "Skipping reports for interface %s with no methods.", messageInterface.name()); return; } logger().debug(element, "Writing reports for interface %s.", messageInterface.name()); final String fileName = messageInterface.simpleName() + reportType.getExtension(); try ( final BufferedWriter writer = createWriter(messageInterface.packageName(), fileName); final ReportWriter reportWriter = ReportWriter.of(reportType, messageInterface, writer) ) { reportWriter.writeHeader(reportTitle); // Process the methods for (MessageMethod messageMethod : getSortedMessageMethods(messageInterface)) { reportWriter.writeDetail(messageMethod); } reportWriter.writeFooter(); } } catch (IOException e) { logger().error(element, e, "Failed to generate %s report", reportType); } } } private BufferedWriter createWriter(final String packageName, final String fileName) throws IOException { if (reportPath == null) { return new BufferedWriter(processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName).openWriter()); } final Path outputPath = Paths.get(reportPath, packageName.replace(".", FileSystems.getDefault().getSeparator()), fileName); Files.createDirectories(outputPath.getParent()); return Files.newBufferedWriter(outputPath, StandardCharsets.UTF_8, StandardOpenOption.CREATE); } /** * Returns a sorted collection of the message methods on the interface. The methods are sorted by the message id. * * @param messageInterface the message interface to get the methods for * * @return a sorted collection of message methods */ private static Collection getSortedMessageMethods(final MessageInterface messageInterface) { final Collection messageMethods = new TreeSet<>(MessageMethodSortComparator.INSTANCE); messageMethods.addAll(messageInterface.methods()); return messageMethods; } private static class MessageMethodSortComparator implements Comparator { static final MessageMethodSortComparator INSTANCE = new MessageMethodSortComparator(); @Override public int compare(final MessageMethod o1, final MessageMethod o2) { // First sort by message id, then message to ensure uniqueness int result = Integer.compare(o1.message().id(), o2.message().id()); if (result == 0) { result = o1.message().value().compareTo(o2.message().value()); } return result; } } } ReturnTypeFactory.java000066400000000000000000000202641356560461700355370ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import java.util.List; import java.util.function.Supplier; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.NoType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Types; import org.jboss.logging.annotations.ConstructType; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.ReturnType; import org.jboss.logging.processor.model.ThrowableType; import org.jboss.logging.processor.util.ElementHelper; import org.jboss.logging.processor.util.Objects; /** * Date: 29.07.2011 * * @author James R. Perkins */ final class ReturnTypeFactory { /** * Private constructor for factory. */ private ReturnTypeFactory() { } public static ReturnType of(final ProcessingEnvironment processingEnv, final TypeMirror returnType, final MessageMethod method) { if (returnType.getKind() == TypeKind.VOID) { return VoidReturnType.getInstance(processingEnv.getTypeUtils()); } final AptReturnType result = new AptReturnType(processingEnv, returnType, method); result.init(); return result; } /** * Implementation of return type. */ private static class AptReturnType extends AbstractClassType implements ReturnType { private final TypeMirror returnType; private final MessageMethod method; private final Element delegate; private final TypeMirror resolvedType; private final boolean isThrowable; private ThrowableType throwableType; AptReturnType(final ProcessingEnvironment processingEnv, final TypeMirror returnType, final MessageMethod method) { super(processingEnv, returnType); this.returnType = returnType; this.method = method; delegate = types.asElement(returnType); throwableType = null; if (types.isSubtype(types.erasure(returnType), types.erasure(ElementHelper.toType(elements, Supplier.class)))) { final List typeArgs = ElementHelper.getTypeArguments(returnType); if (typeArgs.isEmpty()) { resolvedType = elements.getTypeElement(Object.class.getCanonicalName()).asType(); } else { resolvedType = typeArgs.get(0); } } else { resolvedType = returnType; } isThrowable = types.isSubtype(types.erasure(resolvedType), ElementHelper.toType(elements, Throwable.class)); } @Override public Element getDelegate() { return delegate; } @Override public TypeMirror asType() { return returnType; } @Override public boolean isThrowable() { return isThrowable; } @Override public String name() { return types.erasure(returnType).toString(); } @Override public ThrowableType throwableReturnType() { return throwableType; } @Override public TypeMirror resolvedType() { return resolvedType; } private void init() { if (isThrowable()) { // The resolved type needs to be used in cases where a Supplier is being returned TypeMirror throwableReturnType = resolvedType; if (method.isAnnotatedWith(ConstructType.class)) { final TypeElement constructTypeValue = ElementHelper.getClassAnnotationValue(method, ConstructType.class); // Shouldn't be null if (constructTypeValue == null) { throw new ProcessingException(method, "Class not defined for the ConstructType"); } throwableReturnType = constructTypeValue.asType(); if (!types.isAssignable(throwableReturnType, resolvedType)) { throw new ProcessingException(method, "The requested type %s can not be assigned to %s.", throwableReturnType, resolvedType); } } throwableType = ThrowableTypeFactory.forReturnType(processingEnv, throwableReturnType, method); } } @Override public int hashCode() { return HashCodeBuilder.builder().add(name()).toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptReturnType)) { return false; } final AptReturnType other = (AptReturnType) obj; return areEqual(name(), other.name()); } @Override public String toString() { return Objects.ToStringBuilder.of(this) .add("name", name()) .add("throwable", isThrowable()) .add("throwableType", throwableType).toString(); } } private static class VoidReturnType implements ReturnType { private static VoidReturnType INSTANCE = null; private final Element voidElement; private final NoType voidType; private final int hash; private VoidReturnType(final Types types) { voidType = types.getNoType(TypeKind.VOID); voidElement = types.asElement(voidType); hash = "void".hashCode(); } private static synchronized VoidReturnType getInstance(final Types types) { if (INSTANCE == null) { INSTANCE = new VoidReturnType(types); } return INSTANCE; } @Override public TypeMirror asType() { return voidType; } @Override public boolean isThrowable() { return false; } @Override public String name() { return "void"; } @Override public ThrowableType throwableReturnType() { return null; } @Override public int hashCode() { return hash; } @Override public boolean equals(final Object obj) { return obj == this || obj instanceof VoidReturnType; } @Override public String toString() { return "void"; } @Override public boolean isAssignableFrom(final Class type) { return type == Void.class || type == void.class; } @Override public boolean isSubtypeOf(final Class type) { return false; } @Override public boolean isSameAs(final Class type) { return type == Void.class || type == void.class; } @Override public Element getDelegate() { return voidElement; } } } ThrowableTypeFactory.java000066400000000000000000000366111356560461700362120ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Signature; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.model.ThrowableType; import org.jboss.logging.processor.util.ElementHelper; import org.jboss.logging.processor.util.Objects; /** * Describes information about the return type. * * @author James R. Perkins */ final class ThrowableTypeFactory { private ThrowableTypeFactory() { } /** * Creates a new descriptor that is not primitive. * * @param processingEnv the annotation processing environment. * @param type the class name of the return type. * @param messageMethod the message method. * * @return the return type descriptor. */ public static ThrowableType forReturnType(final ProcessingEnvironment processingEnv, final TypeMirror type, final MessageMethod messageMethod) { final AptReturnThrowableType result = new AptReturnThrowableType(processingEnv, messageMethod, type); result.init(); return result; } /** * Creates a new descriptor that is not primitive. * * @param processingEnv the annotation processing environment. * @param type the class name of the return type. * * @return the return type descriptor. */ public static ThrowableType of(final ProcessingEnvironment processingEnv, final TypeMirror type) { final AptThrowableType result = new AptThrowableType(processingEnv, type); result.init(); return result; } private static class AptThrowableType extends AbstractClassType implements ThrowableType { private final TypeMirror type; private final boolean isChecked; private final Element delegate; private boolean defaultConstructor = false; private boolean stringConstructor = false; private boolean throwableConstructor = false; private boolean stringAndThrowableConstructor = false; private boolean throwableAndStringConstructor = false; protected final TypeMirror stringType; protected final TypeMirror throwableType; /** * Creates a new descriptor that is not primitive. * * @param processingEnv the annotation processing environment. * @param type the class name of the return type. */ private AptThrowableType(final ProcessingEnvironment processingEnv, final TypeMirror type) { super(processingEnv, type); this.type = type; this.delegate = types.asElement(type); stringType = ElementHelper.toType(elements, String.class); throwableType = ElementHelper.toType(elements, Throwable.class); final TypeMirror runtimeException = ElementHelper.toType(elements, RuntimeException.class); final TypeMirror error = ElementHelper.toType(elements, Error.class); isChecked = !(types.isAssignable(runtimeException, type) && types.isAssignable(error, type)); } /** * Initializes the object. */ protected void init() { if (!type.getKind().isPrimitive() && type.getKind() != TypeKind.VOID) { final Element element = types.asElement(type); final List constructors = ElementFilter.constructorsIn(element.getEnclosedElements()); for (ExecutableElement constructor : constructors) { // Only allow public constructors if (!constructor.getModifiers().contains(Modifier.PUBLIC)) { continue; } final List params = constructor.getParameters(); switch (params.size()) { case 0: defaultConstructor = true; break; case 1: if (types.isAssignable(stringType, params.get(0).asType())) { stringConstructor = true; } else if (types.isAssignable(params.get(0).asType(), throwableType)) { throwableConstructor = true; } break; case 2: if (types.isAssignable(stringType, params.get(0).asType()) && types.isAssignable(params.get(1).asType(), throwableType)) { stringAndThrowableConstructor = true; } else if (types.isAssignable(params.get(0).asType(), throwableType) && types.isAssignable(stringType, params.get(1).asType())) { throwableAndStringConstructor = true; } break; } init(params); } } } /** * Allows for additional processing of parameters. * * @param params the parameters to be processed. */ protected void init(final List params) { } @Override public Element getDelegate() { return delegate; } @Override public TypeMirror asType() { return type; } @Override public boolean hasDefaultConstructor() { return defaultConstructor; } @Override public boolean hasStringAndThrowableConstructor() { return stringAndThrowableConstructor; } @Override public boolean hasStringConstructor() { return stringConstructor; } @Override public boolean hasThrowableAndStringConstructor() { return throwableAndStringConstructor; } @Override public boolean hasThrowableConstructor() { return throwableConstructor; } @Override public boolean useConstructionParameters() { return false; } @Override public Set constructionParameters() { return Collections.emptySet(); } @Override public boolean isChecked() { return isChecked; } @Override public String name() { return type.toString(); } @Override public int hashCode() { return HashCodeBuilder.builder().add(type).toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof AptThrowableType)) { return false; } final AptThrowableType other = (AptThrowableType) obj; return areEqual(this.type, other.type); } @Override public String toString() { return Objects.ToStringBuilder.of(this) .add("type", type) .add("stringConstructor", stringConstructor) .add("throwableConstructor", throwableConstructor) .add("stringAndThrowableConstructor", stringAndThrowableConstructor) .add("throwableAndStringConstructor", throwableAndStringConstructor).toString(); } @Override public int compareTo(final ThrowableType o) { return name().compareTo(o.name()); } } private static class AptReturnThrowableType extends AptThrowableType { private final MessageMethod messageMethod; private final Set constructionParameters; private boolean useConstructionParameters = false; private boolean causeSet = false; /** * Creates a new descriptor that is not primitive. * * @param processingEnv the annotation processing environment. * @param messageMethod the message method. * @param type the class name of the return type. */ private AptReturnThrowableType(final ProcessingEnvironment processingEnv, final MessageMethod messageMethod, final TypeMirror type) { super(processingEnv, type); this.messageMethod = messageMethod; constructionParameters = new LinkedHashSet<>(); } @Override protected void init() { final ExecutableElement method = messageMethod; final Signature signature = method.getAnnotation(Signature.class); // If using the @Signature annotation we're attempting to use an exact constructor. if (signature != null) { final List args = ElementHelper.getClassArrayAnnotationValue(method, Signature.class, "value"); // Validate the constructor exists if (!ElementHelper.hasConstructor(types, this, args)) { throw new ProcessingException(method, "Constructor of type %s could not be found with arguments %s", this.asType(), args); } final int causeIndex = signature.causeIndex(); final int messageIndex = signature.messageIndex(); // Note that the messageIndex is required and must be 0 or greater if (messageIndex < 0) { throw new ProcessingException(method, "A messageIndex of 0 or greater is required. Value %d is invalid.", messageIndex); } final List methodConstructorParameters = new ArrayList<>(messageMethod.parametersAnnotatedWith(Param.class)); constructionParameters.clear(); useConstructionParameters = true; causeSet = !messageMethod.hasCause(); // The required length is the number of parameters plus the message and optional cause. final int len = methodConstructorParameters.size() + (causeIndex < 0 ? 1 : 2); int offset = 0; for (int i = 0; i < len; i++) { if (causeIndex == i) { causeSet = true; constructionParameters.add(messageMethod.cause()); offset++; } else if (messageIndex == i) { constructionParameters.add(ParameterFactory.forMessageMethod(messageMethod)); offset++; } else { constructionParameters.add(methodConstructorParameters.get(i - offset)); } } } else { super.init(); } } @Override protected void init(final List params) { final Set methodConstructorParameters = messageMethod.parametersAnnotatedWith(Param.class); // If there are no construction parameters or a constructor was already found, no need to process if (methodConstructorParameters.isEmpty() || useConstructionParameters) { return; } // The number of parameters needed has to include the cause, if specified, and the message it self final int neededParamSize = methodConstructorParameters.size() + (messageMethod.hasCause() ? 2 : 1); if (neededParamSize == params.size()) { // Checks for the first constructor that can be used. The compiler will end-up determining the constructor // to use, so a best guess should work. final Iterator methodParameterIterator = methodConstructorParameters.iterator(); final Set matchedParams = new LinkedHashSet<>(); boolean match = false; boolean causeFound = false; boolean messageFound = false; for (VariableElement param : params) { if (!causeFound && messageMethod.hasCause() && types.isAssignable(throwableType, param.asType())) { causeFound = true; matchedParams.add(messageMethod.cause()); continue; } if (!messageFound && types.isAssignable(param.asType(), stringType)) { messageFound = true; matchedParams.add(ParameterFactory.forMessageMethod(messageMethod)); continue; } if (methodParameterIterator.hasNext()) { final Parameter parameter = methodParameterIterator.next(); match = types.isAssignable(parameter.asType(), param.asType()); if (match) { matchedParams.add(parameter); } } // Short circuit if (!match) break; } if (match) { constructionParameters.clear(); useConstructionParameters = true; constructionParameters.addAll(matchedParams); causeSet = causeFound; } } } @Override public boolean useConstructionParameters() { return useConstructionParameters; } @Override public boolean causeSetInConstructor() { return causeSet; } @Override public Set constructionParameters() { return constructionParameters; } } } ToolLogger.java000066400000000000000000000301561356560461700341440ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.tools.Diagnostic.Kind; import org.jboss.logging.processor.model.DelegatingElement; /** * A logger for logging messages for annotation processors. * * @author James R. Perkins * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ public final class ToolLogger { private final Messager messager; private final boolean isDebugEnabled; private ToolLogger(final Messager messager, final boolean isDebugEnabled) { this.messager = messager; this.isDebugEnabled = isDebugEnabled; } /** * Creates a new tool logger. * * @param processingEnv the processing environment * * @return a new tool logger */ public static ToolLogger getLogger(final ProcessingEnvironment processingEnv) { String debug = processingEnv.getOptions().get(LoggingToolsProcessor.DEBUG_OPTION); boolean isDebugEnabled = Boolean.parseBoolean(debug); return new ToolLogger(processingEnv.getMessager(), isDebugEnabled); } /** * Returns {@code true} if debugging is enabled, otherwise {@code false}. *

* It is not necessary to invoke this method before invoking {@code debug} * methods. The debug methods will only log messages if debugging is * enabled. *

* * @return {@code true} if debugging is enabled, otherwise {@code false}. */ public boolean isDebugEnabled() { return isDebugEnabled; } /** * Prints a note message. * * @param element the element to print with the note. * @param message the message. */ public void note(final Element element, final String message) { log(Kind.NOTE, element, message); } /** * Prints a formatted note message. * * @param element the element to print with the note. * @param messageFormat the message format. * @param args the format arguments. */ public void note(final Element element, final String messageFormat, final Object... args) { log(Kind.NOTE, element, messageFormat, args); } /** * Prints a formatted debug message if debugging is enabled. * * @param messageFormat the message format. * @param args the format arguments. */ public void debug(final String messageFormat, final Object... args) { if (isDebugEnabled) { debug(null, messageFormat, args); } } /** * Prints a debug message. * * @param element the element to print with the note. * @param message the message. */ public void debug(final Element element, final String message) { if (isDebugEnabled) { other(element, message); } } /** * Prints a formatted debug message if debugging is enabled. * * @param element the element to print with the note. * @param messageFormat the message format. * @param args the format arguments. */ public void debug(final Element element, final String messageFormat, final Object... args) { if (isDebugEnabled) { other(null, messageFormat, element, args); } } /** * Prints a warning message. * * @param element the element to print with the message. * @param message the message. */ public void warn(final Element element, final String message) { log(Kind.WARNING, element, message); } /** * Prints a formatted warning message. * * @param element the element that caused the warning. * @param messageFormat the message format. * @param args the format arguments. */ public void warn(final Element element, final String messageFormat, final Object... args) { log(Kind.WARNING, element, messageFormat, args); } /** * Prints a warning message. * * @param element the element to print with the message. * @param message the message. */ public void mandatoryWarning(final Element element, final String message) { log(Kind.MANDATORY_WARNING, element, message); } /** * Prints a formatted warning message. * * @param element the element that caused the warning. * @param messageFormat the message format. * @param args the format arguments. */ public void mandatoryWarning(final Element element, final String messageFormat, final Object... args) { log(Kind.MANDATORY_WARNING, element, messageFormat, args); } /** * Prints a formatted error message. * * @param messageFormat the message format. * @param args the format arguments. */ public void error(final String messageFormat, final Object... args) { log(Kind.ERROR, null, messageFormat, args); } /** * Prints a error message. * * @param element the element to print with the message. * @param message the message. */ public void error(final Element element, final String message) { log(Kind.ERROR, element, message); } /** * Prints a formatted error message. * * @param messageFormat the message format. * @param element the element that caused the warning. * @param args the format arguments. */ public void error(final Element element, final String messageFormat, final Object... args) { log(Kind.ERROR, element, messageFormat, args); } /** * Prints an error message. * * @param cause the cause of the error. */ public void error(final Throwable cause) { error(null, cause); } /** * Prints a error message. * * @param cause the cause of the error. * @param element the element to print with the message. * @param message the message. */ public void error(final Throwable cause, final Element element, final String message) { log(Kind.ERROR, element, cause, message); } /** * Prints an error message. * * @param cause the cause of the error. * @param messageFormat the message format. * @param args the format arguments. */ public void error(final Throwable cause, final String messageFormat, final Object... args) { error(null, cause, messageFormat, args); } /** * Prints an error message. * * @param cause the cause of the error. * @param element the element that caused the error. */ public void error(final Element element, final Throwable cause) { log(Kind.ERROR, element, cause, null); } /** * Prints an error message. * * @param cause the cause of the error. * @param messageFormat the message format. * @param element the element that caused the warning. * @param args the format arguments. */ public void error(final Element element, final Throwable cause, final String messageFormat, final Object... args) { log(Kind.ERROR, element, cause, messageFormat, args); } /** * Prints a message that does not fit the other types. * * @param element the element to print with the message. * @param message the message. */ public void other(final Element element, final String message) { log(Kind.OTHER, element, message); } /** * Prints a formatted message that does not fit the other types. * * @param element the element to print with the note. * @param messageFormat the message format. * @param args the format arguments. */ public void other(final Element element, final String messageFormat, final Object... args) { log(Kind.OTHER, element, messageFormat, args); } private void log(final Kind kind, final Element element, final String message) { if (element == null) { messager.printMessage(kind, message); } else { messager.printMessage(kind, message, getElement(element)); } } private void log(final Kind kind, final Element element, final String messageFormat, final Object... args) { try { String message = ((args == null || args.length == 0) ? messageFormat : String.format(messageFormat, args)); if (element == null) { messager.printMessage(kind, message); } else { messager.printMessage(kind, message, getElement(element)); } // Fail gracefully } catch (Throwable t) { if (element == null) { messager.printMessage(Kind.ERROR, "Error logging original message: " + messageFormat); } else { messager.printMessage(Kind.ERROR, "Error logging original message: " + messageFormat, getElement(element)); } } } private void log(final Kind kind, final Element element, final Throwable cause, final String messageFormat, final Object... args) { String stringCause = stackTraceToString(cause); if (messageFormat == null) { log(kind, element, stringCause); } else { String messageWithCause = messageFormat.concat(", cause : %s"); List newArgs = new ArrayList<>(); newArgs.addAll(Arrays.asList(args)); newArgs.add(stringCause); //Add cause to error message logging log(kind, element, messageWithCause, newArgs.toArray()); } } private void log(final Kind kind, final Element element, final Throwable cause, final String message) { String stringCause = stackTraceToString(cause); if (message == null) { log(kind, element, stringCause); } else { String messageWithCause = message.concat(", cause : %s"); //Add cause to error message logging log(kind, element, messageWithCause); } } /** * Converts a stack trace to string output. * * @param t the stack trace to convert. * * @return a string version of the stack trace. */ public static String stackTraceToString(final Throwable t) { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter, true); t.printStackTrace(printWriter); printWriter.flush(); stringWriter.flush(); printWriter.close(); try { stringWriter.close(); } catch (IOException e) { // Do nothing } return stringWriter.toString(); } private static Element getElement(final Element element) { // We need to the delegate element as some implementations rely on private types return (element instanceof DelegatingElement ? ((DelegatingElement) element).getDelegate() : element); } } TranslationClassGenerator.java000066400000000000000000000320641356560461700372220ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import static org.jboss.logging.processor.util.TranslationHelper.getEnclosingTranslationFileName; import static org.jboss.logging.processor.util.TranslationHelper.getTranslationClassNameSuffix; import java.io.File; import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Pattern; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.SupportedOptions; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.StandardLocation; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.processor.generator.model.ClassModel; import org.jboss.logging.processor.generator.model.ClassModelFactory; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.validation.FormatValidator; import org.jboss.logging.processor.validation.FormatValidatorFactory; import org.jboss.logging.processor.validation.StringFormatValidator; /** * The translation class generator. *

* The aim of this generator is to generate * the classes corresponding to translation * files of a MessageLogger or MessageBundle. *

* * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ @SupportedOptions({ TranslationClassGenerator.TRANSLATION_FILES_PATH_OPTION, TranslationClassGenerator.SKIP_TRANSLATIONS }) final class TranslationClassGenerator extends AbstractGenerator { public static final String TRANSLATION_FILES_PATH_OPTION = "translationFilesPath"; public static final String SKIP_TRANSLATIONS = "skipTranslations"; /** * The properties file pattern. The property file must * match the given pattern org.pkgname.InterfaceName.i18n_locale.properties where locale is : *
    *
  • xx - where xx is the language like (e.g. en)
  • *
  • xx_YY - where xx is the language and YY is the country like (e.g. en_US)
  • *
  • xx_YY_ZZ - where xx is the language, YY is the country and ZZ is the variant like (e.g. en_US_POSIX)
  • *
*/ private static final String TRANSLATION_FILE_EXTENSION_PATTERN = ".i18n_[a-z]*(_[A-Z]*){0,2}\\.properties"; private final String translationFilesPath; private final boolean skipTranslations; /** * Construct an instance of the Translation * Class Generator. * * @param processingEnv the processing environment */ public TranslationClassGenerator(final ProcessingEnvironment processingEnv) { super(processingEnv); Map options = processingEnv.getOptions(); this.translationFilesPath = options.get(TRANSLATION_FILES_PATH_OPTION); final String value = options.get(SKIP_TRANSLATIONS); this.skipTranslations = (options.containsKey(SKIP_TRANSLATIONS) && (value == null ? true : Boolean.valueOf(value))); } @Override public void processTypeElement(final TypeElement annotation, final TypeElement element, final MessageInterface messageInterface) { if (skipTranslations) { logger().debug(element, "Skipping processing of translation implementation"); return; } try { final List files = findTranslationFiles(messageInterface); final Map> validTranslations = allInterfaceTranslations(messageInterface, files); if (files != null) { for (File file : files) { generateSourceFileFor(messageInterface, file, validTranslations.get(file)); } } } catch (IOException e) { logger().error(e, "Cannot read %s package files", messageInterface.packageName()); } } private Map> allInterfaceTranslations(final MessageInterface messageInterface, final List files) throws IOException { final Map> validTranslations = new LinkedHashMap<>(); for (MessageInterface superInterface : messageInterface.extendedInterfaces()) { validTranslations.putAll(allInterfaceTranslations(superInterface, findTranslationFiles(superInterface))); } if (files != null) { for (File file : files) { validTranslations.put(file, validateTranslationMessages(messageInterface, file)); } } return validTranslations; } private List findTranslationFiles(final MessageInterface messageInterface) throws IOException { final String packageName = messageInterface.packageName(); final String interfaceName = messageInterface.simpleName(); final String classTranslationFilesPath; //User defined if (translationFilesPath != null) { classTranslationFilesPath = translationFilesPath + packageName.replace('.', File.separatorChar); //By default use the class output folder } else { FileObject fObj = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, packageName, interfaceName); classTranslationFilesPath = fObj.toUri().getPath().replace(interfaceName, ""); } final List result; File[] files = new File(classTranslationFilesPath).listFiles(new TranslationFileFilter(interfaceName)); if (files == null) { result = Collections.emptyList(); } else { result = Arrays.asList(files); Collections.sort(result, new Comparator() { public int compare(final File o1, final File o2) { int result = o1.getAbsolutePath().compareTo(o2.getAbsolutePath()); result = (result != 0 ? result : Integer.signum(o1.getName().length() - o2.getName().length())); return result; } }); } return result; } /** * Returns only the valid translations message corresponding * to the declared {@link org.jboss.logging.processor.model.MessageMethod} methods in the * {@link org.jboss.logging.annotations.MessageBundle} or {@link org.jboss.logging.annotations.MessageLogger} * interface. * * @param messageInterface the message interface. * @param file the translation file * * @return the valid translations messages */ private Map validateTranslationMessages(final MessageInterface messageInterface, final File file) { Map validTranslations = new LinkedHashMap<>(); try { //Load translations Properties translations = new Properties(); translations.load(new InputStreamReader(new FileInputStream(file), "utf-8")); final Set messageMethods = new LinkedHashSet<>(); messageMethods.addAll(messageInterface.methods()); for (MessageInterface msgIntf : messageInterface.extendedInterfaces()) { if (msgIntf.isAnnotatedWith(MessageBundle.class) || msgIntf.isAnnotatedWith(MessageLogger.class)) { messageMethods.addAll(msgIntf.methods()); } } for (MessageMethod messageMethod : messageMethods) { final String key = messageMethod.translationKey(); if (translations.containsKey(key)) { final String translationMessage = translations.getProperty(key); if (!translationMessage.trim().isEmpty()) { final FormatValidator validator = getValidatorFor(messageMethod, translationMessage); if (validator.isValid()) { if (validator.argumentCount() == messageMethod.formatParameterCount()) { validTranslations.put(messageMethod, translationMessage); } else { logger().warn(messageMethod, "The parameter count for the format (%d) and the number of format parameters (%d) do not match.", validator.argumentCount(), messageMethod.formatParameterCount()); } } else { logger().warn(messageMethod, "%s Resource Bundle: %s", validator.summaryMessage(), file.getAbsolutePath()); } } else { logger().warn(messageMethod, "The translation message with key %s is ignored because value is empty or contains only whitespace", key); } } else { logger().warn(messageMethod, "The translation message with key %s have no corresponding messageMethod.", key); } } } catch (IOException e) { logger().error(e, "Cannot read the %s translation file", file.getName()); } return validTranslations; } /** * Generate a class for the given translation file. * * @param messageInterface the message interface * @param translationFile the translation file * @param translations the translations message */ private void generateSourceFileFor(final MessageInterface messageInterface, final File translationFile, final Map translations) { //Generate empty translation super class if needed //Check if enclosing translation file exists, if not generate an empty super class final String enclosingTranslationFileName = getEnclosingTranslationFileName(translationFile); final File enclosingTranslationFile = new File(translationFile.getParent(), enclosingTranslationFileName); if (!enclosingTranslationFileName.equals(translationFile.getName()) && !enclosingTranslationFile.exists()) { generateSourceFileFor(messageInterface, enclosingTranslationFile, Collections.emptyMap()); } //Create source file final ClassModel classModel = ClassModelFactory.translation(processingEnv, messageInterface, getTranslationClassNameSuffix(translationFile.getName()), translations); try { classModel.generateAndWrite(); } catch (IllegalStateException | IOException e) { logger().error(e, "Cannot generate %s source file", classModel.qualifiedClassName()); } } private static FormatValidator getValidatorFor(final MessageMethod messageMethod, final String translationMessage) { FormatValidator result = FormatValidatorFactory.create(messageMethod.message().format(), translationMessage); if (result.isValid()) { if (messageMethod.message().format() == Message.Format.PRINTF) { result = StringFormatValidator.withTranslation(messageMethod.message().value(), translationMessage); } } return result; } /** * Translation file Filter. */ private class TranslationFileFilter implements FilenameFilter { private final String className; /** * The property file filter. * * @param className the class that have i18n property file */ public TranslationFileFilter(final String className) { this.className = className; } @Override public boolean accept(final File dir, final String name) { boolean isGenerated = name.endsWith(TranslationFileGenerator.GENERATED_FILE_EXTENSION); boolean isTranslationFile = name.matches(Pattern.quote(className) + TRANSLATION_FILE_EXTENSION_PATTERN); return !isGenerated && isTranslationFile; } } } TranslationFileGenerator.java000066400000000000000000000464661356560461700370470ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.SupportedOptions; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.tools.FileObject; import javax.tools.StandardLocation; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.validation.StringFormatValidator; /** * The generator of skeletal * translations files. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) * @author James R. Perkins */ @SuppressWarnings("MagicNumber") @SupportedOptions({TranslationFileGenerator.GENERATED_FILES_PATH_OPTION, TranslationFileGenerator.LEVEL_OPTION, TranslationFileGenerator.SKIP_INDEX}) final class TranslationFileGenerator extends AbstractGenerator { private static final Map levels = new HashMap<>(); private static final Pattern PATTERN = Pattern.compile("((@[a-zA-Z_0-9]+)\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s+([a-zA-Z_][a-zA-Z_0-9].*)\\s*)"); private static final String EMPTY_STRING = ""; private static final String JAVA_DOC_PARAM = "@param"; private static final String DEFAULT_FILE_EXTENSION = ".i18n.properties"; private static final String DEFAULT_FILE_COMMENT = "# This file is for reference only, changes have no effect on the generated interface implementations."; static final String GENERATED_FILES_PATH_OPTION = "generatedTranslationFilesPath"; static final String GENERATED_FILE_EXTENSION = ".i18n_locale_COUNTRY_VARIANT.properties"; static final String LEVEL_OPTION = "org.jboss.logging.tools.level"; static final String SKIP_INDEX = "org.jboss.logging.tools.generated.skip.index"; static { levels.put("ALL", Integer.MIN_VALUE); levels.put("CONFIG", 700); levels.put("DEBUG", 500); levels.put("ERROR", 1000); levels.put("FATAL", 1100); levels.put("FINE", 500); levels.put("FINER", 400); levels.put("FINEST", 300); levels.put("INFO", 800); levels.put("OFF", Integer.MAX_VALUE); levels.put("SEVERE", 1000); levels.put("TRACE", 400); levels.put("WARN", 900); levels.put("WARNING", 900); } private final String generatedFilesPath; private final LevelComparator comparator; private final boolean skipIndex; /** * The constructor. * * @param processingEnv the processing env */ TranslationFileGenerator(final ProcessingEnvironment processingEnv) { super(processingEnv); Map options = processingEnv.getOptions(); this.generatedFilesPath = options.get(GENERATED_FILES_PATH_OPTION); String highLevel = options.get(LEVEL_OPTION); if (highLevel == null) { // Check for a system property highLevel = AccessController.doPrivileged(new PrivilegedAction() { public String run() { return System.getProperty(LEVEL_OPTION); } }); } if (highLevel != null) { if (!levels.containsKey(highLevel)) { logger().error("Invalid property '%s' defined. The value %s is invalid.", LEVEL_OPTION, highLevel); } comparator = new LevelComparator(highLevel); } else { comparator = null; } final String value = options.get(SKIP_INDEX); this.skipIndex = options.containsKey(SKIP_INDEX) && (value == null || value.isEmpty() || Boolean.parseBoolean(value)); } @Override public void processTypeElement(final TypeElement annotation, final TypeElement element, final MessageInterface messageInterface) { if (generatedFilesPath != null) { if (element.getKind().isInterface()) { String packageName = processingEnv.getElementUtils().getPackageOf(element).getQualifiedName().toString(); String relativePath = packageName.replace('.', File.separatorChar); String fileName = getPrimaryClassNamePrefix(element) + GENERATED_FILE_EXTENSION; this.generateSkeletalTranslationFile(relativePath, fileName, messageInterface); } } // Always generate an Interface.i18n.properties file. generateDefaultTranslationFile(messageInterface); } /** * Generate the translation file containing the given * translations. * * @param relativePath the relative path * @param fileName the file name * @param messageInterface the message interface */ private void generateSkeletalTranslationFile(final String relativePath, final String fileName, final MessageInterface messageInterface) { if (messageInterface == null) { throw new IllegalArgumentException("The translations parameter cannot be null"); } File pathFile = new File(generatedFilesPath, relativePath); pathFile.mkdirs(); File file = new File(pathFile, fileName); BufferedWriter writer = null; try { writer = new BufferedWriter(new FileWriter(file)); final Set processed = new HashSet<>(); for (MessageMethod messageMethod : messageInterface.methods()) { if (isMethodWritable(messageMethod)) { if (processed.add(messageMethod.translationKey())) { writeSkeletonMessageMethod(writer, messageMethod); } } } } catch (IOException e) { logger().error(e, "Cannot write generated skeletal translation file %s", fileName); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { logger().error(e, "Cannot close generated skeletal translation file %s", fileName); } } } /** * Generates a default i18n properties file. * * @param messageInterface the message interface */ private void generateDefaultTranslationFile(final MessageInterface messageInterface) { final String fileName = messageInterface.simpleName() + DEFAULT_FILE_EXTENSION; BufferedWriter writer = null; try { if (generatedFilesPath == null) { final FileObject fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, messageInterface.packageName(), fileName); // Note the FileObject#openWriter() is used here. The FileObject#openOutputStream() returns an output stream // that writes each byte separately which results in poor performance. writer = new BufferedWriter(fileObject.openWriter()); } else { String relativePath = messageInterface.packageName().replace('.', File.separatorChar); final File path = new File(generatedFilesPath, relativePath); path.mkdirs(); final File file = new File(path, fileName); writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); } // Write comments writeSeparatorLine(writer); writer.write("#"); writer.newLine(); writer.write(DEFAULT_FILE_COMMENT); writer.newLine(); writer.write("#"); writer.newLine(); writeSeparatorLine(writer); writer.newLine(); final Set processed = new HashSet<>(); for (MessageMethod messageMethod : messageInterface.methods()) { if (isMethodWritable(messageMethod)) { if (processed.add(messageMethod.translationKey())) { writeSkeletonMessageMethod(writer, messageMethod); } } } } catch (IOException e) { logger().error(e, "Cannot write generated default translation file %s", fileName); } finally { try { if (writer != null) { writer.close(); } } catch (IOException e) { logger().error(e, "Cannot write generated default translation file %s", fileName); } } } private void writeSkeletonMessageMethod(final BufferedWriter writer, final MessageMethod messageMethod) throws IOException { final MessageMethod.Message msg = messageMethod.message(); writer.write(String.format("# Id: %s", (msg.hasId() ? msg.id() : "none"))); writer.newLine(); if (messageMethod.isLoggerMethod()) { writer.write(String.format("# Level: %s", messageMethod.logLevel())); writer.newLine(); } writer.write(String.format("# Message: %s", msg.value())); writer.newLine(); final Map parameterComments = parseParameterComments(messageMethod); int i = 0; for (Parameter parameter : messageMethod.parameters()) { final String name = parameter.name(); final String comment = (parameterComments.containsKey(name) ? parameterComments.get(name) : EMPTY_STRING); if (parameter.isAnnotatedWith(Transform.class)) { final List transformTypes = Arrays.asList(parameter.getAnnotation(Transform.class).value()); if (transformTypes.contains(TransformType.GET_CLASS)) { if (transformTypes.size() == 1) { writer.write(String.format("# @param class of %s - %s", name, comment)); } else if (transformTypes.contains(TransformType.HASH_CODE)) { writer.write(String.format("# @param hashCode of class of %s - %s", name, comment)); } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE)) { writer.write(String.format("# @param identityHashCode of class of %s - %s", name, comment)); } } else if (transformTypes.contains(TransformType.HASH_CODE)) { writer.write(String.format("# @param hashCode of %s - %s", name, comment)); } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE)) { writer.write(String.format("# @param identityHashCode of %s - %s", name, comment)); } else if (transformTypes.contains(TransformType.SIZE)) { if (parameter.isArray() || parameter.isVarArgs() || parameter.isSubtypeOf(String.class)) { writer.write(String.format("# @param length of %s - %s", name, comment)); } else { writer.write(String.format("# @param size of %s - %s", name, comment)); } } writer.newLine(); } else if (parameter.isFormatParameter()) { writer.write(String.format("# @param %d: %s - %s", ++i, name, comment)); writer.newLine(); } } writer.write(String.format("%s=", messageMethod.translationKey())); if (!skipIndex && messageMethod.message().format() == Message.Format.PRINTF) { writer.write(addIndexesToFormat(messageMethod)); } else { writer.write(messageMethod.message().value()); } writer.newLine(); } private Map parseParameterComments(final MessageMethod messageMethod) throws IOException { final Map result = new LinkedHashMap<>(); final String comment = messageMethod.getComment(); if (comment != null) { final Matcher matcher = PATTERN.matcher(comment); while (matcher.find()) { if (matcher.groupCount() > 3) { final String annotation = matcher.group(2); if (annotation != null && annotation.trim().equals(JAVA_DOC_PARAM)) result.put(matcher.group(3), matcher.group(4)); } } } return result; } private boolean isMethodWritable(final MessageMethod method) { return !(comparator != null && method.isLoggerMethod()) || (comparator.compareTo(method.logLevel()) >= 0); } private static void writeSeparatorLine(final BufferedWriter writer) throws IOException { final int len = DEFAULT_FILE_COMMENT.length(); for (int i = 0; i < len; i++) { writer.append('#'); } writer.newLine(); } /** * Returns the primary class simple name prefix for an element * who represents a MessageBundle or MessageLogger interface. * * @param element the element * * @return the translation file name prefix * * @throws IllegalArgumentException if element is null or the element is not an interface */ private static String getPrimaryClassNamePrefix(final TypeElement element) { if (element == null) { throw new IllegalArgumentException("The element parameter cannot be null"); } if (!element.getKind().isInterface()) { throw new IllegalArgumentException("The element parameter is not an interface"); } String translationFileName = element.getSimpleName().toString(); //Check if it's an inner interface Element enclosingElt = element.getEnclosingElement(); while (enclosingElt != null && enclosingElt instanceof TypeElement) { translationFileName = String.format("%s$%s", enclosingElt.getSimpleName().toString(), translationFileName); enclosingElt = enclosingElt.getEnclosingElement(); } return translationFileName; } private String addIndexesToFormat(final MessageMethod method) { final String format = method.message().value(); int pos = 0; int i = 0; final Matcher matcher = StringFormatValidator.PATTERN.matcher(format); final StringBuilder newFormat = new StringBuilder(); while (i < format.length()) { if (matcher.find(i)) { if (matcher.start() != i) { newFormat.append(format, i, matcher.start()); } // Pattern should produce 6 groups. if (matcher.groupCount() != 6) { logger().warn(method, "Invalid format using \"%s\" for the skeleton value.", format); return format; } // The % is stripped so we need to add it back newFormat.append('%'); // Initialize the parts so they can be added if they're not null final String index = matcher.group(1); final String flags = matcher.group(2); final String width = matcher.group(3); final String precision = matcher.group(4); final String t = matcher.group(5); final char conversion = matcher.group(6).charAt(0); if (index == null) { // If the flags contain < that's a previous index identifier so we should not replace it. Also new // line (%n) and an escaped percent (%%) do not allow index arguments. if (flags != null && !flags.contains("<") && conversion != 'n' && conversion != '%') { newFormat.append(++pos).append('$'); } } else { // The index already exists so we'll use that newFormat.append(index); } if (flags != null) { newFormat.append(flags); } if (width != null) { newFormat.append(width); } if (precision != null) { newFormat.append(precision); } if (t != null) { newFormat.append(t); } newFormat.append(conversion); i = matcher.end(); } else { // No more formats found, but validate for invalid remaining characters. newFormat.append(format, i, format.length()); break; } } final String result = newFormat.toString(); // Validate if the changed format is valid and if not fallback to the default format from the message annotation final StringFormatValidator validator = StringFormatValidator.of(result); if (!validator.isValid()) { logger().warn(method, "Could not properly use indexes in the format %s.", format); return format; } return result; } private static final class LevelComparator implements Comparable { private final Integer levelIntValue; private LevelComparator(final String level) { levelIntValue = levels.get(level); if (levelIntValue == null) { throw new IllegalArgumentException(String.format("Level %s is invalid.", level)); } } @Override public int compareTo(final String o) { String cmpLevel = o; // Get the actual level final int lastDot = o.lastIndexOf("."); if (lastDot > -1) { cmpLevel = o.substring(lastDot + 1); } final Integer level = levels.get(cmpLevel); if (level == null) { throw new IllegalArgumentException(String.format("Level %s is invalid.", cmpLevel)); } return level.compareTo(levelIntValue); } } } jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/000077500000000000000000000000001356560461700326115ustar00rootroot00000000000000AsciidocReportWriter.java000066400000000000000000000116251356560461700375110ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt.report; import java.io.BufferedWriter; import java.io.IOException; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * @author James R. Perkins */ class AsciidocReportWriter extends ReportWriter { private final BufferedWriter writer; AsciidocReportWriter(final MessageInterface messageInterface, final BufferedWriter writer) { super(messageInterface); this.writer = writer; } @Override public void writeHeader(final String title) throws IOException { // Write the title for the document final String escapedTitle; if (title != null) { escapedTitle = escape(title).toString(); } else { escapedTitle = "Messages"; } writer.write(escapedTitle); writer.newLine(); for (int i = 0; i < escapedTitle.length(); i++) { writer.append('='); } writer.newLine(); writer.newLine(); // Write the table title writer.append('.').append(messageInterface.name()); writer.newLine(); // Write the table configuration, 4 columns writer.write("[cols=\"1,5,^1,2m\"]"); writer.newLine(); // Write the table header writer.write("|==="); writer.newLine(); writer.write("|Message Id |Message |Log Level |Return Type"); writer.newLine(); writer.newLine(); } @Override public void writeDetail(final MessageMethod messageMethod) throws IOException { final MessageMethod.Message msg = messageMethod.message(); final String id = (msg.hasId() ? String.format(messageIdFormat, msg.id()) : DEFAULT_ID); final String url = getUrl(messageMethod, id); if (url.isEmpty()) { writer.append('|').append(escape(id)); } else { writer.append("|link:").append(url).append('[').append(id).append(']'); } writer.newLine(); writer.append('|').append(escape(msg.value())); writer.newLine(); if (messageMethod.isLoggerMethod()) { writer.append('|').append(getLogLevel(messageMethod)); writer.newLine(); writer.append("|void"); } else { writer.append("|--"); writer.newLine(); writer.append('|').append(messageMethod.returnType().name()); } writer.newLine(); writer.newLine(); } @Override public void writeFooter() throws IOException { // End the table writer.write("|==="); writer.newLine(); } @Override public void close() throws IOException { writer.close(); } @Override ReportType getReportType() { return ReportType.ASCIIDOC; } private CharSequence escape(final CharSequence s) { final StringBuilder sb = new StringBuilder(); final int len = s.length(); int aPos = -1; int offset = 0; char previous = 0x00; for (int i = 0; i < len; i++) { final char c = s.charAt(i); switch (c) { // Asterisks around text make it bold, unless there is a space after a beginning asterisk or a space // before an ending asterisk case '*': if (aPos >= 0) { if (previous != ' ') { sb.insert(aPos + offset++, '\\'); } aPos = -1; } else if ((i + 1) < len) { final char next = s.charAt(i + 1); if (next != ' ') { aPos = i; } } break; } previous = c; sb.append(c); } return sb; } } IndentingXmlWriter.java000066400000000000000000000216701356560461700372000ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt.report; import java.util.Iterator; import java.util.stream.Stream; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * @author James R. Perkins */ class IndentingXmlWriter implements XMLStreamWriter, XMLStreamConstants { private static final String SPACES = " "; private final XMLStreamWriter delegate; private int index; private int state = START_DOCUMENT; private boolean indentEnd; public IndentingXmlWriter(final XMLStreamWriter delegate) { this.delegate = delegate; index = 0; indentEnd = false; } private void indent() throws XMLStreamException { final int index = this.index; if (index > 0) { for (int i = 0; i < index; i++) { delegate.writeCharacters(SPACES); } } } private void newline() throws XMLStreamException { delegate.writeCharacters(System.lineSeparator()); } @Override public void writeStartElement(final String localName) throws XMLStreamException { newline(); indent(); delegate.writeStartElement(localName); indentEnd = false; state = START_ELEMENT; index++; } @Override public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException { newline(); indent(); delegate.writeStartElement(namespaceURI, localName); indentEnd = false; state = START_ELEMENT; index++; } @Override public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException { newline(); indent(); delegate.writeStartElement(prefix, localName, namespaceURI); indentEnd = false; state = START_ELEMENT; index++; } @Override public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException { newline(); indent(); delegate.writeEmptyElement(namespaceURI, localName); state = END_ELEMENT; } @Override public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException { newline(); indent(); delegate.writeEmptyElement(prefix, localName, namespaceURI); state = END_ELEMENT; } @Override public void writeEmptyElement(final String localName) throws XMLStreamException { newline(); indent(); delegate.writeEmptyElement(localName); state = END_ELEMENT; } @Override public void writeEndElement() throws XMLStreamException { index--; if (state != CHARACTERS || indentEnd) { newline(); indent(); indentEnd = false; } delegate.writeEndElement(); state = END_ELEMENT; } @Override public void writeEndDocument() throws XMLStreamException { delegate.writeEndDocument(); state = END_DOCUMENT; } @Override public void close() throws XMLStreamException { delegate.close(); } @Override public void flush() throws XMLStreamException { delegate.flush(); } @Override public void writeAttribute(final String localName, final String value) throws XMLStreamException { delegate.writeAttribute(localName, value); } @Override public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException { delegate.writeAttribute(prefix, namespaceURI, localName, value); } @Override public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException { delegate.writeAttribute(namespaceURI, localName, value); } @Override public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException { delegate.writeNamespace(prefix, namespaceURI); } @Override public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException { delegate.writeDefaultNamespace(namespaceURI); } @Override public void writeComment(final String data) throws XMLStreamException { newline(); indent(); delegate.writeComment(data); state = COMMENT; } @Override public void writeProcessingInstruction(final String target) throws XMLStreamException { newline(); indent(); delegate.writeProcessingInstruction(target); state = PROCESSING_INSTRUCTION; } @Override public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException { newline(); indent(); delegate.writeProcessingInstruction(target, data); state = PROCESSING_INSTRUCTION; } @Override public void writeCData(final String data) throws XMLStreamException { delegate.writeCData(data); state = CDATA; } @Override public void writeDTD(final String dtd) throws XMLStreamException { newline(); indent(); delegate.writeDTD(dtd); state = DTD; } @Override public void writeEntityRef(final String name) throws XMLStreamException { delegate.writeEntityRef(name); state = ENTITY_REFERENCE; } @Override public void writeStartDocument() throws XMLStreamException { delegate.writeStartDocument(); newline(); state = START_DOCUMENT; } @Override public void writeStartDocument(final String version) throws XMLStreamException { delegate.writeStartDocument(version); newline(); state = START_DOCUMENT; } @Override public void writeStartDocument(final String encoding, final String version) throws XMLStreamException { delegate.writeStartDocument(encoding, version); newline(); state = START_DOCUMENT; } @Override public void writeCharacters(final String text) throws XMLStreamException { indentEnd = false; boolean first = true; final Iterator iterator = Stream.of(text.split("\n")).iterator(); while (iterator.hasNext()) { final String t = iterator.next(); // On first iteration if more than one line is required, skip to a new line and indent if (first && iterator.hasNext()) { first = false; newline(); indent(); } delegate.writeCharacters(t); if (iterator.hasNext()) { newline(); indent(); indentEnd = true; } } state = CHARACTERS; } @Override public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException { delegate.writeCharacters(text, start, len); } @Override public String getPrefix(final String uri) throws XMLStreamException { return delegate.getPrefix(uri); } @Override public void setPrefix(final String prefix, final String uri) throws XMLStreamException { delegate.setPrefix(prefix, uri); } @Override public void setDefaultNamespace(final String uri) throws XMLStreamException { delegate.setDefaultNamespace(uri); } @Override public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException { delegate.setNamespaceContext(context); } @Override public NamespaceContext getNamespaceContext() { return delegate.getNamespaceContext(); } @Override public Object getProperty(final String name) throws IllegalArgumentException { return delegate.getProperty(name); } } ReportType.java000066400000000000000000000030271356560461700355140ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt.report; /** * Defines the report type for generating reports. * * @author James R. Perkins */ public enum ReportType { ASCIIDOC(".adoc"), XML(".xml"); private final String extension; ReportType(final String extension) { this.extension = extension; } /** * Returns the extension used for the file. * * @return the extension */ public String getExtension() { return extension; } } ReportWriter.java000066400000000000000000000144751356560461700360600ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt.report; import java.io.BufferedWriter; import java.io.Closeable; import java.io.IOException; import javax.xml.stream.XMLStreamException; import org.jboss.logging.annotations.BaseUrl; import org.jboss.logging.annotations.ResolutionDoc; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.util.Expressions; /** * Writes reports based on a {@link MessageInterface}. These reports could be used for documented messages from logging * or message bundle interfaces. * * @author James R. Perkins */ public abstract class ReportWriter implements Closeable { static final String DEFAULT_ID = "--"; private final String baseUrl; final MessageInterface messageInterface; final String messageIdFormat; ReportWriter(final MessageInterface messageInterface) { this.messageInterface = messageInterface; final int idLen = messageInterface.getIdLength(); if (idLen > 0) { messageIdFormat = messageInterface.projectCode() + "%0" + messageInterface.getIdLength() + "d"; } else { messageIdFormat = messageInterface.projectCode() + "%d"; } if (messageInterface.isAnnotatedWith(BaseUrl.class)) { baseUrl = messageInterface.getAnnotation(BaseUrl.class).value(); } else { baseUrl = null; } } /** * Creates a new report writer based on the report type. * * @param reportType the report type to create the writer for * @param writer the used to write the contents to * * @return the report writer to use * * @throws IllegalStateException if there was an error creating the report writer * @throws IllegalArgumentException if the {@code reportType} is invalid */ public static ReportWriter of(final ReportType reportType, final MessageInterface messageInterface, final BufferedWriter writer) { if (reportType == ReportType.ASCIIDOC) { return new AsciidocReportWriter(messageInterface, writer); } else if (reportType == ReportType.XML) { try { return new XmlReportWriter(messageInterface, writer); } catch (XMLStreamException e) { throw new IllegalStateException("Failed to create XML report writer.", e); } } throw new IllegalArgumentException("Type " + reportType + " is not a known report type."); } /** * Writes the header for the report. * * @param title the title of the header * * @throws IOException if an I/O error occurs */ public abstract void writeHeader(String title) throws IOException; /** * Writes a detail line for the report. * * @param messageMethod the method to write the details for * * @throws IOException if an I/O error occurs */ public abstract void writeDetail(MessageMethod messageMethod) throws IOException; /** * Writes the footer for the report. * * @throws IOException if an I/O error occurs */ public abstract void writeFooter() throws IOException; /** * The report type for this writer. * * @return the report type */ abstract ReportType getReportType(); /** * Gets the log level from the {@code @Message} annotation. * * @param method the method to get the log level from * * @return the log level or an empty string */ String getLogLevel(final MessageMethod method) { if (method.isLoggerMethod()) { final String logLevel = method.logLevel(); final int index = logLevel.lastIndexOf('.'); if (index > 0) { return logLevel.substring(index + 1); } return logLevel; } return ""; } String getUrl(final MessageMethod messageMethod, final String id) { final ResolutionDoc resolutionDoc = getResolutionDoc(messageMethod); if (resolutionDoc == null || resolutionDoc.skip() || DEFAULT_ID.equals(id)) { return ""; } final StringBuilder result = new StringBuilder(); String base = baseUrl == null ? "" : baseUrl; final String path = resolutionDoc.path(); final String suffix = resolutionDoc.suffix(); final String url = resolutionDoc.url(); if (!url.isEmpty()) { base = url; } if (!base.isEmpty()) { result.append(base); if (!base.endsWith("/") && !base.endsWith("#")) { result.append('/'); } } if (path.isEmpty()) { result.append(id); } else { result.append(path); } if (suffix.isEmpty()) { result.append(getReportType().getExtension()); } else { result.append(suffix); } return Expressions.resolve(messageInterface.expressionProperties(), result.toString()); } private ResolutionDoc getResolutionDoc(final MessageMethod messageMethod) { if (messageMethod.isAnnotatedWith(ResolutionDoc.class)) { return messageMethod.getAnnotation(ResolutionDoc.class); } return messageInterface.getAnnotation(ResolutionDoc.class); } } XmlReportWriter.java000066400000000000000000000103141356560461700365250ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/apt/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.apt.report; import java.io.BufferedWriter; import java.io.IOException; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * @author James R. Perkins */ class XmlReportWriter extends ReportWriter { private static final String NAMESPACE = "urn:jboss:logging:report:1.0"; private final XMLStreamWriter xmlWriter; XmlReportWriter(final MessageInterface messageInterface, final BufferedWriter writer) throws XMLStreamException { super(messageInterface); final XMLOutputFactory factory = XMLOutputFactory.newInstance(); xmlWriter = new IndentingXmlWriter(factory.createXMLStreamWriter(writer)); } @Override public void writeHeader(final String title) throws IOException { try { xmlWriter.writeStartDocument(); xmlWriter.setDefaultNamespace(NAMESPACE); xmlWriter.writeStartElement("report"); xmlWriter.writeNamespace(null, NAMESPACE); if (title != null) { xmlWriter.writeAttribute("title", title); } xmlWriter.writeStartElement("messages"); xmlWriter.writeAttribute("interface", messageInterface.name()); } catch (XMLStreamException e) { throw new IOException(e); } } @Override public void writeDetail(final MessageMethod messageMethod) throws IOException { try { xmlWriter.writeStartElement("message"); final MessageMethod.Message msg = messageMethod.message(); final String url; if (msg.hasId()) { final String id = String.format(messageIdFormat, msg.id()); xmlWriter.writeAttribute("id", id); url = getUrl(messageMethod, id); } else { url = getUrl(messageMethod, DEFAULT_ID); } if (!url.isEmpty()) { xmlWriter.writeAttribute("resolutionUrl", url); } if (messageMethod.isLoggerMethod()) { xmlWriter.writeAttribute("logLevel", getLogLevel(messageMethod)); } else { xmlWriter.writeAttribute("returnType", messageMethod.returnType().name()); } xmlWriter.writeCharacters(msg.value()); xmlWriter.writeEndElement(); } catch (XMLStreamException e) { throw new IOException(e); } } @Override public void writeFooter() throws IOException { try { xmlWriter.writeEndElement(); // end xmlWriter.writeEndElement(); // end xmlWriter.writeEndDocument(); } catch (XMLStreamException e) { throw new IOException(e); } } @Override public void close() throws IOException { try { if (xmlWriter != null) xmlWriter.close(); } catch (XMLStreamException ignore) { } } @Override ReportType getReportType() { return ReportType.XML; } } jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/000077500000000000000000000000001356560461700325005ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/000077500000000000000000000000001356560461700336005ustar00rootroot00000000000000ClassModel.java000066400000000000000000000340401356560461700364130ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import static org.jboss.jdeparser.JExprs.$v; import static org.jboss.jdeparser.JMod.FINAL; import static org.jboss.jdeparser.JTypes.$t; import static org.jboss.jdeparser.JTypes.typeOf; import java.io.IOException; import java.io.Serializable; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.TypeElement; import org.jboss.jdeparser.FormatPreferences; import org.jboss.jdeparser.JBlock; import org.jboss.jdeparser.JCall; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JDeparser; import org.jboss.jdeparser.JExpr; import org.jboss.jdeparser.JExprs; import org.jboss.jdeparser.JFiler; import org.jboss.jdeparser.JMethodDef; import org.jboss.jdeparser.JMod; import org.jboss.jdeparser.JSourceFile; import org.jboss.jdeparser.JSources; import org.jboss.jdeparser.JType; import org.jboss.jdeparser.JVarDeclaration; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.processor.apt.ProcessingException; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * The basic java class model. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) * @author James R. Perkins */ public abstract class ClassModel { private static final String INSTANCE_FIELD_NAME = "INSTANCE"; private static final String GET_INSTANCE_METHOD_NAME = "readResolve"; private final JSources sources; private final JClassDef classDef; private final MessageInterface messageInterface; private final String className; private final String superClassName; private final String format; private final Map messageMethods; final JSourceFile sourceFile; final ProcessingEnvironment processingEnv; /** * Construct a class model. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. * @param superClassName the super class used for the translation implementations. */ ClassModel(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface, final String className, final String superClassName) { this.processingEnv = processingEnv; this.messageInterface = messageInterface; this.className = messageInterface.packageName() + "." + className; this.superClassName = superClassName; sources = JDeparser.createSources(JFiler.newInstance(processingEnv.getFiler()), new FormatPreferences(new Properties())); sourceFile = sources.createSourceFile(messageInterface.packageName(), className); classDef = sourceFile._class(JMod.PUBLIC, className); final int idLen = messageInterface.getIdLength(); if (idLen > 0) { format = "%s%0" + messageInterface.getIdLength() + "d: %s"; } else { format = "%s%d: %s"; } messageMethods = new HashMap<>(); } /** * Returns the message interface being used. * * @return the message interface. */ public final MessageInterface messageInterface() { return messageInterface; } /** * Writes the generated source file to the file system. * * @throws java.io.IOException if the file could not be written */ public final void generateAndWrite() throws IOException { generateModel(); sources.writeSources(); JDeparser.dropCaches(); } /** * Generate the code corresponding to this * class model * * @return the generated code * * @throws IllegalStateException if the class has already been defined. */ JClassDef generateModel() throws IllegalStateException { // Add generated annotation if required final TypeElement generatedAnnotation = messageInterface.generatedAnnotation(); if (generatedAnnotation != null) { final JType generatedType = typeOf(generatedAnnotation.asType()); sourceFile._import(generatedType); classDef.annotate(generatedType) .value("value", getClass().getName()) .value("date", JExprs.str(ClassModelHelper.generatedDateValue())); } // Create the default JavaDoc classDef.docComment().text("Warning this class consists of generated code."); // Add extends if (superClassName != null) { classDef._extends(superClassName); } // Always implement the interface classDef._implements(typeOf(messageInterface.asType())); //Add implements if (!messageInterface.extendedInterfaces().isEmpty()) { for (MessageInterface intf : messageInterface.extendedInterfaces()) { final JType interfaceName = typeOf(intf.asType()); sourceFile._import(interfaceName); classDef._implements(interfaceName); } } final JType serializable = $t(Serializable.class); sourceFile._import(serializable); classDef._implements(serializable); classDef.field(JMod.PRIVATE | JMod.STATIC | FINAL, JType.LONG, "serialVersionUID", JExprs.decimal(1L)); return classDef; } /** * Adds a method to return the message value. The method name should be the * method name annotated {@code org.jboss.logging.Message}. This method will * be appended with {@code $str}. *

*

* If the message method has already been defined the previously created * method is returned. *

*

* * @param messageMethod the message method * * @return the newly created method. * * @throws IllegalStateException if this method is called before the generateModel method */ JMethodDef addMessageMethod(final MessageMethod messageMethod) { return addMessageMethod(messageMethod, messageMethod.message().value()); } /** * Adds a method to return the message value. The method name should be the * method name annotated {@code org.jboss.logging.Message}. This method will * be appended with {@code $str}. *

*

* If the message method has already been defined the previously created * method is returned. *

*

* * @param messageMethod the message method. * @param messageValue the message value. * * @return the newly created method. * * @throws IllegalStateException if this method is called before the generateModel method */ JMethodDef addMessageMethod(final MessageMethod messageMethod, final String messageValue) { // Values could be null and we shouldn't create message methods for null values. if (messageValue == null) { return null; } // Create the method that returns the string message for formatting JMethodDef method = messageMethods.get(messageMethod.messageMethodName()); if (method == null) { method = classDef.method(JMod.PROTECTED, String.class, messageMethod.messageMethodName()); final JBlock body = method.body(); final String msg; if (messageInterface.projectCode() != null && !messageInterface.projectCode().isEmpty() && messageMethod.message().hasId()) { // Prefix the id to the string message msg = String.format(format, messageInterface.projectCode(), messageMethod.message().id(), messageValue); } else { msg = messageValue; } body._return(JExprs.str(msg)); messageMethods.put(messageMethod.messageMethodName(), method); } return method; } /** * Get the class name. * * @return the class name */ public final String qualifiedClassName() { return className; } /** * Creates the read resolve method and instance field. * * @return the read resolve method. */ protected JMethodDef createReadResolveMethod() { final JType type = typeOf(classDef); final JVarDeclaration instance = classDef.field(JMod.PUBLIC | JMod.STATIC | JMod.FINAL, type, INSTANCE_FIELD_NAME, type._new()); final JMethodDef readResolveMethod = classDef.method(JMod.PROTECTED, Object.class, GET_INSTANCE_METHOD_NAME); readResolveMethod.body()._return($v(instance)); return readResolveMethod; } /** * Creates the method used to get the locale for formatting messages. *

* If the {@code locale} parameter is {@code null} the {@link MessageLogger#rootLocale()} or * {@link MessageBundle#rootLocale()} will be used to determine the {@linkplain Locale locale} to use. *

* * @param locale the locale to use * @param override {@code true} if the {@link Override} annotation should be added to the method * * @return the call to the locale getter */ JCall createLocaleGetter(final String locale, final boolean override) { final String methodName = "getLoggingLocale"; // Create the type and import it final JType localeType = typeOf(Locale.class); sourceFile._import(localeType); final JVarDeclaration defaultInstance = classDef.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, localeType, "LOCALE", determineLocale(locale, localeType)); // Create the method final JMethodDef method = classDef.method(JMod.PROTECTED, localeType, methodName); if (override) { method.annotate(Override.class); } method.body()._return($v(defaultInstance)); return JExprs.call(methodName); } private JExpr determineLocale(final String locale, final JType localeType) { final JExpr initializer; if (locale == null) { // Create a static instance field for the default locale final String bcp47Value; if (messageInterface.isAnnotatedWith(MessageBundle.class)) { bcp47Value = messageInterface.getAnnotation(MessageBundle.class).rootLocale(); } else if (messageInterface.isAnnotatedWith(MessageLogger.class)) { bcp47Value = messageInterface.getAnnotation(MessageLogger.class).rootLocale(); } else { bcp47Value = ""; } if (bcp47Value.isEmpty()) { initializer = localeType.$v("ROOT"); } else { initializer = localeType.call("forLanguageTag").arg(JExprs.str(bcp47Value)); } } else { if ("en_CA".equals(locale)) { initializer = localeType.$v("CANADA"); } else if ("fr_CA".equals(locale)) { initializer = localeType.$v("CANADA_FRENCH"); } else if ("zh".equals(locale)) { initializer = localeType.$v("CHINESE"); } else if ("en".equals(locale)) { initializer = localeType.$v("ENGLISH"); } else if ("fr_FR".equals(locale)) { initializer = localeType.$v("FRANCE"); } else if ("fr".equals(locale)) { initializer = localeType.$v("FRENCH"); } else if ("de".equals(locale)) { initializer = localeType.$v("GERMAN"); } else if ("de_DE".equals(locale)) { initializer = localeType.$v("GERMANY"); } else if ("it".equals(locale)) { initializer = localeType.$v("ITALIAN"); } else if ("it_IT".equals(locale)) { initializer = localeType.$v("ITALY"); } else if ("ja_JP".equals(locale)) { initializer = localeType.$v("JAPAN"); } else if ("ja".equals(locale)) { initializer = localeType.$v("JAPANESE"); } else if ("ko_KR".equals(locale)) { initializer = localeType.$v("KOREA"); } else if ("ko".equals(locale)) { initializer = localeType.$v("KOREAN"); } else if ("zh_CN".equals(locale)) { initializer = localeType.$v("SIMPLIFIED_CHINESE"); } else if ("zh_TW".equals(locale)) { initializer = localeType.$v("TRADITIONAL_CHINESE"); } else if ("en_UK".equals(locale)) { initializer = localeType.$v("UK"); } else if ("en_US".equals(locale)) { initializer = localeType.$v("US"); } else { final JCall newInstance = localeType._new(); // Split the locale final String[] parts = locale.split("_"); if (parts.length > 3) { throw new ProcessingException(messageInterface, "Failed to parse %s to a Locale.", locale); } for (String arg : parts) { newInstance.arg(JExprs.str(arg)); } initializer = newInstance; } } return initializer; } } ClassModelFactory.java000066400000000000000000000114161356560461700377450ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import static org.jboss.logging.processor.generator.model.ClassModelHelper.implementationClassName; import static org.jboss.logging.processor.util.TranslationHelper.getEnclosingTranslationClassName; import java.util.Map; import javax.annotation.processing.ProcessingEnvironment; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * Creates a class model for the message interface. * * @author James R. Perkins */ public class ClassModelFactory { /** * Private constructor for the factory. */ private ClassModelFactory() { } /** * Creates an implementation code model from the message interface. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement * * @return the class model used to implement the interface. * * @throws IllegalArgumentException if interface is not annotated with {@link MessageBundle @MessageBundle} or {@link MessageLogger @MessageLogger} */ public static ClassModel implementation(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface) throws IllegalArgumentException { if (messageInterface.isAnnotatedWith(MessageBundle.class)) { return new MessageBundleImplementor(processingEnv, messageInterface); } if (messageInterface.isAnnotatedWith(MessageLogger.class)) { return new MessageLoggerImplementor(processingEnv, messageInterface); } throw new IllegalArgumentException(String.format("Message interface %s is not a valid message logger or message bundle.", messageInterface)); } /** * Creates a class model for created translation implementations of the message interface. *

* Note: The implementation class must exist before the translation implementations can be created. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. * @param translationSuffix the translation locale suffix. * @param translations a map of the translations for the methods. * * @return the class model used to create translation implementations of the interface. * * @throws IllegalArgumentException if interface is not annotated with {@link MessageBundle @MessageBundle} or {@link MessageLogger @MessageLogger} */ public static ClassModel translation(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface, final String translationSuffix, final Map translations) throws IllegalArgumentException { final String generatedClassName = implementationClassName(messageInterface, translationSuffix); final String superClassName = getEnclosingTranslationClassName(generatedClassName); // The locale should be the same as the translationsSuffix minus the leading _ final String locale = translationSuffix.substring(1); if (messageInterface.isAnnotatedWith(MessageBundle.class)) { return new MessageBundleTranslator(processingEnv, messageInterface, generatedClassName, superClassName, locale, translations); } if (messageInterface.isAnnotatedWith(MessageLogger.class)) { return new MessageLoggerTranslator(processingEnv, messageInterface, generatedClassName, superClassName, locale, translations); } throw new IllegalArgumentException(String.format("Message interface %s is not a valid message logger or message bundle.", messageInterface)); } } ClassModelHelper.java000066400000000000000000000077361356560461700375670ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import java.text.SimpleDateFormat; import java.util.Date; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.util.ElementHelper; /** * Utilities for the code model. * * @author James R. Perkins */ public final class ClassModelHelper { private static final String STRING_ID_FORMAT2 = "%s%06d: "; /** * Constructor for singleton model. */ private ClassModelHelper() { } /** * Returns the current date formatted in the ISO 8601 format. * * @return the current date formatted in ISO 8601. */ static String generatedDateValue() { final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); return sdf.format(new Date()); } /** * Formats message id. * * @param projectCode the project code for the message * @param messageId the message id to format * * @return the formatted message id */ public static String formatMessageId(final String projectCode, final int padLength, final int messageId) { return String.format(STRING_ID_FORMAT2, projectCode, messageId); } /** * Creates the implementation class name for the message interface. * * @param messageInterface the message interface to generate the implementation name for. * * @return the implementation class name * * @throws IllegalArgumentException if the message interface is not a message bundle or a message logger. */ public static String implementationClassName(final MessageInterface messageInterface) throws IllegalArgumentException { final StringBuilder result = new StringBuilder(messageInterface.simpleName()); if (messageInterface.isAnnotatedWith(MessageBundle.class)) { result.append("_$bundle"); } else if (messageInterface.isAnnotatedWith(MessageLogger.class)) { result.append("_$logger"); } else { throw new IllegalArgumentException(String.format("Message interface %s is not a message bundle or message logger.", messageInterface)); } return result.toString(); } /** * Creates the implementation class name for the message interface. * * @param messageInterface the message interface to generate the implementation name for. * @param translationSuffix the local suffix for the translation. * * @return the implementation class name * * @throws IllegalArgumentException if the message interface is not a message bundle or a message logger. */ public static String implementationClassName(final MessageInterface messageInterface, final String translationSuffix) throws IllegalArgumentException { return implementationClassName(messageInterface) + translationSuffix; } } ImplementationClassModel.java000066400000000000000000001007021356560461700413200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import static org.jboss.jdeparser.JExpr.NULL; import static org.jboss.jdeparser.JExprs.$v; import static org.jboss.jdeparser.JMod.FINAL; import static org.jboss.jdeparser.JTypes.$t; import static org.jboss.logging.processor.generator.model.ClassModelHelper.implementationClassName; import java.text.FieldPosition; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; import java.util.function.Supplier; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.SimpleAnnotationValueVisitor8; import javax.lang.model.util.Types; import org.jboss.jdeparser.JAssignableExpr; import org.jboss.jdeparser.JBlock; import org.jboss.jdeparser.JBlock.Braces; import org.jboss.jdeparser.JCall; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JExpr; import org.jboss.jdeparser.JExprs; import org.jboss.jdeparser.JIf; import org.jboss.jdeparser.JLambda; import org.jboss.jdeparser.JMethodDef; import org.jboss.jdeparser.JMod; import org.jboss.jdeparser.JParamDeclaration; import org.jboss.jdeparser.JType; import org.jboss.jdeparser.JTypes; import org.jboss.jdeparser.JVarDeclaration; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.Fields; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Producer; import org.jboss.logging.annotations.Properties; import org.jboss.logging.annotations.Property; import org.jboss.logging.annotations.Suppressed; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; import org.jboss.logging.processor.apt.ProcessingException; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.model.ThrowableType; import org.jboss.logging.processor.util.ElementHelper; /** * An abstract code model to create the source file that implements the * interface. *

*

* Essentially this uses the org.jboss.jdeparser.JDeparser to generate the * source files with. This class is for convenience in generating default source * files. *

* * @author James R. Perkins */ abstract class ImplementationClassModel extends ClassModel { private final AtomicBoolean messageFormatMethodGenerated = new AtomicBoolean(false); private final AtomicBoolean copyStackTraceMethodGenerated = new AtomicBoolean(false); private final TypeMirror stringType; /** * Class constructor. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. */ ImplementationClassModel(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface) { super(processingEnv, messageInterface, implementationClassName(messageInterface), null); stringType = ElementHelper.toType(processingEnv, String.class); } /** * Create the bundle method body. * * @param classDef the class definition * @param messageMethod the message method. */ void createBundleMethod(final JClassDef classDef, final JCall localeGetter, final MessageMethod messageMethod) { // Add the message messageMethod. addMessageMethod(messageMethod); final TypeMirror returnTypeMirror = messageMethod.returnType().asType(); final JType returnType = JTypes.typeOf(returnTypeMirror); final JMethodDef method = classDef.method(JMod.PUBLIC | FINAL, returnType, messageMethod.name()); method.annotate(Override.class); addThrownTypes(messageMethod, method); addMethodTypeParameters(method, returnTypeMirror); // If this a declared type we should import it if (returnTypeMirror.getKind() == TypeKind.DECLARED) { sourceFile._import(returnType); } // Create the body of the method and add the text final JBlock body = method.body(); final MessageMethod.Message message = messageMethod.message(); final JCall formatterCall; switch (message.format()) { case MESSAGE_FORMAT: { if (messageMethod.formatParameterCount() > 0) { formatterCall = getFormatMethod(classDef, localeGetter); formatterCall.arg(JExprs.call(messageMethod.messageMethodName())); } else { formatterCall = JExprs.call(messageMethod.messageMethodName()); } break; } case PRINTF: { final JType formatter = $t(String.class); formatterCall = formatter.call("format").arg(localeGetter).arg(JExprs.call(messageMethod.messageMethodName())); break; } default: formatterCall = JExprs.call(messageMethod.messageMethodName()); break; } // Create maps for the fields and properties. Key is the field or setter method, value is the parameter to set // the value to. final Set allParameters = messageMethod.parameters(); final Map fields = new LinkedHashMap<>(); final Map properties = new LinkedHashMap<>(); // First load the parameter names final List parameterNames = new ArrayList<>(allParameters.size()); for (Parameter param : allParameters) { parameterNames.add(param.name()); } final List args = new ArrayList<>(); // Create the parameters for (Parameter param : allParameters) { final JParamDeclaration var = addMethodParameter(method, param); final String formatterClass = param.formatterClass(); if (param.isFormatParameter()) { boolean added = false; if (param.isAnnotatedWith(Transform.class)) { if (formatterCall == null) { // This should never happen, but let's safe guard against it throw new IllegalStateException("No format parameters are allowed when NO_FORMAT is specified."); } else { final JAssignableExpr transformVar = createTransformVar(parameterNames, body, param, $v(var)); if (formatterClass == null) { args.add(transformVar); } else { args.add($t(formatterClass)._new().arg(transformVar)); } } added = true; } if (param.isAnnotatedWith(Pos.class)) { if (formatterCall == null) { // This should never happen, but let's safe guard against it throw new IllegalStateException("No format parameters are allowed when NO_FORMAT is specified."); } else { final Pos pos = param.getAnnotation(Pos.class); final int[] positions = pos.value(); final Transform[] transform = pos.transform(); for (int i = 0; i < positions.length; i++) { final int index = positions[i] - 1; if (transform != null && transform.length > 0) { final JAssignableExpr tVar = createTransformVar(parameterNames, method.body(), param, transform[i], $v(var)); if (index < args.size()) { args.add(index, tVar); } else { args.add(tVar); } } else { if (index < args.size()) { args.add(index, $v(var)); } else { args.add($v(var)); } } } } added = true; } if (!added) { if (formatterCall == null) { // This should never happen, but let's safe guard against it throw new ProcessingException(messageMethod, "No format parameters are allowed when NO_FORMAT is specified."); } else { if (formatterClass == null) { if (param.isArray() || param.isVarArgs()) { final JType arrays = $t(Arrays.class); sourceFile._import(arrays); args.add(arrays.call("toString").arg($v(var))); } else { args.add($v(var)); } } else { args.add($t(formatterClass)._new().arg($v(var))); } } } } if (param.isAnnotatedWith(Field.class)) { fields.put(param.targetName(), var); } if (param.isAnnotatedWith(Property.class)) { properties.put(param.targetName(), var); } } // If a format method, add the arguments for (JExpr arg : args) { formatterCall.arg(arg); } final boolean isSupplier = messageMethod.returnType().isSubtypeOf(Supplier.class); // Setup the return type final JExpr result; if (messageMethod.returnType().isThrowable()) { if (isSupplier) { final JLambda lambda = JExprs.lambda(); final JBlock lambdaBody = lambda.body(); lambdaBody._return(createReturnType(classDef, messageMethod, lambdaBody, formatterCall, fields, properties)); result = lambda; } else { result = createReturnType(classDef, messageMethod, body, formatterCall, fields, properties); } } else { if (isSupplier) { final JLambda lambda = JExprs.lambda(); lambda.body()._return(formatterCall); result = lambda; } else { result = formatterCall; } } body._return(result); } JAssignableExpr createTransformVar(final List parameterNames, final JBlock methodBody, final Parameter param, final JExpr var) { return createTransformVar(parameterNames, methodBody, param, param.getAnnotation(Transform.class), var); } JAssignableExpr createTransformVar(final List parameterNames, final JBlock methodBody, final Parameter param, final Transform transform, final JExpr var) { final List transformTypes = Arrays.asList(transform.value()); // GET_CLASS should always be processed first final JAssignableExpr result; if (transformTypes.contains(TransformType.GET_CLASS)) { // Determine the result field type if (transformTypes.size() == 1) { // Get the parameter name final String paramName = getUniqueName(parameterNames, param, "Class"); parameterNames.add(paramName); result = $v(methodBody.var(FINAL, $t(Class.class).typeArg(JType.WILDCARD), paramName)); final JIf stmt = methodBody._if(var.eq(NULL)); stmt.block(Braces.REQUIRED).assign(result, NULL); stmt._else().assign(result, var.call("getClass")); } else { // Get the parameter name final String paramName = getUniqueName(parameterNames, param, "HashCode"); parameterNames.add(paramName); result = $v(methodBody.var(FINAL, JType.INT, paramName)); final JIf stmt = methodBody._if(var.eq(NULL)); stmt.assign(result, JExpr.ZERO); if (transformTypes.contains(TransformType.HASH_CODE)) { stmt._else().assign(result, var.call("getClass").call("hashCode")); } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE)) { stmt._else().assign(result, $t(System.class).call("identityHashCode").arg(var.call("getClass"))); } else { throw new IllegalStateException(String.format("Invalid transform type combination: %s", transformTypes)); } } } else if (transformTypes.contains(TransformType.HASH_CODE)) { // Get the parameter name final String paramName = getUniqueName(parameterNames, param, "HashCode"); parameterNames.add(paramName); result = $v(methodBody.var(FINAL, JType.INT, paramName)); final JIf stmt = methodBody._if(var.eq(NULL)); stmt.assign(result, JExpr.ZERO); if (param.isArray() || param.isVarArgs()) { final JType arrays = $t(Arrays.class); sourceFile._import(arrays); stmt._else().assign(result, arrays.call("hashCode").arg(var)); } else { stmt._else().assign(result, var.call("hashCode")); } } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE)) { // Get the parameter name final String paramName = getUniqueName(parameterNames, param, "HashCode"); parameterNames.add(paramName); result = $v(methodBody.var(FINAL, JType.INT, paramName)); final JIf stmt = methodBody._if(var.eq(NULL)); stmt.assign(result, JExpr.ZERO); stmt._else().assign(result, $t(System.class).call("identityHashCode").arg(var)); } else if (transformTypes.contains(TransformType.SIZE)) { // Get the parameter name final String paramName = getUniqueName(parameterNames, param, "Size"); parameterNames.add(paramName); result = $v(methodBody.var(FINAL, JType.INT, paramName)); final JIf stmt = methodBody._if(var.eq(NULL)); stmt.assign(result, JExpr.ZERO); if (param.isArray() || param.isVarArgs()) { stmt._else().assign(result, var.field("length")); } else if (param.isSubtypeOf(Map.class) || param.isSubtypeOf(Collection.class)) { stmt._else().assign(result, var.call("size")); } else if (param.isSubtypeOf(CharSequence.class)) { stmt._else().assign(result, var.call("length")); } else { throw new IllegalStateException(String.format("Invalid type for %s. Must be an array, %s, %s or %s.", TransformType.SIZE, Collection.class.getName(), Map.class.getName(), CharSequence.class.getName())); } } else { throw new IllegalStateException(String.format("Invalid transform type: %s", transformTypes)); } return result; } private String getUniqueName(final List parameterNames, final Parameter parameter, final String suffix) { String result = (suffix == null ? parameter.name() : parameter.name().concat(suffix)); if (parameterNames.contains(result)) { return getUniqueName(parameterNames, new StringBuilder(result), 0); } return result; } private String getUniqueName(final List parameterNames, final StringBuilder sb, final int index) { String result = sb.append(index).toString(); if (parameterNames.contains(result)) { return getUniqueName(parameterNames, sb, index + 1); } return result; } private void addMethodTypeParameters(final JMethodDef method, final TypeMirror type) { final Types types = processingEnv.getTypeUtils(); if (type.getKind() == TypeKind.TYPEVAR) { // Determine the extended type final TypeMirror resolved = types.erasure(type); final JType resolvedType = JTypes.typeOf(resolved); sourceFile._import(resolvedType); method.typeParam(type.toString())._extends(resolvedType); } else if (type.getKind() == TypeKind.DECLARED) { final List typeArgs = ElementHelper.getTypeArguments(type); for (TypeMirror typeArg : typeArgs) { addMethodTypeParameters(method, typeArg); } } } private JExpr createReturnType(final JClassDef classDef, final MessageMethod messageMethod, final JBlock body, final JCall format, final Map fields, final Map properties) { boolean callInitCause = false; final Set producers = messageMethod.parametersAnnotatedWith(Producer.class); final JType type; final JVarDeclaration resultField; // If there are no producers we need to construct a new return type if (producers.isEmpty()) { final ThrowableType returnType = messageMethod.returnType().throwableReturnType(); type = JTypes.typeOf(returnType.asType()); // Import once more as the throwable return type may be different than the actual return type sourceFile._import(type); final JCall result = type._new(); resultField = body.var(FINAL, type, "result", result); if (returnType.useConstructionParameters()) { for (Parameter param : returnType.constructionParameters()) { if (param.isMessageMethod()) { result.arg(format); } else { result.arg($v(param.name())); } } callInitCause = messageMethod.hasCause() && !returnType.causeSetInConstructor(); } else if (returnType.hasStringAndThrowableConstructor() && messageMethod.hasCause()) { result.arg(format).arg($v(messageMethod.cause().name())); } else if (returnType.hasThrowableAndStringConstructor() && messageMethod.hasCause()) { result.arg($v(messageMethod.cause().name())).arg(format); } else if (returnType.hasStringConstructor()) { result.arg(format); if (messageMethod.hasCause()) { callInitCause = true; } } else if (returnType.hasThrowableConstructor() && messageMethod.hasCause()) { result.arg($v(messageMethod.cause().name())); } else if (returnType.hasStringAndThrowableConstructor() && !messageMethod.hasCause()) { result.arg(format).arg(NULL); } else if (returnType.hasThrowableAndStringConstructor() && !messageMethod.hasCause()) { result.arg(NULL).arg(format); } else if (messageMethod.hasCause()) { callInitCause = true; } } else { final TypeMirror returnType = messageMethod.returnType().resolvedType(); // Should only be one producer final Parameter producer = producers.iterator().next(); type = JTypes.typeOf(returnType); JCall result = $v(producer.name()).call("apply"); // For a BiFunction we pass both the cause, even if null, and the message if (producer.isSubtypeOf(BiFunction.class)) { // Get the type arguments of the BiFunction to determine the order to pass parameters final List typeArguments = ElementHelper.getTypeArguments(producer); // If we don't have any type arguments assume String, Throwable if (typeArguments.isEmpty()) { result = result.arg(format); result = result.arg($v(messageMethod.cause().name())); } else { // Just get the first type argument an decide the order based on it final TypeMirror typeArg = typeArguments.get(0); if (processingEnv.getTypeUtils().isAssignable(typeArg, stringType)) { result = result.arg(format); if (messageMethod.hasCause()) { result = result.arg($v(messageMethod.cause().name())); } else { result = result.arg(JExpr.NULL); } } else { if (messageMethod.hasCause()) { result = result.arg($v(messageMethod.cause().name())); } else { result = result.arg(JExpr.NULL); } result = result.arg(format); } } } else { // Assume this must be a Function // Pass the message as the argument to the function result = result.arg(format); callInitCause = messageMethod.hasCause(); } resultField = body.var(FINAL, type, "result", result); } // Assign the result field the result value if (callInitCause) { body.add($v(resultField).call("initCause").arg($v(messageMethod.cause().name()))); } // Get the @Property or @Properties annotation values addDefultProperties(messageMethod, ElementHelper.getAnnotations(messageMethod, Properties.class, Property.class), body, $v(resultField), false); addDefultProperties(messageMethod, ElementHelper.getAnnotations(messageMethod, Fields.class, Field.class), body, $v(resultField), true); // Remove this caller from the stack trace body.add(getCopyStackMethod(classDef).arg($v(resultField))); // Add any suppressed messages final Set suppressed = messageMethod.parametersAnnotatedWith(Suppressed.class); for (Parameter p : suppressed) { if (p.isArray() || p.isVarArgs()) { final String name = String.format("$%sVar", p.name()); // TODO (jrp) the " " can be removed after an upgrade to JDeparser2; this is a workaround for a formatting bug body.forEach(0, JTypes.typeOf(((ArrayType) p.asType()).getComponentType()), " " + name, $v(p.name())) .block(Braces.REQUIRED) .add($v(resultField).call("addSuppressed").arg($v(name))); } else if (p.isAssignableFrom(Collection.class)) { final String name = String.format("$%sVar", p.name()); body.add($v(p.name()).call("forEach").arg(JExprs.lambda().param(name).body($v(resultField).call("addSuppressed").arg($v(name))))); } else { body.add($v(resultField).call("addSuppressed").arg($v(p.name()))); } } // Add the possible fields and properties to be set on the returned exception final JExpr resultExpr = $v(resultField); fields.forEach((key, value) -> body.assign(resultExpr.field(key), $v(value))); properties.forEach((key, value) -> body.add(resultExpr.call(key).arg($v(value)))); return resultExpr; } protected final void addThrownTypes(final MessageMethod messageMethod, final JMethodDef jMethod) { for (ThrowableType thrownType : messageMethod.thrownTypes()) { jMethod._throws(thrownType.name()); } } /** * Adds the parameter to the method returning the reference to the parameter. * * @param method the method to add the parameter to * @param param the parameter to add * * @return the reference to the parameter on the method */ protected JParamDeclaration addMethodParameter(final JMethodDef method, final Parameter param) { final JType paramType = JTypes.typeOf(param.asType()); if (!param.isPrimitive()) { sourceFile._import(paramType); } if (param.isVarArgs()) { return method.varargParam(FINAL, paramType.elementType(), param.name()); } return method.param(FINAL, paramType, param.name()); } private void addDefultProperties(final MessageMethod messageMethod, final Collection annotations, final JBlock body, final JAssignableExpr resultField, final boolean field) { for (AnnotationMirror propertyAnnotation : annotations) { String name = null; AnnotationValue annotationValue = null; for (Map.Entry entry : propertyAnnotation.getElementValues().entrySet()) { final ExecutableElement attribute = entry.getKey(); final AnnotationValue attributeValue = entry.getValue(); if ("name".contentEquals(attribute.getSimpleName())) { name = String.valueOf(attributeValue.getValue()); } else { annotationValue = attributeValue; } } if (name == null) { throw new ProcessingException(messageMethod, propertyAnnotation, "The name attribute is required for the annotation."); } if (annotationValue == null || annotationValue.getValue() == null) { throw new ProcessingException(messageMethod, propertyAnnotation, "A value for one of the default attributes is required."); } final JExpr resultValue = annotationValue.accept(JExprAnnotationValueVisitor.INSTANCE, null); if (resultValue == null) { final Object value = annotationValue.getValue(); throw new ProcessingException(messageMethod, propertyAnnotation, annotationValue, "Could not resolve value type for %s (%s)", value, value.getClass()); } if (field) { body.add(resultField.field(name).assign(resultValue)); } else { body.add(resultField.call("set" + Character.toUpperCase(name.charAt(0)) + name.substring(1)).arg(resultValue)); } } } /** * Creates a method for formatting {@link MessageFormat} messages. The method should look something like: *
     *     
     *
     * private String _formatMessage(final String format, final Object... args) {
     *     final java.text.MessageFormat formatter = new java.text.MessageFormat(format, getLoggingLocale());
     *     return formatter.format(args, new StringBuffer(), new java.text.FieldPosition(0)).toString();
     * }
     *     
     * 
*

* This can be invoked multiple times resulting in only a single method being created in the source. *

* * @param classDef the class to add the method to * @param localeGetter the getter for the locale * * @return a method call representation of the {@code _formatMessage(String, Object...)} method */ private JCall getFormatMethod(final JClassDef classDef, final JCall localeGetter) { final String methodName = "_formatMessage"; // Create the method if it does not exist yet if (messageFormatMethodGenerated.compareAndSet(false, true)) { // Create the method final JMethodDef method = classDef.method(JMod.PRIVATE, String.class, methodName); final JParamDeclaration format = method.param(JMod.FINAL, String.class, "format"); final JParamDeclaration args = method.varargParam(JMod.FINAL, Object.class, "args"); // Generate the body of the method final JBlock body = method.body(); final JType formatterType = $t(MessageFormat.class); final JCall initializer = formatterType._new() .arg($v(format)) .arg(localeGetter); final JVarDeclaration formatter = body.var(JMod.FINAL, formatterType, "formatter", initializer); // Invoke the formatter and return the toString() value of the StringBuffer result body._return( $v(formatter) .call("format") .arg($v(args)) .arg($t(StringBuffer.class)._new()) .arg($t(FieldPosition.class)._new() .arg(JExpr.ZERO) ) .call("toString") ); } return JExprs.call(methodName); } private JCall getCopyStackMethod(final JClassDef classDef) { final String methodName = "_copyStackTraceMinusOne"; if (copyStackTraceMethodGenerated.compareAndSet(false, true)) { final JMethodDef method = classDef.method(JMod.PRIVATE | JMod.STATIC, JType.VOID, methodName); final JParamDeclaration param = method.param(JMod.FINAL, Throwable.class, "e"); final JBlock body = method.body(); // Remove this caller from the stack trace final JType arrays = $t(Arrays.class); sourceFile._import(arrays); final JExpr e = $v(param); final JVarDeclaration st = body.var(FINAL, $t(StackTraceElement.class).array(), "st", e.call("getStackTrace")); body.add(e.call("setStackTrace").arg(arrays.call("copyOfRange").arg($v(st)).arg(JExpr.ONE).arg($v(st).field("length")))); } return JExprs.call(methodName); } private static class JExprAnnotationValueVisitor extends SimpleAnnotationValueVisitor8 { private static final JExprAnnotationValueVisitor INSTANCE = new JExprAnnotationValueVisitor(); @Override public JExpr visitBoolean(final boolean b, final Void v) { return b ? JExpr.TRUE : JExpr.FALSE; } @Override public JExpr visitByte(final byte b, final Void v) { return JExprs.decimal(b).cast(JType.BYTE); } @Override public JExpr visitChar(final char c, final Void v) { return JExprs.ch(c); } @Override public JExpr visitDouble(final double d, final Void v) { // TODO (jrp) this is fixed in upstream JDeparser, but for now we need to use this // setterValue = JExprs.hex(d); return JExprs.$v(String.format("%ad", d)); } @Override public JExpr visitFloat(final float f, final Void v) { return JExprs.hex(f); } @Override public JExpr visitInt(final int i, final Void v) { return JExprs.decimal(i); } @Override public JExpr visitLong(final long i, final Void v) { return JExprs.decimal(i); } @Override public JExpr visitShort(final short s, final Void v) { return JExprs.decimal((int) s).cast(JType.SHORT); } @Override public JExpr visitString(final String s, final Void v) { return JExprs.str(s); } @Override public JExpr visitType(final TypeMirror t, final Void v) { return JExprs.$v(t.toString() + ".class"); } } } MessageBundleImplementor.java000066400000000000000000000063621356560461700413250ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import java.util.LinkedHashSet; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import org.jboss.jdeparser.JCall; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JMod; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.util.ElementHelper; /** * Used to generate a message bundle implementation. *

* Creates an implementation of the interface passed in. *

* * @author James R. Perkins * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ class MessageBundleImplementor extends ImplementationClassModel { /** * Creates a new message bundle code model. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. */ public MessageBundleImplementor(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface) { super(processingEnv, messageInterface); } @Override protected JClassDef generateModel() throws IllegalStateException { final JClassDef classDef = super.generateModel(); // Add default constructor classDef.constructor(JMod.PROTECTED); createReadResolveMethod(); final JCall localeGetter = createLocaleGetter(null, false); final Set messageMethods = new LinkedHashSet<>(); messageMethods.addAll(messageInterface().methods()); for (MessageInterface messageInterface : messageInterface().extendedInterfaces()) { if (messageInterface.isAnnotatedWith(MessageBundle.class) || messageInterface.isAnnotatedWith(MessageLogger.class)) { messageMethods.addAll(messageInterface.methods()); } } // Process the method descriptors and add to the model before // writing. for (MessageMethod messageMethod : messageMethods) { createBundleMethod(classDef, localeGetter, messageMethod); } return classDef; } } MessageBundleTranslator.java000066400000000000000000000070551356560461700411630ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JMethodDef; import org.jboss.jdeparser.JMod; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * The java message bundle class model. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ class MessageBundleTranslator extends ClassModel { /** * The translation map. */ private final Map translations; private final String locale; /** * Create a MessageBundle with super class and interface. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. * @param className the implementation class name. * @param superClassName the super class name * @param locale the locale used to override the default locale * @param translations the translation map. */ public MessageBundleTranslator(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface, final String className, final String superClassName, final String locale, final Map translations) { super(processingEnv, messageInterface, className, superClassName); this.locale = locale; if (translations != null) { this.translations = translations; } else { this.translations = Collections.emptyMap(); } } @Override public JClassDef generateModel() throws IllegalStateException { JClassDef classDef = super.generateModel(); JMethodDef constructor = classDef.constructor(JMod.PROTECTED); constructor.body().callSuper(); JMethodDef readResolve = createReadResolveMethod(); readResolve.annotate(Override.class); // Override the locale getter createLocaleGetter(locale, true); final Set> entries = translations.entrySet(); final Set methodNames = new LinkedHashSet<>(); for (Map.Entry entry : entries) { JMethodDef method = addMessageMethod(entry.getKey(), entry.getValue()); if (methodNames.add(method)) { method.annotate(Override.class); } } return classDef; } } MessageLoggerImplementor.java000066400000000000000000000321001356560461700413200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import static org.jboss.jdeparser.JExpr.NULL; import static org.jboss.jdeparser.JExpr.THIS; import static org.jboss.jdeparser.JExprs.$v; import static org.jboss.jdeparser.JTypes.$t; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.processing.ProcessingEnvironment; import org.jboss.jdeparser.JAssignableExpr; import org.jboss.jdeparser.JBlock; import org.jboss.jdeparser.JBlock.Braces; import org.jboss.jdeparser.JCall; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JExpr; import org.jboss.jdeparser.JExprs; import org.jboss.jdeparser.JMethodDef; import org.jboss.jdeparser.JMod; import org.jboss.jdeparser.JParamDeclaration; import org.jboss.jdeparser.JType; import org.jboss.jdeparser.JVarDeclaration; import org.jboss.logging.DelegatingBasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LoggingClass; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Once; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Transform; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; /** * Used to generate a message logger implementation. *

* Creates an implementation of the interface passed in. *

* * @author James R. Perkins * @author David M. Lloyd */ final class MessageLoggerImplementor extends ImplementationClassModel { private static final String LOG_FIELD_NAME = "log"; private static final String FQCN_FIELD_NAME = "FQCN"; private final Map logOnceVars = new HashMap<>(); /** * Creates a new message logger code model. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement */ public MessageLoggerImplementor(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface) { super(processingEnv, messageInterface); } @Override protected JClassDef generateModel() throws IllegalStateException { final JClassDef classDef = super.generateModel(); // Add FQCN if (messageInterface().loggingFQCN() == null) { classDef.field(JMod.PRIVATE | JMod.FINAL | JMod.STATIC, String.class, FQCN_FIELD_NAME, $t(classDef)._class().call("getName")); } else { classDef.field(JMod.PRIVATE | JMod.FINAL | JMod.STATIC, String.class, FQCN_FIELD_NAME, $t(messageInterface().loggingFQCN())._class().call("getName")); } // Add default constructor final JMethodDef constructor = classDef.constructor(JMod.PUBLIC); final JType loggerType = $t(Logger.class); // Import the logger type and the level type sourceFile._import(loggerType); final JParamDeclaration constructorParam = constructor.param(JMod.FINAL, loggerType, LOG_FIELD_NAME); final JBlock constructorBody = constructor.body(); final JAssignableExpr logger; if (messageInterface().extendsLoggerInterface()) { sourceFile._import(DelegatingBasicLogger.class); classDef._extends(DelegatingBasicLogger.class); constructorBody.callSuper().arg($v(constructorParam)); logger = $v("super").field("log"); } else { JVarDeclaration logVar = classDef.field(JMod.PROTECTED | JMod.FINAL, loggerType, LOG_FIELD_NAME); constructorBody.assign(THIS.field(logVar.name()), $v(constructorParam)); logger = $v(logVar); } final JCall localeGetter = createLocaleGetter(null, false); // Process the method descriptors and add to the model before writing. final Set messageMethods = new LinkedHashSet<>(); messageMethods.addAll(messageInterface().methods()); for (MessageInterface messageInterface : messageInterface().extendedInterfaces()) { if (messageInterface.isAnnotatedWith(MessageBundle.class) || messageInterface.isAnnotatedWith(MessageLogger.class)) { messageMethods.addAll(messageInterface.methods()); } } for (MessageMethod messageMethod : messageMethods) { // Create the messageMethod body if (messageMethod.isLoggerMethod()) { createLoggerMethod(messageMethod, classDef, logger); } else { createBundleMethod(classDef, localeGetter, messageMethod); } } return classDef; } /** * Create the logger method body. * * @param messageMethod the message method. * @param classDef the class definition used to create the method on * @param logger the logger to use. */ private void createLoggerMethod(final MessageMethod messageMethod, final JClassDef classDef, final JAssignableExpr logger) { final String msgMethodName = messageMethod.messageMethodName(); final JMethodDef method = classDef.method(JMod.PUBLIC | JMod.FINAL, messageMethod.returnType().name(), messageMethod.name()); method.annotate(Override.class); addMessageMethod(messageMethod); addThrownTypes(messageMethod, method); // Initialize the method parameters final Map params = createParameters(messageMethod, method); // First load the parameter names final List parameterNames = new ArrayList<>(params.size()); for (Parameter param : params.keySet()) { parameterNames.add(param.name()); } // Check for the @Once annotation final JBlock body; if (messageMethod.isAnnotatedWith(Once.class) && messageMethod.isLoggerMethod()) { final JType atomicBoolean = $t(AtomicBoolean.class); sourceFile._import(atomicBoolean); // The variable will be shared with overloaded methods final String varName = messageMethod.name() + "_$Once"; final JVarDeclaration var; if (logOnceVars.containsKey(varName)) { var = logOnceVars.get(varName); } else { var = classDef.field(JMod.PRIVATE | JMod.STATIC | JMod.FINAL, atomicBoolean, varName, atomicBoolean._new().arg(JExpr.FALSE)); logOnceVars.put(varName, var); } body = method.body()._if( logger.call("isEnabled").arg($v(messageMethod.logLevel())).and( $v(var).call("compareAndSet").arg(JExpr.FALSE).arg(JExpr.TRUE))) .block(Braces.REQUIRED); } else if (!messageMethod.parametersAnnotatedWith(Transform.class).isEmpty()) { body = method.body()._if(logger.call("isEnabled").arg($v(messageMethod.logLevel()))).block(Braces.REQUIRED); } else { body = method.body(); } // Determine which logger method to invoke final JCall logCaller = logger.call(messageMethod.loggerMethod()); final Set fqcnParameters = messageMethod.parametersAnnotatedWith(LoggingClass.class); if (fqcnParameters.isEmpty()) { logCaller.arg($v(FQCN_FIELD_NAME)); } else { logCaller.arg($v(params.get(fqcnParameters.iterator().next())).call("getName")); } // Use static imports for the levels final String levelName = messageMethod.logLevel(); sourceFile.importStatic(Logger.Level.class, levelName); logCaller.arg($v(levelName)); final MessageMethod.Message message = messageMethod.message(); // No format log messages need the message before the cause if (message.format() == Format.NO_FORMAT) { logCaller.arg(JExprs.call(msgMethodName)); // Next for no format should always be null logCaller.arg(NULL); // The cause is the final argument if (messageMethod.hasCause()) { logCaller.arg($v(messageMethod.cause().name())); } else { logCaller.arg(NULL); } } else { if (messageMethod.hasCause()) { logCaller.arg($v(messageMethod.cause().name())); } else { logCaller.arg(NULL); } // The next parameter is the message. Should be accessed via the // message retrieval method. logCaller.arg(JExprs.call(msgMethodName)); final List args = new ArrayList<>(); // Create the parameters for (Map.Entry entry : params.entrySet()) { final Parameter param = entry.getKey(); final String formatterClass = param.formatterClass(); final JParamDeclaration var = entry.getValue(); boolean added = false; if (param.isFormatParameter()) { if (param.isAnnotatedWith(Transform.class)) { final JAssignableExpr transformVar = createTransformVar(parameterNames, body, param, $v(var)); if (formatterClass == null) { args.add(transformVar); } else { args.add($t(formatterClass)._new().arg(transformVar)); } added = true; } if (param.isAnnotatedWith(Pos.class)) { final Pos pos = param.getAnnotation(Pos.class); final int[] positions = pos.value(); final Transform[] transform = pos.transform(); for (int i = 0; i < positions.length; i++) { final int index = positions[i] - 1; if (transform != null && transform.length > 0) { final JAssignableExpr tVar = createTransformVar(parameterNames, body, param, transform[i], $v(var)); if (index < args.size()) { args.add(index, tVar); } else { args.add(tVar); } } else { if (index < args.size()) { args.add(index, $v(var)); } else { args.add($v(var)); } } } added = true; } if (!added) { if (formatterClass == null) { if (param.isArray() || param.isVarArgs()) { args.add($t(Arrays.class).call("toString").arg($v(var))); } else { args.add($v(var)); } } else { args.add($t(formatterClass)._new().arg($v(var))); } } } } for (JExpr arg : args) { logCaller.arg(arg); } } body.add(logCaller); } private Map createParameters(final MessageMethod messageMethod, final JMethodDef method) { final Map result = new LinkedHashMap<>(); // Create the parameters for (Parameter param : messageMethod.parameters()) { final JParamDeclaration var = addMethodParameter(method, param); result.put(param, var); } return result; } } MessageLoggerTranslator.java000066400000000000000000000075301356560461700411670ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/generator/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generator.model; import static org.jboss.jdeparser.JExprs.$v; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import org.jboss.jdeparser.JBlock; import org.jboss.jdeparser.JClassDef; import org.jboss.jdeparser.JMethodDef; import org.jboss.jdeparser.JMod; import org.jboss.logging.Logger; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; /** * The java message logger translation class model. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ class MessageLoggerTranslator extends ClassModel { /** * The logger parameter name. */ private static final String LOGGER_PARAMETER_NAME = "logger"; /** * The translation map. */ private final Map translations; private final String locale; /** * Create a MessageLogger with super class and interface. * * @param processingEnv the processing environment * @param messageInterface the message interface to implement. * @param className the implementation class name. * @param superClassName the super class name * @param locale the locale used to override the default locale * @param translations the translation map. */ public MessageLoggerTranslator(final ProcessingEnvironment processingEnv, final MessageInterface messageInterface, final String className, final String superClassName, final String locale, final Map translations) { super(processingEnv, messageInterface, className, superClassName); this.locale = locale; if (translations != null) { this.translations = translations; } else { this.translations = Collections.emptyMap(); } } @Override public JClassDef generateModel() throws IllegalStateException { JClassDef classDef = super.generateModel(); JMethodDef constructor = classDef.constructor(JMod.PUBLIC); constructor.param(JMod.FINAL, Logger.class, LOGGER_PARAMETER_NAME); JBlock constructorBody = constructor.body(); constructorBody.callSuper().arg($v(LOGGER_PARAMETER_NAME)); // Override the locale getter createLocaleGetter(locale, true); final Set> entries = this.translations.entrySet(); final Set methodNames = new LinkedHashSet<>(); for (Map.Entry entry : entries) { JMethodDef method = addMessageMethod(entry.getKey(), entry.getValue()); if (methodNames.add(method)) { method.annotate(Override.class); } } return classDef; } } jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/000077500000000000000000000000001356560461700316125ustar00rootroot00000000000000ClassType.java000066400000000000000000000047661356560461700343220ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import javax.lang.model.AnnotatedConstruct; /** * Date: 23.08.2011 * * @author James R. Perkins */ public interface ClassType extends AnnotatedConstruct { /** * Determines if this type is either the same as, or is a supertype of, the class represented by the {@code type} * parameter. If this type is assignable from the class {@code true} is returned, otherwise {@code false}. * * @param type the class type to check. * * @return {@code true} if this type is the same as or a superclass of the class, otherwise {@code false}. */ boolean isAssignableFrom(Class type); /** * Determines if this type is a subtype of the class represented by the {@code type} parameter. If this type is a * subtype of the class {@code true} is returned, otherwise {@code false}. * * @param type the class type to check. * * @return {@code true} if this type is a subtype of the class, otherwise {@code false}. */ boolean isSubtypeOf(Class type); /** * Determines if this type is the same type as the class represented by the {@code type} parameter. If this type is * the same type as the class {@code true} is returned, otherwise {@code false}. * * @param type the class type to check. * * @return {@code true} if this type is the same type as the class, otherwise {@code false}. */ boolean isSameAs(Class type); } DelegatingElement.java000066400000000000000000000066661356560461700357710ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.lang.annotation.Annotation; import java.util.List; import java.util.Set; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ElementVisitor; import javax.lang.model.element.Modifier; import javax.lang.model.element.Name; import javax.lang.model.type.TypeMirror; /** * A delegating {@link Element} interface. All methods are invoked on the {@linkplain #getDelegate() delegate element} * by default. * * @author James R. Perkins */ public interface DelegatingElement extends Element { /** * The element to delegate the default methods to. * * @return the delegate */ Element getDelegate(); @Override default TypeMirror asType() { return getDelegate().asType(); } @Override default ElementKind getKind() { return getDelegate().getKind(); } @Override default Set getModifiers() { return getDelegate().getModifiers(); } @Override default Name getSimpleName() { return getDelegate().getSimpleName(); } @Override default Element getEnclosingElement() { return getDelegate().getEnclosingElement(); } @Override default List getEnclosedElements() { return getDelegate().getEnclosedElements(); } @Override default A getAnnotation(final Class annotationType) { return getDelegate().getAnnotation(annotationType); } @Override default List getAnnotationMirrors() { return getDelegate().getAnnotationMirrors(); } @Override default R accept(final ElementVisitor v, final P p) { return getDelegate().accept(v, p); } @Override default A[] getAnnotationsByType(final Class annotationType) { return getDelegate().getAnnotationsByType(annotationType); } /** * Checks whether or not the annotation is present on the element. * * @param annotation the annotation to check for * * @return {@code true} if the annotation is present, otherwise {@code false} */ default boolean isAnnotatedWith(Class annotation) { return getAnnotation(annotation) != null; } } DelegatingExecutableElement.java000066400000000000000000000054641356560461700377660ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.util.List; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Name; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.TypeMirror; /** * A delegating {@link ExecutableElement} interface. All methods are invoked on the {@linkplain #getDelegate() delegate element} * by default. * * @author James R. Perkins */ public interface DelegatingExecutableElement extends ExecutableElement, DelegatingElement { @Override ExecutableElement getDelegate(); @Override default TypeMirror asType() { return getDelegate().asType(); } @Override default List getTypeParameters() { return getDelegate().getTypeParameters(); } @Override default TypeMirror getReturnType() { return getDelegate().getReturnType(); } @Override default List getParameters() { return getDelegate().getParameters(); } @Override default TypeMirror getReceiverType() { return getDelegate().getReceiverType(); } @Override default boolean isVarArgs() { return getDelegate().isVarArgs(); } @Override default boolean isDefault() { return getDelegate().isDefault(); } @Override default List getThrownTypes() { return getDelegate().getThrownTypes(); } @Override default AnnotationValue getDefaultValue() { return getDelegate().getDefaultValue(); } @Override default Name getSimpleName() { return getDelegate().getSimpleName(); } } DelegatingTypeElement.java000066400000000000000000000052651356560461700366250ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.util.List; import javax.lang.model.element.Element; import javax.lang.model.element.Name; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.TypeParameterElement; import javax.lang.model.type.TypeMirror; /** * A delegating {@link TypeElement} interface. All methods are invoked on the {@linkplain #getDelegate() delegate element} * by default. * * @author James R. Perkins */ public interface DelegatingTypeElement extends TypeElement, DelegatingElement { @Override TypeElement getDelegate(); @Override default TypeMirror asType() { return getDelegate().asType(); } @Override default List getEnclosedElements() { return getDelegate().getEnclosedElements(); } @Override default NestingKind getNestingKind() { return getDelegate().getNestingKind(); } @Override default Name getQualifiedName() { return getDelegate().getQualifiedName(); } @Override default Name getSimpleName() { return getDelegate().getSimpleName(); } @Override default TypeMirror getSuperclass() { return getDelegate().getSuperclass(); } @Override default List getInterfaces() { return getDelegate().getInterfaces(); } @Override default List getTypeParameters() { return getDelegate().getTypeParameters(); } @Override default Element getEnclosingElement() { return getDelegate().getEnclosingElement(); } } JavaDocComment.java000066400000000000000000000026251356560461700352350ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; /** * Represents the {@code JavaDoc's} documentation. * * @author James R. Perkins */ public interface JavaDocComment { /** * The JavaDoc comments if available or {@code null} if there are no JavaDoc's present. * * @return the JavaDoc comments or {@code null}. */ String getComment(); } MessageInterface.java000066400000000000000000000102311356560461700356000ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.util.Collection; import java.util.List; import java.util.Properties; import java.util.Set; import javax.lang.model.element.TypeElement; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; /** * Date: 28.07.2011 * * @author James R. Perkins */ public interface MessageInterface extends Comparable, ClassType, JavaDocComment, DelegatingTypeElement { /** * Checks the interface to see if the {@link org.jboss.logging.BasicLogger logger interface} is being extended in * this interface. * * @return {@code true} if this interface extends the logger interface, otherwise {@code false}. */ boolean extendsLoggerInterface(); /** * A set of qualified interface names this interface extends or an empty set. * * @return a set of interface names or an empty set. */ Set extendedInterfaces(); /** * A collection of all the methods this interface needs to implement. * * @return a collection of methods. */ Collection methods(); /** * The project code for the message interface or {@code null} if not annotated with * {@link MessageBundle @MessageBundle} or {@link MessageLogger @MessageLogger}. * * @return the project code or {@code null} if not annotated with * {@link MessageBundle @MessageBundle} or {@link MessageLogger @MessageLogger} */ String projectCode(); /** * The qualified name of the message interface. * * @return the qualified name. */ String name(); /** * The package name of the message interface. * * @return the package name. */ String packageName(); /** * The name of the interface without the package. * * @return the simple interface name. */ String simpleName(); /** * The fully qualified class name to use for log methods. This will generally be the same result as {@link * #name()}. * * @return the fully qualified class name to use for logging. */ String loggingFQCN(); /** * Returns a list of {@link ValidIdRange valid id ranges}. * * @return a list of valid id ranges or an empty list */ List validIdRanges(); /** * The length to pad the id with. A value of less than 0 indicates no padding. * * @return the length to pad the id with */ int getIdLength(); /** * Returns the type to use for the {@code @Generated} annotation. This may return {@code null} of the implementation * should not be annotated. * * @return the type for the generated annotation or {@code null} if no annotation is wanted */ default TypeElement generatedAnnotation() { return null; } /** * The properties used to resolve expressions. * * @return the properties used to resolve expressions */ default Properties expressionProperties() { return new Properties(); } } MessageMethod.java000066400000000000000000000142201356560461700351220ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.lang.annotation.Annotation; import java.util.Set; import org.jboss.logging.annotations.Message.Format; /** * Date: 29.07.2011 * * @author James R. Perkins */ public interface MessageMethod extends Comparable, JavaDocComment, DelegatingExecutableElement { /** * Returns the method name. * * @return the method name. */ String name(); /** * Returns the parameters for the method. * * @return the parameters for the method */ Set parameters(); /** * Returns an unmodifiable collection of the parameters specified by the parameter type or an empty set. * * @param annotation the annotation to get the parameters for * * @return a collection of the parameters or an empty set. */ Set parametersAnnotatedWith(Class annotation); /** * Returns the return type for the method. * * @return the return type for the method. */ ReturnType returnType(); /** * Returns a collection of throwable types the method throws. If the method throws no exceptions an empty * collection is returned. * * @return a collection of throwable types or an empty collection. */ Set thrownTypes(); /** * The {@link Message} to be used for the method. * * @return the message. */ Message message(); /** * Indicates whether the message was inherited from another message or not. If {@code true} is returned the * {@link Message} was inherited from a different method, otherwise {@code false}. *

* Note: {@code false} does not indicate the method has a {@link org.jboss.logging.annotations.Message} * annotation. * * @return {@code true} if the message was inherited from a different method, otherwise {@code false}. */ boolean inheritsMessage(); /** * Returns the name of the method used to retrieve the message. * * @return the name of the message method. */ String messageMethodName(); /** * Returns the name of the key used in the translation files for the message translation. * * @return the name of the key in the translation files. */ String translationKey(); /** * Returns {@code true} if there is a cause element, otherwise {@code false}. * * @return {@code true} if there is a cause element, otherwise {@code false} */ boolean hasCause(); /** * Returns {@code true} if the method is overloaded, otherwise {@code false} * . * * @return {@code true} if the method is overloaded, otherwise {@code false} */ boolean isOverloaded(); /** * Returns the cause element if {@link #hasCause()} returns {@code true}, otherwise {@code null}. * * @return the cause element, otherwise {@code null}. */ Parameter cause(); /** * Returns the LogMessage annotation associated with this method only if {@link #isLoggerMethod()} returns * {@code true}. * * @return the log message annotation */ String loggerMethod(); /** * Returns the log level parameter associated with the method only if {@link #isLoggerMethod()} returns * {@code true}. * * @return the enum name of the {@linkplain org.jboss.logging.Logger.Level log level} */ String logLevel(); /** * Returns the number of parameters minus the cause parameter count for the method. * * @return the number of parameters minus the cause parameter count for the method. */ int formatParameterCount(); /** * Returns {@code true} if this is a logger method, otherwise {@code false}. * * @return {@code true} if this is a logger method, otherwise {@code false}. */ boolean isLoggerMethod(); /** * Represents a {@link org.jboss.logging.annotations.Message} annotation on a method. */ interface Message { /** * The message id for the message to use. Any id less than 0 will be ignored. * * @return the message id. */ int id(); /** * Checks if the message has an id that was provided. Returns {@code true} if the message id was specified or * inherited, otherwise returns {@code false}. * * @return {@code true} if the message id was provided, otherwise {@code false}. */ boolean hasId(); /** * Checks if the message id was inherited. Returns {@code true} only if the message id is inherited, otherwise * {@code false} is returned. * * @return {@code true} if the message id was inherited, otherwise {@code false}. */ boolean inheritsId(); /** * A format string that can be used with the {@link #format()}. * * @return a format string. */ String value(); /** * The message format type for the message. * * @return the format type. */ Format format(); } } Parameter.java000066400000000000000000000061151356560461700343210ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; /** * @author James R. Perkins - 20.Feb.2011 */ public interface Parameter extends Comparable, ClassType, DelegatingElement { /** * The variable name of the parameter. * * @return the variable name of the parameter. */ String name(); /** * Returns {@code true} if the type is an array, otherwise {@code false}. * * @return {@code true} if an array, otherwise {@code false} */ boolean isArray(); /** * Returns {@code true} if the type is a primitive type, otherwise {@code false}. * * @return {@code true} if primitive type, otherwise {@code false} */ boolean isPrimitive(); /** * Returns {@code true} if the parameter is a var args parameter, otherwise {@code false}. * * @return {@code true} if var args parameter, otherwise {@code false}. */ boolean isVarArgs(); /** * Indicates whether or not the parameter is used a format parameter for the message. * * @return {@code true} if this parameter that should used as a format parameter for the message */ default boolean isFormatParameter() { return true; } /** * Indicates whether or not this parameter represents the message method. * * @return {@code true} if this is the message method parameter */ default boolean isMessageMethod() { return false; } /** * The formatter class, or {@code null} if there is none. * * @return the formatter class */ String formatterClass(); /** * Returns the name of the target field or method. For example if the parameter is annotated with * {@link org.jboss.logging.annotations.Field @Field} the target name is the name of the field to set on the * {@link org.jboss.logging.processor.model.ReturnType return type}. If no target name is defined an empty String * is returned. * * @return the target field name, method name or an empty string. */ String targetName(); } ReturnType.java000066400000000000000000000056041356560461700345240ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.util.List; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import org.jboss.logging.processor.util.ElementHelper; /** * Date: 29.07.2011 * * @author James R. Perkins */ public interface ReturnType extends ClassType, DelegatingElement { /** * Checks to see if the return type is an exception, extends Throwable or the value of a * {@link java.util.function.Supplier} is a Throwable type. * * @return {@code true} if the return type is an exception, otherwise {@code false}. * * @see #resolvedType() */ boolean isThrowable(); /** * Returns the qualified class name of the return type. * * @return the qualified class name fo the return type. */ String name(); /** * Returns the exception return type if {@link #isThrowable()} returns {@code true}. Otherwise {@code null} is * returned. * * @return an exception return type, otherwise {@code null}. */ ThrowableType throwableReturnType(); /** * Checks this {@linkplain #asType() type} to see if there are any * {@linkplain DeclaredType#getTypeArguments() type arguments}. If any type arguments are found the first type is * returned and assumed to be the resolved type. Otherwise this {@linkplain #asType() type} is returned. *

* This is useful for the {@link java.util.function.Supplier Supplier} return type. *

* * @return the resolved return type */ default TypeMirror resolvedType() { final TypeMirror type = asType(); final List typeArgs = ElementHelper.getTypeArguments(type); if (typeArgs.isEmpty()) { return type; } // Assume the first type only return typeArgs.get(0); } } ThrowableType.java000066400000000000000000000104601356560461700351700ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/model/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.model; import java.util.Set; /** * Date: 27.09.2011 * * @author James R. Perkins */ public interface ThrowableType extends ClassType, Comparable, DelegatingElement { /** * Checks to see the throwable has a default constructor. * * @return {@code true} if the throwable has a default constructor, otherwise {@code false}. */ boolean hasDefaultConstructor(); /** * Checks to see if the throwable has a string and throwable ({@code Throwable(String, Throwable)}) constructor. * * @return {@code true} if the throwable has both a string and throwable constructor, otherwise {@code false}. */ boolean hasStringAndThrowableConstructor(); /** * Checks to see if the throwable has a string ({@code Throwable(String)}) constructor. *

* If {@code true}, {@link Throwable#initCause(Throwable)} can be used to set the throwable. * * @return {@code true} if the throwable has a string constructor, otherwise {@code false}. */ boolean hasStringConstructor(); /** * Checks to see if the throwable has a throwable and string ({@code Throwable(Throwable, String)}) constructor. * * @return {@code true} if the throwable has both a throwable and string constructor, otherwise {@code false}. */ boolean hasThrowableAndStringConstructor(); /** * Checks to see if the throwable has a string and throwable ({@code Throwable(String, Throwable)}) constructor. * * @return {@code true} if the throwable has a throwable constructor, otherwise {@code false}. */ boolean hasThrowableConstructor(); /** * Checks to see if the throwable has and can use a custom constructor. *

* If {@code true}, the constructor parameters can be retrieved from the {@link #constructionParameters()} method. * * @return {@code true} if the throwable has a custom constructor that can be used, otherwise {@code false}. */ boolean useConstructionParameters(); /** * Indicates whether or not the {@linkplain org.jboss.logging.annotations.Cause cause} was set in the constructor. * * @return {@code true} if the cause was set in the constructor, {@code false} if the * {@link Throwable#initCause(Throwable)} should be executed */ default boolean causeSetInConstructor() { return false; } /** * The parameters needed to construct the throwable, if not using the default constructor. If the default * constructor should be used an empty set should be returned. *

* The order the set is returned is the order in which the parameters must be in for the constructor. * * @return a set of construction parameters or an empty set. */ Set constructionParameters(); /** * Checks if the throwable is a checked exception. If the throwable is a checked exception, {@code true} is * returned, otherwise {@code false}. * * @return {@code true} if the throwable is a checked exception, otherwise {@code false}. */ boolean isChecked(); /** * Returns the qualified class name of the return type. * * @return the qualified class name fo the return type. */ String name(); } jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/000077500000000000000000000000001356560461700314675ustar00rootroot00000000000000Comparison.java000066400000000000000000000235571356560461700344010ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.util.Comparator; /** * Date: 30.08.2011 * * @author James R. Perkins */ public abstract class Comparison { public static final int EQUAL = 0; public static final int LESS = -1; public static final int GREATER = 1; private static final Comparison LESS_COMPARISON = new DeadComparison(-1); private static final Comparison GREATER_COMPARISON = new DeadComparison(1); private static final Comparison ALLOW_NULL_INSTANCE = new Comparison() { @Override @SuppressWarnings("unchecked") public Comparison compare(final Comparable left, final Comparable right) { final int result; if (left == null && right == null) { result = EQUAL; } else if (left == null) { result = LESS; } else if (right == null) { result = GREATER; } else { result = left.compareTo(right); } return super.checkResult(result); } @Override public Comparison compare(final T left, final T right, final Comparator comparator) { final int result; if (left == null && right == null) { result = EQUAL; } else if (left == null) { result = LESS; } else if (right == null) { result = GREATER; } else { result = comparator.compare(left, right); } return super.checkResult(result); } @Override public Comparison getInstance() { return ALLOW_NULL_INSTANCE; } }; private static final Comparison INSTANCE = new Comparison() { @Override @SuppressWarnings("unchecked") public Comparison compare(final Comparable left, final Comparable right) { return super.checkResult(left.compareTo(right)); } @Override public Comparison compare(final T left, final T right, final Comparator comparator) { return super.checkResult(comparator.compare(left, right)); } @Override public Comparison getInstance() { return INSTANCE; } }; private static final class DeadComparison extends Comparison { private final int result; public DeadComparison(final int result) { this.result = result; } @Override public Comparison compare(final Comparable left, final Comparable right) { return this; } @Override public Comparison compare(final T left, final T right, final Comparator comparator) { return this; } @Override public Comparison compare(final int left, final int right) { return this; } @Override public Comparison compare(final long left, final long right) { return this; } @Override public Comparison compare(final float left, final float right) { return this; } @Override public Comparison compare(final double left, final double right) { return this; } @Override public Comparison compare(final boolean left, final boolean right) { return this; } @Override public int result() { return result; } @Override public Comparison getInstance() { return this; } } /** * Private constructor for singleton pattern. */ private Comparison() { } /** * Begins a new comparison. * * @return the comparison. */ public static Comparison begin() { return INSTANCE; } /** * Begins a new comparison, but allows for {@code null} values to be passed. *

*

* If the first value is {@code null} and the second value is * {@code non-null}, the comparison will return -1. If the first value is * {@code non-null} and the second value is {@code null}, the comparison * will return 1. If both values are {@code null} 0 is returned. *

* * @return the comparison. */ public static Comparison beginAllowNull() { return ALLOW_NULL_INSTANCE; } /** * Compares the left comparable to the right as specified by the {@link * Comparable#compareTo(Object)} interface. * * @param left the object to compare to the right. * @param right the object compared to the left. * * @return the the same instance if the objects are equal, otherwise a * comparison that will return a defined value. */ public abstract Comparison compare(Comparable left, Comparable right); /** * Compares the left object to the right object as specified by the {@link * java.util.Comparator#compare(Object, Object)} * interface. * * @param the type of the object to the compared. * @param left the object to compare to the right. * @param right the object compared to the left. * @param comparator the comparator used to compare the objects. * * @return the the same instance if the objects are equal, otherwise a * comparison that will return a defined value. */ public abstract Comparison compare(T left, T right, Comparator comparator); /** * Compares the left integer to the right integer. * * @param left the integer to compare to the right. * @param right the integer compared to the left. * * @return the the same instance if the integers are equal, otherwise a * comparison that will return a defined value. */ public Comparison compare(int left, int right) { int result = EQUAL; if (left < right) { result = LESS; } else if (left > right) { result = GREATER; } return checkResult(result); } /** * Compares the left long to the right long. * * @param left the long to compare to the right. * @param right the long compared to the left. * * @return the the same instance if the longs are equal, otherwise a * comparison that will return a defined value. */ public Comparison compare(long left, long right) { int result = EQUAL; if (left < right) { result = LESS; } else if (left > right) { result = GREATER; } return checkResult(result); } /** * Compares the left float to the float integer. * * @param left the float to compare to the right. * @param right the float compared to the left. * * @return the the same instance if the floats are equal, otherwise a * comparison that will return a defined value. */ public Comparison compare(float left, float right) { return checkResult(Float.compare(left, right)); } /** * Compares the left double to the double integer. * * @param left the double to compare to the right. * @param right the double compared to the left. * * @return the the same instance if the doubles are equal, otherwise a * comparison that will return a defined value. */ public Comparison compare(double left, double right) { return checkResult(Double.compare(left, right)); } /** * Compares the left boolean to the double boolean. * * @param left the boolean to compare to the right. * @param right the boolean compared to the left. * * @return the the same instance if the booleans are equal, otherwise a * comparison that will return a defined value. */ public Comparison compare(boolean left, boolean right) { return checkResult((left == right) ? EQUAL : (left ? GREATER : LESS)); } /** * Ends the comparison and returns 0 if all comparisons were equal, -1 if * the any of the left comparisons were less than the right comparisons or * 1 if any of the right comparisons were less than the left. * * @return zero if equal, otherwise the a value with the same sign as the first * non-equal comparison. */ public int result() { return EQUAL; } /** * Returns the comparison instance being used. * * @return the comparison instance being used. */ protected abstract Comparison getInstance(); /** * Checks to see which comparison to return. * * @param result the result of the comparison. * * @return the comparison that should be used. */ private Comparison checkResult(final int result) { return (result < 0) ? LESS_COMPARISON : (result > 0) ? GREATER_COMPARISON : getInstance(); } } ElementHelper.java000066400000000000000000000333671356560461700350200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.AnnotatedConstruct; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; /** * An utility class to work with element. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) * @author James R. Perkins */ public final class ElementHelper { /** * Disable instantiation. */ private ElementHelper() { } /** * Returns the type arguments for the element. If the elements {@linkplain Element#asType() type} is not a * {@link DeclaredType} or the element does not have any type arguments an empty list is returned. * * @param element the element to get the type arguments for * * @return the type arguments or an empty list */ public static List getTypeArguments(final Element element) { return getTypeArguments(element.asType()); } /** * Returns the type arguments for the type. If the type is not a {@link DeclaredType} or the type does not have any * type arguments an empty list is returned. * * @param type the type to get the type arguments for * * @return the type arguments or an empty list */ public static List getTypeArguments(final TypeMirror type) { if (type instanceof DeclaredType) { return ((DeclaredType) type).getTypeArguments(); } return Collections.emptyList(); } /** * Check if an element is annotated with the given annotation. * * @param annotatedConstruct the object to look for the annotation on. * @param clazz the annotation class * * @return {@code true} if the element is annotated, otherwise {@code false} * * @throws IllegalArgumentException if element parameter is null */ public static boolean isAnnotatedWith(final AnnotatedConstruct annotatedConstruct, final Class clazz) { if (annotatedConstruct == null) { throw new IllegalArgumentException("The element parameter is null"); } Annotation annotation = annotatedConstruct.getAnnotation(clazz); return (annotation != null); } /** * Retrieves the first attribute value from the annotation and assumes it's a {@link Class class} type. * * @param element the element the annotation is on * @param annotation the annotation to get the value from * * @return a {@link TypeElement} representing the value for the first annotation attribute or {@code null} if no * attributes were found */ public static TypeElement getClassAnnotationValue(final Element element, final Class annotation) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { final DeclaredType annotationType = mirror.getAnnotationType(); if (annotationType.toString().equals(annotation.getName())) { final AnnotationValue value = mirror.getElementValues().values().iterator().next(); return ((TypeElement) (((DeclaredType) value.getValue()).asElement())); } } return null; } /** * Retrieves the attribute value from the annotation and assumes it's a {@link Class class} type. * * @param element the element the annotation is on * @param annotation the annotation to get the value from * @param attributeName the name of the attribute to retrieve the class value for * * @return a {@link TypeElement} representing the value for the annotation attribute or {@code null} if the * attribute was not found */ @SuppressWarnings({"StaticMethodOnlyUsedInOneClass", "SameParameterValue"}) public static TypeElement getClassAnnotationValue(final Element element, final Class annotation, final String attributeName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { final DeclaredType annotationType = mirror.getAnnotationType(); if (annotationType.toString().equals(annotation.getName())) { final Map map = mirror.getElementValues(); for (ExecutableElement key : map.keySet()) { if (key.getSimpleName().contentEquals(attributeName)) { return ((TypeElement) (((DeclaredType) map.get(key).getValue()).asElement())); } } } } return null; } /** * Retrieves the attribute value from the annotation and assumes it's an array {@link Class classes}. * * @param element the element the annotation is on * @param annotation the annotation to get the value from * @param attributeName the name of the attribute to retrieve the class value array for * * @return a list of {@link TypeMirror} representing the value for the annotation attribute or an empty list */ public static List getClassArrayAnnotationValue(final Element element, final Class annotation, @SuppressWarnings("SameParameterValue") final String attributeName) { for (AnnotationMirror mirror : element.getAnnotationMirrors()) { final DeclaredType annotationType = mirror.getAnnotationType(); if (annotationType.toString().equals(annotation.getName())) { final Map map = mirror.getElementValues(); for (ExecutableElement key : map.keySet()) { if (key.getSimpleName().contentEquals(attributeName)) { @SuppressWarnings("unchecked") final List annotationValues = (List) map.get(key).getValue(); final List result = new ArrayList<>(annotationValues.size()); for (AnnotationValue value : annotationValues) { result.add((TypeMirror) value.getValue()); } return result; } } } } return Collections.emptyList(); } /** * Returns annotations that are associated with the element that match the {@code annotation} parameter type. If the * {@code groupedAnnotation} is not {@code null} then any repeated annotations that math the {@code annotation} * parameter type are also returned. *

*

* The {@code groupedAnnotation} must have a value attribute that includes an array of annotations that math the * {@code annotation} parameter type. *

* * @param element the element to search for annotations * @param groupedAnnotation the grouped annotation, e.g. collector for repeatable annotations, or {@code null} if not a repeatable annotation * @param annotation the annotation to search for * * @return a collection matched annotations */ public static Collection getAnnotations(final Element element, final Class groupedAnnotation, final Class annotation) { final Collection result = new ArrayList<>(); final List annotations = element.getAnnotationMirrors(); for (AnnotationMirror annotationMirror : annotations) { if (isSameType(groupedAnnotation, annotationMirror.getAnnotationType())) { result.addAll(getContainingAnnotations(annotationMirror)); } else if (isSameType(annotation, annotationMirror.getAnnotationType())) { result.add(annotationMirror); } } return result; } /** * Checks whether or not a constructor matching the parameters exists. * * @param types the type utility used to compare the type arguments * @param element the element that contains the constructors * @param args the arguments the constructor should match * * @return {@code true} if a matching constructor was found otherwise {@code false} */ public static boolean hasConstructor(final Types types, final Element element, final List args) { final int len = args.size(); final List constructors = ElementFilter.constructorsIn(element.getEnclosedElements()); for (ExecutableElement constructor : constructors) { final List parameters = constructor.getParameters(); if (len == parameters.size()) { boolean match = false; for (int i = 0; i < len; i++) { final TypeMirror type = args.get(i); final VariableElement parameter = parameters.get(i); if (types.isSameType(type, parameter.asType())) { match = true; } else { match = false; break; } } if (match) { return true; } } } return false; } /** * Returns the type as a {@link TypeMirror}. * * @param processingEnv the processing environment to get the elements utility * @param type the type to create the {@link TypeMirror} for * * @return the type */ public static TypeElement toTypeElement(final ProcessingEnvironment processingEnv, final Class type) { return toTypeElement(processingEnv.getElementUtils(), type); } /** * Returns the type as a {@link TypeMirror}. * * @param elements the element utility used to generate the tye type * @param type the type to create the {@link TypeMirror} for * * @return the type */ public static TypeElement toTypeElement(final Elements elements, final Class type) { return elements.getTypeElement(type.getCanonicalName()); } /** * Returns the type as a {@link TypeMirror}. * * @param processingEnv the processing environment to get the elements utility * @param type the type to create the {@link TypeMirror} for * * @return the type */ public static TypeMirror toType(final ProcessingEnvironment processingEnv, final Class type) { return toType(processingEnv.getElementUtils(), type); } /** * Returns the type as a {@link TypeMirror}. * * @param elements the element utility used to generate the tye type * @param type the type to create the {@link TypeMirror} for * * @return the type */ public static TypeMirror toType(final Elements elements, final Class type) { return toTypeElement(elements, type).asType(); } private static boolean isSameType(final Class c, final TypeMirror type) { return c != null && c.getCanonicalName().equals(type.toString()); } @SuppressWarnings("unchecked") private static Collection getContainingAnnotations(final AnnotationMirror annotation) { final Collection result = new ArrayList<>(); // Return any child annotations final Map childAnnotations = annotation.getElementValues(); childAnnotations.entrySet().stream().filter(entry -> entry.getKey().getSimpleName().contentEquals("value")).forEach(entry -> { final Object value = entry.getValue().getValue(); if (value instanceof List) { final List values = (List) value; for (AnnotationValue subValue : values) { if (subValue instanceof AnnotationMirror) { result.add((AnnotationMirror) subValue); } else { result.add((AnnotationMirror) subValue.getValue()); } } } }); return result; } } Expressions.java000066400000000000000000000131761356560461700346050ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.util.Properties; /** * @author James R. Perkins */ public class Expressions { private static final int INITIAL = 0; private static final int GOT_DOLLAR = 1; private static final int GOT_OPEN_BRACE = 2; private static final int RESOLVED = 3; private static final int DEFAULT = 4; public static String resolve(final Properties props, final String expression) { if (expression == null) return null; final StringBuilder builder = new StringBuilder(); final char[] chars = expression.toCharArray(); final int len = chars.length; int state = 0; int start = -1; int nameStart = -1; for (int i = 0; i < len; i++) { char ch = chars[i]; switch (state) { case INITIAL: { switch (ch) { case '$': { state = GOT_DOLLAR; continue; } default: { builder.append(ch); continue; } } // not reachable } case GOT_DOLLAR: { switch (ch) { case '$': { builder.append(ch); state = INITIAL; continue; } case '{': { start = i + 1; nameStart = start; state = GOT_OPEN_BRACE; continue; } default: { // invalid; emit and resume builder.append('$').append(ch); state = INITIAL; continue; } } // not reachable } case GOT_OPEN_BRACE: { switch (ch) { case ':': case '}': case ',': { final String name = expression.substring(nameStart, i).trim(); final String val; if (name.startsWith("env.")) { val = System.getenv(name.substring(4)); } else if (name.startsWith("sys.")) { val = System.getProperty(name.substring(4)); } else { val = props.getProperty(name); } if (val != null) { builder.append(val); state = ch == '}' ? INITIAL : RESOLVED; continue; } else if (ch == ',') { nameStart = i + 1; continue; } else if (ch == ':') { start = i + 1; state = DEFAULT; continue; } else { builder.append(expression.substring(start - 2, i + 1)); state = INITIAL; continue; } } default: { continue; } } // not reachable } case RESOLVED: { if (ch == '}') { state = INITIAL; } continue; } case DEFAULT: { if (ch == '}') { state = INITIAL; builder.append(expression.substring(start, i)); } continue; } default: throw new IllegalStateException(); } } switch (state) { case GOT_DOLLAR: { builder.append('$'); break; } case DEFAULT: case GOT_OPEN_BRACE: { builder.append(expression.substring(start - 2)); break; } } return builder.toString(); } } Objects.java000066400000000000000000000331521356560461700336500ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.List; /** * Date: 30.08.2011 * * @author James R. Perkins */ public final class Objects { /** * Not used */ private Objects() { } /** * Checks to see if two booleans are equal. * * @param first the first boolean. * @param second the second boolean. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final boolean first, final boolean second) { return first == second; } /** * Checks to see if two characters are equal. * * @param first the first character. * @param second the second character. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final char first, final char second) { return first == second; } /** * Checks to see if two longs are equal. This method is also used for int's, * shorts, and bytes. * * @param first the first long. * @param second the second long. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final long first, final long second) { return first == second; } /** * Checks to see if two floats are equal. * * @param first the first float. * @param second the second float. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final float first, final float second) { return Float.floatToIntBits(first) == Float.floatToIntBits(second); } /** * Checks to see if two doubles are equal. * * @param first the first double. * @param second the second double. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final double first, final double second) { return Double.doubleToLongBits(first) == Double.doubleToLongBits(second); } /** * Checks to see if two objects are equal. *

*

* Note this method does not handle arrays. The {@link java.util.Arrays} * class has utilities for equality of arrays. *

* * @param first the first optionally {@code null} object. * @param second the second optionally {@code null} object. * * @return {@code true} if the first is equal to the second, otherwise * {@code false}. */ public static boolean areEqual(final Object first, final Object second) { return (first == null ? second == null : first.equals(second)); } /** * Checks to see if an object is {@code null}, otherwise throws an * {@link IllegalArgumentException}. * * @param the type of the object. * @param ref the reference to the object. * * @return the reference if it is not {@code null}. */ public static T checkNonNull(final T ref) { if (ref == null) { throw new IllegalArgumentException(); } return ref; } /** * Checks to see if an object is {@code null}, otherwise throws an * {@link IllegalArgumentException}. * * @param the type of the object. * @param ref the reference to the object. * @param message the message used in the {@code IllegalArgumentException} * constructor. * * @return the reference if it is not {@code null}. */ public static T checkNonNull(final T ref, final String message) { if (ref == null) { throw new IllegalArgumentException(message); } return ref; } /** * Checks to see if an object is {@code null}, otherwise throws an * {@link IllegalArgumentException}. * * @param the type of the object. * @param ref the reference to the object. * @param message the message format used in the * {@code IllegalArgumentException} constructor. * @param args the arguments used to format the message. * * @return the reference if it is not {@code null}. */ public static T checkNonNull(final T ref, final String message, final Object... args) { if (ref == null) { throw new IllegalArgumentException(String.format(message, args)); } return ref; } /** * A builder to simplify the building of hash codes. */ public static class HashCodeBuilder { private final int seed; private int hash; /** * Private constructor for builder pattern. * * @param seed the seed for the hash code. */ private HashCodeBuilder(final int seed) { this.seed = seed; hash = 17; } /** * Creates a new builder with 31 as the seed. * * @return the new builder. */ public static HashCodeBuilder builder() { return new HashCodeBuilder(31); } /** * Creates a new builder with the seed that is passed. * * @param seed the seed for the hash code. * * @return the new builder. */ public static HashCodeBuilder builder(final int seed) { return new HashCodeBuilder(seed); } /** * Adds the hash code of a boolean to the final hash code value. * * @param b a boolean to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final boolean b) { hash = calc() + (b ? 1 : 0); return this; } /** * Adds the hash code of a character to the final hash code value. * * @param c a character to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final char c) { hash = calc() + (int) c; return this; } /** * Adds the hash code of an integer to the final hash code value. *

*

* Both shorts and bytes use this method to add the hash value. *

* * @param i an integer to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final int i) { hash = calc() + i; return this; } /** * Adds the hash code of a long to the final hash code value. * * @param lng a long to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final long lng) { hash = calc() + (int) (lng ^ (lng >>> 32)); return this; } /** * Adds the hash code of a float to the final hash code value. * * @param flt a float to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final float flt) { return add(Float.floatToIntBits(flt)); } /** * Adds the hash code of a double to the final hash code value. * * @param dbl a double to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final double dbl) { return add(Double.doubleToLongBits(dbl)); } /** * Adds the hash code of an object to the final hash code value. *

*

* If the {@code obj} is {@code null} the hash code is calculated using * {@link #add(int)} with a value of 0. Otherwise the hash code is * calculated using {@link #add(int)} with a value of * {@code obj.hashCode()}, unless the object is an array. In this case * the array is processed and this is recursively invoked. *

* * @param obj the object to calculate the hash code of. * * @return the current builder. */ public HashCodeBuilder add(final Object obj) { if (obj == null) { add(0); } else if (!obj.getClass().isArray()) { add(obj.hashCode()); } else { final int len = Array.getLength(obj); for (int i = 0; i < len; i++) { final Object arrayObj = Array.get(obj, i); add(arrayObj); } } return this; } /** * Returns the calculated hash code. * * @return the calculated hash code. */ public int toHashCode() { return hash; } /** * This method overrides the default {@code Object#hashCode()}, but does * not return a proper hash of this builder. Returns the value of * {@code toHashCode()} to insure the incorrect hash code is not returned * by mistake. * * @return the value of {@link #toHashCode()}. */ @Override public int hashCode() { return toHashCode(); } /** * Should never be invoked on this object. * * @param obj an object. */ @Override public boolean equals(final Object obj) { return obj == this; } /** * Calculates the default. * * @return the default hash value. */ private int calc() { return seed * hash; } } /** * A builder to build a default {@code Object#toString()} value. *

* Not thread safe. */ public static class ToStringBuilder { private final List fieldValue = new ArrayList<>(); private final String className; /** * Private constructor for builder pattern. * * @param className the class name to prepend the result with. */ private ToStringBuilder(final String className) { this.className = className; } /** * Creates a new string builder for the {@code clazz}. * * @param clazz the base class for the string result. * * @return the current builder. */ public static ToStringBuilder of(final Class clazz) { return new ToStringBuilder(checkNonNull(clazz.getSimpleName())); } /** * Creates a new string builder for the {@code className}. * * @param className the class name to prepend the string value with. * * @return the current builder. */ public static ToStringBuilder of(final String className) { return new ToStringBuilder(checkNonNull(className)); } /** * Creates a new string builder for the {@code self}. * * @param self the object to create the builder for. * * @return the current builder. */ public static ToStringBuilder of(final Object self) { return of(checkNonNull(self.getClass())); } public ToStringBuilder add(final Object value) { fieldValue.add((value == null ? "null" : value.toString())); return this; } /** * Adds the field and value to the value returned. * * @param field the field for the value. * @param value the value of the field. * * @return the current instance of the builder. */ public ToStringBuilder add(final String field, final Object value) { final String result = checkNonNull(field) + "=" + value; fieldValue.add(result); return this; } @Override public String toString() { final StringBuilder result = new StringBuilder(); result.append(className); result.append("{"); final int size = fieldValue.size(); int count = 0; for (String s : fieldValue) { count++; result.append(s); if (count < size) { result.append(","); } } return result.append("}").toString(); } } } TranslationHelper.java000066400000000000000000000104641356560461700357160ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Utility class to work with translation filename. * * @author Kevin Pollet - SERLI - (kevin.pollet@serli.com) */ public final class TranslationHelper { private static final String TRANSLATION_FILE_NAME_EXTENSION = ".properties"; /** * Private constructor to * disable instantiation. */ private TranslationHelper() { } /** * Get the class name suffix to be added to the * generated class for the given translation file name. * * @param translationFileName the translation file name * * @return the class name suffix corresponding to the given translation filename * * @throws IllegalArgumentException if translationFileName is null or not valid */ public static String getTranslationClassNameSuffix(final String translationFileName) { if (translationFileName == null) { throw new IllegalArgumentException("The translationFileName parameter cannot be null"); } Pattern pattern = Pattern.compile("[^_]*((_[^_.]*){1,3}).*"); Matcher matcher = pattern.matcher(translationFileName); boolean found = matcher.find(); if (!found) { throw new IllegalArgumentException("The given filename is not a valid property filename"); } return matcher.group(1); } /** * Returns the enclosing translation file name for the given * translation file name. *

* If the given translation file name is InterfaceName.i18n_locale * the given translation file name is returned. * * @param translationFile the translation file * * @return the enclosing file name * * @throws IllegalArgumentException if translationFileName is null */ public static String getEnclosingTranslationFileName(final File translationFile) { if (translationFile == null) { throw new IllegalArgumentException("The translationClassName parameter cannot be null"); } final String translationFileName = translationFile.getName(); int lastUnderscore = translationFileName.lastIndexOf('_'); if (translationFileName.indexOf('_') == lastUnderscore) { return translationFileName; } else { return translationFileName.substring(0, lastUnderscore).concat(TRANSLATION_FILE_NAME_EXTENSION); } } /** * Returns the enclosing translation class name for * the given translation class name. If the given translation * class name is the upper class name then the parameter class * name is returned. * * @param translationClassName the translation class name * * @return the enclosing class name * * @throws IllegalArgumentException if translationClassName is null */ public static String getEnclosingTranslationClassName(final String translationClassName) { if (translationClassName == null) { throw new IllegalArgumentException("The translationClassName parameter cannot be null"); } int lastUnderScore = translationClassName.lastIndexOf("_"); return lastUnderScore != -1 ? translationClassName.substring(0, lastUnderScore) : translationClassName; } } VersionComparator.java000066400000000000000000000072301356560461700357320ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Compares 2 different version strings. *

* The version strings must be valid integers separated by {@code .} (dots). *

* Date: 09.11.2011 * * @author James R. Perkins */ public class VersionComparator implements Comparator { public static VersionComparator INSTANCE = new VersionComparator(); private VersionComparator() { } /** * Compares the first version to the second version and returns, 0 if they are equal, a value less than 0 if the * first version is less than the second version or a value greater than 0 if the first version is greater than * the second version. * * @param version1 the first version to compare. * @param version2 the second version to compare. * * @return a value of 0 if the versions are equal, less than 0 if {@code version1} is less than {@code version2}, * a value greater than 0 if {@code version1} is greater than {@code version2}. */ public static int compareVersion(final String version1, final String version2) { return INSTANCE.compare(version1, version2); } @Override public int compare(final String o1, final String o2) { final String[] vs1 = o1.split("\\."); final String[] vs2 = o2.split("\\."); final int len = (vs1.length > vs2.length ? vs1.length : vs2.length); final List v1 = convert(vs1, len); final List v2 = convert(vs2, len); int result = 0; for (int i = 0; i < len; i++) { final Integer vi1 = v1.get(i); final Integer vi2 = v2.get(i); result = vi1.compareTo(vi2); if (result != 0) { break; } } return result; } private static List convert(final String[] version, final int len) { final List result = new ArrayList<>(len); for (int i = 0; i < len; i++) { if (i < version.length) { final String s = version[i]; if ("x".equalsIgnoreCase(s)) { result.add(0); } else { try { result.add(Integer.valueOf(s)); } catch (NumberFormatException e) { throw new IllegalArgumentException(String.format("Version part %s is not a valid integer", s), e); } } } else { result.add(0); } } return result; } } jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/000077500000000000000000000000001356560461700326445ustar00rootroot00000000000000AbstractFormatPart.java000066400000000000000000000037141356560461700372000ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import org.jboss.logging.processor.util.Comparison; /** * Abstract class that only implements Comparable for convenience. Uses the {@link org.jboss.logging.processor.validation.FormatPart#position()} for * the comparison. *

* Date: 13.06.2011 * * @author James R. Perkins */ abstract class AbstractFormatPart implements FormatPart { @Override public int compareTo(final FormatPart other) { return Comparison.begin(). compare(position(), other.position()).result(); } @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append("[") .append("index=") .append(index()) .append(", position=") .append(position()) .append(", part=") .append(part()) .toString(); } } AbstractFormatValidator.java000066400000000000000000000041551356560461700402170ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * Date: 12.08.2011 * * @author James R. Perkins */ abstract class AbstractFormatValidator implements FormatValidator { private String summaryMessage; private String detailMessage; AbstractFormatValidator() { detailMessage = ""; summaryMessage = ""; } final void setDetailMessage(final String detailMessage) { this.detailMessage = detailMessage; } final void setDetailMessage(final String format, final Object... args) { this.detailMessage = String.format(format, args); } final void setSummaryMessage(final String summaryMessage) { this.summaryMessage = summaryMessage; } final void setSummaryMessage(final String format, final Object... args) { this.summaryMessage = String.format(format, args); } @Override public final String detailMessage() { return (detailMessage.isEmpty() ? summaryMessage : detailMessage); } @Override public final String summaryMessage() { return summaryMessage; } } FormatPart.java000066400000000000000000000032151356560461700355100ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * Date: 13.06.2011 * * @author James R. Perkins */ interface FormatPart extends Comparable { /** * The default string index. */ int STRING = -2; /** * The parameter index. For default strings (non-parameters) the value is {@code -2}. * * @return the index. */ int index(); /** * The position for the part. * * @return the position. */ int position(); /** * The part of the format. * * @return the part of the format. */ String part(); } FormatValidator.java000066400000000000000000000040151356560461700365260ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * Date: 14.06.2011 * * @author James R. Perkins */ public interface FormatValidator { /** * The number of arguments needed for the format. * * @return the number of arguments needed. */ int argumentCount(); /** * Returns the format string used for validation. * * @return the format string. */ String format(); /** * Returns {@code true} of the format is valid, otherwise {@code false}. * * @return {@code true} of the format is valid, otherwise {@code false}. */ boolean isValid(); /** * A detail message if {@link #isValid()} returns {@code false}, otherwise an empty string. * * @return a detailed message. */ String detailMessage(); /** * A summary message if {@link #isValid()} returns {@code false}, otherwise an empty string. * * @return a summary message. */ String summaryMessage(); } FormatValidatorFactory.java000066400000000000000000000066031356560461700400630ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.processor.model.MessageMethod; /** * Date: 12.08.2011 * * @author James R. Perkins */ public final class FormatValidatorFactory { private FormatValidatorFactory() { } public static FormatValidator create(final MessageMethod messageMethod) throws IllegalStateException { if (messageMethod.message() == null) { return InvalidFormatValidator.of("No message annotation found."); } return create(messageMethod.message().format(), messageMethod.message().value()); } public static FormatValidator create(final Format format, final String message) throws IllegalStateException { if (message == null) { return InvalidFormatValidator.of("A message is required for the format."); } if (format == null) { return InvalidFormatValidator.of("A format is required for the message."); } switch (format) { case MESSAGE_FORMAT: return MessageFormatValidator.of(message); case PRINTF: return StringFormatValidator.of(message); case NO_FORMAT: return NoFormatValidator.INSTANCE; } return InvalidFormatValidator.of(String.format("Format %s is invalid.", format)); } private static final class InvalidFormatValidator extends AbstractFormatValidator { private InvalidFormatValidator() { super(); } static FormatValidator of(final String summaryMessage) { final InvalidFormatValidator result = new InvalidFormatValidator(); result.setSummaryMessage(summaryMessage); return result; } static FormatValidator of(final String summaryMessage, final String detailMessage) { final InvalidFormatValidator result = new InvalidFormatValidator(); result.setDetailMessage(detailMessage); result.setSummaryMessage(summaryMessage); return result; } @Override public String format() { return ""; } @Override public int argumentCount() { return 0; } @Override public boolean isValid() { return false; } } } IdLengthValidator.java000066400000000000000000000050711356560461700367770ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createError; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.jboss.logging.processor.model.MessageInterface; /** * @author James R. Perkins */ public class IdLengthValidator { private final Map lengths = new HashMap<>(); public Collection validate(final MessageInterface messageInterface) { final List messages = new LinkedList<>(); final String projectCode = messageInterface.projectCode(); final int idLength = messageInterface.getIdLength(); if ((idLength > 0 && idLength < 3) || idLength > 8) { messages.add(createError(messageInterface, "The length of the message id padding must be between 3 and 8. The value %d is invalid.", idLength)); } else { synchronized (this) { // Check the length id's if (lengths.containsKey(projectCode)) { final int len = lengths.get(projectCode); if (len != idLength) { messages.add(createError(messageInterface, "A length of %d was already used for project code '%s'.", len, projectCode)); } } else { lengths.put(projectCode, idLength); } } } return messages; } } IdRangeValidator.java000066400000000000000000000106161356560461700366130ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createError; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.processor.model.MessageInterface; /** * @author James R. Perkins */ public class IdRangeValidator { private final Map> processed = new HashMap<>(); public Collection validate(final MessageInterface messageInterface) { final List messages = new LinkedList<>(); for (ValidIdRange validIdRange : messageInterface.validIdRanges()) { if (validIdRange.min() > validIdRange.max()) { messages.add(createError(messageInterface, "Minimum id value (%d) cannot be greater than the maximum value (%d).", validIdRange.min(), validIdRange.max())); } else { final Map processed = getProcessed(messageInterface); for (Entry entry : processed.entrySet()) { final ValidIdRange vid = entry.getKey(); if (overlap(validIdRange, vid)) { messages.add(createError(messageInterface, "@ValidIdRange min/max (%d/%d) overlap the range (%d/%d) on '%s'.", validIdRange.min(), validIdRange.max(), vid.min(), vid.max(), entry.getValue().name())); } } final MessageInterface previous = processed.put(validIdRange, messageInterface); if (previous != null) { messages.add(createError(messageInterface, "%s was used on %s", validIdRange, messageInterface.name())); } } } return messages; } private boolean overlap(final ValidIdRange r1, final ValidIdRange r2) { return (r1.min() >= r2.min() && r1.min() <= r2.max()) || (r1.max() >= r2.min() && r1.max() <= r2.max()) || (r2.min() >= r1.min() && r2.min() <= r1.max()) || (r2.max() >= r1.min() && r2.max() <= r1.max()); } private Map findAll(final MessageInterface messageInterface) { final Map result = new HashMap<>(); for (ValidIdRange validIdRange : messageInterface.validIdRanges()) { result.put(validIdRange, messageInterface); } for (MessageInterface sub : messageInterface.extendedInterfaces()) { result.putAll(findAll(sub)); } return result; } private Map getProcessed(final MessageInterface messageInterface) { final String projectCode = messageInterface.projectCode(); if (projectCode.isEmpty()) { return Collections.emptyMap(); } if (processed.containsKey(projectCode)) { return processed.get(projectCode); } final Map result = new HashMap<>(); processed.put(projectCode, result); return result; } } MessageFormatPart.java000066400000000000000000000070171356560461700370210ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * The parameter portion of the a {@link java.text.MessageFormat}. *

* **Note: Currently the format type and format style are not validated *

* Date: 14.06.2011 * * @author James R. Perkins */ class MessageFormatPart extends AbstractFormatPart { private final String originalFormat; private final int position; private int index; private String formatType; private String formatStyle; private MessageFormatPart(final int position, final String format) { this.position = position; originalFormat = format; index = 0; } public static MessageFormatPart of(final int position, final String format) { final MessageFormatPart result = new MessageFormatPart(position, format); // The first character and last character must be { and } respectively. if (format.charAt(0) != '{' || format.charAt(format.length() - 1) != '}') { throw new IllegalArgumentException("Format must begin with '{' and end with '}'. Format: " + format); } // Trim off the {} String formatText = format.substring(1, format.length() - 1); // Can't contain any more { or } if (formatText.contains("{") || formatText.contains("}")) { throw new IllegalArgumentException("String contains an invalid character. Cannot specify either '{' or '}'."); } result.init(formatText); return result; } @Override public int index() { return index; } @Override public int position() { return position; } @Override public String part() { return originalFormat; /** Should use something like this when final StringBuilder result = new StringBuilder("{"); if (index >= 0) { result.append(index); } if (formatType != null) { result.append(",").append(formatType); } if (formatStyle != null) { result.append(",").append(formatStyle); } return result.append("}").toString(); **/ } private void init(final String formatText) { if (formatText != null && !formatText.trim().isEmpty()) { try { index = Integer.parseInt(formatText.substring(0, 1)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid index portion of format.", e); } } } } MessageFormatValidator.java000066400000000000000000000133411356560461700400350ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Represents a {@link java.text.MessageFormat} string. *

* **Note: Currently the format type and format style are not validated *

* Date: 14.06.2011 * * @author James R. Perkins */ class MessageFormatValidator extends AbstractFormatValidator { public static final Pattern PATTERN = Pattern.compile("\\{}|\\{.+?}"); private final Set formatParts = new TreeSet<>(); private final Set formats = new TreeSet<>(); private int argumentCount; private boolean valid; private final String format; private MessageFormatValidator(final String format) { super(); this.format = format; valid = true; } public static MessageFormatValidator of(final String format) { final MessageFormatValidator result = new MessageFormatValidator(format); result.init(); result.validate(); return result; } public static MessageFormatValidator of(final String format, final Object... parameters) { final MessageFormatValidator result = new MessageFormatValidator(format); result.init(); result.validate(); result.parameterCheck(parameters); return result; } public static MessageFormatValidator of(final String format, final int parameterCount) { final MessageFormatValidator result = new MessageFormatValidator(format); result.init(); result.validate(); result.parameterCheck(parameterCount); return result; } @Override public int argumentCount() { return argumentCount; } @Override public String format() { return format; } @Override public boolean isValid() { return valid; } private void validate() { // Simple argument parser int start = format.indexOf("{"); int end = format.indexOf("}"); while (start != -1 && valid) { if (end < start) { valid = false; setSummaryMessage("Format %s appears to be missing an ending bracket.", format); } start = format.indexOf("{", end); if (start > 0) { end = format.indexOf("}", start); } } } private void parameterCheck(final Object... parameters) { if (argumentCount > 0 && parameters == null) { valid = false; setSummaryMessage("Invalid parameter count. Required %d provided null for format '%s'.", argumentCount, format); setDetailMessage("Required %d parameters, but none were provided for format %s.", argumentCount, format); } else { parameterCheck(parameters.length); } } private void parameterCheck(final int parameterCount) { if (argumentCount != parameterCount) { valid = false; setSummaryMessage("Invalid parameter count. Required: %d provided %d for format '%s'.", argumentCount, parameterCount, format); setDetailMessage("Required %d parameters, but %d were provided for format %s.", argumentCount, parameterCount, format); } } private void init() { final Matcher matcher = PATTERN.matcher(format); int position = 0; int i = 0; while (i < format.length()) { if (matcher.find(i)) { if (matcher.start() != i) { formatParts.add(StringPart.of(position++, format.substring(i, matcher.start()))); } final MessageFormatPart messageFormatPart = MessageFormatPart.of(position++, matcher.group()); formatParts.add(messageFormatPart); formats.add(messageFormatPart); i = matcher.end(); } else { formatParts.add(StringPart.of(position, format.substring(i))); break; } } final Set counted = new HashSet<>(); // Initialize the argument count for (MessageFormatPart messageFormatPart : formats) { if (messageFormatPart.index() >= 0) { if (counted.add(messageFormatPart.index())) argumentCount++; } } } @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append("[") .append("formatParts=") .append(formatParts) .append(", argumentCount=") .append(argumentCount) .append("]").toString(); } } MessageIdValidator.java000066400000000000000000000137671356560461700371550ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.jboss.logging.processor.util.Objects.HashCodeBuilder; import static org.jboss.logging.processor.util.Objects.areEqual; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createError; import java.util.Collection; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.util.Comparison; /** * Date: 16.08.2011 * * @author James R. Perkins */ public final class MessageIdValidator { private final Map usedMessageIds = new HashMap<>(); MessageIdValidator() { } public Collection validate(final MessageInterface messageInterface, final MessageMethod messageMethod) { final List messages = new LinkedList<>(); final MessageMethod.Message message = messageMethod.message(); if (message == null) { messages.add(createError(messageMethod, "No message annotation found.")); } else { final Collection interfaceMessageMethods = messageInterface.methods(); if (!messageMethod.inheritsMessage() && !message.inheritsId()) { final int id = message.id(); if (interfaceMessageMethods.contains(messageMethod)) { final List validIdRanges = messageInterface.validIdRanges(); boolean invalidId = !validIdRanges.isEmpty(); for (ValidIdRange validIdRange : validIdRanges) { if (id >= validIdRange.min() && id <= validIdRange.max()) { invalidId = false; break; } } if (invalidId) { final StringBuilder ranges = new StringBuilder(); int count = 0; for (ValidIdRange validIdRange : validIdRanges) { ranges.append(validIdRange.min()).append('-').append(validIdRange.max()); if (++count < validIdRanges.size()) { ranges.append(", "); } } messages.add(createError(messageMethod, "Message id %d on method %s is not within the valid range: %s", id, messageMethod.name(), ranges.toString())); } } final String projectCode = messageInterface.projectCode(); final MessageKey key = createMessageKey(projectCode, id); synchronized (this) { if (usedMessageIds.containsKey(key)) { final MessageMethod previousMethod = usedMessageIds.get(key); // Allow methods with the same name to use the same id, like INHERIT does if (!previousMethod.name().equals(messageMethod.name())) { messages.add(createError(previousMethod, "Message id %s is not unique for messageMethod %s with project code %s.", id, previousMethod.name(), projectCode)); messages.add(createError(messageMethod, "Message id %s is not unique for messageMethod %s with project code %s.", id, messageMethod.name(), projectCode)); } } else { usedMessageIds.put(key, messageMethod); } } } } return messages; } private static MessageKey createMessageKey(final String projectCode, final int messageId) { return new MessageKey(projectCode, messageId); } private static class MessageKey implements Comparable { final String projectCode; final int id; MessageKey(final String projectCode, final int id) { this.projectCode = (projectCode == null ? "" : projectCode); this.id = id; } @Override public int hashCode() { return HashCodeBuilder.builder() .add(projectCode) .add(id).toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof MessageKey)) { return false; } final MessageKey other = (MessageKey) obj; return areEqual(projectCode, other.projectCode) && areEqual(id, other.id); } @Override public int compareTo(final MessageKey other) { return Comparison.begin() .compare(projectCode, other.projectCode) .compare(id, other.id).result(); } } } NoFormatValidator.java000066400000000000000000000027411356560461700370270ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * @author James R. Perkins */ final class NoFormatValidator extends AbstractFormatValidator { static final NoFormatValidator INSTANCE = new NoFormatValidator(); @Override public int argumentCount() { return 0; } @Override public String format() { return "none"; } @Override public boolean isValid() { return true; } } PropertyValidator.java000066400000000000000000000326561356560461700371360ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createError; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.lang.model.util.SimpleAnnotationValueVisitor8; import javax.lang.model.util.Types; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.Fields; import org.jboss.logging.annotations.Properties; import org.jboss.logging.annotations.Property; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.util.ElementHelper; /** * Validates property annotations on methods. *

* Valid property annotations are: *

    *
  • {@link Properties}
  • *
  • {@link Property}
  • *
  • {@link Fields}
  • *
  • {@link Field}
  • *
*

* * @author James R. Perkins */ class PropertyValidator { private static final List> VALIDATING_ANNOTATIONS = Arrays.asList(Properties.class, Property.class, Fields.class, Field.class); private final Elements elements; private final Types types; private final MessageMethod method; private final TypeMirror resultType; private final Collection messages; private PropertyValidator(final ProcessingEnvironment processingEnv, final MessageMethod method, final TypeMirror resultType, final Collection messages) { elements = processingEnv.getElementUtils(); types = processingEnv.getTypeUtils(); this.method = method; this.resultType = resultType; this.messages = messages; } /** * Validates the message method property annotations. * * @param processingEnv the annotation processing environment * @param messageMethod the method to validate * * @return a collection of validation messages */ static Collection validate(final ProcessingEnvironment processingEnv, final MessageMethod messageMethod) { boolean continueValidation = !(messageMethod.parametersAnnotatedWith(Field.class).isEmpty() && messageMethod.parametersAnnotatedWith(Property.class).isEmpty()); for (Class annotation : VALIDATING_ANNOTATIONS) { if (messageMethod.isAnnotatedWith(annotation)) { continueValidation = true; break; } } if (continueValidation) { // Use the resolved return type to validate if parameters can be assigned to the type final TypeMirror returnType = processingEnv.getTypeUtils().erasure(messageMethod.returnType().resolvedType()); final List result = new ArrayList<>(); if (returnType.getKind() == TypeKind.DECLARED) { final PropertyValidator validator = new PropertyValidator(processingEnv, messageMethod, returnType, result); validator.validate(); } else { result.add(createError(messageMethod, "The return type is invalid for property annotations.")); } return result; } return Collections.emptyList(); } private void validate() { final Map> fields = new HashMap<>(); final Map> methods = new HashMap<>(); final TypeElement e = (TypeElement) types.asElement(resultType); for (ExecutableElement executableElement : ElementFilter.methodsIn(elements.getAllMembers(e))) { if (executableElement.getModifiers().contains(Modifier.PUBLIC) && executableElement.getParameters().size() == 1) { final String methodName = executableElement.getSimpleName().toString(); // Only add setters and use a property style name if (methodName.startsWith("set")) { final String name = Character.toLowerCase(methodName.charAt(3)) + methodName.substring(4); final Set types = methods.computeIfAbsent(name, (key -> new HashSet<>())); types.add(executableElement.getParameters().get(0).asType()); } } } for (Element element : ElementFilter.fieldsIn(elements.getAllMembers(e))) { if (element.getModifiers().contains(Modifier.PUBLIC) && !element.getModifiers().contains(Modifier.FINAL)) { final Set types = fields.computeIfAbsent(element.getSimpleName().toString(), (key -> new HashSet<>())); types.add(element.asType()); } } // Validate default properties ElementHelper.getAnnotations(method, Fields.class, Field.class).forEach(a -> validateAnnotation(a, fields)); ElementHelper.getAnnotations(method, Properties.class, Property.class).forEach(a -> validateAnnotation(a, methods)); // Validate fields for (Parameter parameter : method.parametersAnnotatedWith(Field.class)) { final Set propertyTypes = fields.get(resolveFieldName(parameter)); final TypeMirror valueType = parameter.asType(); if (!assignablePropertyFound(valueType, propertyTypes)) { messages.add(createError(parameter, "No target field found in %s with name %s with type %s.", resultType, parameter.targetName(), valueType)); } validateCommonAnnotation(parameter, Field.class); } // Validate properties for (Parameter parameter : method.parametersAnnotatedWith(Property.class)) { final Set propertyTypes = methods.get(resolveSetterName(parameter)); final TypeMirror valueType = parameter.asType(); if (!assignablePropertyFound(valueType, propertyTypes)) { messages.add(createError(parameter, "No method found in %s with signature %s(%s).", resultType, parameter.targetName(), valueType)); } validateCommonAnnotation(parameter, Property.class); } } private void validateCommonAnnotation(final Parameter parameter, final Class annotation) { final Collection annotations = ElementHelper.getAnnotations(parameter, null, annotation); // There should only be one annotation if (annotations.size() != 1) { messages.add(createError(parameter, "Parameters can contain only a single @%s annotation.", annotation.getName())); } else { // We should have a name value and one other value final AnnotationMirror annotationMirror = annotations.iterator().next(); final Map map = annotationMirror.getElementValues(); if (!map.isEmpty()) { // Look for the name attribute and a single value for (Map.Entry entry : map.entrySet()) { final ExecutableElement attribute = entry.getKey(); final AnnotationValue attributeValue = entry.getValue(); if (!"name".contentEquals(attribute.getSimpleName())) { messages.add(createError(parameter, annotationMirror, attributeValue, "Default values are not allowed for parameters annotated with @%s. %s", annotation.getName(), annotationMirror)); } } } } } private void validateAnnotation(final AnnotationMirror annotationMirror, final Map> properties) { // We should have a name value and one other value final Map map = annotationMirror.getElementValues(); final int size = map.size(); if (size < 2) { messages.add(createError(method, annotationMirror, "The name attribute and at least one default value are required: %s", annotationMirror)); } else if (size > 2) { messages.add(createError(method, annotationMirror, "Only the name attribute and one default attribute are allowed to be defined: %s", annotationMirror)); } else { // Look for the name attribute and a single value String name = null; AnnotationValue value = null; for (Map.Entry entry : map.entrySet()) { final ExecutableElement attribute = entry.getKey(); final AnnotationValue attributeValue = entry.getValue(); if ("name".contentEquals(attribute.getSimpleName())) { name = String.valueOf(attributeValue.getValue()); } else { value = attributeValue; } } if (name == null) { messages.add(createError(method, annotationMirror, "The name attribute is required on %s", annotationMirror)); } else if (value == null) { messages.add(createError(method, annotationMirror, "No value could be determined for %s", annotationMirror)); } else { final Set propertyTypes = properties.get(name); if (propertyTypes == null) { messages.add(createError(method, annotationMirror, value, "Could not find property %s on %s.", name, resultType)); } else { final TypeMirror defaultValueType = value.accept(ValueTypeAnnotationValueVisitor.INSTANCE, elements); if (!assignablePropertyFound(defaultValueType, propertyTypes)) { messages.add(createError(method, annotationMirror, value, "Expected property with type %s found with type %s", defaultValueType, propertyTypes)); } } } } } private boolean assignablePropertyFound(final TypeMirror valueType, final Set propertyTypes) { if (propertyTypes != null) { for (TypeMirror propertyType : propertyTypes) { if (types.isAssignable(types.erasure(valueType), types.erasure(propertyType))) { return true; } } } return false; } private String resolveFieldName(final Parameter parameter) { String result = ""; final Field field = parameter.getAnnotation(Field.class); if (field != null) { final String name = field.name(); if (name.isEmpty()) { result = parameter.getSimpleName().toString(); } else { result = name; } } return result; } private String resolveSetterName(final Parameter parameter) { String result = ""; final Property property = parameter.getAnnotation(Property.class); if (property != null) { final String name = property.name(); if (name.isEmpty()) { result = parameter.getSimpleName().toString(); } else { result = name; } } return result; } private static class ValueTypeAnnotationValueVisitor extends SimpleAnnotationValueVisitor8 { private static final ValueTypeAnnotationValueVisitor INSTANCE = new ValueTypeAnnotationValueVisitor(); @Override protected TypeMirror defaultAction(final Object o, final Elements elements) { return ElementHelper.toType(elements, o.getClass()); } @Override public TypeMirror visitType(final TypeMirror t, final Elements elements) { return ElementHelper.toType(elements, Class.class); } } } StringFormatPart.java000066400000000000000000000526611356560461700367100ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import java.util.Collections; import java.util.DuplicateFormatFlagsException; import java.util.IllegalFormatPrecisionException; import java.util.IllegalFormatWidthException; import java.util.LinkedHashSet; import java.util.Set; import java.util.UnknownFormatConversionException; import java.util.UnknownFormatFlagsException; /** * The parameter part of a format for {@link java.util.Formatter}. *

* Represents the following format {@linkplain %[argument_index$][flags][width][.precision]conversion}. *

* Date: 13.06.2011 * * @author James R. Perkins */ class StringFormatPart extends AbstractFormatPart { private int index; private final Set flags; private int width; private int precision; private Conversion conversion; private Character dateTimeConversion; private final int position; /** * Creates a parameter format part. * * @param position the position in the string format. */ private StringFormatPart(final int position) { this.flags = new LinkedHashSet<>(); this.position = position; } /** * Creates a parameter part of a format string. * * @param position the position of the part. * @param group the group array of the formats (must be a length of 6). * * @return the the parameter part. * * @throws IllegalArgumentException if the length of the group array is not equal to 6 or a format was invalid. */ public static StringFormatPart of(final int position, final String[] group) throws IllegalArgumentException { if (group.length != 6) { throw new IllegalArgumentException("Groups must have a length of 6."); } final StringFormatPart result = new StringFormatPart(position); int charIndex = 0; result.initIndex(group[charIndex++]); result.initFlags(group[charIndex++]); result.initWidth(group[charIndex++]); result.initPrecision(group[charIndex++]); // Handle date/time if (group[charIndex] != null && group[charIndex].equalsIgnoreCase(Conversion.DATE_TIME.asString())) { result.conversion = Conversion.DATE_TIME; result.dateTimeConversion = group[++charIndex].charAt(0); } else { result.conversion = Conversion.fromChar(group[++charIndex].charAt(0)); result.dateTimeConversion = null; } return result; } /** * Returns the format parameter index. *

* If the index is inherited, {@code -1} is returned. * * @return the format parameter index. */ public int index() { return index; } /** * A collection of the flags. * * @return the flags. */ public Set flags() { return Collections.unmodifiableSet(flags); } /** * The width for the format. *

* If the width was not specified, {@code -1} is returned. * * @return the width. */ public int width() { return width; } /** * The precision for the format. *

* If the precision was not specified, {@code -1} is returned. * * @return the precision. */ public int precision() { return precision; } /** * The conversion for the string format. * * @return the conversion. */ public Conversion conversion() { return conversion; } /** * The date/time conversion character. *

* {@code null} if there is not date time conversion character. * * @return the date/time conversion character or {@code null}. */ public char dateTimeChar() { return dateTimeConversion; } /** * Initializes the index field based on the string. * * @param s the index in string form. * * @throws IllegalArgumentException if the string is not a number. */ private void initIndex(final String s) throws IllegalArgumentException { if (s == null) { index = 0; } else { try { index = Integer.parseInt(s.substring(0, s.length() - 1)); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid index argument.", e); } } } /** * Initializes the flags based on the string. *

* Will set the {@link org.jboss.logging.processor.validation.StringFormatPart#index} to {@code -1} if the {@link Flag#PREVIOUS} flag is found. * * @param s the flags in string form. * * @throws java.util.DuplicateFormatFlagsException * if the flag is specified more than once. */ private void initFlags(final String s) throws DuplicateFormatFlagsException { final char[] chars = s.toCharArray(); for (char c : chars) { final Flag flag = Flag.parse(c); if (flags.contains(flag)) { throw new DuplicateFormatFlagsException(String.format("Duplicate %s flag found. Current flags: %s", flag, flags)); } flags.add(flag); } if (flags.contains(Flag.PREVIOUS)) { index = -1; } } /** * Initializes the width based on the string. * * @param s the width in string form. * * @throws IllegalArgumentException the string is an invalid number. */ private void initWidth(final String s) throws IllegalArgumentException { if (s == null) { width = -1; } else { try { width = Integer.parseInt(s); if (width < 0) { throw new IllegalFormatWidthException(width); } } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid width argument.", e); } } } /** * Initializes the precision based on the string. * * @param s the precision in string form. * * @throws IllegalArgumentException if the precision is less than 0 or an invalid number. */ private void initPrecision(final String s) throws IllegalArgumentException { if (s == null) { precision = -1; } else { try { // Remove the '.' from the prevision precision = Integer.parseInt(s.substring(1)); if (precision < 0) throw new IllegalFormatPrecisionException(precision); } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid precision argument.", e); } } } @Override public int position() { return position; } @Override public String part() { final StringBuilder result = new StringBuilder("%"); if (index > 0) { result.append(index).append("$"); } if (!flags.isEmpty()) { for (Flag flag : flags) { result.append(flag.flag); } } if (width > 0) { result.append(width); } if (precision > 0) { result.append(".").append(precision); } result.append(conversion.asChar()); if (conversion.isDateTime() && dateTimeConversion != null) { result.append(dateTimeConversion); } return result.toString(); } @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append("[") .append("index=") .append(index) .append(", flags=") .append(flags) .append(", width=") .append(width) .append(", precision=") .append(precision) .append(", conversion=") .append(conversion) .append("]") .toString(); } /** * The flags for the string message format. * * @author James R. Perkins */ public enum Flag { /** * The result will be left-justified. *

* Works on all conversions. */ LEFT_JUSTIFY('-'), /** * The result should use a conversion-dependent alternate form. *

* Works on conversions {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#OCTAL_INTEGER}, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#HEX_INTEGER}, all floating points * and most general conversions depending on the definition of {@link java.util.Formattable}. */ CONVERSION_DEPENDENT_ALTERNATE('#'), /** * The result will always include a sign. *

* Works on all floating points, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER}, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#OCTAL_INTEGER}, * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#HEX_INTEGER} when applied to {@link java.math.BigInteger} or * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER} when applied to {@code byte}, {@link Byte}, {@code short}, {@link Short}, * {@code int}, {@link Integer}, {@code long} and {@link Long}. */ INCLUDE_SIGN('+'), /** * The result will include a leading space for positive values. *

* Works on all floating points, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER}, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#OCTAL_INTEGER}, * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#HEX_INTEGER} when applied to {@link java.math.BigInteger} or * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER} when applied to {@code byte}, {@link Byte}, {@code short}, {@link Short}, * {@code int}, {@link Integer}, {@code long} and {@link Long}. */ SPACE_FOR_POSITIVE_VALUES(' '), /** * The result will be zero-padded. *

* Works on all integrals and floating points. */ ZERO_PADDED('0'), /** * The result will include locale-specific grouping separators. *

* Works only on {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER} integrals and {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#SCIENTIFIC_NOTATION}, * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL} and {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#SCIENTIFIC_NOTATION_OR_DECIMAL} floating points. */ LOCALE_GROUPING_SEPARATOR(','), /** * The result will enclose negative numbers in parentheses. *

* Works only on {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER}, {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#OCTAL_INTEGER}, * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#HEX_INTEGER} when applied to {@link java.math.BigInteger} or * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL_INTEGER} when applied to {@code byte}, {@link Byte}, {@code short}, {@link Short}, * {@code int}, {@link Integer}, {@code long} and {@link Long} integrals and {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#SCIENTIFIC_NOTATION}, * {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#DECIMAL} and {@link org.jboss.logging.processor.validation.StringFormatPart.Conversion#SCIENTIFIC_NOTATION_OR_DECIMAL} floating points. */ PARENTHESES_FOR_NEGATIVES('('), /** * The previous position. */ PREVIOUS('<'); /** * The character flag. */ final char flag; private Flag(final char flag) { this.flag = flag; } @Override public String toString() { return new StringBuilder(name()).append("(").append(flag).append(")").toString(); } /** * Checks to see if the character is a valid flag. * * @param c the character to check. * * @return the corresponding flag for the character. * * @throws java.util.UnknownFormatFlagsException * if the flag is invalid. */ public static Flag parse(final char c) throws UnknownFormatFlagsException { for (Flag flag : Flag.values()) { if (flag.flag == c) { return flag; } } throw new UnknownFormatFlagsException("Invalid flag: " + c); } } /** * The conversions for the string format. * * @author James R. Perkins */ public enum Conversion { /** * A boolean conversion 'c' or 'C'. */ BOOLEAN('b', true) { @Override public boolean isGeneral() { return true; } }, /** * A hexadecimal conversion 'h' or 'H'. */ HEX('h', true) { @Override public boolean isGeneral() { return true; } }, /** * A string conversion 's' or 'S'. */ STRING('s', true) { @Override public boolean isGeneral() { return true; } }, /** * A unicode conversion 'c' or 'C'. */ UNICODE_CHAR('c', true) { @Override public boolean isCharacter() { return true; } }, /** * A decimal integer conversion 'd'. */ DECIMAL_INTEGER('d', false) { @Override public boolean isIntegral() { return true; } }, /** * An octal integer conversion 'o'. */ OCTAL_INTEGER('o', false) { @Override public boolean isIntegral() { return true; } }, /** * A hexadecimal integer conversion 'x' or 'X'. */ HEX_INTEGER('x', true) { @Override public boolean isIntegral() { return true; } }, /** * A scientific notation conversion 'e' or 'E'. */ SCIENTIFIC_NOTATION('e', true) { @Override public boolean isFloatingPoint() { return true; } }, /** * A decimal conversion 'f'. */ DECIMAL('f', false) { @Override public boolean isFloatingPoint() { return true; } }, /** * A scientific notation or decimal 'g' or 'G' */ SCIENTIFIC_NOTATION_OR_DECIMAL('g', true) { @Override public boolean isFloatingPoint() { return true; } }, /** * A hexadecimal floating point number 'a' or 'A'. */ HEX_FLOATING_POINT('a', true) { @Override public boolean isFloatingPoint() { return true; } }, /** * A date or time conversion 't' or 'T'. */ DATE_TIME('t', true) { @Override public boolean isDateTime() { return true; } }, /** * A percentage conversion '%'. */ PERCENT('%', false) { @Override public boolean isPercent() { return true; } }, /** * A line separator conversion 'n'. */ LINE_SEPARATOR('n', false) { @Override public boolean isLineSeparator() { return true; } }; private final char conversion; /** * @code true} for the case should be ignored, otherwise {@code false} */ final boolean ignoreCase; /** * Private enum conversion. * * @param conversion the conversion character. * @param ignoreCase {@code true} for the case should be ignored, otherwise {@code false}. */ private Conversion(final char conversion, final boolean ignoreCase) { this.conversion = conversion; this.ignoreCase = ignoreCase; } /** * If the conversion is a general conversion {@code true} is returned, otherwise {@code false}. * * @return {@code true} if a general conversion, otherwise {@code false}. */ public boolean isGeneral() { return false; } /** * If the conversion is a character {@code true} is returned, otherwise {@code false}. * * @return {@code true} if c character, otherwise {@code false}. */ public boolean isCharacter() { return false; } /** * If the conversion is an integral {@code true} is returned, otherwise {@code false}. * * @return {@code true} if an integral, otherwise {@code false}. */ public boolean isIntegral() { return false; } /** * If the conversion is a floating point {@code true} is returned, otherwise {@code false}. * * @return {@code true} if a line separator, otherwise {@code false}. */ public boolean isFloatingPoint() { return false; } /** * If the conversion is a date or time {@code true} is returned, otherwise {@code false}. * * @return {@code true} if a date or time, otherwise {@code false}. */ public boolean isDateTime() { return false; } /** * If the conversion is a percent {@code true} is returned, otherwise {@code false}. * * @return {@code true} if a percent, otherwise {@code false}. */ public boolean isPercent() { return false; } /** * If the conversion is a line separator {@code true} is returned, otherwise {@code false}. * * @return {@code true} if a line separator, otherwise {@code false}. */ public boolean isLineSeparator() { return false; } /** * Returns the conversion character. * * @return the conversion character. */ public char asChar() { return conversion; } /** * Returns the conversion character as a {@link String} * * @return the conversion character. */ public String asString() { return String.valueOf(conversion); } @Override public String toString() { final StringBuilder result = new StringBuilder(name()); result.append("("); result.append(conversion); if (ignoreCase) { result.append(", ").append(Character.toUpperCase(conversion)); } result.append(")"); return result.toString(); } /** * Converts the character into a conversion descriptor. * * @param c the character to convert. * * @return the conversion descriptor. * * @throws java.util.UnknownFormatConversionException * if the character is not a valid conversion format. */ public static Conversion fromChar(final char c) throws UnknownFormatConversionException { for (Conversion conversion : Conversion.values()) { if (conversion.ignoreCase && conversion.asChar() == Character.toLowerCase(c)) { return conversion; } else if (conversion.asChar() == c) { return conversion; } } throw new UnknownFormatConversionException(String.valueOf(c)); } } } StringFormatValidator.java000066400000000000000000000413111356560461700377150ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.IllegalFormatException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import java.util.UnknownFormatConversionException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A string format representation. *

* Date: 13.06.2011 * * @author James R. Perkins */ public final class StringFormatValidator extends AbstractFormatValidator { /** * The Regex pattern. */ public static final Pattern PATTERN = Pattern.compile("%(\\d+\\$)?([-#+ 0,(\\<]*)?(\\d+)?(\\.\\d+)?([tT])?([a-zA-Z%])"); private final Set formatParts = new TreeSet<>(); private final Set formats = new TreeSet<>(); private int argumentCount; private boolean valid; private final String format; /** * Private constructor for the singleton pattern. * * @param format the format. */ private StringFormatValidator(final String format) { super(); this.format = format; this.valid = true; } /** * Creates a string format. * * @param format the format. * * @return the string format. */ public static StringFormatValidator of(final String format) { final StringFormatValidator result = new StringFormatValidator(format); try { result.init(); result.validate(); } catch (RuntimeException e) { if (result.isValid()) { result.valid = false; result.setDetailMessage("Format '%s' appears to be invalid. Error: %s", format, e.getMessage()); } } return result; } /** * Creates a string format. *

* Note: The validator returned is the validator for the translation format. * * @param format the format. * @param translationFormat the format of the translation * * @return the string format. */ public static StringFormatValidator withTranslation(final String format, final String translationFormat) { final StringFormatValidator result = new StringFormatValidator(format); final StringFormatValidator translationResult = new StringFormatValidator(translationFormat); try { result.init(); result.validate(); } catch (RuntimeException e) { if (result.isValid()) { result.valid = false; result.setDetailMessage("Format '%s' appears to be invalid. Error: %s", format, e.getMessage()); } } try { translationResult.init(); translationResult.validate(); } catch (RuntimeException e) { if (translationResult.isValid()) { translationResult.valid = false; translationResult.setDetailMessage("Format '%s' appears to be invalid. Error: %s", format, e.getMessage()); } } // If either is invalid, return the invalid one if (!result.isValid()) return result; if (!translationResult.isValid()) return translationResult; // Sort the formats final List initParts = sortParts(result.formats); final List translationParts = sortParts(translationResult.formats); // The size should be the same as well as the position of each element if (initParts.size() == translationParts.size()) { // Parameters should be in the exact order final Iterator initIter = initParts.iterator(); final Iterator translationIter = translationParts.iterator(); while (initIter.hasNext()) { final StringFormatPart initPart = initIter.next(); final StringFormatPart translationPart = translationIter.next(); if (initPart.conversion() != translationPart.conversion()) { translationResult.valid = false; translationResult.setDetailMessage("The translated message format (%s) does not match the initial message format (%s).", translationFormat, format); translationResult.setSummaryMessage("The translated message format (%s) does not match the initial message format (%s).", translationFormat, format); break; } } } else { translationResult.valid = false; translationResult.setDetailMessage("The translated message format (%s) does not match the initial message format (%s).", translationFormat, format); translationResult.setSummaryMessage("The translated message format (%s) does not match the initial message format (%s).", translationFormat, format); } return translationResult; } /** * Creates a string format. * * @param format the format. * @param parameters the parameters to validate against. * * @return the string format. */ public static StringFormatValidator of(final String format, final Object... parameters) { final StringFormatValidator result = new StringFormatValidator(format); try { result.init(); result.validate(parameters); } catch (RuntimeException e) { if (result.isValid()) { result.valid = false; result.setSummaryMessage("Format '%s' appears to be invalid. Error: %s", format, e.getMessage()); } } return result; } static List sortParts(final Collection parts) { final TreeMap> paramMap = new TreeMap<>(); final int newLineIndex = Integer.MAX_VALUE - 1; final int percentageIndex = Integer.MAX_VALUE; int index = 0; int count = 0; for (StringFormatPart part : parts) { // Line separators and percentage constants need to be handled specially if (part.conversion().isLineSeparator()) { final Set set = getOrAdd(paramMap, newLineIndex); set.add(part); continue; } else if (part.conversion().isPercent()) { final Set set = getOrAdd(paramMap, percentageIndex); set.add(part); continue; } // Check the index and set appropriately if (part.index() > 0) { index = part.index(); } else if (part.index() == 0) { index = ++count; } if (!paramMap.containsKey(index)) { paramMap.put(index, Collections.singleton(part)); } } final List result = new ArrayList<>(); for (Set p : paramMap.values()) { result.addAll(p); } return result; } /** * Validates */ private void validate() { if (!format.equalsIgnoreCase(asFormat())) { valid = false; setSummaryMessage("Formats don't match. Internal error: %s Reconstructed: %s", format, asFormat()); setDetailMessage("The original is '%s' and the reconstructed format is '%s'. This is likely an internal error and should be reported.", format, asFormat()); } else { // Create a multimap to hold the parameter values for sorting final Map> paramMap = new TreeMap<>(); int counter = 0; int index = 0; // Initialize the argument count for (StringFormatPart stringFormatPart : formats) { if (counter == argumentCount) { break; } // Check the index and set appropriately if (stringFormatPart.index() > 0 || stringFormatPart.index() == 0) { index = stringFormatPart.index(); } else if (stringFormatPart.index() < -1) { index = 0; } // Find or create the list for the multimap. final List params; if (paramMap.containsKey(index)) { params = paramMap.get(index); // Skip positional if already defined. if (index > 0) { continue; } } else { params = new ArrayList<>(); paramMap.put(index, params); } counter++; // Add the type. switch (stringFormatPart.conversion()) { case BOOLEAN: params.add(true); break; case DATE_TIME: params.add(new Date()); break; case DECIMAL: case HEX_FLOATING_POINT: params.add(1.5f); break; case DECIMAL_INTEGER: case HEX_INTEGER: case OCTAL_INTEGER: params.add(33); break; case HEX: case STRING: params.add("JBoss"); break; case SCIENTIFIC_NOTATION: case SCIENTIFIC_NOTATION_OR_DECIMAL: params.add(10000.55050d); break; case UNICODE_CHAR: params.add('c'); break; case LINE_SEPARATOR: case PERCENT: counter--; break; default: valid = false; setSummaryMessage("Format not found: %s", stringFormatPart); } } if (valid) { try { // Copy the results in order to a new list. final List params = new ArrayList<>(); for (Map.Entry> entry : paramMap.entrySet()) { params.addAll(entry.getValue()); } // Test the format String.format(format, params.toArray()); } catch (final IllegalFormatException e) { valid = false; setSummaryMessage("Invalid format for '%s' with parameters '%s'. java.util.Formatter Error: %s", format, paramMap, e.getMessage()); setDetailMessage("Format '%s' with parameters '%s' is invalid. StringFormatValidator: %s", format, paramMap, this); } } } } private void validate(final Object... parameters) { // First perform general validation validate(); // Now test parameters counts final int paramCount = (parameters == null ? 0 : parameters.length); if (argumentCount != paramCount) { valid = false; setSummaryMessage("Parameter lengths do not match. Format (%s) requires %d arguments, supplied %d.", format, argumentCount, paramCount); } // Create a parameter list based on the parameters passed if (valid) { try { String.format(format, parameters); } catch (final IllegalFormatException e) { valid = false; setSummaryMessage("Invalid format for '%s' with parameters '%s'. java.util.Formatter Error: %s", format, Arrays.toString(parameters), e.getMessage()); setDetailMessage("Format '%s' with parameters '%s' is invalid. StringFormatValidator: %s", format, Arrays.toString(parameters), this); } } } @Override public int argumentCount() { return argumentCount; } @Override public String format() { return format; } @Override public boolean isValid() { return valid; } /** * Recreates the format using the internal formatting descriptors. * * @return the format. */ public String asFormat() { final StringBuilder result = new StringBuilder(); for (FormatPart formatPart : formatParts) { result.append(formatPart.part()); } return result.toString(); } @Override public String toString() { return new StringBuilder(getClass().getSimpleName()).append("[") .append("formatParts=") .append(formatParts) .append(", argumentCount=") .append(argumentCount) .append("]").toString(); } /** * Initialize the string format. */ private void init() { final Matcher matcher = PATTERN.matcher(format); int position = 0; int i = 0; while (i < format.length()) { if (matcher.find(i)) { if (matcher.start() != i) { formatParts.add(StringPart.of(position++, format.substring(i, matcher.start()))); } // Pattern should produce 6 groups. final String[] formatGroup = new String[6]; for (int groupIndex = 0; groupIndex < matcher.groupCount(); groupIndex++) { formatGroup[groupIndex] = matcher.group(groupIndex + 1); } final StringFormatPart stringFormatPart = StringFormatPart.of(position++, formatGroup); formatParts.add(stringFormatPart); formats.add(stringFormatPart); i = matcher.end(); } else { // No more formats found, but validate for invalid remaining characters. checkText(format.substring(i)); formatParts.add(StringPart.of(position, format.substring(i))); break; } } final Set counted = new HashSet<>(); int count = 1; // Initialize the argument count for (StringFormatPart stringFormatPart : formats) { if (stringFormatPart.conversion().isLineSeparator() || stringFormatPart.conversion().isPercent()) continue; if (stringFormatPart.index() > 0) { if (counted.add(stringFormatPart.index())) { argumentCount++; } } else if (stringFormatPart.index() == 0) { if (!counted.contains(count)) { argumentCount++; counted.add(count); count++; } } } } /** * Checks text to make sure we don't have extra garbage. * * @param text the text to check. */ private static void checkText(final String text) { final int index; // If there are any '%' in the given string, we got a bad format // specifier. if ((index = text.indexOf('%')) != -1) { final char c = (index > text.length() - 2 ? '%' : text.charAt(index + 1)); throw new UnknownFormatConversionException(String.valueOf(c)); } } private static > Set getOrAdd(final Map> map, final K key) { Set set = map.get(key); if (set == null) { set = new TreeSet<>(); map.put(key, set); } return set; } } StringPart.java000066400000000000000000000041011356560461700355210ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; /** * Represents the string portions of a format string. *

* Date: 13.06.2011 * * @author James R. Perkins */ class StringPart extends AbstractFormatPart { private final int position; private final String part; /** * Creates a new string part. * * @param position the position. * @param part the string. */ public StringPart(final int position, final String part) { this.position = position; this.part = part; } /** * Creates a new string part. * * @param position the position. * @param part the string. * * @return the string part. */ public static StringPart of(final int position, final String part) { return new StringPart(position, part); } @Override public int index() { return STRING; } @Override public int position() { return position; } @Override public String part() { return part; } } ValidationMessage.java000066400000000000000000000070461356560461700370360ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.tools.Diagnostic; import org.jboss.logging.processor.model.DelegatingElement; /** * Date: 12.08.2011 * * @author James R. Perkins */ public interface ValidationMessage { /** * Validation message type enum. */ enum Type { ERROR, WARN } /** * The type of the message. * * @return the type of the message. */ Type type(); /** * Returns the element that caused the error. * * @return the element that caused the error. */ Element getElement(); /** * The annotation the error occurred on. * * @return the annotation the error occurred on or {@code null} if this was not an annotation error */ AnnotationMirror getAnnotationMirror(); /** * The value of the annotation which caused the error. * * @return the value of the annotation or {@code null} */ AnnotationValue getAnnotationValue(); /** * Returns the error message. * * @return the error message. */ String getMessage(); /** * Prints the message and returns {@code true} if the message was an error message. * * @param messager the messager used to print the message * * @return {@code true} if this was an error message otherwise {@code false} */ default boolean printMessage(final Messager messager) { boolean error = false; Element element = getElement(); element = (element instanceof DelegatingElement ? ((DelegatingElement) element).getDelegate() : element); final AnnotationMirror annotationMirror = getAnnotationMirror(); final AnnotationValue annotationValue = getAnnotationValue(); final Diagnostic.Kind kind; if (type() == Type.ERROR) { kind = Diagnostic.Kind.ERROR; error = true; } else { kind = Diagnostic.Kind.WARNING; } if (annotationMirror == null) { messager.printMessage(kind, getMessage(), element); } else if (annotationValue == null) { messager.printMessage(kind, getMessage(), element, annotationMirror); } else { messager.printMessage(kind, getMessage(), element, annotationMirror, annotationValue); } return error; } } ValidationMessageFactory.java000066400000000000000000000122541356560461700403630ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; /** * Date: 12.08.2011 * * @author James R. Perkins */ public final class ValidationMessageFactory { /** * Private constructor for factory. */ private ValidationMessageFactory() { } public static ValidationMessage createError(final Element element, final String message) { return new ValidationErrorMessage(element, message, null, null); } public static ValidationMessage createError(final Element element, final String format, final Object... args) { return new ValidationErrorMessage(element, String.format(format, args), null, null); } public static ValidationMessage createError(final Element element, final AnnotationMirror annotationMirror, final String message) { return new ValidationErrorMessage(element, message, annotationMirror, null); } public static ValidationMessage createError(final Element element, final AnnotationMirror annotationMirror, final String format, final Object... args) { return new ValidationErrorMessage(element, String.format(format, args), annotationMirror, null); } public static ValidationMessage createError(final Element element, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue, final String message) { return new ValidationErrorMessage(element, message, annotationMirror, annotationValue); } public static ValidationMessage createError(final Element element, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue, final String format, final Object... args) { return new ValidationErrorMessage(element, String.format(format, args), annotationMirror, annotationValue); } public static ValidationMessage createWarning(final Element element, final String message) { return new ValidationWarningMessage(element, message, null, null); } public static ValidationMessage createWarning(final Element element, final String format, final Object... args) { return new ValidationWarningMessage(element, String.format(format, args), null, null); } private static abstract class AbstractValidationMessage implements ValidationMessage { private final Element element; private final String message; private final AnnotationMirror annotationMirror; private final AnnotationValue annotationValue; AbstractValidationMessage(final Element element, final String message, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue) { this.element = element; this.message = message; this.annotationMirror = annotationMirror; this.annotationValue = annotationValue; } @Override public final Element getElement() { return element; } @Override public final String getMessage() { return message; } @Override public AnnotationMirror getAnnotationMirror() { return annotationMirror; } @Override public AnnotationValue getAnnotationValue() { return annotationValue; } } private static class ValidationErrorMessage extends AbstractValidationMessage { private ValidationErrorMessage(final Element element, final String message, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue) { super(element, message, annotationMirror, annotationValue); } @Override public Type type() { return Type.ERROR; } } private static class ValidationWarningMessage extends AbstractValidationMessage { private ValidationWarningMessage(final Element element, final String message, final AnnotationMirror annotationMirror, final AnnotationValue annotationValue) { super(element, message, annotationMirror, annotationValue); } @Override public Type type() { return Type.WARN; } } } Validator.java000066400000000000000000000772321356560461700353700ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createError; import static org.jboss.logging.processor.validation.ValidationMessageFactory.createWarning; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.function.BiFunction; import java.util.function.Function; import javax.annotation.processing.ProcessingEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.ConstructType; import org.jboss.logging.annotations.LoggingClass; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Once; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Producer; import org.jboss.logging.annotations.Signature; import org.jboss.logging.annotations.Suppressed; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; import org.jboss.logging.processor.model.MessageInterface; import org.jboss.logging.processor.model.MessageMethod; import org.jboss.logging.processor.model.Parameter; import org.jboss.logging.processor.model.ReturnType; import org.jboss.logging.processor.model.ThrowableType; import org.jboss.logging.processor.util.ElementHelper; /** * Date: 12.08.2011 * * @author James R. Perkins */ public final class Validator { private static final Collection AVAILABLE_LANGUAGES = new HashSet<>(Arrays.asList(Locale.getISOLanguages())); private final MessageIdValidator messageIdValidator; private final IdLengthValidator idLengthValidator; private final IdRangeValidator idRangeValidator; private final ProcessingEnvironment processingEnv; private final Elements elements; private final Types types; public Validator(final ProcessingEnvironment processingEnv) { messageIdValidator = new MessageIdValidator(); idLengthValidator = new IdLengthValidator(); idRangeValidator = new IdRangeValidator(); this.processingEnv = processingEnv; this.elements = processingEnv.getElementUtils(); this.types = processingEnv.getTypeUtils(); } /** * Validates the message interface and returns a collection of validation messages or an empty collection. * * @param messageInterface the message interface to validate. * * @return a collection of validation messages or an empty collection. */ public final Collection validate(final MessageInterface messageInterface) { final List messages = new ArrayList<>(); String locale = null; if (messageInterface.isAnnotatedWith(MessageBundle.class)) { // Get all messageMethods except logger interface messageMethods final Set messageMethods = getAllMethods(messageInterface); messages.addAll(validateCommon(messageInterface, messageMethods)); messages.addAll(validateBundle(messageMethods)); locale = messageInterface.getAnnotation(MessageBundle.class).rootLocale(); } else if (messageInterface.isAnnotatedWith(MessageLogger.class)) { // Get all messageMethods except logger interface messageMethods final Set messageMethods = getAllMethods(messageInterface); messages.addAll(validateCommon(messageInterface, messageMethods)); messages.addAll(validateLogger(messageMethods)); locale = messageInterface.getAnnotation(MessageLogger.class).rootLocale(); } else { messages.add(createError(messageInterface, "Message interface %s is not a message bundle or message logger.", messageInterface.name())); } // Check the locale is in the list of available locales if (locale != null && !locale.isEmpty() && !AVAILABLE_LANGUAGES.contains(Locale.forLanguageTag(locale).getLanguage())) { // Only warn as there may be a change the locale exists on the target runtime messages.add(createWarning(messageInterface, "The locale '%s' may be invalid. The target runtime must " + "include this locale to ensure formatting is handled correctly.", locale)); } return messages; } /** * Validate common attributes to all interfaces. * * @param messageInterface the interface. * @param messageMethods the messageMethods to validate. * * @return a collection of validation messages. */ private Collection validateCommon(final MessageInterface messageInterface, final Set messageMethods) { final List messages = new ArrayList<>(); final Map methodNames = new HashMap<>(); messages.addAll(idLengthValidator.validate(messageInterface)); messages.addAll(idRangeValidator.validate(messageInterface)); for (MessageMethod messageMethod : messageMethods) { // Check for checked exceptions thrown on the interface messageMethod for (ThrowableType throwableType : messageMethod.thrownTypes()) { if (throwableType.isChecked()) { messages.add(createError(messageMethod, "Interface message methods cannot throw checked exceptions.")); } } final MessageMethod.Message message = messageMethod.message(); if (message == null) { messages.add(createError(messageMethod, "All message bundles and message logger message methods must have or inherit a message.")); continue; } // Check the message id if (message.hasId()) { // Make sure the message id is greater than 0 if (message.id() < 0) { messages.add(createError(messageMethod, "Message id %d is invalid. Must be greater than 0 or inherit another valid id.", message.id())); } else { messages.addAll(messageIdValidator.validate(messageInterface, messageMethod)); } } final FormatValidator formatValidator = FormatValidatorFactory.create(messageMethod); if (formatValidator.isValid()) { final int paramCount = messageMethod.formatParameterCount(); if (messageMethod.formatParameterCount() != formatValidator.argumentCount()) { messages.add(createError(messageMethod, "Parameter count does not match for format '%s'. Required: %d Provided: %d", formatValidator.format(), formatValidator.argumentCount(), paramCount)); } final Map positions = new TreeMap<>(); boolean validatePositions = false; for (Parameter parameter : messageMethod.parameters()) { // Validate the transform parameter if (parameter.isAnnotatedWith(Transform.class)) { validateTransform(messages, parameter, parameter.getAnnotation(Transform.class)); } // Validate the POS annotated parameters if (parameter.isAnnotatedWith(Pos.class)) { validatePositions = true; final Pos pos = parameter.getAnnotation(Pos.class); final Transform[] transforms = pos.transform(); if (transforms != null && transforms.length > 0) { if (pos.value().length != transforms.length) { messages.add(createError(parameter, "Positional parameters with transforms must have an equal number of positions and transforms.")); } else { for (Transform transform : transforms) { validateTransform(messages, parameter, transform); } } } // Validate the positions final Set usedPositions = new HashSet<>(); for (int position : pos.value()) { if (usedPositions.contains(position)) { messages.add(createError(parameter, "Position '%d' already used for this parameter.", position)); } else { usedPositions.add(position); } if (positions.containsKey(position)) { messages.add(createError(parameter, "Position '%d' already defined on parameter '%s'", position, positions.get(position).name())); } else { positions.put(position, parameter); } } } // Validate the @Suppressed parameter is on a message bundle, the return type is an exception and the parameter is an exception if (parameter.isAnnotatedWith(Suppressed.class)) { if (!messageMethod.returnType().isThrowable()) { messages.add(createError(messageMethod, "The @Suppressed parameter annotation can only be used with message bundle methods that return an exception.")); } if (!isTypeAssignableFrom(parameter, Throwable.class)) { messages.add(createError(parameter, "The parameter annotated with @Suppressed must be assignable to a Throwable type.")); } } } // Check for missing indexed parameters if (validatePositions) { for (int i = 0; i < messageMethod.formatParameterCount(); i++) { final int positionIndex = i + 1; if (!positions.containsKey(positionIndex)) { messages.add(createError(messageMethod, "Missing parameter with position '%d' defined.", positionIndex)); } } } } else { messages.add(createError(messageMethod, formatValidator.summaryMessage())); } // Make sure there is only one @Message annotation per messageMethod name. if (!messageMethod.inheritsMessage()) { final String key = messageMethod.name() + messageMethod.formatParameterCount(); if (methodNames.containsKey(key)) { final MessageMethod previousMethod = methodNames.get(key); messages.add(createError(previousMethod, "Only one message with the same format parameters is allowed.")); messages.add(createError(messageMethod, "Only one message with the same format parameters is allowed.")); } else { methodNames.put(key, messageMethod); } } // Validate the parameters messages.addAll(validateParameters(messageMethod)); // Validate property annotations messages.addAll(PropertyValidator.validate(processingEnv, messageMethod)); } return messages; } private void validateTransform(final List messages, final Parameter parameter, final Transform transform) { final List transformTypes = Arrays.asList(transform.value()); // If annotated with @Transform, must be an Object, primitives are not allowed if (parameter.isPrimitive()) { messages.add(createError(parameter, "Parameters annotated with @Transform cannot be primitives.")); } else if (transformTypes.contains(TransformType.GET_CLASS) && transformTypes.contains(TransformType.SIZE)) { messages.add(createError(parameter, "Transform type '%s' not allowed with type '%s'", TransformType.GET_CLASS, TransformType.SIZE)); } else if (transformTypes.contains(TransformType.HASH_CODE) && transformTypes.contains(TransformType.SIZE)) { messages.add(createError(parameter, "Transform type '%s' not allowed with type '%s'", TransformType.HASH_CODE, TransformType.SIZE)); } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE) && transformTypes.contains(TransformType.SIZE)) { messages.add(createError(parameter, "Transform type '%s' not allowed with type '%s'", TransformType.IDENTITY_HASH_CODE, TransformType.SIZE)); } else if (transformTypes.contains(TransformType.IDENTITY_HASH_CODE) && transformTypes.contains(TransformType.HASH_CODE)) { messages.add(createError(parameter, "Transform type '%s' not allowed with type '%s'", TransformType.IDENTITY_HASH_CODE, TransformType.HASH_CODE)); } else if (transformTypes.contains(TransformType.SIZE)) { if (!(parameter.isArray() || parameter.isVarArgs() || parameter.isSubtypeOf(Map.class) || parameter.isSubtypeOf(Collection.class) || parameter.isSubtypeOf(CharSequence.class))) { messages.add(createError(parameter, "Invalid type (%s) for %s. Must be an array, %s, %s or %s.", parameter.asType(), TransformType.SIZE, Collection.class.getName(), Map.class.getName(), CharSequence.class.getName())); } } } private Collection validateParameters(final MessageMethod messageMethod) { final List messages = new ArrayList<>(); boolean foundCause = false; boolean producerFound = false; for (Parameter parameter : messageMethod.parameters()) { if (parameter.isAnnotatedWith(Cause.class)) { if (foundCause) { messages.add(createError(messageMethod, "Only one cause parameter is allowed.")); } else { foundCause = true; } } if (parameter.isAnnotatedWith(LoggingClass.class)) { if (!parameter.isSameAs(Class.class)) { messages.add(createError(parameter, "Parameter %s annotated with @LoggingClass on method %s must be of type %s.", parameter.name(), messageMethod.name(), Class.class.getName())); } } if (parameter.isAnnotatedWith(Producer.class)) { final boolean isFunction = parameter.isSubtypeOf(Function.class); final boolean isBiFunction = parameter.isSubtypeOf(BiFunction.class); // Check the type arguments final TypeMirror requiredReturnType = messageMethod.returnType().resolvedType(); final List typeArgs = ElementHelper.getTypeArguments(parameter); final int size = typeArgs.size(); if (isFunction) { if (size == 2) { final TypeMirror message = typeArgs.get(0); final TypeMirror returnType = typeArgs.get(1); if (!isTypeAssignableFrom(message, String.class)) { messages.add(createError(parameter, "The type %s must be assignable to a String.", message)); } if (!isTypeAssignableFrom(returnType, requiredReturnType)) { messages.add(createError(parameter, "The return type parameter of the function " + "must be assignable from %s", requiredReturnType)); } } else { messages.add(createError(parameter, "The type parameters could not be validated for the " + "function. The first type argument of the function must be a String and the second type " + "parameter must be the same as or a super type of %s.", requiredReturnType)); } } else if (isBiFunction) { if (size == 3) { final TypeMirror returnType = typeArgs.get(2); final TypeMirror first = typeArgs.get(0); final TypeMirror second = typeArgs.get(1); if (!isTypeAssignableFrom(first, String.class) && !types.isSubtype(first, ElementHelper.toType(elements, Throwable.class))) { messages.add(createError(parameter, "The first type type parameter for %s " + "must be assignable to a String or a super type of a Throwable.", parameter.asType())); } if (!isTypeAssignableFrom(second, String.class) && !types.isSubtype(second, ElementHelper.toType(elements, Throwable.class))) { messages.add(createError(parameter, "The second type parameter for %s " + "must be assignable to a String or a super type of a Throwable.", parameter.asType())); } if (!isTypeAssignableFrom(returnType, requiredReturnType)) { messages.add(createError(parameter, "The return type parameter of the function " + "must be assignable from %s", requiredReturnType)); } if (messageMethod.hasCause()) { // Make sure the cause parameter can be assigned to the cause parameter for the BiFunction if (types.isSubtype(first, ElementHelper.toType(elements, Throwable.class)) && !isTypeAssignableFrom(messageMethod.cause().asType(), first)) { messages.add(createError(parameter, "The first parameter type, %s, of the BiFunction must be assignable to the cause %s.", first, messageMethod.cause().asType())); } if (types.isSubtype(second, ElementHelper.toType(elements, Throwable.class)) && !isTypeAssignableFrom(messageMethod.cause().asType(), second)) { messages.add(createError(parameter, "The second parameter type, %s, of the BiFunction must be assignable to the cause %s.", second, messageMethod.cause().asType())); } } else { messages.add(createWarning(messageMethod, "No @Cause parameter was found on the method. " + "A null value will always be passed as the cause parameter to the BiFunction.")); } } else { messages.add(createError(parameter, "The type parameters could not be validated for the " + "function. The first and second type arguments of the function must be a String " + "or a super type of Throwable. The third type parameter must be the same as or " + "a super type of %s.", requiredReturnType)); } } else { messages.add(createError(parameter, "Parameter annotated with %s must be a %s or %s type", Producer.class.getName(), Function.class.getName(), BiFunction.class.getName())); } if (producerFound) { messages.add(createError(messageMethod, "Only one parameter is allowed to be annotated with %s.", Producer.class.getName())); } producerFound = true; } } return messages; } /** * Validate message bundle messageMethods. * * @param messageMethods the messageMethods to validate. * * @return a collection of the validation messages. */ private Collection validateBundle(final Set messageMethods) { final List messages = new ArrayList<>(); for (MessageMethod messageMethod : messageMethods) { messages.addAll(validateBundleMethod(messageMethod)); } return messages; } private Collection validateBundleMethod(final MessageMethod messageMethod) { final List messages = new ArrayList<>(); // The return type must be a Throwable, String or a Supplier that returns a Throwable or String final ReturnType returnType = messageMethod.returnType(); final TypeMirror returnTypeMirror = returnType.asType(); final TypeMirror resolvedReturnType = returnType.resolvedType(); if (returnTypeMirror.getKind() == TypeKind.VOID || returnTypeMirror.getKind().isPrimitive()) { messages.add(createError(messageMethod, "Message bundle messageMethod %s has an invalid return type. Cannot be void or a primitive.", messageMethod.name())); } else if (returnType.isThrowable()) { final ThrowableType throwableReturnType = returnType.throwableReturnType(); if (throwableReturnType.useConstructionParameters()) { // Check for a matching constructor final Signature signature = messageMethod.getAnnotation(Signature.class); if (signature != null) { final List args = ElementHelper.getClassArrayAnnotationValue(messageMethod, Signature.class, "value"); // Validate the constructor exists if (!ElementHelper.hasConstructor(types, returnType, args)) { messages.add(createError(messageMethod, "Could not find constructor for %s with arguments %s", messageMethod.asType(), args)); } final int messageIndex = signature.messageIndex(); // Note that the messageIndex is required and must be 0 or greater if (messageIndex < 0) { messages.add(createError(messageMethod, "A messageIndex of 0 or greater is required. Value %d is invalid.", messageIndex)); } } // Validate the construct type is valid if (messageMethod.isAnnotatedWith(ConstructType.class)) { final TypeElement constructTypeValue = ElementHelper.getClassAnnotationValue(messageMethod, ConstructType.class); // Shouldn't be null if (constructTypeValue == null) { messages.add(createError(messageMethod, "Class not defined for the ConstructType")); } else { if (!types.isAssignable(constructTypeValue.asType(), returnType.asType())) { messages.add(createError(messageMethod, "The requested type %s can not be assigned to %s.", constructTypeValue.asType(), returnType.asType())); } } } } else if (!throwableReturnType.useConstructionParameters() && !messageMethod.parametersAnnotatedWith(Param.class).isEmpty()) { messages.add(createError(messageMethod, "MessageMethod does not have an usable constructor for the return type %s.", returnType.name())); } else { final boolean hasMessageConstructor = (throwableReturnType.hasStringAndThrowableConstructor() || throwableReturnType.hasThrowableAndStringConstructor() || throwableReturnType.hasStringConstructor()); final boolean usableConstructor = (throwableReturnType.hasDefaultConstructor() || throwableReturnType.hasStringAndThrowableConstructor() || throwableReturnType.hasStringConstructor() || throwableReturnType.hasThrowableAndStringConstructor() || throwableReturnType.hasThrowableConstructor()); if (!messageMethod.parametersAnnotatedWith(Producer.class).isEmpty()) { if (messageMethod.isAnnotatedWith(ConstructType.class)) { messages.add(createError(messageMethod, "Method annotated with %s cannot have a parameter annotated with %s.", ConstructType.class.getName(), Producer.class.getName())); } final TypeMirror erasure = types.erasure(resolvedReturnType); if (!isTypeAssignableFrom(erasure, Throwable.class)) { messages.add(createError(messageMethod, "The return type must be a subclass of a java.lang.Throwable")); } } else if (!usableConstructor) { messages.add(createError(messageMethod, "MessageMethod does not have an usable constructor for the return type %s.", returnType.name())); } else if (!hasMessageConstructor) { // Check to see if there is no message constructor messages.add(createWarning(messageMethod, "The message cannot be set via the throwable constructor and will be ignored.")); } } } else { if (!isTypeAssignableFrom(resolvedReturnType, String.class) && !returnType.isThrowable()) { messages.add(createError(messageMethod, "Message bundle method (%s) has an invalid return type of %s. " + "Return types must be a String, a subtype of Throwable or a java.util.function.Supplier which " + "returns a String or a subtype of Throwable.", messageMethod.name(), returnTypeMirror)); } if (messageMethod.isAnnotatedWith(ConstructType.class)) { messages.add(createError(messageMethod, "ConstructType annotation requires a throwable or supplier which produces a throwable return type")); } } return messages; } /** * Validate message logger messageMethods. * * @param messageMethods the messageMethods to validate. * * @return a collection of the validation messages. */ private Collection validateLogger(final Set messageMethods) { final List messages = new ArrayList<>(); for (MessageMethod messageMethod : messageMethods) { if (messageMethod.isLoggerMethod()) { messages.addAll(validateLoggerMethod(messageMethod)); } else { messages.addAll(validateBundleMethod(messageMethod)); if (messageMethod.isAnnotatedWith(Once.class)) { messages.add(createError(messageMethod, "Only @LogMessage method can be annoted with @Once")); } } } return messages; } private Collection validateLoggerMethod(final MessageMethod messageMethod) { final List messages = new ArrayList<>(); // The return type must be void if (messageMethod.returnType().asType().getKind() != TypeKind.VOID) { messages.add(createError(messageMethod, "Message logger methods can only have a void return type.")); } return messages; } /** * Finds all methods for the given interface, but ignores logger interface methods. * * @param messageInterface the interface to find all methods for. * * @return a set of all the methods (exception logger interface methods) the interface must implement. */ private Set getAllMethods(final MessageInterface messageInterface) { if (messageInterface.isAnnotatedWith(MessageBundle.class) || messageInterface.isAnnotatedWith(MessageLogger.class)) { final Set messageMethods = new LinkedHashSet<>(); for (MessageMethod messageMethod : messageInterface.methods()) { messageMethods.add(messageMethod); } for (MessageInterface msgInterface : messageInterface.extendedInterfaces()) { messageMethods.addAll(getAllMethods(msgInterface)); } return messageMethods; } return Collections.emptySet(); } /** * Checks the element type, if an array the type of the array is checked, against the class. If the element type is * assignable to the class type. * * @param element the element to test * @param type the type the element needs to be assignable to * * @return {@code true} if the element type is assignable to the class type, otherwise {@code false} */ private boolean isTypeAssignableFrom(final Element element, final Class type) { return isTypeAssignableFrom(element.asType(), type); } /** * Checks the type, if an array the type of the array is checked, against the class. If the element type is * assignable to the class type. * * @param typeMirror the type to test * @param type the type the element needs to be assignable to * * @return {@code true} if the element type is assignable to the class type, otherwise {@code false} */ private boolean isTypeAssignableFrom(final TypeMirror typeMirror, final Class type) { return isTypeAssignableFrom(typeMirror, ElementHelper.toType(elements, type)); } /** * Checks the type, if an array the type of the array is checked, against the class. If the element type is * assignable to the class type. * * @param typeMirror the type to test * @param type the type the element needs to be assignable to * * @return {@code true} if the element type is assignable to the class type, otherwise {@code false} */ private boolean isTypeAssignableFrom(final TypeMirror typeMirror, final TypeMirror type) { TypeMirror t = typeMirror; if (t.getKind() == TypeKind.ARRAY) { t = ((ArrayType) t).getComponentType(); } if (types.isAssignable(types.erasure(t), ElementHelper.toType(elements, Collection.class))) { // We only need the first type t = types.erasure(ElementHelper.getTypeArguments(t).iterator().next()); } return types.isAssignable(t, type); } } jboss-logging-tools-2.2.1.Final/processor/src/main/resources/000077500000000000000000000000001356560461700242275ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/resources/META-INF/000077500000000000000000000000001356560461700253675ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/resources/META-INF/LICENSE.txt000066400000000000000000000636421356560461700272250ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! jboss-logging-tools-2.2.1.Final/processor/src/main/resources/META-INF/services/000077500000000000000000000000001356560461700272125ustar00rootroot00000000000000javax.annotation.processing.Processor000066400000000000000000000000651356560461700364720ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/resources/META-INF/servicesorg.jboss.logging.processor.apt.LoggingToolsProcessorjboss-logging-tools-2.2.1.Final/processor/src/main/resources/schema/000077500000000000000000000000001356560461700254675ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/main/resources/schema/logging-report_1_0.xsd000066400000000000000000000104311356560461700316040ustar00rootroot00000000000000 The optional title of the report. A group of messages for a logger or message bundle interface. The fully qualified class name of the interface. Represents a message from a logger or message bundle interface. The id associated with the message if one is present. An optional URL to a resolution document for the error. The log level if this is a logger message. The return type if this is a message bundle message. jboss-logging-tools-2.2.1.Final/processor/src/test/000077500000000000000000000000001356560461700222505ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/000077500000000000000000000000001356560461700231715ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/000077500000000000000000000000001356560461700237605ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/000077500000000000000000000000001356560461700251005ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/000077500000000000000000000000001356560461700265265ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/000077500000000000000000000000001356560461700305455ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/000077500000000000000000000000001356560461700325035ustar00rootroot00000000000000AbstractLoggerTest.java000066400000000000000000000046771356560461700370500ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.junit.AfterClass; import org.junit.BeforeClass; /** * @author James R. Perkins */ public abstract class AbstractLoggerTest { static final String PROJECT_CODE = "LOGL"; static final QueuedMessageHandler HANDLER = new QueuedMessageHandler(); static final String CATEGORY = AbstractLoggerTest.class.getPackage().getName(); static final String LOGGER_ID_PATTERN = "LOG.*[0-9]:\\s"; private static final org.jboss.logmanager.Logger LOGGER = org.jboss.logmanager.Logger.getLogger(CATEGORY); @BeforeClass public static void installHandler() { LOGGER.addHandler(HANDLER); } @AfterClass public static void uninstallHandler() { LOGGER.removeHandler(HANDLER); HANDLER.close(); } protected String parseStringLoggerId(final String message) { final Pattern p = Pattern.compile(LOGGER_ID_PATTERN); final Matcher m = p.matcher(message); if (m.find()) { return m.group(); } return null; } protected int parseLoggerId(final String message) { final String stringId = parseStringLoggerId(message); if (stringId != null) { final String s = message.replaceAll("([a-zA-z]|:.*)", ""); return Integer.parseInt(s); } return 0; } } DefaultLogger.java000077500000000000000000000070051356560461700360200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * */ package org.jboss.logging.processor.generated; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.FormatWith; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; /** * @author James R. Perkins Jr. (jrp) */ @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) @ValidIdRange(min = 100, max = 150) interface DefaultLogger extends BasicLogger { final String TEST_MSG = "No format%n"; /** * The default logger. */ DefaultLogger LOGGER = Logger.getMessageLogger(DefaultLogger.class, AbstractLoggerTest.CATEGORY); // Used to test the ambiguous log field in the DelegatingBasicLogger DefaultLogger log = Logger.getMessageLogger(DefaultLogger.class, AbstractLoggerTest.CATEGORY); static DefaultLogger get(final String category) { return Logger.getMessageLogger(DefaultLogger.class, category); } default void initialized() { LOGGER.info("Initialized"); } @LogMessage(level = Level.INFO) @Message(id = 100, value = "Hello %s.") void hello(String name); @LogMessage(level = Level.INFO) @Message(id = 101, value = "How are you %s?") void howAreYou(String name); @LogMessage(level = Level.INFO) @Message(id = 102, format = Format.NO_FORMAT, value = TEST_MSG) void noFormat(); @LogMessage(level = Level.INFO) @Message(id = 103, format = Format.NO_FORMAT, value = TEST_MSG) void noFormatWithCause(@Cause Throwable cause); @LogMessage(level = Level.INFO) @Message(id = 104, value = "Test Message: %s") void formatWith(@FormatWith(CustomFormatter.class) String msg); @LogMessage(level = Level.ERROR) @Message(id = 105, value = "Valid values are; %s") void invalidSelection(String... validValues); @LogMessage(level = Level.ERROR) @Message(id = Message.INHERIT, value = "Invalid value '%s'. Valid values are; %s") void invalidSelection(String selected, String[] validValues); static class CustomFormatter { private final String msg; public CustomFormatter(final String msg) { this.msg = msg; } @Override public String toString() { return String.format("Message: %s", msg); } } } DefaultMessages.java000077500000000000000000000032251356560461700363500ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * */ package org.jboss.logging.processor.generated; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.ValidIdRange; /** * @author James R. Perkins Jr. (jrp) */ @MessageBundle(projectCode = AbstractLoggerTest.PROJECT_CODE) @ValidIdRange(min = 10000, max = 10050) interface DefaultMessages { @Message(id = 10000, value = "Hello %s.") String hello(String name); @Message(id = 10001, value = "How are you %s?") String howAreYou(String name); @Message(id = 10002, value = "Username %s is invalid.") RuntimeException invalidUser(String name); } ExpressionLogger.java000066400000000000000000000042021356560461700365640ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.annotations.ValidIdRanges; /** * @author James R. Perkins */ @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) public interface ExpressionLogger { ExpressionLogger LOGGER = Logger.getMessageLogger(ExpressionLogger.class, AbstractLoggerTest.CATEGORY); @LogMessage(level = Level.INFO) @Message(value = "${test.property}") void logProperty(); @LogMessage(level = Level.INFO) @Message(value = "${test.property.nonexistent:default value}") void logPropertyDefault(); @Message(value = "${test.property}") String property(); @Message(value = "${test.property.nonexistent:default value}") String propertyDefault(); } ExpressionMessagesTest.java000066400000000000000000000035011356560461700377550ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class ExpressionMessagesTest extends AbstractLoggerTest { @After public void clearHandler() { HANDLER.close(); } @Test public void testExpressions() throws Exception { ExpressionLogger.LOGGER.logProperty(); Assert.assertEquals("test property value", HANDLER.getMessage()); ExpressionLogger.LOGGER.logPropertyDefault(); Assert.assertEquals("default value", HANDLER.getMessage()); Assert.assertEquals("test property value", ExpressionLogger.LOGGER.property()); Assert.assertEquals("default value", ExpressionLogger.LOGGER.propertyDefault()); } } ExtendedLogger.java000066400000000000000000000031751356560461700361750ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; /** * @author James R. Perkins */ @ValidIdRange(min = 1000, max = 1500) @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) public interface ExtendedLogger extends DefaultLogger { @LogMessage(level = Level.ERROR) @Message(id = 1000, value = "Extension error") void extensionError(); } GeneratedSkeletonTest.java000066400000000000000000000113531356560461700375350ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2019, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Date; import java.util.Properties; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class GeneratedSkeletonTest { private static final String DIR = System.getProperty("test.skeleton.file.path"); @Test public void testLoggerIndexes() throws Exception { final Properties properties = resolveProperties(StringFormatLogger.class); Assert.assertEquals("String %1$s integer %2$d", properties.getProperty("stringInt")); Assert.assertEquals("Duke's Birthday: %1$tm % type) throws IOException { final Path file = findFile(type); final Properties properties = new Properties(); try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { properties.load(reader); } return properties; } private static Path findFile(final Class type) { final String filePath = type.getName().replace('.', File.separatorChar) + ".i18n.properties"; Assert.assertNotNull("Could not find the test.skeleton.file.path", DIR); final Path file = Paths.get(DIR, filePath); Assert.assertTrue(String.format("File %s was not found.", file), Files.exists(file)); return file; } } GeneratedSourceAnalysisTest.java000066400000000000000000000405231356560461700407160ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.jboss.forge.roaster.Roaster; import org.jboss.forge.roaster.model.Method; import org.jboss.forge.roaster.model.Named; import org.jboss.forge.roaster.model.Type; import org.jboss.forge.roaster.model.source.FieldSource; import org.jboss.forge.roaster.model.source.JavaClassSource; import org.jboss.forge.roaster.model.source.JavaInterfaceSource; import org.jboss.forge.roaster.model.source.MethodSource; import org.jboss.forge.roaster.model.source.ParameterSource; import org.jboss.logging.DelegatingBasicLogger; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * @author James R. Perkins */ public class GeneratedSourceAnalysisTest { private static String TEST_SRC_PATH = null; private static String TEST_GENERATED_SRC_PATH = null; private static final Map LOCALE_CONSTANTS = new LinkedHashMap<>(); static { LOCALE_CONSTANTS.put(Locale.CANADA, "Locale.CANADA"); LOCALE_CONSTANTS.put(Locale.CANADA_FRENCH, "Locale.CANADA_FRENCH"); LOCALE_CONSTANTS.put(Locale.CHINESE, "Locale.CHINESE"); LOCALE_CONSTANTS.put(Locale.ENGLISH, "Locale.ENGLISH"); LOCALE_CONSTANTS.put(Locale.FRANCE, "Locale.FRANCE"); LOCALE_CONSTANTS.put(Locale.FRENCH, "Locale.FRENCH"); LOCALE_CONSTANTS.put(Locale.GERMAN, "Locale.GERMAN"); LOCALE_CONSTANTS.put(Locale.GERMANY, "Locale.GERMANY"); LOCALE_CONSTANTS.put(Locale.ITALIAN, "Locale.ITALIAN"); LOCALE_CONSTANTS.put(Locale.ITALY, "Locale.ITALY"); LOCALE_CONSTANTS.put(Locale.JAPAN, "Locale.JAPAN"); LOCALE_CONSTANTS.put(Locale.JAPANESE, "Locale.JAPANESE"); LOCALE_CONSTANTS.put(Locale.KOREA, "Locale.KOREA"); LOCALE_CONSTANTS.put(Locale.KOREAN, "Locale.KOREAN"); LOCALE_CONSTANTS.put(Locale.SIMPLIFIED_CHINESE, "Locale.SIMPLIFIED_CHINESE"); LOCALE_CONSTANTS.put(Locale.TRADITIONAL_CHINESE, "Locale.TRADITIONAL_CHINESE"); LOCALE_CONSTANTS.put(Locale.UK, "Locale.UK"); LOCALE_CONSTANTS.put(Locale.US, "Locale.US"); } @BeforeClass public static void setUp() { TEST_SRC_PATH = System.getProperty("test.src.path"); TEST_GENERATED_SRC_PATH = System.getProperty("test.generated.src.path"); } @Test public void testBundles() throws Exception { compareBundle(DefaultMessages.class); compareBundle(ValidMessages.class); } @Test public void testLoggers() throws Exception { compareLogger(DefaultLogger.class); compareLogger(ExtendedLogger.class); compareLogger(ValidLogger.class); compareLogger(RootLocaleLogger.class); } @Test public void testGeneratedTranslations() throws Exception { compareTranslations(DefaultLogger.class); compareTranslations(DefaultMessages.class); compareTranslations(RootLocaleLogger.class); } @Test public void testRootLocale() throws Exception { JavaClassSource implementationSource = parseGenerated(RootLocaleLogger.class); FieldSource locale = implementationSource.getField("LOCALE"); Assert.assertNotNull("Expected a LOCALE field for " + implementationSource.getName(), locale); Assert.assertEquals("Locale.forLanguageTag(\"en-UK\")", locale.getLiteralInitializer()); implementationSource = parseGenerated(DefaultLogger.class); locale = implementationSource.getField("LOCALE"); Assert.assertNotNull("Expected a LOCALE field for " + implementationSource.getName(), locale); Assert.assertEquals("Locale.ROOT", locale.getLiteralInitializer()); } private void compareLogger(final Class intf) throws IOException { final JavaInterfaceSource interfaceSource = parseInterface(intf); final JavaClassSource implementationSource = parseGenerated(intf); compareCommon(interfaceSource, implementationSource); // Logger implementations should have a single constructor which accepts a org.jboss.logging.Logger final List> implementationMethods = implementationSource.getMethods(); final Optional> constructor = findConstructor(implementationMethods); Assert.assertTrue("No constructor found for " + implementationSource.getName(), constructor.isPresent()); final List> parameters = constructor.get().getParameters(); Assert.assertEquals("Found more than one parameter for " + implementationSource.getName() + ": " + parameters, 1, parameters.size()); final ParameterSource parameter = parameters.get(0); final Type type = parameter.getType(); Assert.assertEquals(Logger.class.getName(), type.getQualifiedName()); // If the logger is not extending the DelegatingBasicLogger there should be a protected final org.jboss.logging.Logger field if (!DelegatingBasicLogger.class.getName().equals(implementationSource.getSuperType())) { final FieldSource log = implementationSource.getField("log"); Assert.assertNotNull("Expected a log field in " + implementationSource.getName(), log); Assert.assertTrue("Expected the log field to be protected and final in " + implementationSource.getName(), log.isProtected() && log.isFinal()); } } private void compareBundle(final Class intf) throws IOException { final JavaInterfaceSource interfaceSource = parseInterface(intf); final JavaClassSource implementationSource = parseGenerated(intf); compareCommon(interfaceSource, implementationSource); // Message bundles should have an INSTANCE field final FieldSource instance = implementationSource.getField("INSTANCE"); Assert.assertNotNull("Expected an INSTANCE field in " + implementationSource.getName(), instance); Assert.assertTrue("Expected the instance field to be public, static and final in " + implementationSource.getName(), instance.isStatic() && instance.isFinal() && instance.isPublic()); // Expect a protected constructor with no parameters final Optional> constructor = findConstructor(implementationSource.getMethods()); Assert.assertTrue("No constructor found for " + implementationSource.getName(), constructor.isPresent()); final MethodSource c = constructor.get(); Assert.assertTrue("Expected the constructor parameters to be empty for " + implementationSource.getName(), c.getParameters().isEmpty()); Assert.assertTrue("Expected the constructor to be protected for " + implementationSource.getName(), c.isProtected()); } private void compareCommon(final JavaInterfaceSource interfaceSource, final JavaClassSource implementationSource) { final List> interfaceMethods = interfaceSource.getMethods(); final List> implementationMethods = implementationSource.getMethods(); // Validate the implementation has all the interface methods, note this should be the cause final Collection interfaceMethodNames = toNames(interfaceMethods); final Collection implementationMethodNames = toNames(implementationMethods); Assert.assertTrue(String.format("Implementation is missing methods from the interface:%n\timplementation: %s%n\tinterface:%s", implementationMethodNames, interfaceMethodNames), implementationMethodNames.containsAll(interfaceMethodNames)); // The generates source files should have a serialVersionUID with a value of one Assert.assertTrue("Expected a serialVersionUID field in " + implementationSource.getName(), implementationSource.hasField("serialVersionUID")); final FieldSource serialVersionUID = implementationSource.getField("serialVersionUID"); Assert.assertEquals("Expected serialVersionUID to be set to 1L in " + implementationSource.getName(), "1L", serialVersionUID.getLiteralInitializer()); // All bundles should have a getLoggingLocale() final MethodSource getLoggingLocale = implementationSource.getMethod("getLoggingLocale"); Assert.assertNotNull("Expected a getLoggingLocale() method in " + implementationSource.getName(), getLoggingLocale); Assert.assertTrue("Expected the getLoggingLocale() to be protected in " + implementationSource.getName(), getLoggingLocale.isProtected()); } private void compareTranslations(final Class intf) throws IOException { final JavaInterfaceSource interfaceSource = parseInterface(intf); final Collection implementations = parseGeneratedTranslations(intf); // Find the default source file final JavaClassSource superImplementationSource = parseGenerated(intf); for (JavaClassSource implementationSource : implementations) { compareTranslations(interfaceSource, superImplementationSource, implementationSource); } } private void compareTranslations(final JavaInterfaceSource interfaceSource, final JavaClassSource superImplementationSource, final JavaClassSource implementationSource) { // The implementations should not contain any methods from the interface final List interfaceMethods = interfaceSource.getMethods() .stream() .map(Named::getName) .collect(Collectors.toList()); final Collection found = new ArrayList<>(); for (MethodSource method : implementationSource.getMethods()) { if (interfaceMethods.contains(method.getName())) { found.add(method.getName()); } } Assert.assertTrue("Found methods in implementation that were in the interface " + implementationSource.getName() + " : " + found, found.isEmpty()); // The getLoggerLocale() should be overridden final MethodSource getLoggerLocale = implementationSource.getMethod("getLoggingLocale"); Assert.assertNotNull("Missing overridden getLoggingLocale() method " + implementationSource.getName(), getLoggerLocale); // If the file should have a locale constant, validate the constant is one of the Locale constants LOCALE_CONSTANTS.forEach((locale, constant) -> { if (implementationSource.getName().endsWith(locale.toString())) { // Get the LOCALE field final FieldSource localeField = implementationSource.getField("LOCALE"); Assert.assertNotNull("Expected a LOCALE field " + implementationSource.getName(), localeField); Assert.assertEquals("Expected the LOCALE to be set to " + constant + " in " + implementationSource.getName(), constant, localeField.getLiteralInitializer()); } }); // Get all the method names from the super class final List superMethods = superImplementationSource.getMethods() .stream() .filter(method -> !method.isConstructor()) .map(Named::getName) .collect(Collectors.toList()); // All methods in the translation implementation should be overrides of methods in the super class implementationSource.getMethods().forEach(method -> { if (!method.isConstructor()) { Assert.assertTrue(String.format("Expected method %s to be overridden in %s.", method.getName(), implementationSource.getName()), method.hasAnnotation(Override.class)); Assert.assertTrue(String.format("Expected method %s to override the super (%s) method in %s.", method.getName(), superImplementationSource.getName(), implementationSource.getName()), superMethods.contains(method.getName())); } }); } private Optional> findConstructor(final List> implementationMethods) { return implementationMethods.stream() .filter(Method::isConstructor) .findFirst(); } private Collection toNames(final List> methods) { return methods.stream() // Skip default methods, static methods and constructors .filter(m -> !m.isDefault() && !m.isStatic() && !m.isConstructor()) .map(Named::getName) .collect(Collectors.toList()); } private String packageToPath(final Package pkg) { String result = pkg.getName().replace('.', File.separatorChar); return result.endsWith(File.separator) ? result : result + File.separator; } private JavaClassSource parseGenerated(final Class intf) throws IOException { final Pattern pattern = Pattern.compile(Pattern.quote(intf.getSimpleName()) + "_\\$(logger|bundle)\\.java$"); // Find all the files that match final FileFilter filter = pathname -> pattern.matcher(pathname.getName()).find(); final File dir = new File(TEST_GENERATED_SRC_PATH, packageToPath(intf.getPackage())); final File[] files = dir.listFiles(filter); // There should only be one file Assert.assertNotNull("Did not find any implementation files for interface " + intf.getName(), files); Assert.assertEquals("Found more than one implementation for interface " + intf.getName() + " " + Arrays.asList(files), 1, files.length); return Roaster.parse(JavaClassSource.class, files[0]); } private Collection parseGeneratedTranslations(final Class intf) throws IOException { final Pattern pattern = Pattern.compile(Pattern.quote(intf.getSimpleName()) + "_\\$(logger|bundle)_.*\\.java$"); // Find all the files that match final FileFilter filter = pathname -> pattern.matcher(pathname.getName()).matches(); final File dir = new File(TEST_GENERATED_SRC_PATH, packageToPath(intf.getPackage())); final File[] files = dir.listFiles(filter); // There should only be one file Assert.assertNotNull("Did not find any implementation files for interface " + intf.getName(), files); Assert.assertTrue("Did not find any translation implementations for interface " + intf.getName(), files.length > 0); final Collection result = new ArrayList<>(); for (final File file : files) { result.add(Roaster.parse(JavaClassSource.class, file)); } return result; } private JavaInterfaceSource parseInterface(final Class intf) throws IOException { final File srcFile = new File(TEST_SRC_PATH, packageToPath(intf.getPackage()) + intf.getSimpleName() + ".java"); return Roaster.parse(JavaInterfaceSource.class, srcFile); } } LevelIdCheckTest.java000066400000000000000000000037111356560461700364130ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class LevelIdCheckTest extends AbstractLoggerTest { @After public void clearHandler() { HANDLER.close(); } @Test public void inheritedId() throws Exception { ValidLogger.LOGGER.processingError(); ValidLogger.LOGGER.processingError(new IllegalArgumentException()); ValidLogger.LOGGER.processingError(new IllegalArgumentException(), "generated"); ValidLogger.LOGGER.processingError(this, "invalid reference"); Assert.assertEquals(203, parseLoggerId(HANDLER.getMessage())); Assert.assertEquals(203, parseLoggerId(HANDLER.getMessage())); Assert.assertEquals(203, parseLoggerId(HANDLER.getMessage())); Assert.assertEquals(203, parseLoggerId(HANDLER.getMessage())); } } LogOnceLogger.java000066400000000000000000000047551356560461700357700ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.util.Collection; import java.util.Map; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Once; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; /** * @author James R. Perkins */ @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) public interface LogOnceLogger { public final LogOnceLogger LOGGER = Logger.getMessageLogger(LogOnceLogger.class, LogOnceLogger.class.getName()); @LogMessage(level = Level.WARN) @Once @Message("'%s' has been deprecated.") void deprecated(String key); @LogMessage(level = Level.WARN) @Once @Message("'%s' has been deprecated. Please use '%s'.") void deprecated(String key, String replacement); @LogMessage void deprecated(Member member); @LogMessage @Once @Message("Cache size changed to '%d'") void cacheSizeChanged(@Transform(TransformType.SIZE) Collection c); @LogMessage void cacheSizeChanged(@Transform(TransformType.SIZE) String... array); @LogMessage @Once void cacheSizeChanged(@Transform(TransformType.SIZE) Map map); } LogOnceTest.java000066400000000000000000000072301356560461700354570ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.lang.reflect.Method; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Assert; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; /** * @author James R. Perkins */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LogOnceTest extends AbstractLoggerTest { @After public void clearHandler() { HANDLER.close(); } @Test public void logOnce() throws Exception { LogOnceLogger.LOGGER.deprecated("test.property"); LogOnceLogger.LOGGER.deprecated("test.property"); Assert.assertEquals("Only one message should have been logged", 1, HANDLER.size()); LogOnceLogger.LOGGER.deprecated("test.property", "new.test.property"); Assert.assertEquals("Only one message should have been logged", 1, HANDLER.size()); final Method method = LogOnceTest.class.getMethod("logOnce"); LogOnceLogger.LOGGER.deprecated(method); LogOnceLogger.LOGGER.deprecated(method); Assert.assertEquals("The message should have been logged three times", 3, HANDLER.size()); } @Test public void newLogger() throws Exception { final LogOnceLogger logger = Logger.getMessageLogger(LogOnceLogger.class, CATEGORY); logger.deprecated("test.property"); Assert.assertEquals("No messages should have been logged", 0, HANDLER.size()); logger.deprecated("test.property", "new.test.property"); Assert.assertEquals("No messages should have been logged", 0, HANDLER.size()); } @Test public void transformTests() throws Exception { final List listCache = Arrays.asList("item1", "item2", "item3"); LogOnceLogger.LOGGER.cacheSizeChanged(listCache); LogOnceLogger.LOGGER.cacheSizeChanged(listCache); Assert.assertEquals("Only one message should have been logged", 1, HANDLER.size()); final Map mapCache = new HashMap<>(); for (int i = 0; i < 5; i++) { mapCache.put("item" + i, "value " + i); } LogOnceLogger.LOGGER.cacheSizeChanged(mapCache); Assert.assertEquals("Only one message should have been logged", 1, HANDLER.size()); LogOnceLogger.LOGGER.cacheSizeChanged("item1", "item2", "item3", "item4"); LogOnceLogger.LOGGER.cacheSizeChanged("item1", "item2", "item3", "item4", "item5", "item6"); Assert.assertEquals("The message should have been logged twice", 3, HANDLER.size()); } } LoggerVerificationTest.java000066400000000000000000000154501356560461700377160ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.Properties; import org.jboss.logging.Logger; import org.jboss.logging.processor.generated.DefaultLogger.CustomFormatter; import org.junit.After; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class LoggerVerificationTest extends AbstractLoggerTest { private static final String NAME = System.getProperty("user.name"); private static final String FILE_NAME_FORMAT = "DefaultLogger.i18n%s.properties"; @After public void clearHandler() { HANDLER.close(); } @Test public void defaultTest() throws Exception { final DefaultLogger logger = getLogger(Locale.ROOT); logger.hello(NAME); logger.howAreYou(NAME); logger.noFormat(); logger.noFormatWithCause(new IllegalArgumentException("No format cause")); final String msg = "This is a test message"; logger.formatWith(msg); final String[] values = {"A", "B", "C", "D"}; logger.invalidSelection("G", values); logger.invalidSelection("A", "B", "C", "D"); final Properties properties = findFile(String.format(FILE_NAME_FORMAT, "")); Assert.assertEquals(HANDLER.size(), properties.size()); compare("hello", properties, NAME); compare("howAreYou", properties, NAME); compare("noFormat", properties); compare("noFormatWithCause", properties); compare("formatWith", properties, new CustomFormatter(msg)); compare("invalidSelection.2", properties, "G", Arrays.toString(values)); compare("invalidSelection.1", properties, Arrays.toString(values)); } @Test public void germanTest() throws Exception { DefaultLogger logger = getLogger(Locale.GERMAN); logger.hello(NAME); logger.howAreYou(NAME); final Properties properties = findFile(String.format(FILE_NAME_FORMAT, "_de")); Assert.assertEquals(HANDLER.size(), properties.size()); compare("hello", properties, NAME); compare("howAreYou", properties, NAME); } @Test public void frenchTest() throws Exception { DefaultLogger logger = getLogger(Locale.FRENCH); logger.hello(NAME); logger.howAreYou(NAME); final Properties properties = findFile(String.format(FILE_NAME_FORMAT, "_fr")); Assert.assertEquals(HANDLER.size(), properties.size()); compare("hello", properties, NAME); compare("howAreYou", properties, NAME); } @Test public void spanishTest() throws Exception { DefaultLogger logger = getLogger(new Locale("es")); logger.hello(NAME); logger.howAreYou(NAME); final Properties properties = findFile(String.format(FILE_NAME_FORMAT, "_es")); Assert.assertEquals(HANDLER.size(), properties.size()); compare("hello", properties, NAME); compare("howAreYou", properties, NAME); } @Test public void japaneseTest() throws Exception { DefaultLogger logger = getLogger(new Locale("ja")); logger.hello(NAME); logger.howAreYou(NAME); final Properties properties = findFile(String.format(FILE_NAME_FORMAT, "_ja")); Assert.assertEquals(HANDLER.size(), properties.size()); compare("hello", properties, NAME); compare("howAreYou", properties, NAME); } @Test public void testStringFormat() throws Exception { final String fileName = "StringFormatLogger.i18n%s.properties"; final Properties en = findFile(String.format(fileName, "")); final Properties es = findFile(String.format(fileName, "_es")); final StringFormatLogger logger = Logger.getMessageLogger(StringFormatLogger.class, CATEGORY, new Locale("es")); final Date date = new Date(); logger.dukesBirthday(date); logger.dukesBirthdayFailure(date); compare("dukesBirthday", es, date); compare("dukesBirthdayFailure", en, date); logger.stringInt("string", 1); logger.stringIntFailure("string", 1); compare("stringInt", es, "string", 1); compare("stringIntFailure", en, "string", 1); logger.repeat("invalid"); logger.repeatFailure("invalid"); compare("repeat", es, "invalid"); compare("repeatFailure", en, "invalid"); } private static DefaultLogger getLogger(final Locale locale) { return Logger.getMessageLogger(DefaultLogger.class, CATEGORY, locale); } private void compare(final String key, final Properties properties, final Object... params) throws InterruptedException { final String expectedMessage = getFormattedProperty(key, properties, params); final String loggedMessage = HANDLER.getMessage().replaceAll(LOGGER_ID_PATTERN, ""); Assert.assertEquals(expectedMessage, loggedMessage); } private String getFormattedProperty(final String key, final Properties properties, final Object... params) { final String format = properties.getProperty(key); if (format == null) { return null; } if (params != null && params.length > 0) return String.format(format, params); return format; } private static Properties findFile(final String fileName) throws IOException { final Properties properties = new Properties(); final String name = CATEGORY.replace(".", File.separator) + File.separator + fileName; final InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); properties.load(new InputStreamReader(in, "utf-8")); return properties; } } MessagesTest.java000066400000000000000000000321171356560461700357020ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.io.IOException; import java.text.MessageFormat; import java.util.Arrays; import java.util.function.Supplier; import org.jboss.logging.processor.generated.ValidMessages.CustomException; import org.jboss.logging.processor.generated.ValidMessages.LoggingException; import org.jboss.logging.processor.generated.ValidMessages.StringOnlyException; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class MessagesTest { private static final String FORMATTED_TEST_MSG = String.format(ValidMessages.TEST_MSG); @Test public void testFormats() { Assert.assertEquals(FORMATTED_TEST_MSG, ValidMessages.MESSAGES.testWithNewLine()); Assert.assertEquals(ValidMessages.TEST_MSG, ValidMessages.MESSAGES.noFormat()); Assert.assertEquals(ValidMessages.TEST_MSG, ValidMessages.MESSAGES.noFormatException(new IllegalArgumentException()).getLocalizedMessage()); final int value = 10; Assert.assertEquals(value, ValidMessages.MESSAGES.fieldMessage(value).value); Assert.assertEquals(value, ValidMessages.MESSAGES.paramMessage(value).value); Assert.assertEquals(value, ValidMessages.MESSAGES.propertyMessage(value).value); final StringOnlyException e = ValidMessages.MESSAGES.stringOnlyException(new RuntimeException()); Assert.assertEquals(FORMATTED_TEST_MSG, e.getMessage()); Assert.assertNotNull(e.getCause()); Assert.assertTrue("Incorrect type constructed", ValidMessages.MESSAGES.invalidCredentials() instanceof IllegalArgumentException); final String arg1 = "value-1"; final String arg2 = "value-2"; final String messageFormatMessage = MessageFormat.format(ValidMessages.TEST_MESSAGE_FORMAT, arg1, arg2); Assert.assertEquals(messageFormatMessage, ValidMessages.MESSAGES.testMessageFormat(arg1, arg2)); Assert.assertEquals(messageFormatMessage, ValidMessages.MESSAGES.testMessageFormatException(arg1, arg2).getMessage()); } @Test public void testSuppressed() { final IllegalArgumentException e1 = new IllegalArgumentException("First exception"); final IllegalStateException e2 = new IllegalStateException("Second exception"); final RuntimeException e3 = new RuntimeException("Third exception"); RuntimeException expected = new RuntimeException(ValidMessages.MULTIPLE_ERRORS); expected.addSuppressed(e1); expected.addSuppressed(e2); expected.addSuppressed(e3); RuntimeException actual = ValidMessages.MESSAGES.multipleErrors(e1, e2, e3); compare(expected.getSuppressed(), actual.getSuppressed()); actual = ValidMessages.MESSAGES.multipleErrorsCollection(Arrays.asList(e1, e2, e3)); compare(expected.getSuppressed(), actual.getSuppressed()); expected = new RuntimeException(ValidMessages.SUPPRESSED_ERROR); expected.addSuppressed(e1); actual = ValidMessages.MESSAGES.suppressedError(e1); compare(expected.getSuppressed(), actual.getSuppressed()); expected = new RuntimeException(ValidMessages.SUPPRESSED_ERRORS); expected.addSuppressed(e1); expected.addSuppressed(e2); actual = ValidMessages.MESSAGES.suppressedErrors(e1, e2); compare(expected.getSuppressed(), actual.getSuppressed()); } @Test public void testPropertyConstants() { Assert.assertEquals(true, MethodMessageConstants.MESSAGES.booleanProperty().value); Assert.assertEquals("x".getBytes()[0], MethodMessageConstants.MESSAGES.byteProperty().value); Assert.assertEquals(MethodMessageConstants.testChar, MethodMessageConstants.MESSAGES.charProperty().value); Assert.assertEquals(MethodMessageConstants.ValueType.class, MethodMessageConstants.MESSAGES.classProperty().value); Assert.assertEquals(Double.MAX_VALUE, MethodMessageConstants.MESSAGES.douleProperty().value, 0); Assert.assertEquals(Float.MAX_VALUE, MethodMessageConstants.MESSAGES.floatProperty().value, 0); Assert.assertEquals(Integer.MAX_VALUE, MethodMessageConstants.MESSAGES.intProperty().value); Assert.assertEquals(Long.MAX_VALUE, MethodMessageConstants.MESSAGES.longProperty().value); Assert.assertEquals(Short.MAX_VALUE, MethodMessageConstants.MESSAGES.shortProperty().value); Assert.assertEquals(MethodMessageConstants.stringTest, MethodMessageConstants.MESSAGES.stringProperty().value); MethodMessageConstants.TypeException exception = MethodMessageConstants.MESSAGES.multiProperty(); Assert.assertEquals(String.class, exception.type); Assert.assertEquals(MethodMessageConstants.stringTest, exception.value); exception = MethodMessageConstants.MESSAGES.repeatableProperty(); Assert.assertEquals(String.class, exception.type); Assert.assertEquals(MethodMessageConstants.stringTest, exception.value); } @Test public void testFieldConstants() { Assert.assertEquals(true, MethodMessageConstants.MESSAGES.booleanField().value); Assert.assertEquals("x".getBytes()[0], MethodMessageConstants.MESSAGES.byteField().value); Assert.assertEquals(MethodMessageConstants.testChar, MethodMessageConstants.MESSAGES.charField().value); Assert.assertEquals(MethodMessageConstants.ValueType.class, MethodMessageConstants.MESSAGES.classField().value); Assert.assertEquals(Double.MAX_VALUE, MethodMessageConstants.MESSAGES.douleField().value, 0); Assert.assertEquals(Float.MAX_VALUE, MethodMessageConstants.MESSAGES.floatField().value, 0); Assert.assertEquals(Integer.MAX_VALUE, MethodMessageConstants.MESSAGES.intField().value); Assert.assertEquals(Long.MAX_VALUE, MethodMessageConstants.MESSAGES.longField().value); Assert.assertEquals(Short.MAX_VALUE, MethodMessageConstants.MESSAGES.shortField().value); Assert.assertEquals(MethodMessageConstants.stringTest, MethodMessageConstants.MESSAGES.stringField().value); MethodMessageConstants.TypeException exception = MethodMessageConstants.MESSAGES.multiField(); Assert.assertEquals(String.class, exception.type); Assert.assertEquals(MethodMessageConstants.stringTest, exception.value); exception = MethodMessageConstants.MESSAGES.repeatableField(); Assert.assertEquals(String.class, exception.type); Assert.assertEquals(MethodMessageConstants.stringTest, exception.value); } @Test public void testSupplierReturnType() throws Exception { Supplier runtimeExceptionSupplier = ValidMessages.MESSAGES.testSupplierRuntimeException(); Assert.assertNotNull(runtimeExceptionSupplier); RuntimeException runtimeException = runtimeExceptionSupplier.get(); Assert.assertEquals(FORMATTED_TEST_MSG, runtimeException.getMessage()); Assert.assertEquals(RuntimeException.class, runtimeException.getClass()); Assert.assertEquals(ValidMessages.MESSAGES.testSupplierString().get(), FORMATTED_TEST_MSG); runtimeExceptionSupplier = ValidMessages.MESSAGES.invalidCredentialsSupplier(); Assert.assertNotNull(runtimeExceptionSupplier); runtimeException = runtimeExceptionSupplier.get(); Assert.assertEquals(IllegalArgumentException.class, runtimeException.getClass()); // Test suppliers with fields/properties int value = 5; Supplier customExceptionSupplier = ValidMessages.MESSAGES.fieldMessageSupplier(value); Assert.assertNotNull(customExceptionSupplier); CustomException customException = customExceptionSupplier.get(); Assert.assertEquals(FORMATTED_TEST_MSG, customException.getMessage()); Assert.assertEquals(CustomException.class, customException.getClass()); Assert.assertEquals(value, customException.value); value = 20; customExceptionSupplier = ValidMessages.MESSAGES.propertyMessageSupplier(value); Assert.assertNotNull(customExceptionSupplier); customException = customExceptionSupplier.get(); Assert.assertEquals(FORMATTED_TEST_MSG, customException.getMessage()); Assert.assertEquals(CustomException.class, customException.getClass()); Assert.assertEquals(value, customException.value); } @Test public void testFunctionProducerMessages() throws Exception { RuntimeException runtimeException = ValidMessages.MESSAGES.operationFailed(IllegalArgumentException::new, "start"); Assert.assertEquals(IllegalArgumentException.class, runtimeException.getClass()); Assert.assertEquals(String.format(ValidMessages.TEST_OP_FAILED_MSG, "start"), runtimeException.getMessage()); IOException ioException = ValidMessages.MESSAGES.operationFailed(IOException::new, "query"); Assert.assertEquals(String.format(ValidMessages.TEST_OP_FAILED_MSG, "query"), ioException.getMessage()); final Supplier supplier = ValidMessages.MESSAGES.supplierFunction(IllegalStateException::new); runtimeException = supplier.get(); Assert.assertEquals(IllegalStateException.class, runtimeException.getClass()); Assert.assertEquals(FORMATTED_TEST_MSG, runtimeException.getMessage()); // Test functions with fields/properties int value = 5; CustomException customException = ValidMessages.MESSAGES.fieldMessageFunction(CustomException::new, value); Assert.assertEquals(FORMATTED_TEST_MSG, customException.getMessage()); Assert.assertEquals(CustomException.class, customException.getClass()); Assert.assertEquals(customException.value, value); value = 20; customException = ValidMessages.MESSAGES.propertyMessageFunction(CustomException::new, value); Assert.assertEquals(FORMATTED_TEST_MSG, customException.getMessage()); Assert.assertEquals(CustomException.class, customException.getClass()); Assert.assertEquals(value, customException.value); } @Test public void testBiFunctionProducerMessages() throws Exception { final RuntimeException cause = new RuntimeException("This is the cause"); RuntimeException runtimeException = ValidMessages.MESSAGES.operationFailed(IllegalArgumentException::new, cause, "start"); Assert.assertEquals(IllegalArgumentException.class, runtimeException.getClass()); Assert.assertEquals(String.format(ValidMessages.TEST_OP_FAILED_MSG, "start"), runtimeException.getMessage()); Assert.assertEquals(cause, runtimeException.getCause()); runtimeException = ValidMessages.MESSAGES.throwableStringBiFunction(LoggingException::new, cause); Assert.assertEquals(LoggingException.class, runtimeException.getClass()); Assert.assertEquals(cause, runtimeException.getCause()); final Supplier supplier = ValidMessages.MESSAGES.throwableStringBiFunctionSupplier(IllegalArgumentException::new, cause); runtimeException = supplier.get(); Assert.assertEquals(IllegalArgumentException.class, runtimeException.getClass()); Assert.assertEquals(FORMATTED_TEST_MSG, runtimeException.getMessage()); Assert.assertEquals(cause, runtimeException.getCause()); } private void compare(final T[] a1, final T[] a2) { Assert.assertTrue(String.format("Expected: %s%n Actual: %s", Arrays.toString(a1), Arrays.toString(a2)), equalsIgnoreOrder(a1, a2)); } private boolean equalsIgnoreOrder(final T[] a1, final T[] a2) { if (a1.length != a2.length) { return false; } final T[] ca2 = Arrays.copyOf(a2, a2.length); boolean found = false; for (T t : a1) { final int i = search(ca2, t); if (i >= 0) { found = true; ca2[i] = null; } else { found = false; } if (!found) { break; } } return found; } private int search(final T[] a, final T key) { for (int i = 0; i < a.length; i++) { if (key.equals(a[i])) { return i; } } return -1; } } MethodMessageConstants.java000066400000000000000000000202621356560461700377130ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.Fields; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.Properties; import org.jboss.logging.annotations.Property; /** * @author James R. Perkins */ @MessageBundle(projectCode = "CONSTANTS") public interface MethodMessageConstants { String TEST_MSG = "Test method message constant"; MethodMessageConstants MESSAGES = Messages.getBundle(MethodMessageConstants.class); // Properties @Message(TEST_MSG) @Property(name = "value", intValue = Integer.MAX_VALUE) IntTypeException intProperty(); @Message(TEST_MSG) @Property(name = "value", longValue = Long.MAX_VALUE) LongTypeException longProperty(); @Message(TEST_MSG) @Property(name = "value", shortValue = Short.MAX_VALUE) ShortTypeException shortProperty(); @Message(TEST_MSG) @Property(name = "value", doubleValue = Double.MAX_VALUE) DoubleTypeException douleProperty(); @Message(TEST_MSG) @Property(name = "value", floatValue = Float.MAX_VALUE) FloatTypeException floatProperty(); @Message(TEST_MSG) @Property(name = "value", booleanValue = true) BooleanTypeException booleanProperty(); @Message(TEST_MSG) @Property(name = "value", charValue = testChar) CharTypeException charProperty(); @Message(TEST_MSG) @Property(name = "value", byteValue = (byte) 'x') ByteTypeException byteProperty(); @Message(TEST_MSG) @Property(name = "value", classValue = ValueType.class) ClassTypeException classProperty(); @Message(TEST_MSG) @Property(name = "value", stringValue = stringTest) StringTypeException stringProperty(); @Message(TEST_MSG) @Property(name = "value", stringValue = stringTest) @Property(name = "type", classValue = String.class) TypeException repeatableProperty(); @Message(TEST_MSG) @Properties({ @Property(name = "value", stringValue = stringTest), @Property(name = "type", classValue = String.class) }) TypeException multiProperty(); // Fields @Message(TEST_MSG) @Field(name = "value", intValue = Integer.MAX_VALUE) IntTypeException intField(); @Message(TEST_MSG) @Field(name = "value", longValue = Long.MAX_VALUE) LongTypeException longField(); @Message(TEST_MSG) @Field(name = "value", shortValue = Short.MAX_VALUE) ShortTypeException shortField(); @Message(TEST_MSG) @Field(name = "value", doubleValue = Double.MAX_VALUE) DoubleTypeException douleField(); @Message(TEST_MSG) @Field(name = "value", floatValue = Float.MAX_VALUE) FloatTypeException floatField(); @Message(TEST_MSG) @Field(name = "value", booleanValue = true) BooleanTypeException booleanField(); char testChar = 'c'; @Message(TEST_MSG) @Field(name = "value", charValue = testChar) CharTypeException charField(); @Message(TEST_MSG) @Field(name = "value", byteValue = (byte) 'x') ByteTypeException byteField(); @Message(TEST_MSG) @Field(name = "value", classValue = ValueType.class) ClassTypeException classField(); String stringTest = "test"; @Message(TEST_MSG) @Field(name = "value", stringValue = stringTest) StringTypeException stringField(); @Message(TEST_MSG) @Field(name = "value", stringValue = stringTest) @Field(name = "type", classValue = String.class) TypeException repeatableField(); @Message(TEST_MSG) @Fields({ @Field(name = "value", stringValue = stringTest), @Field(name = "type", classValue = String.class) }) TypeException multiField(); class TypeException extends RuntimeException { public Class type; public Object value; public TypeException() { } public TypeException(final String msg) { super(msg); } public TypeException(final Throwable t) { super(t); } public TypeException(final String msg, final Throwable t) { super(msg, t); } public void setValue(final Object value) { this.value = value; } public void setType(final Class type) { this.type = type; } } class IntTypeException extends RuntimeException { public int value; public IntTypeException(final String message) { super(message); } public void setValue(final Integer value) { this.value = value; } } class LongTypeException extends RuntimeException { public long value; public LongTypeException(final String message) { super(message); } public void setValue(final long value) { this.value = value; } } class ShortTypeException extends RuntimeException { public short value; public ShortTypeException(final String message) { super(message); } public void setValue(final short value) { this.value = value; } } class FloatTypeException extends RuntimeException { public float value; public FloatTypeException(final String message) { super(message); } public void setValue(final float value) { this.value = value; } } class DoubleTypeException extends RuntimeException { public double value; public DoubleTypeException(final String message) { super(message); } public void setValue(final double value) { this.value = value; } } class BooleanTypeException extends RuntimeException { public boolean value; public BooleanTypeException(final String message) { super(message); } public void setValue(final boolean value) { this.value = value; } } class ByteTypeException extends RuntimeException { public byte value; public ByteTypeException(final String message) { super(message); } public void setValue(final byte value) { this.value = value; } } class CharTypeException extends RuntimeException { public char value; public CharTypeException(final String message) { super(message); } public void setValue(final char value) { this.value = value; } } class ClassTypeException extends RuntimeException { public Class value; public ClassTypeException(final String message) { super(message); } public void setValue(final Class value) { this.value = value; } } class StringTypeException extends RuntimeException { public String value; public StringTypeException(final String message) { super(message); } public void setValue(final String value) { this.value = value; } } class ValueType { } } QueuedMessageHandler.java000066400000000000000000000043221356560461700373230ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.logmanager.ExtHandler; import org.jboss.logmanager.ExtLogRecord; /** * @author James R. Perkins */ class QueuedMessageHandler extends ExtHandler { //private final List messages = Collections.synchronizedList(new ArrayList<>()); private final BlockingQueue messages = new LinkedBlockingQueue<>(); @Override protected void doPublish(final ExtLogRecord record) { messages.add(record.getFormattedMessage()); } /** * Polls the message from queue waiting for up to 1 second for the message to appear. * * @return the message * * @throws InterruptedException if the poll was interrupted */ String getMessage() throws InterruptedException { return messages.poll(1, TimeUnit.SECONDS); } int size() { return messages.size(); } @Override public void flush() { // no-op } @Override public void close() throws SecurityException { messages.clear(); } } RootLocaleLogger.java000066400000000000000000000034171356560461700364770ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author James R. Perkins */ @MessageLogger(projectCode = "LOCALE", rootLocale = "en-UK") public interface RootLocaleLogger { @LogMessage(level = Level.INFO) @Message(id = 10, value = "Initialised %s") void init(Object object); @LogMessage(level = Level.ERROR) @Message(id = 20, value = "Initialisation failed, behaviour may be unpredictable.") void initFailed(); @Message(id = 50, value = "Authorisation failed for %s") RuntimeException authFailed(String user); } SignatureMessages.java000066400000000000000000000213131356560461700367200ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import static org.jboss.logging.processor.util.Objects.areEqual; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Signature; import org.jboss.logging.processor.util.Objects; import org.jboss.logging.processor.util.Objects.HashCodeBuilder; /** * @author James R. Perkins */ @MessageBundle(projectCode = "SIG") public interface SignatureMessages { final String TEST_MSG = "Test signature message"; final SignatureMessages MESSAGES = Messages.getBundle(SignatureMessages.class); @Message(TEST_MSG) RedirectException redirect(@Param int responseCode, @Param String location); RedirectException redirect(@Cause Throwable cause, @Param int responseCode, @Param String location); @Signature({String.class, String.class}) RedirectException redirect(@Cause Throwable cause, @Param String location); @Message(TEST_MSG) TestException test(); TestException test(@Cause Throwable cause); @Message(TEST_MSG) InvalidTextException invalidText(@Param String text); InvalidTextException invalidText(@Cause Throwable cause, @Param String text); @Signature(causeIndex = 1, messageIndex = 3, value = {int.class, Throwable.class, String.class, String.class}) InvalidTextException invalidText(@Param int position, @Cause Throwable cause, @Param String text); @SuppressWarnings("unused") static class RedirectException extends RuntimeException { final int statusCode; final String location; public RedirectException(final String msg, final Throwable cause, final int statusCode, final String location) { super(msg, cause); this.statusCode = statusCode; this.location = location; } public RedirectException(final int statusCode, final String location) { throw new IllegalStateException("Should never be chosen"); } public RedirectException(final Throwable cause, final int statusCode, final String location) { throw new IllegalStateException("Should never be chosen"); } public RedirectException(final String msg, final int statusCode, final String location) { super(msg); this.statusCode = statusCode; this.location = location; } public RedirectException(final String msg, final String location) { super(msg); this.statusCode = 301; this.location = location; } @Override public int hashCode() { return HashCodeBuilder.builder() .add(statusCode) .add(location) .add(getMessage()) .add(getCause()) .toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof RedirectException)) { return false; } final RedirectException other = (RedirectException) obj; return areEqual(statusCode, other.statusCode) && areEqual(location, other.location) && areEqual(getMessage(), other.getMessage()) && areEqual(getCause(), other.getCause()); } @Override public String toString() { return Objects.ToStringBuilder.of(this) .add("statusCode", statusCode) .add("location", location) .add("message", getMessage()) .add("cause", getCause()) .toString(); } } @SuppressWarnings("unused") static class TestException extends RuntimeException { public TestException(final String message) { super(message); } public TestException(final String message, final Throwable cause) { super(message, cause); } public TestException(final Throwable cause) { throw new IllegalStateException("Should never be chosen"); } @Override public int hashCode() { return HashCodeBuilder.builder() .add(getMessage()) .add(getCause()) .toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof TestException)) { return false; } final TestException other = (TestException) obj; return areEqual(getMessage(), other.getMessage()) && areEqual(getCause(), other.getCause()); } @Override public String toString() { return Objects.ToStringBuilder.of(this) .add("message", getMessage()) .add("cause", getCause()) .toString(); } } @SuppressWarnings("unused") static class InvalidTextException extends RuntimeException { final String value; final int position; public InvalidTextException(final String value) { this.value = value; position = -1; } public InvalidTextException(final String msg, final String value) { super(msg); this.value = value; position = -1; } public InvalidTextException(final Throwable cause) { throw new IllegalStateException("Should never be chosen"); } public InvalidTextException(final String message, final Throwable cause) { throw new IllegalStateException("Should never be chosen"); } public InvalidTextException(final String msg, final Throwable cause, final String value) { super(msg, cause); this.value = value; position = -1; } public InvalidTextException(final int position, final Throwable cause, final String value, final String msg) { super(msg, cause); this.value = value; this.position = position; } public InvalidTextException(final Integer position, final Throwable cause, final String value, final String msg) { throw new IllegalStateException("Should never be chosen"); } @Override public int hashCode() { return HashCodeBuilder.builder() .add(value) .add(position) .add(getMessage()) .add(getCause()) .toHashCode(); } @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (!(obj instanceof InvalidTextException)) { return false; } final InvalidTextException other = (InvalidTextException) obj; return areEqual(value, other.value) && areEqual(position, other.position) && areEqual(getMessage(), other.getMessage()) && areEqual(getCause(), other.getCause()); } @Override public String toString() { return Objects.ToStringBuilder.of(this) .add("value", value) .add("position", position) .add("message", getMessage()) .add("cause", getCause()) .toString(); } } } StringFormatLogger.java000066400000000000000000000041541356560461700370520ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.Date; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; /** * @author James R. Perkins */ @MessageLogger(projectCode = "TEST") public interface StringFormatLogger { @LogMessage(level = Level.INFO) @Message("String %s integer %d") void stringInt(String s, int i); @LogMessage(level = Level.INFO) @Message("String %s integer %d") void stringIntFailure(String s, int i); @LogMessage(level = Level.INFO) @Message("Duke's Birthday: %1$tm %James R. Perkins */ @MessageBundle(projectCode = "TEST") public interface StringFormatMessages { StringFormatMessages MESSAGES = Messages.getBundle(StringFormatMessages.class); @Message("String %s integer %d") String stringInt(String s, int i); @Message("Duke's Birthday: %1$tm %James R. Perkins */ public class ThrowableSignatureTest { @Test public void testSignatures() { final String formattedMessage = String.format(SignatureMessages.TEST_MSG); final RuntimeException cause = new RuntimeException("This was the cause"); final int code = 307; final String location = "foo"; RedirectException redirectExpected = new RedirectException(formattedMessage, code, location); Assert.assertEquals(redirectExpected, SignatureMessages.MESSAGES.redirect(code, location)); redirectExpected = new RedirectException(formattedMessage, location); redirectExpected.initCause(cause); Assert.assertEquals(redirectExpected, SignatureMessages.MESSAGES.redirect(cause, location)); redirectExpected = new RedirectException(formattedMessage, cause, code, location); Assert.assertEquals(redirectExpected, SignatureMessages.MESSAGES.redirect(cause, code, location)); TestException testExpected = new TestException(formattedMessage); Assert.assertEquals(testExpected, SignatureMessages.MESSAGES.test()); testExpected = new TestException(formattedMessage, cause); Assert.assertEquals(testExpected, SignatureMessages.MESSAGES.test(cause)); final String invalidText = "invalid"; InvalidTextException invalidTextExpected = new InvalidTextException(formattedMessage, invalidText); Assert.assertEquals(invalidTextExpected, SignatureMessages.MESSAGES.invalidText(invalidText)); invalidTextExpected = new InvalidTextException(formattedMessage, cause, invalidText); Assert.assertEquals(invalidTextExpected, SignatureMessages.MESSAGES.invalidText(cause, invalidText)); invalidTextExpected = new InvalidTextException(3, cause, invalidText, formattedMessage); Assert.assertEquals(invalidTextExpected, SignatureMessages.MESSAGES.invalidText(3, cause, invalidText)); } } TransformLogger.java000066400000000000000000000136711356560461700364120ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.Collection; import java.util.Map; import org.jboss.logging.Logger; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; /** * @author James R. Perkins */ @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) public interface TransformLogger { final TransformLogger LOGGER = Logger.getMessageLogger(TransformLogger.class, AbstractLoggerTest.CATEGORY); final String HASH_CODE_MSG = "hashCode: %d"; final String IDENTITY_HASH_CODE_MSG = "SystemIdentity: %d"; final String GET_CLASS_MSG = "getClass: %s"; final String SIZE_MSG = "size: %d"; // getClass().hashCode(); @LogMessage @Message(HASH_CODE_MSG) void logClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) String s); @LogMessage void logClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Collection c); @LogMessage void logClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) String... array); @LogMessage void logClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Object[] array); @LogMessage void logClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Map map); // hashCode() @LogMessage @Message(HASH_CODE_MSG) void logObjectHashCode(@Transform(TransformType.HASH_CODE) String s); @LogMessage void logObjectHashCode(@Transform(TransformType.HASH_CODE) Collection c); @LogMessage void logObjectHashCode(@Transform(TransformType.HASH_CODE) String... array); @LogMessage void logObjectHashCode(@Transform(TransformType.HASH_CODE) Object[] array); @LogMessage void logObjectHashCode(@Transform(TransformType.HASH_CODE) Map map); // System.identityHashCode(getClass()) @LogMessage @Message(IDENTITY_HASH_CODE_MSG) void logClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) String s); @LogMessage void logClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Collection c); @LogMessage void logClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) String... array); @LogMessage void logClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Object[] array); @LogMessage void logClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Map map); // System.identityHashCode() @LogMessage @Message(IDENTITY_HASH_CODE_MSG) void logObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) String s); @LogMessage void logObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Collection c); @LogMessage void logObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) String... array); @LogMessage void logObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Object[] array); @LogMessage void logObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Map map); // getClass() @LogMessage @Message(GET_CLASS_MSG) void logObjectClass(@Transform(TransformType.GET_CLASS) String s); @LogMessage void logObjectClass(@Transform(TransformType.GET_CLASS) String... array); @LogMessage void logObjectClass(@Transform(TransformType.GET_CLASS) Object[] array); // length/length()/size() @LogMessage @Message(SIZE_MSG) void logSize(@Transform(TransformType.SIZE) String s); @LogMessage void logSize(@Transform(TransformType.SIZE) Collection c); @LogMessage void logSize(@Transform(TransformType.SIZE) String... array); @LogMessage void logSize(@Transform(TransformType.SIZE) Object[] array); @LogMessage void logSize(@Transform(TransformType.SIZE) Map map); // Position tests String POS_MSG_1 = "size %d hashCode %d identityHashCode %d"; @LogMessage @Message(POS_MSG_1) void posTest1(@Pos(value = {2, 3}, transform = {@Transform(TransformType.HASH_CODE), @Transform(TransformType.IDENTITY_HASH_CODE)}) String msg1, @Pos(value = 1, transform = @Transform(TransformType.SIZE)) String msg2); String POS_MSG_2 = "size %d s1=%s s2=%s getClass() %s"; @LogMessage @Message(POS_MSG_2) void posTest2(@Pos(value = 4, transform = @Transform(TransformType.GET_CLASS)) Object type, @Pos(value = 1, transform = @Transform(TransformType.SIZE)) String msg, @Pos(2) String s1, @Pos(3) String s2); } TransformMessages.java000066400000000000000000000127751356560461700367460ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.Collection; import java.util.Map; import org.jboss.logging.Messages; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.Pos; import org.jboss.logging.annotations.Transform; import org.jboss.logging.annotations.Transform.TransformType; /** * @author James R. Perkins */ @MessageBundle(projectCode = AbstractLoggerTest.PROJECT_CODE) public interface TransformMessages { final TransformMessages MESSAGES = Messages.getBundle(TransformMessages.class); final String HASH_CODE_MSG = "hashCode: %d"; final String IDENTITY_HASH_CODE_MSG = "SystemIdentity: %d"; final String GET_CLASS_MSG = "getClass: %s"; final String SIZE_MSG = "size: %d"; // getClass().hashCode(); @Message(HASH_CODE_MSG) String msgClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) String s); String msgClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Collection c); String msgClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) String... array); String msgClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Object[] array); String msgClassHashCode(@Transform({TransformType.GET_CLASS, TransformType.HASH_CODE}) Map map); // hashCode() @Message(HASH_CODE_MSG) String msgObjectHashCode(@Transform(TransformType.HASH_CODE) String s); String msgObjectHashCode(@Transform(TransformType.HASH_CODE) Collection c); String msgObjectHashCode(@Transform(TransformType.HASH_CODE) String... array); String msgObjectHashCode(@Transform(TransformType.HASH_CODE) Object[] array); String msgObjectHashCode(@Transform(TransformType.HASH_CODE) Map map); // System.identityHashCode(getClass()) @Message(IDENTITY_HASH_CODE_MSG) String msgClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) String s); String msgClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Collection c); String msgClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) String... array); String msgClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Object[] array); String msgClassIdentityHashCode(@Transform({TransformType.GET_CLASS, TransformType.IDENTITY_HASH_CODE}) Map map); // System.identityHashCode() @Message(IDENTITY_HASH_CODE_MSG) String msgObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) String s); String msgObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Collection c); String msgObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) String... array); String msgObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Object[] array); String msgObjectIdentityHashCode(@Transform(TransformType.IDENTITY_HASH_CODE) Map map); // getClass() @Message(GET_CLASS_MSG) String msgObjectClass(@Transform(TransformType.GET_CLASS) String s); String msgObjectClass(@Transform(TransformType.GET_CLASS) String... array); String msgObjectClass(@Transform(TransformType.GET_CLASS) Object[] array); // length/length()/size() @Message(SIZE_MSG) String msgSize(@Transform(TransformType.SIZE) String s); String msgSize(@Transform(TransformType.SIZE) Collection c); String msgSize(@Transform(TransformType.SIZE) String... array); String msgSize(@Transform(TransformType.SIZE) Object[] array); String msgSize(@Transform(TransformType.SIZE) Map map); // Position tests String POS_MSG_1 = "size %d hashCode %d identityHashCode %d"; @Message(POS_MSG_1) String posTest1(@Pos(value = {2, 3}, transform = {@Transform(TransformType.HASH_CODE), @Transform(TransformType.IDENTITY_HASH_CODE)}) String msg1, @Pos(value = 1, transform = @Transform(TransformType.SIZE)) String msg2); String POS_MSG_2 = "size %d s1=%s s2=%s getClass() %s"; @Message(POS_MSG_2) String posTest2(@Pos(value = 4, transform = @Transform(TransformType.GET_CLASS)) Object type, @Pos(value = 1, transform = @Transform(TransformType.SIZE)) String msg, @Pos(2) String s1, @Pos(3) String s2); } TransformTest.java000066400000000000000000000310511356560461700361020ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** * @author James R. Perkins */ public class TransformTest extends AbstractLoggerTest { @Test public void testLog() throws Exception { // Log strings final String s = "This is a test string"; TransformLogger.LOGGER.logClassHashCode(s); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, s.getClass().hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logClassIdentityHashCode(s); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(s.getClass())), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectClass(s); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, s.getClass()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectHashCode(s); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, s.hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectIdentityHashCode(s); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(s)), HANDLER.getMessage()); TransformLogger.LOGGER.logSize(s); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, s.length()), HANDLER.getMessage()); // Log collections final Collection c = Arrays.asList("test"); TransformLogger.LOGGER.logClassHashCode(c); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, c.getClass().hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logClassIdentityHashCode(c); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(c.getClass())), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectHashCode(c); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, c.hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectIdentityHashCode(c); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(c)), HANDLER.getMessage()); TransformLogger.LOGGER.logSize(c); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, c.size()), HANDLER.getMessage()); // Log an array final Object[] array = {"test1", "test2", "test3"}; TransformLogger.LOGGER.logClassHashCode(array); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, array.getClass().hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logClassIdentityHashCode(array); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(array.getClass())), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectClass(array); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, array.getClass()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectHashCode(array); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, Arrays.hashCode(array)), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectIdentityHashCode(array); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(array)), HANDLER.getMessage()); TransformLogger.LOGGER.logSize(array); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, array.length), HANDLER.getMessage()); // Log vararg array final String[] sArray = {"test1", "test2", "test3"}; TransformLogger.LOGGER.logClassHashCode(sArray); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, sArray.getClass().hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logClassIdentityHashCode(sArray); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(sArray.getClass())), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectClass(sArray); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, sArray.getClass()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectHashCode(sArray); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, Arrays.hashCode(sArray)), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectIdentityHashCode(sArray); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(sArray)), HANDLER.getMessage()); TransformLogger.LOGGER.logSize(sArray); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, sArray.length), HANDLER.getMessage()); // Log a map final Map map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put("key" + i, "value" + i); } TransformLogger.LOGGER.logClassHashCode(map); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, map.getClass().hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logClassIdentityHashCode(map); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(map.getClass())), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectHashCode(map); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, map.hashCode()), HANDLER.getMessage()); TransformLogger.LOGGER.logObjectIdentityHashCode(map); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(map)), HANDLER.getMessage()); TransformLogger.LOGGER.logSize(map); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, map.size()), HANDLER.getMessage()); } @Test public void testMessage() throws Exception { // Log strings final String s = "This is a test string"; Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, s.getClass().hashCode()), TransformMessages.MESSAGES.msgClassHashCode(s)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(s.getClass())), TransformMessages.MESSAGES.msgClassIdentityHashCode(s)); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, s.getClass()), TransformMessages.MESSAGES.msgObjectClass(s)); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, s.hashCode()), TransformMessages.MESSAGES.msgObjectHashCode(s)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(s)), TransformMessages.MESSAGES.msgObjectIdentityHashCode(s)); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, s.length()), TransformMessages.MESSAGES.msgSize(s)); // Log collections final Collection c = Arrays.asList("test"); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, c.getClass().hashCode()), TransformMessages.MESSAGES.msgClassHashCode(c)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(c.getClass())), TransformMessages.MESSAGES.msgClassIdentityHashCode(c)); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, c.hashCode()), TransformMessages.MESSAGES.msgObjectHashCode(c)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(c)), TransformMessages.MESSAGES.msgObjectIdentityHashCode(c)); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, c.size()), TransformMessages.MESSAGES.msgSize(c)); // Log an array final Object[] array = {"test1", "test2", "test3"}; Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, array.getClass().hashCode()), TransformMessages.MESSAGES.msgClassHashCode(array)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(array.getClass())), TransformMessages.MESSAGES.msgClassIdentityHashCode(array)); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, array.getClass()), TransformMessages.MESSAGES.msgObjectClass(array)); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, Arrays.hashCode(array)), TransformMessages.MESSAGES.msgObjectHashCode(array)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(array)), TransformMessages.MESSAGES.msgObjectIdentityHashCode(array)); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, array.length), TransformMessages.MESSAGES.msgSize(array)); // Log vararg array final String[] sArray = {"test1", "test2", "test3"}; Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, sArray.getClass().hashCode()), TransformMessages.MESSAGES.msgClassHashCode(sArray)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(sArray.getClass())), TransformMessages.MESSAGES.msgClassIdentityHashCode(sArray)); Assert.assertEquals(String.format(TransformLogger.GET_CLASS_MSG, sArray.getClass()), TransformMessages.MESSAGES.msgObjectClass(sArray)); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, Arrays.hashCode(sArray)), TransformMessages.MESSAGES.msgObjectHashCode(sArray)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(sArray)), TransformMessages.MESSAGES.msgObjectIdentityHashCode(sArray)); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, sArray.length), TransformMessages.MESSAGES.msgSize(sArray)); // Log a map final Map map = new HashMap<>(); for (int i = 0; i < 10; i++) { map.put("key" + i, "value" + i); } Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, map.getClass().hashCode()), TransformMessages.MESSAGES.msgClassHashCode(map)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(map.getClass())), TransformMessages.MESSAGES.msgClassIdentityHashCode(map)); Assert.assertEquals(String.format(TransformLogger.HASH_CODE_MSG, map.hashCode()), TransformMessages.MESSAGES.msgObjectHashCode(map)); Assert.assertEquals(String.format(TransformLogger.IDENTITY_HASH_CODE_MSG, System.identityHashCode(map)), TransformMessages.MESSAGES.msgObjectIdentityHashCode(map)); Assert.assertEquals(String.format(TransformLogger.SIZE_MSG, map.size()), TransformMessages.MESSAGES.msgSize(map)); } @Test public void testPositions() throws Exception { // Log strings final String msg1 = "Test message 1"; final String msg2 = "Test message 2"; String expected = String.format(TransformLogger.POS_MSG_1, msg2.length(), msg1.hashCode(), System.identityHashCode(msg1)); TransformLogger.LOGGER.posTest1(msg1, msg2); Assert.assertEquals(expected, HANDLER.getMessage()); Assert.assertEquals(expected, TransformMessages.MESSAGES.posTest1(msg1, msg2)); final Object obj = "Test"; final String msg = "This is a test message"; final String s1 = "s1"; final String s2 = "s2"; expected = String.format(TransformLogger.POS_MSG_2, msg.length(), s1, s2, obj.getClass()); TransformLogger.LOGGER.posTest2(obj, msg, s1, s2); Assert.assertEquals(expected, HANDLER.getMessage()); Assert.assertEquals(expected, TransformMessages.MESSAGES.posTest2(obj, msg, s1, s2)); } } ValidLogger.java000066400000000000000000000071101356560461700354650ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ValidIdRange; import org.jboss.logging.annotations.ValidIdRanges; /** * @author James R. Perkins */ @MessageLogger(projectCode = AbstractLoggerTest.PROJECT_CODE) @ValidIdRanges({ @ValidIdRange(min = 200, max = 202), @ValidIdRange(min = 203, max = 204) }) public interface ValidLogger { final ValidLogger LOGGER = Logger.getMessageLogger(ValidLogger.class, AbstractLoggerTest.CATEGORY); @LogMessage(level = Level.INFO, loggingClass = ValidLogger.class) @Message(id = 200, value = "This is a generated message.") void testInfoMessage(); @LogMessage(level = Level.INFO) @Message(id = 201, value = "Test message format message. Test value: {0}", format = Format.MESSAGE_FORMAT) void testMessageFormat(Object value); /** * Logs a default informational greeting. * * @param name the name. */ @LogMessage @Message(id = 202, value = "Greetings %s") void greeting(String name); /** * Logs an error message indicating a processing error. */ @LogMessage(level = Level.ERROR) @Message(id = 203, value = "Processing error") void processingError(); /** * Logs an error message indicating a processing error. * * @param cause the cause of the error. */ @LogMessage(level = Level.ERROR) void processingError(@Cause Throwable cause); /** * Logs an error message indicating there was a processing error. * * @param cause the cause of the error. * @param moduleName the module that caused the error. */ @LogMessage(level = Level.ERROR) @Message(id = Message.INHERIT, value = "Processing error in module '%s'") void processingError(@Cause Throwable cause, String moduleName); /** * Logs an error message indicating a processing error. * * @param on the object the error occurred on * @param message the error message */ @LogMessage(level = Level.ERROR) @Message(id = 203, value = "Processing error on '%s' with error '%s'") void processingError(Object on, String message); @Message(id = 204, value = "Bundle message inside a logger") String bundleMessage(); } ValidMessages.java000066400000000000000000000147371356560461700360320ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/generated/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.generated; import java.util.Collection; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import org.jboss.logging.Messages; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.ConstructType; import org.jboss.logging.annotations.Field; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.Message.Format; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.Param; import org.jboss.logging.annotations.Producer; import org.jboss.logging.annotations.Property; import org.jboss.logging.annotations.Suppressed; /** * @author James R. Perkins */ @MessageBundle(projectCode = "MSG") public interface ValidMessages { final String TEST_MSG = "Test%n"; final ValidMessages MESSAGES = Messages.getBundle(ValidMessages.class); @Message(value = TEST_MSG) String testWithNewLine(); @Message(format = Format.NO_FORMAT, value = TEST_MSG) String noFormat(); @Message(format = Format.NO_FORMAT, value = TEST_MSG) RuntimeException noFormatException(@Cause Throwable cause); @Message(TEST_MSG) CustomException fieldMessage(@Field(name = "value") int value); @Message(TEST_MSG) CustomException paramMessage(@Param int value); @Message(TEST_MSG) CustomException propertyMessage(@Property int value); @Message(TEST_MSG) LoggingException loggingException(@Cause Exception e); @Message(TEST_MSG) StringOnlyException stringOnlyException(@Cause Exception e); @ConstructType(IllegalArgumentException.class) @Message("Invalid user id or password") RuntimeException invalidCredentials(); String SUPPRESSED_ERROR = "Single error occurred"; @Message(SUPPRESSED_ERROR) RuntimeException suppressedError(@Suppressed Throwable t); String SUPPRESSED_ERRORS = "Two errors occurred"; @Message(SUPPRESSED_ERRORS) RuntimeException suppressedErrors(@Suppressed Throwable error1, @Suppressed Throwable error2); String MULTIPLE_ERRORS = "Multiple errors occurred"; @Message(MULTIPLE_ERRORS) RuntimeException multipleErrors(@Suppressed Throwable... errors); String MULTIPLE_ERRORS_COLLECTION = "Multiple errors occurred"; @Message(MULTIPLE_ERRORS_COLLECTION) RuntimeException multipleErrorsCollection(@Suppressed Collection errors); String TEST_MESSAGE_FORMAT = "A two argument message format test. Argument 1 is {0} argument 2 is {1}."; @Message(format = Format.MESSAGE_FORMAT, value = TEST_MESSAGE_FORMAT) String testMessageFormat(final String arg1, final String arg2); @Message(format = Format.MESSAGE_FORMAT, value = TEST_MESSAGE_FORMAT) RuntimeException testMessageFormatException(final String arg1, final String arg2); @Message(value = TEST_MSG) Supplier testSupplierRuntimeException(); @Message(TEST_MSG) Supplier fieldMessageSupplier(@Field(name = "value") int value); @Message(TEST_MSG) Supplier propertyMessageSupplier(@Property int value); @ConstructType(IllegalArgumentException.class) @Message("Invalid user id or password") Supplier invalidCredentialsSupplier(); @Message(value = TEST_MSG) Supplier testSupplierString(); String TEST_OP_FAILED_MSG = "The operation failed due to %s"; @Message(TEST_OP_FAILED_MSG) T operationFailed(@Producer Function function, String op); T operationFailed(@Producer BiFunction function, @Cause Throwable cause, String op); @Message(TEST_MSG) Supplier supplierFunction(@Producer Function function); @Message(TEST_MSG) T fieldMessageFunction(@Producer Function function, @Field(name = "value") int value); @Message(TEST_MSG) T propertyMessageFunction(@Producer Function function, @Property int value); @Message(TEST_MSG) LoggingException throwableStringBiFunction(@Producer BiFunction function, @Cause Exception cause); @Message(TEST_MSG) Supplier throwableStringBiFunctionSupplier(@Producer BiFunction function, @Cause Exception cause); class CustomException extends RuntimeException { public int value; public CustomException() { } public CustomException(final int value, final String msg) { super(msg); this.value = value; } public CustomException(final String msg) { super(msg); } public CustomException(final Throwable t) { super(t); } public CustomException(final String msg, final Throwable t) { super(msg, t); } public void setValue(final int value) { this.value = value; } } class LoggingException extends RuntimeException { public LoggingException(final Exception e) { super(e); } public LoggingException(final Exception e, final String msg) { super(msg, e); } } class StringOnlyException extends RuntimeException { public StringOnlyException(final String msg) { super(msg); } } } jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/report/000077500000000000000000000000001356560461700320605ustar00rootroot00000000000000ReportGenerationTest.java000066400000000000000000000113261356560461700367760ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/report/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.report; import java.io.IOException; import java.io.Reader; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.validation.SchemaFactory; import org.jboss.logging.processor.apt.report.ReportType; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; /** * @author James R. Perkins */ public class ReportGenerationTest { private static String TEST_REPORT_PATH = null; @BeforeClass public static void setUp() { TEST_REPORT_PATH = System.getProperty("test.report.path"); } @Test public void testAsciidoc() throws Exception { final Collection paths = findFiles(ReportType.ASCIIDOC); // Just ensure they were generated Assert.assertFalse("No asciidoc files found", paths.isEmpty()); } @Test public void testXml() throws Exception { final Collection paths = findFiles(ReportType.XML); Assert.assertFalse("No XML files found", paths.isEmpty()); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); final SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); factory.setSchema(schemaFactory.newSchema(getClass().getResource("/schema/logging-report_1_0.xsd"))); // Crudely test each XML file for (Path path : paths) { final SAXParser parser = factory.newSAXParser(); final XMLReader reader = parser.getXMLReader(); reader.setErrorHandler(new ErrorHandler() { @Override public void warning(final SAXParseException exception) throws SAXException { // ignore } @Override public void error(final SAXParseException exception) throws SAXException { fail(exception); } @Override public void fatalError(final SAXParseException exception) throws SAXException { fail(exception); } private void fail(final SAXParseException exception) { Assert.fail(String.format("%s - Line: %d Column: %d%nPath: %s", exception.getMessage(), exception.getLineNumber(), exception.getColumnNumber(), path)); } }); try (final Reader fileReader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) { reader.parse(new InputSource(fileReader)); } } } private static Collection findFiles(final ReportType reportType) throws IOException { final Path dir = Paths.get(TEST_REPORT_PATH); final List paths = new ArrayList<>(); Files.walkFileTree(dir, new SimpleFileVisitor() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith(reportType.getExtension())) { paths.add(file); } return FileVisitResult.CONTINUE; } }); return paths; } } TestReportLogger.java000066400000000000000000000035561356560461700361300ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/report/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.report; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.logging.annotations.ResolutionDoc; /** * Used for validating the XML for a {@code resolutionUrl} attribute. * * @author James R. Perkins */ @MessageLogger(projectCode = "RPTL", length = 5) @ResolutionDoc public interface TestReportLogger { @LogMessage(level = Level.INFO) @Message(id = 1, value = "Test message") @ResolutionDoc(suffix = ".html") void containsUrl(); @LogMessage(level = Level.INFO) @Message("Test message") void noUrl(); @LogMessage(level = Level.INFO) @Message(id = 2, value = "Test message") void defaultResolutionUrl(); } TestReportMessages.java000066400000000000000000000033651356560461700364560ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/report/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.report; import org.jboss.logging.annotations.BaseUrl; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageBundle; import org.jboss.logging.annotations.ResolutionDoc; /** * Used for validating the XML for a {@code resolutionUrl} attribute. * @author James R. Perkins */ @BaseUrl("http://jboss.org/") @MessageBundle(projectCode = "RPTM") public interface TestReportMessages { @Message(id = 1, value = "Test message") @ResolutionDoc RuntimeException defaultUrl(); @Message("Test message") RuntimeException noUrl(); @Message(id = 2, value = "Test message") @ResolutionDoc RuntimeException containsUrl(); } jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/util/000077500000000000000000000000001356560461700315225ustar00rootroot00000000000000ExpressionsTest.java000066400000000000000000000047541356560461700355020ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2017, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import java.io.IOException; import java.util.Properties; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; /** * @author James R. Perkins */ public class ExpressionsTest { private static final Properties PROPERTIES = new Properties(); @BeforeClass public static void configureProperties() throws IOException { PROPERTIES.load(ExpressionsTest.class.getResourceAsStream("/expression.properties")); } @Test public void testEnvironmentVariables() throws Exception { Assert.assertEquals("envValue", Expressions.resolve(PROPERTIES, "${env.JBOSS_LOGGING_TEST_VAR}")); Assert.assertEquals("defaultValue", Expressions.resolve(PROPERTIES, "${env.JBOSS_LOGGING_TEST_INVALID:defaultValue}")); } @Test public void testSystemProperties() { Assert.assertEquals(System.getProperty("user.home"), Expressions.resolve(PROPERTIES, "${sys.user.home}")); Assert.assertEquals("sysValue", Expressions.resolve(PROPERTIES, "${sys.test.property}")); Assert.assertEquals("defaultValue", Expressions.resolve(PROPERTIES, "${sys.invalid.property:defaultValue}")); } @Test public void testProperties() { Assert.assertEquals("test property value", Expressions.resolve(PROPERTIES, "${test.property}")); Assert.assertEquals("defaultValue", Expressions.resolve(PROPERTIES, "${invalid.property:defaultValue}")); } } VersionComparatorTest.java000066400000000000000000000034611356560461700366270ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/util/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.util; import org.junit.Assert; import org.junit.Test; /** * Date: 09.11.2011 * * @author James R. Perkins */ public class VersionComparatorTest { @Test public void testComparator() { final String version = "3.1"; Assert.assertTrue(VersionComparator.compareVersion("3.1.1", version) > 0); Assert.assertTrue(VersionComparator.compareVersion("3.1", version) == 0); Assert.assertTrue(VersionComparator.compareVersion("3.0", version) < 0); Assert.assertTrue(VersionComparator.compareVersion("3.0.1", version) < 0); Assert.assertTrue(VersionComparator.compareVersion("3.0.1", version) < 0); Assert.assertTrue(VersionComparator.compareVersion("3.1.x", version) == 0); } } jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/validation/000077500000000000000000000000001356560461700326775ustar00rootroot00000000000000MessageFormatValidatorTest.java000066400000000000000000000045321356560461700407320ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; /** * Date: 14.06.2011 * * @author James R. Perkins */ public class MessageFormatValidatorTest { @Test public void validFormats() { MessageFormatValidator validator = MessageFormatValidator.of("Message {} is valid."); assertTrue(validator.detailMessage(), validator.isValid()); validator = MessageFormatValidator.of("Parameter {1} is not compatible with {2}."); assertTrue(validator.detailMessage(), validator.isValid()); } @Test public void invalidFormats() { MessageFormatValidator validator = MessageFormatValidator.of("Invalid parameter { is not valid."); assertFalse(validator.isValid()); } @Test public void validateParameterCount() { MessageFormatValidator validator = MessageFormatValidator.of("{}", "Test"); assertTrue(validator.detailMessage(), validator.isValid()); validator = MessageFormatValidator.of("{1} {0}", "Test", "Test2"); assertTrue(validator.detailMessage(), validator.isValid()); validator = MessageFormatValidator.of("{0} {0}", "Test"); assertTrue(validator.detailMessage(), validator.isValid()); } } StringFormatValidatorTest.java000066400000000000000000000121531356560461700406120ustar00rootroot00000000000000jboss-logging-tools-2.2.1.Final/processor/src/test/java/org/jboss/logging/processor/validation/* * JBoss, Home of Professional Open Source. * Copyright 2016, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.logging.processor.validation; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.Date; import org.junit.Test; /** * Date: 14.06.2011 * * @author James R. Perkins */ public class StringFormatValidatorTest { @Test public void validFormats() { final StringBuilder sb = new StringBuilder(); for (StringFormatPart.Conversion conversion : StringFormatPart.Conversion.values()) { sb.append("%").append(conversion.asChar()); if (conversion.isDateTime()) { sb.append("m "); } else { sb.append(" "); } } StringFormatValidator validator = StringFormatValidator.of(sb.toString()); assertTrue(validator.detailMessage(), validator.isValid()); final String[] validFormats = { "%1$s %1$s %1$s", "Duke's Birthday: %1$tm %1$te,%1$tY", "Duke's Birthday: %1$tm %