Search in sources :

Example 1 with ToString

use of lombok.ToString in project lombok by rzwitserloot.

the class HandleToString method createToString.

public static MethodDeclaration createToString(EclipseNode type, Collection<EclipseNode> fields, boolean includeFieldNames, boolean callSuper, ASTNode source, FieldAccess fieldAccess) {
    String typeName = getTypeName(type);
    char[] suffix = ")".toCharArray();
    String infixS = ", ";
    char[] infix = infixS.toCharArray();
    int pS = source.sourceStart, pE = source.sourceEnd;
    long p = (long) pS << 32 | pE;
    final int PLUS = OperatorIds.PLUS;
    char[] prefix;
    if (callSuper) {
        prefix = (typeName + "(super=").toCharArray();
    } else if (fields.isEmpty()) {
        prefix = (typeName + "()").toCharArray();
    } else if (includeFieldNames) {
        prefix = (typeName + "(" + new String(((FieldDeclaration) fields.iterator().next().get()).name) + "=").toCharArray();
    } else {
        prefix = (typeName + "(").toCharArray();
    }
    boolean first = true;
    Expression current = new StringLiteral(prefix, pS, pE, 0);
    setGeneratedBy(current, source);
    if (callSuper) {
        MessageSend callToSuper = new MessageSend();
        callToSuper.sourceStart = pS;
        callToSuper.sourceEnd = pE;
        setGeneratedBy(callToSuper, source);
        callToSuper.receiver = new SuperReference(pS, pE);
        setGeneratedBy(callToSuper, source);
        callToSuper.selector = "toString".toCharArray();
        current = new BinaryExpression(current, callToSuper, PLUS);
        setGeneratedBy(current, source);
        first = false;
    }
    for (EclipseNode field : fields) {
        TypeReference fieldType = getFieldType(field, fieldAccess);
        Expression fieldAccessor = createFieldAccessor(field, fieldAccess, source);
        // The distinction between primitive and object will be useful if we ever add a 'hideNulls' option.
        boolean fieldBaseTypeIsPrimitive = BUILT_IN_TYPES.contains(new String(fieldType.getLastToken()));
        boolean fieldIsPrimitive = fieldType.dimensions() == 0 && fieldBaseTypeIsPrimitive;
        boolean fieldIsPrimitiveArray = fieldType.dimensions() == 1 && fieldBaseTypeIsPrimitive;
        boolean fieldIsObjectArray = fieldType.dimensions() > 0 && !fieldIsPrimitiveArray;
        @SuppressWarnings("unused") boolean fieldIsObject = !fieldIsPrimitive && !fieldIsPrimitiveArray && !fieldIsObjectArray;
        Expression ex;
        if (fieldIsPrimitiveArray || fieldIsObjectArray) {
            MessageSend arrayToString = new MessageSend();
            arrayToString.sourceStart = pS;
            arrayToString.sourceEnd = pE;
            arrayToString.receiver = generateQualifiedNameRef(source, TypeConstants.JAVA, TypeConstants.UTIL, "Arrays".toCharArray());
            arrayToString.arguments = new Expression[] { fieldAccessor };
            setGeneratedBy(arrayToString.arguments[0], source);
            arrayToString.selector = (fieldIsObjectArray ? "deepToString" : "toString").toCharArray();
            ex = arrayToString;
        } else {
            ex = fieldAccessor;
        }
        setGeneratedBy(ex, source);
        if (first) {
            current = new BinaryExpression(current, ex, PLUS);
            current.sourceStart = pS;
            current.sourceEnd = pE;
            setGeneratedBy(current, source);
            first = false;
            continue;
        }
        StringLiteral fieldNameLiteral;
        if (includeFieldNames) {
            char[] namePlusEqualsSign = (infixS + field.getName() + "=").toCharArray();
            fieldNameLiteral = new StringLiteral(namePlusEqualsSign, pS, pE, 0);
        } else {
            fieldNameLiteral = new StringLiteral(infix, pS, pE, 0);
        }
        setGeneratedBy(fieldNameLiteral, source);
        current = new BinaryExpression(current, fieldNameLiteral, PLUS);
        setGeneratedBy(current, source);
        current = new BinaryExpression(current, ex, PLUS);
        setGeneratedBy(current, source);
    }
    if (!first) {
        StringLiteral suffixLiteral = new StringLiteral(suffix, pS, pE, 0);
        setGeneratedBy(suffixLiteral, source);
        current = new BinaryExpression(current, suffixLiteral, PLUS);
        setGeneratedBy(current, source);
    }
    ReturnStatement returnStatement = new ReturnStatement(current, pS, pE);
    setGeneratedBy(returnStatement, source);
    MethodDeclaration method = new MethodDeclaration(((CompilationUnitDeclaration) type.top().get()).compilationResult);
    setGeneratedBy(method, source);
    method.modifiers = toEclipseModifier(AccessLevel.PUBLIC);
    method.returnType = new QualifiedTypeReference(TypeConstants.JAVA_LANG_STRING, new long[] { p, p, p });
    setGeneratedBy(method.returnType, source);
    method.annotations = new Annotation[] { makeMarkerAnnotation(TypeConstants.JAVA_LANG_OVERRIDE, source) };
    method.arguments = null;
    method.selector = "toString".toCharArray();
    method.thrownExceptions = null;
    method.typeParameters = null;
    method.bits |= Eclipse.ECLIPSE_DO_NOT_TOUCH_FLAG;
    method.bodyStart = method.declarationSourceStart = method.sourceStart = source.sourceStart;
    method.bodyEnd = method.declarationSourceEnd = method.sourceEnd = source.sourceEnd;
    method.statements = new Statement[] { returnStatement };
    return method;
}
Also used : MethodDeclaration(org.eclipse.jdt.internal.compiler.ast.MethodDeclaration) ToString(lombok.ToString) FieldDeclaration(org.eclipse.jdt.internal.compiler.ast.FieldDeclaration) SuperReference(org.eclipse.jdt.internal.compiler.ast.SuperReference) MessageSend(org.eclipse.jdt.internal.compiler.ast.MessageSend) StringLiteral(org.eclipse.jdt.internal.compiler.ast.StringLiteral) BinaryExpression(org.eclipse.jdt.internal.compiler.ast.BinaryExpression) Expression(org.eclipse.jdt.internal.compiler.ast.Expression) BinaryExpression(org.eclipse.jdt.internal.compiler.ast.BinaryExpression) QualifiedTypeReference(org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference) ReturnStatement(org.eclipse.jdt.internal.compiler.ast.ReturnStatement) EclipseNode(lombok.eclipse.EclipseNode) TypeReference(org.eclipse.jdt.internal.compiler.ast.TypeReference) QualifiedTypeReference(org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference)

Example 2 with ToString

use of lombok.ToString in project lombok by rzwitserloot.

the class HandleToString method handle.

public void handle(AnnotationValues<ToString> annotation, Annotation ast, EclipseNode annotationNode) {
    handleFlagUsage(annotationNode, ConfigurationKeys.TO_STRING_FLAG_USAGE, "@ToString");
    ToString ann = annotation.getInstance();
    List<String> excludes = Arrays.asList(ann.exclude());
    List<String> includes = Arrays.asList(ann.of());
    EclipseNode typeNode = annotationNode.up();
    Boolean callSuper = ann.callSuper();
    if (!annotation.isExplicit("callSuper"))
        callSuper = null;
    if (!annotation.isExplicit("exclude"))
        excludes = null;
    if (!annotation.isExplicit("of"))
        includes = null;
    if (excludes != null && includes != null) {
        excludes = null;
        annotation.setWarning("exclude", "exclude and of are mutually exclusive; the 'exclude' parameter will be ignored.");
    }
    checkForBogusFieldNames(typeNode, annotation);
    Boolean doNotUseGettersConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_DO_NOT_USE_GETTERS);
    boolean doNotUseGetters = annotation.isExplicit("doNotUseGetters") || doNotUseGettersConfiguration == null ? ann.doNotUseGetters() : doNotUseGettersConfiguration;
    FieldAccess fieldAccess = doNotUseGetters ? FieldAccess.PREFER_FIELD : FieldAccess.GETTER;
    Boolean fieldNamesConfiguration = annotationNode.getAst().readConfiguration(ConfigurationKeys.TO_STRING_INCLUDE_FIELD_NAMES);
    boolean includeFieldNames = annotation.isExplicit("includeFieldNames") || fieldNamesConfiguration == null ? ann.includeFieldNames() : fieldNamesConfiguration;
    generateToString(typeNode, annotationNode, excludes, includes, includeFieldNames, callSuper, true, fieldAccess);
}
Also used : EclipseNode(lombok.eclipse.EclipseNode) ToString(lombok.ToString) ToString(lombok.ToString) FieldAccess(lombok.eclipse.handlers.EclipseHandlerUtil.FieldAccess)

Example 3 with ToString

use of lombok.ToString in project cas by apereo.

the class PersonDirectoryPrincipalResolver method convertPersonAttributesToPrincipal.

/**
 * Convert person attributes to principal pair.
 *
 * @param extractedPrincipalId the extracted principal id
 * @param attributes           the attributes
 * @return the pair
 */
protected Pair<String, Map<String, Object>> convertPersonAttributesToPrincipal(final String extractedPrincipalId, final Map<String, List<Object>> attributes) {
    final String[] principalId = { extractedPrincipalId };
    final Map<String, Object> convertedAttributes = new HashMap<>();
    attributes.entrySet().stream().forEach(entry -> {
        final String key = entry.getKey();
        LOGGER.debug("Found attribute [{}]", key);
        final List<Object> values = entry.getValue();
        if (StringUtils.isNotBlank(this.principalAttributeName) && key.equalsIgnoreCase(this.principalAttributeName)) {
            if (values.isEmpty()) {
                LOGGER.debug("[{}] is empty, using [{}] for principal", this.principalAttributeName, extractedPrincipalId);
            } else {
                principalId[0] = values.get(0).toString();
                LOGGER.debug("Found principal attribute value [{}]; removing [{}] from attribute map.", extractedPrincipalId, this.principalAttributeName);
            }
        } else {
            convertedAttributes.put(key, values.size() == 1 ? values.get(0) : values);
        }
    });
    return Pair.of(principalId[0], convertedAttributes);
}
Also used : HashMap(java.util.HashMap) ToString(lombok.ToString)

Example 4 with ToString

use of lombok.ToString in project cas by apereo.

the class DefaultRegisteredServiceAccessStrategy method requiredAttributesFoundInMap.

/**
 * Check whether required attributes are found in the given map.
 *
 * @param principalAttributes the principal attributes
 * @param requiredAttributes  the attributes
 * @return the boolean
 */
protected boolean requiredAttributesFoundInMap(final Map<String, Object> principalAttributes, final Map<String, Set<String>> requiredAttributes) {
    final Set<String> difference = requiredAttributes.keySet().stream().filter(a -> principalAttributes.keySet().contains(a)).collect(Collectors.toSet());
    if (this.requireAllAttributes && difference.size() < requiredAttributes.size()) {
        return false;
    }
    return difference.stream().anyMatch(key -> {
        final Set<String> values = requiredAttributes.get(key);
        final Set<Object> availableValues = CollectionUtils.toCollection(principalAttributes.get(key));
        final Pattern pattern = RegexUtils.concatenate(values, this.caseInsensitive);
        if (pattern != RegexUtils.MATCH_NOTHING_PATTERN) {
            return availableValues.stream().map(Object::toString).anyMatch(pattern.asPredicate());
        }
        return availableValues.stream().anyMatch(values::contains);
    });
}
Also used : Setter(lombok.Setter) Getter(lombok.Getter) Set(java.util.Set) HashMap(java.util.HashMap) EqualsAndHashCode(lombok.EqualsAndHashCode) Collectors(java.util.stream.Collectors) RegexUtils(org.apereo.cas.util.RegexUtils) Slf4j(lombok.extern.slf4j.Slf4j) ObjectUtils(org.apache.commons.lang3.ObjectUtils) PostLoad(javax.persistence.PostLoad) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) ToString(lombok.ToString) CollectionUtils(org.apereo.cas.util.CollectionUtils) URI(java.net.URI) Pattern(java.util.regex.Pattern) Pattern(java.util.regex.Pattern) ToString(lombok.ToString)

Example 5 with ToString

use of lombok.ToString in project MantaroBot by Mantaro.

the class DBUser method generateAndApplyPremiumKey.

@JsonIgnore
public PremiumKey generateAndApplyPremiumKey(int days, String owner) {
    String premiumId = UUID.randomUUID().toString();
    PremiumKey newKey = new PremiumKey(premiumId, TimeUnit.DAYS.toMillis(days), currentTimeMillis() + TimeUnit.DAYS.toMillis(days), PremiumKey.Type.USER, true, owner);
    data.setPremiumKey(premiumId);
    newKey.saveAsync();
    saveAsync();
    return newKey;
}
Also used : ToString(lombok.ToString) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore)

Aggregations

ToString (lombok.ToString)28 Map (java.util.Map)6 HashMap (java.util.HashMap)5 List (java.util.List)4 HashSet (java.util.HashSet)3 EclipseNode (lombok.eclipse.EclipseNode)3 Slf4j (lombok.extern.slf4j.Slf4j)3 lombok.val (lombok.val)3 JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)2 Github (com.jcabi.github.Github)2 JCVariableDecl (com.sun.tools.javac.tree.JCTree.JCVariableDecl)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 LinkedHashMap (java.util.LinkedHashMap)2 Optional (java.util.Optional)2 Collectors (java.util.stream.Collectors)2 Collectors.toList (java.util.stream.Collectors.toList)2 Collectors.toMap (java.util.stream.Collectors.toMap)2 Getter (lombok.Getter)2