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

Whitespaces at the head of line before a cast and after an instanceof or an "enhanced for" results to "'(' should be on the previous line"error #10012

Closed
JacquesLeRoux opened this issue May 17, 2021 · 12 comments

Comments

@JacquesLeRoux
Copy link

JacquesLeRoux commented May 17, 2021

Hi,

I'm a committer of the Apache OFBiz project. We use a checkstyle configuration corresponding to the OFBiz coding conventions roughly simplified “Sun Coding Standards” 150 characters line length and NewlineAtEndOfFile value="lf_cr_crlf"

Below, first, only the relevant parts are shown (checkstyle and 2 Java classes).
Then, for each, the complete source using the "details" tag.

C:\projectsASF\Git\ofbiz-framework>type config\checkstyle\checkstyle.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
          "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
          "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <module name="TreeWalker">
        <!-- Checks for whitespace -->
        <module name="EmptyForIteratorPad"/>
        <module name="GenericWhitespace"/>
        <module name="MethodParamPad"/>
        <module name="NoWhitespaceAfter"/>
        <module name="NoWhitespaceBefore"/>
        <module name="OperatorWrap"/>
        <module name="SeparatorWrap">
            <property name="tokens"
                      value="COMMA,LPAREN,RPAREN,RBRACK,ARRAY_DECLARATOR"/>
            <property name="option" value="eol"/>
        </module>
        <module name="SeparatorWrap">
            <property name="tokens" value="DOT,METHOD_REF,ELLIPSIS,AT"/>
            <property name="option" value="nl"/>
        </module>
        <module name="ParenPad"/>
        <module name="TypecastParenPad"/>
        <module name="WhitespaceAfter"/>
        <module name="WhitespaceAround"/>
        <module name="SingleSpaceSeparator"/>
        </module>
    </module>
</module>
<!-- General file conventions -->
<module name="NewlineAtEndOfFile">
    <property name="lineSeparator" value="lf_cr_crlf" />
</module>
<module name="FileTabCharacter"/>
<module name="RegexpSingleline">
   <property name="format" value="\s+$"/>
   <property name="minimum" value="0"/>
   <property name="maximum" value="0"/>
   <property name="message" value="Line has trailing spaces."/>
</module>
<module name="LineLength">
    <property name="max" value="150"/>
</module>

<module name="TreeWalker">
    <!-- Naming conventions -->
    <module name="ConstantName"/>
    <module name="LocalFinalVariableName"/>
    <module name="LocalVariableName"/>
    <module name="MemberName"/>
    <module name="MethodName"/>
    <module name="PackageName"/>
    <module name="ParameterName"/>
    <module name="StaticVariableName"/>
    <module name="TypeName"/>

    <!-- Checks for imports -->
    <module name="AvoidStarImport"/>
    <module name="IllegalImport"/>
    <module name="RedundantImport"/>
    <module name="UnusedImports">
        <property name="processJavadoc" value="false"/>
    </module>

    <!-- Checks for Size Violations -->
    <module name="MethodLength">
        <property name="tokens" value="METHOD_DEF"/>
        <property name="max" value="500"/>
        <property name="countEmpty" value="false"/>
    </module>
    <module name="ParameterNumber">
        <property name="max" value="10"/>
        <property name="tokens" value="METHOD_DEF"/>
        <property name="ignoreOverriddenMethods" value="true"/>
    </module>

    <!-- Checks for whitespace -->
    <module name="EmptyForIteratorPad"/>
    <module name="GenericWhitespace"/>
    <module name="MethodParamPad"/>
    <module name="NoWhitespaceAfter"/>
    <module name="NoWhitespaceBefore"/>
    <module name="OperatorWrap"/>
    <module name="SeparatorWrap">
        <property name="tokens"
                  value="COMMA,LPAREN,RPAREN,RBRACK,ARRAY_DECLARATOR"/>
        <property name="option" value="eol"/>
    </module>
    <module name="SeparatorWrap">
        <property name="tokens" value="DOT,METHOD_REF,ELLIPSIS,AT"/>
        <property name="option" value="nl"/>
    </module>
    <module name="ParenPad"/>
    <module name="TypecastParenPad"/>
    <module name="WhitespaceAfter"/>
    <module name="WhitespaceAround"/>
    <module name="SingleSpaceSeparator"/>

    <!-- Modifier Checks -->
    <module name="ModifierOrder"/>
    <module name="RedundantModifier"/>

    <!-- Checks for blocks. You know, those {}'s -->
    <module name="AvoidNestedBlocks"/>
    <module name="EmptyBlock"/>
    <module name="LeftCurly"/>
    <module name="NeedBraces">
        <property name="allowSingleLineStatement" value="true"/>
    </module>
    <module name="RightCurly"/>

    <!-- Checks for common coding problems -->
    <module name="EmptyStatement"/>
    <module name="EqualsHashCode"/>
    <module name="IllegalInstantiation"/>
    <module name="InnerAssignment"/>
    <module name="MultipleVariableDeclarations"/>
    <module name="SimplifyBooleanExpression"/>
    <module name="SimplifyBooleanReturn"/>

    <!-- Checks for class design -->
    <module name="DesignForExtension">
        <property name="ignoredAnnotations"
                  value="After, AfterClass, Before, BeforeClass, Test, Property, Override"/>
    </module>
    <module name="FinalClass"/>
    <!-- <module name="HideUtilityClassConstructor"/> -->
    <module name="InterfaceIsType"/>
    <module name="VisibilityModifier"/>

    <!-- Miscellaneous other checks -->
    <!-- module name="ArrayTypeStyle"/-->
    <module name="UpperEll"/>
    <module name="Indentation">
        <property name="caseIndent" value="0"/>
        <property name="lineWrappingIndentation" value="8"/>
    </module>

    <!-- Checks for annotations -->
    <module name="MissingOverride"/>

    <!-- Filters -->
    <module name="SuppressionCommentFilter">
        <!-- This is useful when having deprecated public fields
             which have been superseded by public accessors. -->
        <property name="offCommentFormat" value="ALLOW PUBLIC FIELDS"/>
        <property name="onCommentFormat" value="FORBID PUBLIC FIELDS"/>
        <property name="checkFormat" value="VisibilityModifier"/>
    </module>
</module>

C:\projectsASF\Git\ofbiz-framework>type framework\base\src\main\java\org\apache\ofbiz\base\conversion\NumberConverters.java

        NumberFormat nf = NumberFormat.getNumberInstance(locale);
        if (nf instanceof DecimalFormat) {
            ((DecimalFormat) nf).setParseBigDecimal(true);
        }
}
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.ofbiz.base.conversion;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.ofbiz.base.util.StringUtil;

/** Number Converter classes. */
public class NumberConverters implements ConverterLoader {

protected static Number fromString(String str, Locale locale) throws ConversionException {
    NumberFormat nf = NumberFormat.getNumberInstance(locale);
    if (nf instanceof DecimalFormat) {
        ((DecimalFormat) nf).setParseBigDecimal(true);
    }
    try {
        return nf.parse(str);
    } catch (ParseException e) {
        throw new ConversionException(e);
    }
}

public abstract static class AbstractStringToNumberConverter<N extends Number> extends AbstractNumberConverter<String, N> {
    public AbstractStringToNumberConverter(Class<N> targetClass) {
        super(String.class, targetClass);
    }

    @Override
    public N convert(String obj, Locale locale, TimeZone timeZone) throws ConversionException {
        String trimStr = StringUtil.removeSpaces(obj);
        if (trimStr.isEmpty()) {
            return null;
        }
        return convert(fromString(trimStr, locale));
    }

    protected abstract N convert(Number number) throws ConversionException;
}

public abstract static class AbstractNumberConverter<S, T> extends AbstractLocalizedConverter<S, T> {
    protected AbstractNumberConverter(Class<S> sourceClass, Class<T> targetClass) {
        super(sourceClass, targetClass);
    }

    @Override
    public T convert(S obj, Locale locale, TimeZone timeZone, String formatString) throws ConversionException {
        return convert(obj, locale, null);
    }
}

public abstract static class AbstractNumberToStringConverter<N extends Number> extends AbstractNumberConverter<N, String> {
    public AbstractNumberToStringConverter(Class<N> sourceClass) {
        super(sourceClass, String.class);
    }

    @Override
    public String convert(N obj) throws ConversionException {
        return obj.toString();
    }

    @Override
    public String convert(N obj, Locale locale, TimeZone timeZone) throws ConversionException {
        return format(obj, NumberFormat.getNumberInstance(locale));
    }

    protected abstract String format(N obj, NumberFormat nf) throws ConversionException;
}

public static class GenericNumberToDouble<N extends Number> extends AbstractConverter<N, Double> {
    public GenericNumberToDouble(Class<N> sourceClass) {
        super(sourceClass, Double.class);
    }

    @Override
    public Double convert(N obj) throws ConversionException {
        return obj.doubleValue();
    }
}

public static class GenericNumberToFloat<N extends Number> extends AbstractConverter<N, Float> {
    public GenericNumberToFloat(Class<N> sourceClass) {
        super(sourceClass, Float.class);
    }

    @Override
    public Float convert(N obj) throws ConversionException {
        return obj.floatValue();
    }
}

public static class GenericNumberToInteger<N extends Number> extends AbstractConverter<N, Integer> {
    public GenericNumberToInteger(Class<N> sourceClass) {
        super(sourceClass, Integer.class);
    }

    @Override
    public Integer convert(N obj) throws ConversionException {
        return obj.intValue();
    }
}

public static class GenericNumberToLong<N extends Number> extends AbstractConverter<N, Long> {
    public GenericNumberToLong(Class<N> sourceClass) {
        super(sourceClass, Long.class);
    }

    @Override
    public Long convert(N obj) throws ConversionException {
        return obj.longValue();
    }
}

public static class GenericNumberToShort<N extends Number> extends AbstractConverter<N, Short> {
    public GenericNumberToShort(Class<N> sourceClass) {
        super(sourceClass, Short.class);
    }

    @Override
    public Short convert(N obj) throws ConversionException {
        return obj.shortValue();
    }
}

public static class BigDecimalToString extends AbstractNumberToStringConverter<BigDecimal> {
    public BigDecimalToString() {
        super(BigDecimal.class);
    }

    @Override
    protected String format(BigDecimal obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.doubleValue());
    }
}

public static class DoubleToBigDecimal extends AbstractConverter<Double, BigDecimal> {
    public DoubleToBigDecimal() {
        super(Double.class, BigDecimal.class);
    }

    @Override
    public BigDecimal convert(Double obj) throws ConversionException {
        return BigDecimal.valueOf(obj);
    }
}

public static class BigIntegerToString extends AbstractNumberToStringConverter<BigInteger> {
    public BigIntegerToString() {
        super(BigInteger.class);
    }

    @Override
    protected String format(BigInteger obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.doubleValue());
    }
}

public static class IntegerToBigInteger extends AbstractConverter<Integer, BigInteger> {
    public IntegerToBigInteger() {
        super(Integer.class, BigInteger.class);
    }

    @Override
    public BigInteger convert(Integer obj) throws ConversionException {
        return BigInteger.valueOf(obj.intValue());
    }
}

public static class ByteToString extends AbstractNumberToStringConverter<Byte> {
    public ByteToString() {
        super(Byte.class);
    }

    @Override
    protected String format(Byte obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.floatValue());
    }
}

public static class StringToBigInteger extends AbstractStringToNumberConverter<BigInteger> {
    public StringToBigInteger() {
        super(BigInteger.class);
    }

    @Override
    public BigInteger convert(String obj) throws ConversionException {
        return new BigInteger(obj);
    }

    @Override
    protected BigInteger convert(Number number) throws ConversionException {
        return BigInteger.valueOf(number.longValue());
    }
}

public static class DoubleToString extends AbstractNumberToStringConverter<Double> {
    public DoubleToString() {
        super(Double.class);
    }

    @Override
    protected String format(Double obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.doubleValue());
    }
}

public static class FloatToBigDecimal extends AbstractConverter<Float, BigDecimal> {
    public FloatToBigDecimal() {
        super(Float.class, BigDecimal.class);
    }

    @Override
    public BigDecimal convert(Float obj) throws ConversionException {
        return BigDecimal.valueOf(obj.doubleValue());
    }
}

public static class FloatToString extends AbstractNumberToStringConverter<Float> {
    public FloatToString() {
        super(Float.class);
    }

    @Override
    protected String format(Float obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.floatValue());
    }
}

public static class IntegerToBigDecimal extends AbstractConverter<Integer, BigDecimal> {
    public IntegerToBigDecimal() {
        super(Integer.class, BigDecimal.class);
    }

    @Override
    public BigDecimal convert(Integer obj) throws ConversionException {
        return BigDecimal.valueOf(obj);
    }
}

public static class IntegerToByte extends AbstractConverter<Integer, Byte> {
    public IntegerToByte() {
        super(Integer.class, Byte.class);
    }

    @Override
    public Byte convert(Integer obj) throws ConversionException {
        return obj.byteValue();
    }
}

public static class IntegerToString extends AbstractNumberToStringConverter<Integer> {
    public IntegerToString() {
        super(Integer.class);
    }

    @Override
    protected String format(Integer obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.intValue());
    }
}

public static class LongToBigDecimal extends AbstractConverter<Long, BigDecimal> {
    public LongToBigDecimal() {
        super(Long.class, BigDecimal.class);
    }

    @Override
    public BigDecimal convert(Long obj) throws ConversionException {
        return BigDecimal.valueOf(obj);
    }
}

public static class LongToByte extends AbstractConverter<Long, Byte> {
    public LongToByte() {
        super(Long.class, Byte.class);
    }

    @Override
    public Byte convert(Long obj) throws ConversionException {
        return obj.byteValue();
    }
}

public static class LongToString extends AbstractNumberToStringConverter<Long> {
    public LongToString() {
        super(Long.class);
    }

    @Override
    protected String format(Long obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.longValue());
    }
}

public static class ShortToString extends AbstractNumberToStringConverter<Short> {
    public ShortToString() {
        super(Short.class);
    }

    @Override
    protected String format(Short obj, NumberFormat nf) throws ConversionException {
        return nf.format(obj.floatValue());
    }
}

public static class StringToBigDecimal extends AbstractStringToNumberConverter<BigDecimal> {
    public StringToBigDecimal() {
        super(BigDecimal.class);
    }

    @Override
    public BigDecimal convert(String obj) throws ConversionException {
        return new BigDecimal(obj);
    }

    @Override
    protected BigDecimal convert(Number number) throws ConversionException {
        if (number instanceof BigDecimal) {
            return (BigDecimal) number;
        }
        return BigDecimal.valueOf(number.doubleValue());
    }
}

public static class StringToByte extends AbstractConverter<String, Byte> {
    public StringToByte() {
        super(String.class, Byte.class);
    }

    @Override
    public Byte convert(String obj) throws ConversionException {
        return Byte.valueOf(obj);
    }
}

public static class StringToDouble extends AbstractStringToNumberConverter<Double> {
    public StringToDouble() {
        super(Double.class);
    }

    @Override
    public Double convert(String obj) throws ConversionException {
        return Double.valueOf(obj);
    }

    @Override
    protected Double convert(Number number) throws ConversionException {
        return number.doubleValue();
    }
}

public static class StringToFloat extends AbstractStringToNumberConverter<Float> {
    public StringToFloat() {
        super(Float.class);
    }

    @Override
    public Float convert(String obj) throws ConversionException {
        return Float.valueOf(obj);
    }

    @Override
    protected Float convert(Number number) throws ConversionException {
        return number.floatValue();
    }
}

public static class StringToInteger extends AbstractStringToNumberConverter<Integer> {
    public StringToInteger() {
        super(Integer.class);
    }

    @Override
    public Integer convert(String obj) throws ConversionException {
        return Integer.valueOf(obj);
    }

    @Override
    protected Integer convert(Number number) throws ConversionException {
        return number.intValue();
    }
}

public static class StringToLong extends AbstractStringToNumberConverter<Long> {
    public StringToLong() {
        super(Long.class);
    }

    @Override
    public Long convert(String obj) throws ConversionException {
        return Long.valueOf(obj);
    }

    @Override
    protected Long convert(Number number) throws ConversionException {
        return number.longValue();
    }
}

public static class StringToShort extends AbstractConverter<String, Short> {
    public StringToShort() {
        super(String.class, Short.class);
    }

    @Override
    public Short convert(String obj) throws ConversionException {
        return Short.valueOf(obj);
    }
}

@Override
public void loadConverters() {
    Converters.loadContainedConverters(NumberConverters.class);

    Converters.registerConverter(new GenericNumberToDouble<>(BigDecimal.class));
    Converters.registerConverter(new GenericNumberToDouble<>(BigInteger.class));
    Converters.registerConverter(new GenericNumberToDouble<>(Byte.class));
    Converters.registerConverter(new GenericNumberToDouble<>(Float.class));
    Converters.registerConverter(new GenericNumberToDouble<>(Integer.class));
    Converters.registerConverter(new GenericNumberToDouble<>(Long.class));
    Converters.registerConverter(new GenericNumberToDouble<>(Short.class));

    Converters.registerConverter(new GenericNumberToFloat<>(BigDecimal.class));
    Converters.registerConverter(new GenericNumberToFloat<>(BigInteger.class));
    Converters.registerConverter(new GenericNumberToFloat<>(Byte.class));
    Converters.registerConverter(new GenericNumberToFloat<>(Double.class));
    Converters.registerConverter(new GenericNumberToFloat<>(Integer.class));
    Converters.registerConverter(new GenericNumberToFloat<>(Long.class));
    Converters.registerConverter(new GenericNumberToFloat<>(Short.class));

    Converters.registerConverter(new GenericNumberToInteger<>(BigDecimal.class));
    Converters.registerConverter(new GenericNumberToInteger<>(BigInteger.class));
    Converters.registerConverter(new GenericNumberToInteger<>(Byte.class));
    Converters.registerConverter(new GenericNumberToInteger<>(Double.class));
    Converters.registerConverter(new GenericNumberToInteger<>(Float.class));
    Converters.registerConverter(new GenericNumberToInteger<>(Long.class));
    Converters.registerConverter(new GenericNumberToInteger<>(Short.class));

    Converters.registerConverter(new GenericSingletonToList<>(BigDecimal.class));
    Converters.registerConverter(new GenericSingletonToList<>(BigInteger.class));
    Converters.registerConverter(new GenericSingletonToList<>(Byte.class));
    Converters.registerConverter(new GenericSingletonToList<>(Double.class));
    Converters.registerConverter(new GenericSingletonToList<>(Float.class));
    Converters.registerConverter(new GenericSingletonToList<>(Integer.class));
    Converters.registerConverter(new GenericSingletonToList<>(Long.class));
    Converters.registerConverter(new GenericSingletonToList<>(Short.class));

    Converters.registerConverter(new GenericNumberToLong<>(BigDecimal.class));
    Converters.registerConverter(new GenericNumberToLong<>(BigInteger.class));
    Converters.registerConverter(new GenericNumberToLong<>(Byte.class));
    Converters.registerConverter(new GenericNumberToLong<>(Double.class));
    Converters.registerConverter(new GenericNumberToLong<>(Float.class));
    Converters.registerConverter(new GenericNumberToLong<>(Integer.class));
    Converters.registerConverter(new GenericNumberToLong<>(Short.class));

    Converters.registerConverter(new GenericSingletonToSet<>(BigDecimal.class));
    Converters.registerConverter(new GenericSingletonToSet<>(BigInteger.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Byte.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Double.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Float.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Integer.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Long.class));
    Converters.registerConverter(new GenericSingletonToSet<>(Short.class));

    Converters.registerConverter(new GenericNumberToShort<>(Integer.class));
    Converters.registerConverter(new GenericNumberToShort<>(Long.class));
}

}

framework/base/src/main/java/org/apache/ofbiz/base/util/SSLUtil.java

        for (TrustManager mgr : mgrs) {
            if (mgr instanceof X509TrustManager) {
                try {
                    ((X509TrustManager) mgr).checkClientTrusted(chain, authType);
                    return true;
                } catch (CertificateException e) {
                    Debug.logError(e, MODULE);
                }
            }
        }
/******************************************************************************* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.apache.ofbiz.base.util;

import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.Principal;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;

import org.apache.ofbiz.base.component.ComponentConfig;
import org.apache.ofbiz.base.config.GenericConfigException;

/**

  • KeyStoreUtil - Utilities for setting up SSL connections with specific client certificates

*/
public final class SSLUtil {

private static final String MODULE = SSLUtil.class.getName();

private static final int HOSTCERT_NO_CHECK = 0;
private static final int HOSTCERT_MIN_CHECK = 1;
private static final int HOSTCERT_NORMAL_CHECK = 2;

private static boolean loadedProps = false;

private SSLUtil() { }

static {
    SSLUtil.loadJsseProperties();
}

private static class TrustAnyManager implements X509TrustManager {

    @Override
    public void checkClientTrusted(X509Certificate[] certs, String string) throws CertificateException {
        Debug.logImportant("Trusting (un-trusted) client certificate chain:", MODULE);
        for (X509Certificate cert: certs) {
            Debug.logImportant("---- " + cert.getSubjectX500Principal().getName() + " valid: " + cert.getNotAfter(), MODULE);

        }
    }

    @Override
    public void checkServerTrusted(X509Certificate[] certs, String string) throws CertificateException {
        Debug.logImportant("Trusting (un-trusted) server certificate chain:", MODULE);
        for (X509Certificate cert: certs) {
            Debug.logImportant("---- " + cert.getSubjectX500Principal().getName() + " valid: " + cert.getNotAfter(), MODULE);
        }
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}


public static int getHostCertNoCheck() {
    return HOSTCERT_NO_CHECK;
}

public static int getHostCertMinCheck() {
    return HOSTCERT_MIN_CHECK;
}

public static int getHostCertNormalCheck() {
    return HOSTCERT_NORMAL_CHECK;
}

public static boolean isClientTrusted(X509Certificate[] chain, String authType) {
    TrustManager[] mgrs = new TrustManager[0];
    try {
        mgrs = SSLUtil.getTrustManagers();
    } catch (IOException | GeneralSecurityException | GenericConfigException e) {
        Debug.logError(e, MODULE);
    }

    for (TrustManager mgr : mgrs) {
        if (mgr instanceof X509TrustManager) {
            try {
                ((X509TrustManager) mgr).checkClientTrusted(chain, authType);
                return true;
            } catch (CertificateException e) {
                Debug.logError(e, MODULE);
            }
        }
    }
    return false;
}

public static KeyManager[] getKeyManagers(String alias) throws IOException, GeneralSecurityException, GenericConfigException {
    List<KeyManager> keyMgrs = new LinkedList<>();
    for (ComponentConfig.KeystoreInfo ksi: ComponentConfig.getAllKeystoreInfos()) {
        if (ksi.isCertStore()) {
            KeyStore ks = ksi.getKeyStore();
            if (ks != null) {
                List<KeyManager> newKeyManagers = Arrays.asList(getKeyManagers(ks, ksi.getPassword(), alias));
                keyMgrs.addAll(newKeyManagers);
                if (Debug.verboseOn()) {
                    Debug.logVerbose("Loaded another cert store, adding [" + newKeyManagers.size()
                            + "] KeyManagers for alias [" + alias + "] and keystore: " + ksi.createResourceHandler()
                                    .getFullLocation(), MODULE);
                }
            } else {
                throw new IOException("Unable to load keystore: " + ksi.createResourceHandler().getFullLocation());
            }
        }
    }

    return keyMgrs.toArray(new KeyManager[keyMgrs.size()]);
}

public static KeyManager[] getKeyManagers() throws IOException, GeneralSecurityException, GenericConfigException {
    return getKeyManagers(null);
}

public static TrustManager[] getTrustManagers() throws IOException, GeneralSecurityException, GenericConfigException {
    MultiTrustManager tm = new MultiTrustManager();
    tm.add(KeyStoreUtil.getSystemTrustStore());
    if (tm.getNumberOfKeyStores() < 1) {
        Debug.logWarning("System truststore not found!", MODULE);
    }

    for (ComponentConfig.KeystoreInfo ksi: ComponentConfig.getAllKeystoreInfos()) {
        if (ksi.isTrustStore()) {
            KeyStore ks = ksi.getKeyStore();
            if (ks != null) {
                tm.add(ks);
            } else {
                throw new IOException("Unable to load keystore: " + ksi.createResourceHandler().getFullLocation());
            }
        }
    }

    return new TrustManager[] {tm };
}

public static TrustManager[] getTrustAnyManagers() {
    return new TrustManager[] {new TrustAnyManager() };
}

public static KeyManager[] getKeyManagers(KeyStore ks, String password, String alias) throws GeneralSecurityException {
    KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
    factory.init(ks, password.toCharArray());
    KeyManager[] keyManagers = factory.getKeyManagers();
    if (alias != null) {
        for (int i = 0; i < keyManagers.length; i++) {
            if (keyManagers[i] instanceof X509KeyManager) {
                keyManagers[i] = new AliasKeyManager((X509KeyManager) keyManagers[i], alias);
            }
        }
    }
    return keyManagers;
}

public static TrustManager[] getTrustManagers(KeyStore ks) {
    return new TrustManager[] {new MultiTrustManager(ks) };
}

public static SSLSocketFactory getSSLSocketFactory(KeyStore ks, String password, String alias)
        throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLContext(ks, password, alias, false).getSocketFactory();
}

public static SSLContext getSSLContext(KeyStore ks, String password, String alias, boolean trustAny)
        throws IOException, GeneralSecurityException, GenericConfigException {
    KeyManager[] km = SSLUtil.getKeyManagers(ks, password, alias);
    TrustManager[] tm;
    if (trustAny) {
        tm = SSLUtil.getTrustAnyManagers();
    } else {
        tm = SSLUtil.getTrustManagers();
    }

    SSLContext context = SSLContext.getInstance("SSL");
    context.init(km, tm, new SecureRandom());
    return context;
}

public static SSLSocketFactory getSSLSocketFactory(String alias, boolean trustAny)
        throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLContext(alias, trustAny).getSocketFactory();
}

public static SSLContext getSSLContext(String alias, boolean trustAny) throws IOException, GeneralSecurityException, GenericConfigException {
    KeyManager[] km = SSLUtil.getKeyManagers(alias);
    TrustManager[] tm;
    if (trustAny) {
        tm = SSLUtil.getTrustAnyManagers();
    } else {
        tm = SSLUtil.getTrustManagers();
    }

    SSLContext context = SSLContext.getInstance("SSL");
    context.init(km, tm, new SecureRandom());
    return context;
}

public static SSLSocketFactory getSSLSocketFactory(String alias) throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLSocketFactory(alias, false);
}

public static SSLSocketFactory getSSLSocketFactory() throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLSocketFactory(null);
}

public static SSLServerSocketFactory getSSLServerSocketFactory(KeyStore ks, String password, String alias)
        throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLContext(ks, password, alias, false).getServerSocketFactory();
}

public static SSLServerSocketFactory getSSLServerSocketFactory(String alias)
        throws IOException, GeneralSecurityException, GenericConfigException {
    return getSSLContext(alias, false).getServerSocketFactory();
}

public static HostnameVerifier getHostnameVerifier(int level) {
    switch (level) {
    case HOSTCERT_MIN_CHECK:
        return (hostname, session) -> {
            Certificate[] peerCerts;
            try {
                peerCerts = session.getPeerCertificates();
            } catch (SSLPeerUnverifiedException e) {
                // cert not verified
                Debug.logWarning(e.getMessage(), MODULE);
                return false;
            }
            for (Certificate peerCert : peerCerts) {
                try {
                    Principal x500s = session.getPeerPrincipal();
                    Map<String, String> subjectMap = KeyStoreUtil.getX500Map(x500s);
                    if (Debug.infoOn()) {
                        byte[] encodedCert = peerCert.getEncoded();
                        Debug.logInfo(new BigInteger(encodedCert).toString(16)
                                + " :: " + subjectMap.get("CN"), MODULE);
                    }
                    peerCert.verify(peerCert.getPublicKey());
                } catch (RuntimeException e) {
                    throw e;
                } catch (Exception e) {
                    // certificate not valid
                    Debug.logWarning("Certificate is not valid!", MODULE);
                    return false;
                }
            }
            return true;
        };
    case HOSTCERT_NO_CHECK:
        return (hostname, session) -> true;
    default:
        return null;
    }
}

public static void loadJsseProperties() {
    loadJsseProperties(false);
}

public static synchronized void loadJsseProperties(boolean debug) {
    if (!loadedProps) {
        String protocol = UtilProperties.getPropertyValue("jsse", "java.protocol.handler.pkgs", "NONE");
        String proxyHost = UtilProperties.getPropertyValue("jsse", "https.proxyHost", "NONE");
        String proxyPort = UtilProperties.getPropertyValue("jsse", "https.proxyPort", "NONE");
        String cypher = UtilProperties.getPropertyValue("jsse", "https.cipherSuites", "NONE");
        if (protocol != null && !"NONE".equals(protocol)) {
            System.setProperty("java.protocol.handler.pkgs", protocol);
        }
        if (proxyHost != null && !"NONE".equals(proxyHost)) {
            System.setProperty("https.proxyHost", proxyHost);
        }
        if (proxyPort != null && !"NONE".equals(proxyPort)) {
            System.setProperty("https.proxyPort", proxyPort);
        }
        if (cypher != null && !"NONE".equals(cypher)) {
            System.setProperty("https.cipherSuites", cypher);
        }

        if (debug) {
            System.setProperty("javax.net.debug", "ssl:handshake");
        }
        loadedProps = true;
    }
}

}

C:\projectsASF\Git\ofbiz-framework>java -Duser.language=en -Duser.country=US -jar checkstyle-8.42-all.jar -c config\checkstyle\checkstyle.xml framework\base\src\main\java\org\apache\ofbiz\base\conversion\NumberConverters.java
Starting audit...
[ERROR] C:\projectsASF\Git\ofbiz-framework\framework\base\src\main\java\org\apache\ofbiz\base\conversion\NumberConverters.java:37:13: '(' should be on the previous line. [SeparatorWrap]
Audit done.
Checkstyle ends with 1 errors.

I have been working on MethodParamPad[0]. I could fix few issues but despite my efforts[1][2], as you can see here we have still 22 issues of "'(' should be on the previous line." in Java source code.

Among them there are some cases that can't be handled by changing code, notably when a casting is necessary. Using instanceof or "enhanced for" are typical cases. Of course we could add an initial line to assign the cast to another var before the real expression is used. But it's a tedious work and I'd prefer if we could anticipate (we still recommend JDK 8 but already support JDK 11) something like what JDK 14 provides (I know you also rely on JDK 8 for now). I mean :

for (any instanceof String s) {
  System.out.println(s);
}

Looking at MethodParamPad[0], how could we allow white-spaces at head of the line after instanceof or "enhanced for", do I miss something or is this a real bug?

Note: we don't want to use

<module name="MethodParamPad">
    <property name="allowLineBreaks" value="true" />
</module>

Because we want to check the other cases, as the ones I fixed.

TIA

Jacques

[0] https://checkstyle.sourceforge.io/config_whitespace.html#MethodParamPad
[1] https://github.com/apache/ofbiz-framework/commit/45f50c910d64c12a2601164fbc64a4a02ef1d833/
[2] https://github.com/apache/ofbiz-plugins/commit/dbfa4f0ca0620896a2313d5b784d197bbc25d4d3/

@nrmancuso
Copy link
Member

nrmancuso commented May 17, 2021

Jacques, thanks for the detailed report! Could you pare down your code example and config to just the target code, check module, and specific properties that you are having an issue with? It will make it easier for maintainers to approve and get started on this. If you think that it adds context, you can still include the entire files using the <details>...</details> html5 tags. Also, I do not see an example of your issue with enhanced for, can you include that in your code as well?

@JacquesLeRoux
Copy link
Author

Hi,

Sure I'll do that, I guess directly by editing...

@JacquesLeRoux
Copy link
Author

Done in 1st comment, TIA for reviews

@nrmancuso
Copy link
Member

So, just to be clear, you are not expecting the following violations?

➜  src javac Test.java

➜  src cat Test.java 
public class Test {

    void method1(Object o) {
        if (o instanceof String) {
            ((CharSequence) o).charAt(0);
        }
    }

    void method2(Object... objects) {
        for (Object o : objects) {
            ((CharSequence) o).charAt(0);
        }
    }
}

➜  src cat config.xml 
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC
        "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
        "https://checkstyle.org/dtds/configuration_1_3.dtd">

<module name="Checker">
    <module name="TreeWalker">
        <!-- Checks for whitespace -->
        <module name="SeparatorWrap">
            <property name="tokens"
                      value="COMMA,LPAREN,RPAREN,RBRACK,ARRAY_DECLARATOR"/>
            <property name="option" value="eol"/>
        </module>
    </module>
</module>

➜  src java -jar checkstyle-8.42-all.jar -c config.xml Test.java
Starting audit...
[ERROR] /home/nick/Desktop/Tester/src/Test.java:5:13: '(' should be on the previous line. [SeparatorWrap]
[ERROR] /home/nick/Desktop/Tester/src/Test.java:11:13: '(' should be on the previous line. [SeparatorWrap]
Audit done.
Checkstyle ends with 2 errors.

@JacquesLeRoux
Copy link
Author

No, that's not what I see at https://ci.apache.org/projects/ofbiz/logs/trunk/checkstyle.html where [SeparatorWrap] does not show. I see only '(' should be on the previous line. Maybe I miss something related to SeparatorWrap?

@nrmancuso
Copy link
Member

nrmancuso commented May 19, 2021

Your description is a bit confusing, because you refer to two different checks MethodParamPad and SeparatorWrap, and your config still has several different checks in it. The violation that you have shown above is from SeparatorWrap, so I am not sure how this connects to MethodParamPad. Note that all Checkstyle checks are modular; none interact with the others, so your example config should consist of exactly one check. Please create a simple example as I have above so that we can help identify the issue.

@JacquesLeRoux
Copy link
Author

JacquesLeRoux commented May 19, 2021

OK, I'll, thanks

@JacquesLeRoux
Copy link
Author

Hi,

You are right, MethodParamPad was confusing and misleading. It came from the allowLineBreaks solution I hastily found on StackOverflow. It's unrelated to the issue at hand that is indeed only related to SeparatorWrap.

You are right with your example above too. And yes, I'm not expecting the violations for a cast after and instanceof or an "enhanced for".

Now, if I remove LPAREN from

        <module name="SeparatorWrap">
            <property name="tokens"
                      value="COMMA,LPAREN,RPAREN,RBRACK,ARRAY_DECLARATOR"/>
            <property name="option" value="eol"/>
        </module>

Then the remaining issues related to casting after instanceof or "enhanced for" disappear. I mean no <<'(' should be on the previous line>> errors remain.

I did not create the checkstyle config we use. The person who did is no longer available. I'm not sure removing LPAREN like above is the right solution. I'll revert back to 1 year ago to see what's happening when does so and if it's applicable...

@nrmancuso
Copy link
Member

I'm not sure removing LPAREN like above is the right solution.

If it helps at all, our documentation always shows our own usage of checks at the bottom of each section. Here is our config for SeparatorWrap:

<module name="SeparatorWrap">
<property name="tokens" value="DOT"/>
<property name="tokens" value="AT"/>
<property name="tokens" value="METHOD_REF"/>
<property name="option" value="nl"/>
</module>
<module name="SeparatorWrap">
<property name="tokens" value="COMMA"/>
<property name="tokens" value="RBRACK"/>
<property name="tokens" value="ARRAY_DECLARATOR"/>
<property name="tokens" value="ELLIPSIS"/>
<property name="tokens" value="SEMI"/>
<property name="option" value="EOL"/>
</module>

@JacquesLeRoux
Copy link
Author

Thanks for the suggestion. It gives the same result (number of errors) than removing LPAREN. I'll check both options on an one year old situation. Currently remain 116 errors, was 35k+ last year.

@JacquesLeRoux
Copy link
Author

OK, there is a difference when using your proposition with a checkout from 1 year ago, 26953 errors with the original and 26761 w/ your changes applied. So we would escape 192 issues. When only removing LPARENT we get 26866 errors, so only 87 issues less. I'm not sure what to do yet. I'll discuss that w/ the team... Thanks again for your help!

@JacquesLeRoux
Copy link
Author

This is not a bug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants