com.github.triceo.robozonky.internal.api.ToStringBuilder Maven / Gradle / Ivy
/*
* Copyright 2017 Lukáš Petrovický
*
* 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 com.github.triceo.robozonky.internal.api;
import java.lang.reflect.Field;
import java.util.Objects;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class ToStringBuilder {
private final ReflectionToStringBuilder builder;
public ToStringBuilder(final Object o, final String... excludeFields) {
this.builder = new ToStringBuilder.CustomReflectionToStringBuilder(o)
.setExcludeFieldNames(excludeFields);
}
public ToStringBuilder(final Object o) {
this(o, "password");
}
@Override
public String toString() {
return this.builder.toString();
}
private static class CustomReflectionToStringBuilder extends ReflectionToStringBuilder {
private static final int MAX_STRING_LENGTH = 70;
public CustomReflectionToStringBuilder(final Object o) {
super(o);
}
@Override
protected boolean accept(final Field field) { // ignore passwords
return super.accept(field) && (!Objects.equals(field.getType(), char[].class));
}
@Override
protected Object getValue(final Field field) throws IllegalAccessException {
final Object value = super.getValue(field);
if (value != null && Objects.equals(field.getType(), String.class)) { // long strings will get truncated
final String stringValue = (String)value;
final int length = ToStringBuilder.CustomReflectionToStringBuilder.MAX_STRING_LENGTH;
if (stringValue.length() > length) {
return stringValue.substring(0, length) + "...";
}
}
return value;
}
}
}