Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for excluding fields from generated toString methods #720

Merged
merged 1 commit into from
Apr 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ public class Jsonschema2PojoTask extends Task implements GenerationConfig {

private boolean includeToString = true;

private String[] toStringExcludes = new String[] {};

private AnnotationStyle annotationStyle = AnnotationStyle.JACKSON;

private InclusionLevel inclusionLevel = InclusionLevel.NON_NULL;
Expand Down Expand Up @@ -808,6 +810,11 @@ public boolean isIncludeToString() {
return includeToString;
}

@Override
public String[] getToStringExcludes() {
return toStringExcludes;
}

@Override
public AnnotationStyle getAnnotationStyle() {
return annotationStyle;
Expand Down
5 changes: 5 additions & 0 deletions jsonschema2pojo-ant/src/site/Jsonschema2PojoTask.html
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,11 @@ <h3>Parameters</h3>
<td valign="top">Whether to use include a <code>toString</code> method in generated Java types.</td>
<td align="center" valign="top">No (default <code>true</code>)</td>
</tr>
<tr>
<td valign="top">toStringExcludes</td>
<td valign="top">A string containing fields to be excluded from toString generation.</td>
<td align="center" valign="top">No (default <code>""</code> (none))</td>
</tr>
<tr>
<td valign="top">initializeCollections</td>
<td valign="top">Whether to initialize Set and List fields as empty collections, or leave them as
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ public class Arguments implements GenerationConfig {

@Parameter(names = { "-S", "--omit-tostring" }, description = "Omit the toString method in the generated Java types")
private boolean omitToString = false;

@Parameter(names = { "-tse", "--tostring-excludes" }, description = "The fields that should be excluded from generated toString methods")
private String toStringExcludes = "";

@Parameter(names = { "-a", "--annotation-style" })
private AnnotationStyle annotationStyle = AnnotationStyle.JACKSON;
Expand Down Expand Up @@ -266,6 +269,11 @@ public boolean isIncludeToString() {
return !omitToString;
}

@Override
public String[] getToStringExcludes() {
return defaultString(toStringExcludes).split(" ");
}

@Override
public AnnotationStyle getAnnotationStyle() {
return annotationStyle;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,14 @@ public boolean isIncludeHashcodeAndEquals() {
public boolean isIncludeToString() {
return true;
}

/**
* @return no exclusions
*/
@Override
public String[] getToStringExcludes() {
return new String[] {};
}

/**
* @return {@link AnnotationStyle#JACKSON2}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,15 @@ public interface GenerationConfig {
* generated Java types.
*/
boolean isIncludeToString();


/**
* Gets the 'toStringExcludes' configuration option.
*
* @return An array of strings representing fields
* that should be excluded from toString methods
*/
String[] getToStringExcludes();

/**
* Gets the 'annotationStyle' configuration option.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import com.fasterxml.jackson.databind.JsonNode;
import com.sun.codemodel.ClassType;
import com.sun.codemodel.JAnnotationUse;
import com.sun.codemodel.JArray;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JClass;
import com.sun.codemodel.JClassAlreadyExistsException;
Expand Down Expand Up @@ -373,12 +374,25 @@ private void addJsonTypeInfoAnnotation(JDefinedClass jclass, JsonNode node) {
private void addToString(JDefinedClass jclass) {
JMethod toString = jclass.method(JMod.PUBLIC, String.class, "toString");

Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class;

JBlock body = toString.body();
JInvocation reflectionToString = jclass.owner().ref(toStringBuilder).staticInvoke("reflectionToString");
reflectionToString.arg(JExpr._this());
body._return(reflectionToString);

if ( ruleFactory.getGenerationConfig().getToStringExcludes().length > 0 ) {
Class<?> reflectionToStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ReflectionToStringBuilder.class : org.apache.commons.lang.builder.ReflectionToStringBuilder.class;
JInvocation toStringExclude = jclass.owner().ref(reflectionToStringBuilder).staticInvoke("toStringExclude");

JArray arr = JExpr.newArray(jclass.owner().ref(String.class));
for ( String exclude : ruleFactory.getGenerationConfig().getToStringExcludes() ) {
arr.add(JExpr.lit(exclude));
}

toStringExclude.arg(JExpr._this()).arg(arr);
body._return(toStringExclude);
} else {
Class<?> toStringBuilder = ruleFactory.getGenerationConfig().isUseCommonsLang3() ? org.apache.commons.lang3.builder.ToStringBuilder.class : org.apache.commons.lang.builder.ToStringBuilder.class;
JInvocation reflectionToString = jclass.owner().ref(toStringBuilder).staticInvoke("reflectionToString");
reflectionToString.arg(JExpr._this());
body._return(reflectionToString);
}

toString.annotate(Override.class);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public class JsonSchemaExtension implements GenerationConfig {
boolean includeJsr303Annotations
boolean includeJsr305Annotations
boolean includeToString
String[] toStringExcludes
boolean initializeCollections
String outputEncoding
boolean parcelable
Expand Down Expand Up @@ -93,6 +94,7 @@ public class JsonSchemaExtension implements GenerationConfig {
includeConstructors = false
constructorsRequiredPropertiesOnly = false
includeToString = true
toStringExcludes = [] as String[]
annotationStyle = AnnotationStyle.JACKSON
inclusionLevel = InclusionLevel.NON_NULL
customAnnotator = NoopAnnotator.class
Expand Down Expand Up @@ -181,6 +183,7 @@ public class JsonSchemaExtension implements GenerationConfig {
|includeHashcodeAndEquals = ${includeHashcodeAndEquals}
|includeConstructors = ${includeConstructors}
|includeToString = ${includeToString}
|toStringExcludes = ${Arrays.toString(toStringExcludes)}
|annotationStyle = ${annotationStyle.toString().toLowerCase()}
|inclusionLevel = ${InclusionLevel.toString() }
|customAnnotator = ${customAnnotator.getName()}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
*
* 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.jsonschema2pojo.integration.config;

import static org.jsonschema2pojo.integration.util.CodeGenerationHelper.config;
import static org.junit.Assert.*;

import java.lang.reflect.Method;
import java.util.Map;

import org.jsonschema2pojo.integration.util.Jsonschema2PojoRule;
import org.junit.Rule;
import org.junit.Test;

public class IncludeToStringExcludesIT {

@Rule public Jsonschema2PojoRule schemaRule = new Jsonschema2PojoRule();

@SuppressWarnings({ "unchecked", "rawtypes" })
private void testConfig(Map<String,Object> config, String expectedResultTemplate) throws ClassNotFoundException, SecurityException, NoSuchMethodException {
ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config);

Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");

// throws NoSuchMethodException if method is not found
Method toString = generatedType.getDeclaredMethod("toString");
try {
Object primitiveProperties = generatedType.newInstance();
Object result = toString.invoke(primitiveProperties);
assertEquals(String.format(expectedResultTemplate, Integer.toHexString(System.identityHashCode(primitiveProperties))), result);
} catch (Exception e) {
fail("Unable to invoke toString method: "+ e.getMessage());
}
}

@Test
public void beansIncludeAllToStringPropertiesByDefaultCL() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config(),
"com.example.PrimitiveProperties@%s[a=<null>,b=<null>,c=<null>,additionalProperties={}]");
}

@Test
public void beansIncludeAllToStringPropertiesByDefaultCL3() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config("useCommonsLang3", true),
"com.example.PrimitiveProperties@%s[a=<null>,b=<null>,c=<null>,additionalProperties={}]");
}

@Test
public void beansOmitToStringPropertiesWhenConfigIsSetCL() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config("toStringExcludes", new String[] {"b","c"}),
"com.example.PrimitiveProperties@%s[a=<null>,additionalProperties={}]");
}

@Test
public void beansOmitToStringPropertiesWhenConfigIsSetCL3() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
testConfig(config("useCommonsLang3", true,"toStringExcludes", new String[] {"b","c"}),
"com.example.PrimitiveProperties@%s[a=<null>,additionalProperties={}]");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ public void beansIncludeToStringByDefault() throws ClassNotFoundException, Secur

@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void beansOmitHashCodeAndEqualsWhenConfigIsSet() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
public void beansOmitToStringWhenConfigIsSet() throws ClassNotFoundException, SecurityException, NoSuchMethodException {
ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/primitiveProperties.json", "com.example", config("includeToString", false));

Class generatedType = resultsClassLoader.loadClass("com.example.PrimitiveProperties");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,15 @@ public class Jsonschema2PojoMojo extends AbstractMojo implements GenerationConfi
* @since 0.3.1
*/
private boolean includeToString = true;

/**
* The fields to be excluded from toString generation
*
* @parameter expression="${jsonschema2pojo.toStringExcludes}"
* default-value=""
* @since 0.4.34
*/
private String[] toStringExcludes = new String[] {};

/**
* The style of annotations to use in the generated Java types.
Expand Down Expand Up @@ -761,6 +770,11 @@ public boolean isIncludeHashcodeAndEquals() {
public boolean isIncludeToString() {
return includeToString;
}

@Override
public String[] getToStringExcludes() {
return toStringExcludes;
}

@Override
public AnnotationStyle getAnnotationStyle() {
Expand Down