@@ -37,6 +37,7 @@ import java.util.function.Consumer;
  * A literal string.
  *
"Hello World!"
  *
"\"\n"
+ *
"\u2122"
  *
"™"
  *
"💩"
  *

/*
 * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
 * Copyright (C) 2011, 2013-2016 The JavaParser Team.
 *
 * This file is part of JavaParser.
 *
 * JavaParser can be used either under the terms of
 * a) the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * b) the terms of the Apache License
 *
 * You should have received a copy of both licenses in LICENCE.LGPL and
 * LICENCE.APACHE. Please refer to those files for details.
 *
 * JavaParser 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.
 */
package com.github.javaparser.ast.expr;

import com.github.javaparser.ast.AllFieldsConstructor;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import com.github.javaparser.metamodel.StringLiteralExprMetaModel;
import com.github.javaparser.utils.StringEscapeUtils;
import com.github.javaparser.utils.Utils;
import javax.annotation.Generated;
import com.github.javaparser.TokenRange;
import java.util.function.Consumer;

/**
 * A literal string.
 *
"Hello World!"
 *
"\"\n"
 *
"™"
 *
"💩"
 *
 * @author Julio Vilmar Gesser
 */
public final class StringLiteralExpr extends LiteralStringValueExpr {

    public StringLiteralExpr() {
        this(null, "empty");
    }

    /**
     * Creates a string literal expression from given string. Escapes EOL characters.
     *
     * @param value the value of the literal
     */
    @AllFieldsConstructor
    public StringLiteralExpr(final String value) {
        this(null, Utils.escapeEndOfLines(value));
    }

    /**
     * Utility method that creates a new StringLiteralExpr. Escapes EOL characters.
     *
     * @deprecated Use {@link #StringLiteralExpr(String)} instead.
     */
    @Deprecated
    public static StringLiteralExpr escape(String string) {
        return new StringLiteralExpr(Utils.escapeEndOfLines(string));
    }

    /**
     * This constructor is used by the parser and is considered private.
     */
    @Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
    public StringLiteralExpr(TokenRange tokenRange, String value) {
        super(tokenRange, value);
        customInitialization();
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
    public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
        return v.visit(this, arg);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
    public  void accept(final VoidVisitor v, final A arg) {
        v.visit(this, arg);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
    public boolean remove(Node node) {
        if (node == null)
            return false;
        return super.remove(node);
    }

    /**
     * Sets the content of this expressions to given value. Escapes EOL characters.
     *
     * @param value the new literal value
     * @return self
     */
    public StringLiteralExpr setEscapedValue(String value) {
        this.value = Utils.escapeEndOfLines(value);
        return this;
    }

    /**
     * @return the unescaped literal value
     */
    public String asString() {
        return StringEscapeUtils.unescapeJava(value);
    }

    /**
     * Escapes the given string from special characters and uses it as the literal value.
     *
     * @param value unescaped string
     * @return this literal expression
     */
    public StringLiteralExpr setString(String value) {
        this.value = StringEscapeUtils.escapeJava(value);
        return this;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
    public StringLiteralExpr clone() {
        return (StringLiteralExpr) accept(new CloneVisitor(), null);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
    public StringLiteralExprMetaModel getMetaModel() {
        return JavaParserMetaModel.stringLiteralExprMetaModel;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
    public boolean replace(Node node, Node replacementNode) {
        if (node == null)
            return false;
        return super.replace(node, replacementNode);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public boolean isStringLiteralExpr() {
        return true;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public StringLiteralExpr asStringLiteralExpr() {
        return this;
    }

    @Generated("com.github.javaparser.generator.core.node.TypeCastingGenerator")
    public void ifStringLiteralExpr(Consumer<StringLiteralExpr> action) {
        action.accept(this);
    }
}

I am not sure what GitHub wants to tell me with this icon here :)


@@ -90,7 +90,7 @@ public class ViewEngines extends MainWindowView<EngineSidebar> {

         Bindings.bindContent(availableEngines.getTabs(), mappedSubCategoryTabs);

-        this.initializeSidebar();
+        this.setSidebar(this.sidebar);
     }

     public void setOnInstallEngine(Consumer<EngineDTO> onInstallEngine) {

/*
 * Copyright (C) 2015-2017 PÂRIS Quentin
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

package org.phoenicis.javafx.views.mainwindow.engines;

import javafx.animation.PauseTransition;
import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TabPane;
import javafx.scene.layout.VBox;
import javafx.util.Duration;
import org.phoenicis.engines.dto.EngineCategoryDTO;
import org.phoenicis.engines.dto.EngineDTO;
import org.phoenicis.engines.dto.EngineSubCategoryDTO;
import org.phoenicis.engines.dto.EngineVersionDTO;
import org.phoenicis.javafx.views.common.MappedList;
import org.phoenicis.javafx.views.common.ThemeManager;
import org.phoenicis.javafx.views.common.widgets.lists.CombinedListWidget;
import org.phoenicis.javafx.views.mainwindow.MainWindowView;

import java.util.List;
import java.util.function.Consumer;

public class ViewEngines extends MainWindowView<EngineSidebar> {
    private TabPane availableEngines;

    private EnginePanel currentEnginePanel;

    private EngineCategoryDTO selectedCategory;

    private ObservableList<EngineCategoryDTO> engineCategories;

    private ObservableList<EngineSubCategoryDTO> engineSubCategories;
    private MappedList<EngineSubCategoryTab, EngineSubCategoryDTO> mappedSubCategoryTabs;
    private MappedList<CombinedListWidget<EngineVersionDTO>, EngineSubCategoryTab> mappedListWidgets;

    private Consumer<EngineDTO> setOnInstallEngine = (engine) -> {
    };
    private Consumer<EngineDTO> setOnDeleteEngine = (engine) -> {
    };

    private PauseTransition pause = new PauseTransition(Duration.seconds(0.5));

    public ViewEngines(ThemeManager themeManager, String enginesPath) {
        super("Engines", themeManager);

        this.engineCategories = FXCollections.observableArrayList();
        this.engineSubCategories = FXCollections.observableArrayList();
        this.mappedSubCategoryTabs = new MappedList<>(engineSubCategories, engineSubCategory -> {
            EngineSubCategoryTab result = new EngineSubCategoryTab(selectedCategory, engineSubCategory, enginesPath);

            result.setOnSelectEngine(this::showEngineDetails);

            return result;
        });
        this.mappedListWidgets = new MappedList<>(mappedSubCategoryTabs, tab -> tab.getEngineVersionsView());

        this.sidebar = new EngineSidebar(mappedListWidgets);

        this.sidebar.setOnCategorySelection(this::selectCategory);
        this.sidebar.setOnApplyInstalledFilter(newValue -> availableEngines.getTabs()
                .forEach(tab -> ((EngineSubCategoryTab) tab).setFilterForInstalled(newValue)));
        this.sidebar.setOnApplyUninstalledFilter(newValue -> availableEngines.getTabs()
                .forEach(tab -> ((EngineSubCategoryTab) tab).setFilterForNotInstalled(newValue)));
        this.sidebar.setOnSearchTermClear(() -> availableEngines.getTabs()
                .forEach(tab -> ((EngineSubCategoryTab) tab).setFilterForSearchTerm("")));
        this.sidebar.setOnApplySearchTerm(this::processFilterText);

        this.sidebar.bindEngineCategories(engineCategories);

        this.initFailure();
        this.initWineVersions();

        Bindings.bindContent(availableEngines.getTabs(), mappedSubCategoryTabs);

        this.initializeSidebar();
    }

    public void setOnInstallEngine(Consumer<EngineDTO> onInstallEngine) {
        this.setOnInstallEngine = onInstallEngine;
    }

    public void setOnDeleteEngine(Consumer<EngineDTO> onDeleteEngine) {
        this.setOnDeleteEngine = onDeleteEngine;
    }

    private void initFailure() {

    }

    private void initWineVersions() {
        availableEngines = new TabPane();
        availableEngines.getStyleClass().add("rightPane");

        availableEngines.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);
    }

    // TODO: delete this method because it doesn't do what it promises, namely showing the wine versions tab
    @Deprecated
    public void showWineVersions() {
        setCenter(availableEngines);
    }

    public void populate(List<EngineCategoryDTO> engineCategoryDTOS) {
        Platform.runLater(() -> {
            this.engineCategories.setAll(engineCategoryDTOS);

            if (!engineCategoryDTOS.isEmpty()) {
                this.sidebar.selectFirstEngineCategory();
            }

            this.closeDetailsView();
            this.setCenter(availableEngines);
        });
    }

    public void populateEngines(EngineCategoryDTO category) {
        this.selectedCategory = category;
        this.engineSubCategories.setAll(category.getSubCategories());
    }

    private void selectCategory(EngineCategoryDTO category) {
        this.setCenter(availableEngines);
        this.populateEngines(category);
    }

    private void showEngineDetails(EngineDTO engineDTO) {
        currentEnginePanel = new EnginePanel(engineDTO);
        currentEnginePanel.setOnClose(this::closeDetailsView);
        currentEnginePanel.setOnEngineInstall(this::installEngine);
        currentEnginePanel.setOnEngineDelete(this::deleteEngine);

        this.showDetailsView(currentEnginePanel);
    }

    private void processFilterText(String filterText) {
        this.pause.setOnFinished(event -> {
            String text = filterText.toLowerCase();

            availableEngines.getTabs().forEach(tab -> ((EngineSubCategoryTab) tab).setFilterForSearchTerm(text));
        });

        this.pause.playFromStart();
    }

    private void installEngine(EngineDTO engineDTO) {
        this.setOnInstallEngine.accept(engineDTO);
    }

    private void deleteEngine(EngineDTO engineDTO) {
        this.setOnDeleteEngine.accept(engineDTO);
    }

    public void showProgress(VBox progressUi) {
        currentEnginePanel.showProgress(progressUi);
    }
}

I think that it may be better to do it the other way around. I.e. we remove the `setSidebar` method and only provide the `initializeSidebar` method. The reason for this is, that I think we don't want to make the sidebar swapable from outside. In addition a setter method is in my eyes normally not used to directly set complete graphic components. This is normally done by `populate` or `initialize` methods.


@@ -7,7 +7,8 @@ import com.fsck.k9.message.preview.PreviewResult.PreviewType;
 public enum DatabasePreviewType {
     NONE("none", PreviewType.NONE),
     TEXT("text", PreviewType.TEXT),
-    ENCRYPTED("encrypted", PreviewType.ENCRYPTED);
+    ENCRYPTED("encrypted", PreviewType.ENCRYPTED),
+    FAILED_TO_LOAD("failedToLoad", PreviewType.FAILED_TO_LOAD);

     private final String databaseValue;

package com.fsck.k9.mailstore;

import com.fsck.k9.message.preview.PreviewResult.PreviewType;

public enum DatabasePreviewType {
    NONE("none", PreviewType.NONE),
    TEXT("text", PreviewType.TEXT),
    ENCRYPTED("encrypted", PreviewType.ENCRYPTED);

    private final String databaseValue;
    private final PreviewType previewType;

    DatabasePreviewType(String databaseValue, PreviewType previewType) {
        this.databaseValue = databaseValue;
        this.previewType = previewType;
    }

    public static DatabasePreviewType fromDatabaseValue(String databaseValue) {
        for (DatabasePreviewType databasePreviewType : values()) {
            if (databasePreviewType.getDatabaseValue().equals(databaseValue)) {
                return databasePreviewType;
            }
        }

        throw new AssertionError("Unknown database value: " + databaseValue);
    }

    public static DatabasePreviewType fromPreviewType(PreviewType previewType) {
        for (DatabasePreviewType databasePreviewType : values()) {
            if (databasePreviewType.previewType == previewType) {
                return databasePreviewType;
            }
        }

        throw new AssertionError("Unknown preview type: " + previewType);
    }

    public String getDatabaseValue() {
        return databaseValue;
    }

    public PreviewType getPreviewType() {
        return previewType;
    }
}

Maybe just `FAILED`. We can't be sure loading was the thing that failed.


@@ -18,14 +18,19 @@
 package org.apache.servicecomb.foundation.vertx.server;

 import java.net.InetSocketAddress;
+import java.util.concurrent.atomic.AtomicInteger;

+import org.apache.servicecomb.foundation.common.event.EventManager;
 import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
 import org.apache.servicecomb.foundation.ssl.SSLCustom;
 import org.apache.servicecomb.foundation.ssl.SSLOption;
 import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
 import org.apache.servicecomb.foundation.vertx.AsyncResultCallback;
+import org.apache.servicecomb.foundation.vertx.ClientConnectedEvent;
 import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;

+import com.netflix.config.DynamicPropertyFactory;
+
 import io.vertx.core.Vertx;
 import io.vertx.core.net.NetServer;
 import io.vertx.core.net.NetServerOptions;

/*
 * 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.servicecomb.foundation.vertx.server;

import java.net.InetSocketAddress;

import org.apache.servicecomb.foundation.common.net.URIEndpointObject;
import org.apache.servicecomb.foundation.ssl.SSLCustom;
import org.apache.servicecomb.foundation.ssl.SSLOption;
import org.apache.servicecomb.foundation.ssl.SSLOptionFactory;
import org.apache.servicecomb.foundation.vertx.AsyncResultCallback;
import org.apache.servicecomb.foundation.vertx.VertxTLSBuilder;

import io.vertx.core.Vertx;
import io.vertx.core.net.NetServer;
import io.vertx.core.net.NetServerOptions;

public class TcpServer {
  private URIEndpointObject endpointObject;

  public TcpServer(URIEndpointObject endpointObject) {
    this.endpointObject = endpointObject;
  }

  public void init(Vertx vertx, String sslKey, AsyncResultCallback<InetSocketAddress> callback) {
    NetServer netServer;
    if (endpointObject.isSslEnabled()) {
      SSLOptionFactory factory =
          SSLOptionFactory.createSSLOptionFactory(sslKey, null);
      SSLOption sslOption;
      if (factory == null) {
        sslOption = SSLOption.buildFromYaml(sslKey);
      } else {
        sslOption = factory.createSSLOption();
      }
      SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
      NetServerOptions serverOptions = new NetServerOptions();
      VertxTLSBuilder.buildNetServerOptions(sslOption, sslCustom, serverOptions);
      netServer = vertx.createNetServer(serverOptions);
    } else {
      netServer = vertx.createNetServer();
    }

    netServer.connectHandler(netSocket -> {
      TcpServerConnection connection = createTcpServerConnection();
      connection.init(netSocket);
    });

    InetSocketAddress socketAddress = endpointObject.getSocketAddress();
    netServer.listen(socketAddress.getPort(), socketAddress.getHostString(), ar -> {
      if (ar.succeeded()) {
        callback.success(socketAddress);
        return;
      }

      // 监听失败
      String msg = String.format("listen failed, address=%s", socketAddress.toString());
      callback.fail(new Exception(msg, ar.cause()));
    });
  }

  protected TcpServerConnection createTcpServerConnection() {
    return new TcpServerConnection();
  }
}

TcpServer will be created for each HighwayServerVerticle instance so the counter number in server is not correct.


@@ -61,6 +61,13 @@ public class OperationConfig {
   @InjectProperty(keys = {"request.${op-any-priority}.timeout", "request.timeout"}, defaultValue = "30000")
   private long msRequestTimeout;

+  /**
+   * whether to remove certain headers from the 3rd party invocations
+   */
+  @InjectProperty(keys = {"request.${op-any-priority}.clientRequestHeaderFilterEnabled",
+      "request.clientRequestHeaderFilterEnabled"}, defaultValue = "true")
+  private boolean clientRequestHeaderFilterEnabled = true;
+
   /**
    * producer wait in thread pool timeout
    */

/*
 * 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.servicecomb.core.definition;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.apache.servicecomb.config.inject.InjectProperties;
import org.apache.servicecomb.config.inject.InjectProperty;

@InjectProperties(prefix = "servicecomb")
public class OperationConfig {
  public static final List<String> CONSUMER_OP_ANY_PRIORITY = Arrays.asList(
      "${service}.${schema}.${operation}",
      "${service}.${schema}",
      "${service}");

  public static final List<String> PRODUCER_OP_ANY_PRIORITY = Arrays.asList(
      "${schema}.${operation}",
      "${schema}");

  public static final List<String> CONSUMER_OP_PRIORITY = Arrays.asList(
      ".${service}.${schema}.${operation}",
      ".${service}.${schema}",
      ".${service}",
      "");

  public static final List<String> PRODUCER_OP_PRIORITY = Arrays.asList(
      ".${schema}.${operation}",
      ".${schema}",
      "");

  @InjectProperty(keys = {"metrics.${consumer-producer}.invocation.slow.enabled${op-priority}",
      "${consumer-producer}.invocation.slow.enabled${op-priority}"}, defaultValue = "false")
  private boolean slowInvocationEnabled;

  @InjectProperty(keys = {"metrics.${consumer-producer}.invocation.slow.msTime${op-priority}",
      "${consumer-producer}.invocation.slow.msTime${op-priority}"}, defaultValue = "1000")
  private long msSlowInvocation;

  private long nanoSlowInvocation;

  /**
   * consumer request timeout
   */
  @InjectProperty(keys = {"request.${op-any-priority}.timeout", "request.timeout"}, defaultValue = "30000")
  private long msRequestTimeout;

  /**
   * producer wait in thread pool timeout
   */
  @InjectProperty(keys = {
      "Provider.requestWaitInPoolTimeout${op-priority}",
      "highway.server.requestWaitInPoolTimeout"}, defaultValue = "30000")
  private long msHighwayRequestWaitInPoolTimeout;

  private long nanoHighwayRequestWaitInPoolTimeout;

  @InjectProperty(keys = {
      "Provider.requestWaitInPoolTimeout${op-priority}",
      "rest.server.requestWaitInPoolTimeout"}, defaultValue = "30000")
  private long msRestRequestWaitInPoolTimeout;

  private long nanoRestRequestWaitInPoolTimeout;

  public boolean isSlowInvocationEnabled() {
    return slowInvocationEnabled;
  }

  public void setSlowInvocationEnabled(boolean slowInvocationEnabled) {
    this.slowInvocationEnabled = slowInvocationEnabled;
  }

  public long getMsSlowInvocation() {
    return msSlowInvocation;
  }

  public void setMsSlowInvocation(long msSlowInvocation) {
    this.msSlowInvocation = msSlowInvocation;
    this.nanoSlowInvocation = TimeUnit.MILLISECONDS.toNanos(msSlowInvocation);
  }

  public long getNanoSlowInvocation() {
    return nanoSlowInvocation;
  }

  public long getMsRequestTimeout() {
    return msRequestTimeout;
  }

  public void setMsRequestTimeout(long msRequestTimeout) {
    this.msRequestTimeout = msRequestTimeout;
  }

  public long getMsHighwayRequestWaitInPoolTimeout() {
    return msHighwayRequestWaitInPoolTimeout;
  }

  public void setMsHighwayRequestWaitInPoolTimeout(long msHighwayRequestWaitInPoolTimeout) {
    this.msHighwayRequestWaitInPoolTimeout = msHighwayRequestWaitInPoolTimeout;
    this.nanoHighwayRequestWaitInPoolTimeout = TimeUnit.MILLISECONDS.toNanos(msHighwayRequestWaitInPoolTimeout);
  }

  public long getNanoHighwayRequestWaitInPoolTimeout() {
    return nanoHighwayRequestWaitInPoolTimeout;
  }

  public long getMsRestRequestWaitInPoolTimeout() {
    return msRestRequestWaitInPoolTimeout;
  }

  public void setMsRestRequestWaitInPoolTimeout(long msRestRequestWaitInPoolTimeout) {
    this.msRestRequestWaitInPoolTimeout = msRestRequestWaitInPoolTimeout;
    this.nanoRestRequestWaitInPoolTimeout = TimeUnit.MILLISECONDS.toNanos(msRestRequestWaitInPoolTimeout);
  }

  public long getNanoRestRequestWaitInPoolTimeout() {
    return nanoRestRequestWaitInPoolTimeout;
  }
}

if need to compile pattern, then we can do that in setter method that can avoid check changes during main business logic.


@@ -76,11 +76,13 @@ public final class ArrayCreationLevel extends Node implements NodeWithAnnotation
     }

     @Override
+    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
     public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
         return v.visit(this, arg);
     }

     @Override
+    @Generated("com.github.javaparser.generator.core.node.AcceptGenerator")
     public <A> void accept(final VoidVisitor<A> v, final A arg) {
         v.visit(this, arg);
     }

/*
 * Copyright (C) 2007-2010 Júlio Vilmar Gesser.
 * Copyright (C) 2011, 2013-2016 The JavaParser Team.
 *
 * This file is part of JavaParser.
 *
 * JavaParser can be used either under the terms of
 * a) the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * b) the terms of the Apache License
 *
 * You should have received a copy of both licenses in LICENCE.LGPL and
 * LICENCE.APACHE. Please refer to those files for details.
 *
 * JavaParser 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.
 */
package com.github.javaparser.ast;

import com.github.javaparser.ast.expr.AnnotationExpr;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.IntegerLiteralExpr;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.observer.ObservableProperty;
import com.github.javaparser.ast.visitor.GenericVisitor;
import com.github.javaparser.ast.visitor.VoidVisitor;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import static com.github.javaparser.utils.Utils.assertNotNull;
import com.github.javaparser.ast.Node;
import com.github.javaparser.ast.visitor.CloneVisitor;
import com.github.javaparser.metamodel.ArrayCreationLevelMetaModel;
import com.github.javaparser.metamodel.JavaParserMetaModel;
import javax.annotation.Generated;
import com.github.javaparser.TokenRange;

/**
 * In new int[1][2]; there are two ArrayCreationLevel objects,
 * the first one contains the expression "1",
 * the second the expression "2".
 */
public final class ArrayCreationLevel extends Node implements NodeWithAnnotations<ArrayCreationLevel> {

    private Expression dimension;

    private NodeList<AnnotationExpr> annotations = new NodeList<>();

    public ArrayCreationLevel() {
        this(null, null, new NodeList<>());
    }

    public ArrayCreationLevel(int dimension) {
        this(null, new IntegerLiteralExpr("" + dimension), new NodeList<>());
    }

    public ArrayCreationLevel(Expression dimension) {
        this(null, dimension, new NodeList<>());
    }

    @AllFieldsConstructor
    public ArrayCreationLevel(Expression dimension, NodeList<AnnotationExpr> annotations) {
        this(null, dimension, annotations);
    }

    /**This constructor is used by the parser and is considered private.*/
    @Generated("com.github.javaparser.generator.core.node.MainConstructorGenerator")
    public ArrayCreationLevel(TokenRange tokenRange, Expression dimension, NodeList<AnnotationExpr> annotations) {
        super(tokenRange);
        setDimension(dimension);
        setAnnotations(annotations);
        customInitialization();
    }

    @Override
    public <R, A> R accept(final GenericVisitor<R, A> v, final A arg) {
        return v.visit(this, arg);
    }

    @Override
    public  void accept(final VoidVisitor v, final A arg) {
        v.visit(this, arg);
    }

    /**
     * Sets the dimension
     *
     * @param dimension the dimension, can be null
     * @return this, the ArrayCreationLevel
     */
    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public ArrayCreationLevel setDimension(final Expression dimension) {
        if (dimension == this.dimension) {
            return (ArrayCreationLevel) this;
        }
        notifyPropertyChange(ObservableProperty.DIMENSION, this.dimension, dimension);
        if (this.dimension != null)
            this.dimension.setParentNode(null);
        this.dimension = dimension;
        setAsParentNodeOf(dimension);
        return this;
    }

    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public Optional<Expression> getDimension() {
        return Optional.ofNullable(dimension);
    }

    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public NodeList<AnnotationExpr> getAnnotations() {
        return annotations;
    }

    @Generated("com.github.javaparser.generator.core.node.PropertyGenerator")
    public ArrayCreationLevel setAnnotations(final NodeList<AnnotationExpr> annotations) {
        assertNotNull(annotations);
        if (annotations == this.annotations) {
            return (ArrayCreationLevel) this;
        }
        notifyPropertyChange(ObservableProperty.ANNOTATIONS, this.annotations, annotations);
        if (this.annotations != null)
            this.annotations.setParentNode(null);
        this.annotations = annotations;
        setAsParentNodeOf(annotations);
        return this;
    }

    @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
    public ArrayCreationLevel removeDimension() {
        return setDimension((Expression) null);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.RemoveMethodGenerator")
    public boolean remove(Node node) {
        if (node == null)
            return false;
        for (int i = 0; i < annotations.size(); i++) {
            if (annotations.get(i) == node) {
                annotations.remove(i);
                return true;
            }
        }
        if (dimension != null) {
            if (node == dimension) {
                removeDimension();
                return true;
            }
        }
        return super.remove(node);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.CloneGenerator")
    public ArrayCreationLevel clone() {
        return (ArrayCreationLevel) accept(new CloneVisitor(), null);
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.GetMetaModelGenerator")
    public ArrayCreationLevelMetaModel getMetaModel() {
        return JavaParserMetaModel.arrayCreationLevelMetaModel;
    }

    @Override
    @Generated("com.github.javaparser.generator.core.node.ReplaceMethodGenerator")
    public boolean replace(Node node, Node replacementNode) {
        if (node == null)
            return false;
        for (int i = 0; i < annotations.size(); i++) {
            if (annotations.get(i) == node) {
                annotations.set(i, (AnnotationExpr) replacementNode);
                return true;
            }
        }
        if (dimension != null) {
            if (node == dimension) {
                setDimension((Expression) replacementNode);
                return true;
            }
        }
        return super.replace(node, replacementNode);
    }
}

I would love a tool to identify these changes and hide them :D


@@ -4,11 +4,14 @@

 package net.sourceforge.pmd.lang.rule.properties;

+import java.util.Collections;
 import java.util.Enumeration;
 import java.util.Map;

+import net.sourceforge.pmd.EnumeratedPropertyDescriptor;
 import net.sourceforge.pmd.PropertyDescriptorFactory;
-import net.sourceforge.pmd.lang.rule.properties.factories.BasicPropertyDescriptorFactory;
+import net.sourceforge.pmd.PropertyDescriptorField;
+import net.sourceforge.pmd.util.CollectionUtil;

 /**
  * Defines a datatype with a set of preset values of any type as held within a

/**
 * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
 */

package net.sourceforge.pmd.lang.rule.properties;

import java.util.Enumeration;
import java.util.Map;

import net.sourceforge.pmd.PropertyDescriptorFactory;
import net.sourceforge.pmd.lang.rule.properties.factories.BasicPropertyDescriptorFactory;

/**
 * Defines a datatype with a set of preset values of any type as held within a
 * pair of maps. While the values are not serialized out, the labels are and
 * serve as keys to obtain the values. The choices() method provides the ordered
 * selections to be used in an editor widget.
 *
 * @author Brian Remedios
 * @param <E>
 */
public class EnumeratedProperty<E> extends AbstractEnumeratedProperty<E, Object> {

    public static final PropertyDescriptorFactory FACTORY = new BasicPropertyDescriptorFactory<EnumeratedProperty>(
            Enumeration.class) {

        @Override
        public EnumeratedProperty createWith(Map<String, String> valuesById) {

            return new EnumeratedProperty(nameIn(valuesById), descriptionIn(valuesById), labelsIn(valuesById),
                    choicesIn(valuesById), indexIn(valuesById), 0f);
        }
    };

    /**
     * Constructor for EnumeratedProperty.
     *
     * @param theName
     *            String
     * @param theDescription
     *            String
     * @param theLabels
     *            String[]
     * @param theChoices
     *            E[]
     * @param defaultIndex
     *            int
     * @param theUIOrder
     *            float
     * @throws IllegalArgumentException
     */
    public EnumeratedProperty(String theName, String theDescription, String[] theLabels, E[] theChoices,
            int defaultIndex, float theUIOrder) {
        super(theName, theDescription, theLabels, theChoices, new int[] { defaultIndex }, theUIOrder, false);
    }

    /**
     * @return Class
     * @see net.sourceforge.pmd.PropertyDescriptor#type()
     */
    @Override
    public Class<Object> type() {
        return Object.class;
    }

    /**
     * @param value
     *            Object
     * @return String
     * @see net.sourceforge.pmd.PropertyDescriptor#errorFor(Object)
     */
    @Override
    public String errorFor(Object value) {
        return labelsByChoice.containsKey(value) ? null : nonLegalValueMsgFor(value);
    }

    /**
     * @param value
     *            String
     * @return Object
     * @throws IllegalArgumentException
     * @see net.sourceforge.pmd.PropertyDescriptor#valueFrom(String)
     */
    @Override
    public Object valueFrom(String value) throws IllegalArgumentException {
        return choiceFrom(value);
    }

    /**
     *
     * @param value
     *            Object
     * @return String
     * @see net.sourceforge.pmd.PropertyDescriptor#asDelimitedString(Object)
     */
    @Override
    public String asDelimitedString(Object value) {
        return labelsByChoice.get(value);
    }
}

Can we derive `Class<E>` by looking at one of the label choices, if at least one is always provided? Given these are immutable, a real-world case for an empty enumerations eludes me.


@@ -59,6 +59,7 @@ public class EdgeInvocation extends AbstractRestInvocation {
     this.responseEx = new VertxServerResponseToHttpServletResponse(context.response());
     this.httpServerFilters = httpServerFilters;
     requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);
+    setAfterCreateInvocationHandler(invocation -> context.put(RestConst.REST_INVOCATION_CONTEXT, invocation));
   }

   public void edgeInvoke() {

/*
 * 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.servicecomb.edge.core;

import java.util.List;

import org.apache.servicecomb.common.rest.AbstractRestInvocation;
import org.apache.servicecomb.common.rest.RestConst;
import org.apache.servicecomb.common.rest.filter.HttpServerFilter;
import org.apache.servicecomb.common.rest.locator.OperationLocator;
import org.apache.servicecomb.common.rest.locator.ServicePathManager;
import org.apache.servicecomb.core.Const;
import org.apache.servicecomb.core.definition.MicroserviceVersionMeta;
import org.apache.servicecomb.core.invocation.InvocationFactory;
import org.apache.servicecomb.core.provider.consumer.ReactiveResponseExecutor;
import org.apache.servicecomb.core.provider.consumer.ReferenceConfig;
import org.apache.servicecomb.foundation.common.exceptions.ServiceCombException;
import org.apache.servicecomb.foundation.vertx.http.VertxServerRequestToHttpServletRequest;
import org.apache.servicecomb.foundation.vertx.http.VertxServerResponseToHttpServletResponse;
import org.apache.servicecomb.serviceregistry.RegistryUtils;
import org.apache.servicecomb.serviceregistry.consumer.MicroserviceVersionRule;
import org.apache.servicecomb.serviceregistry.definition.DefinitionConst;

import io.vertx.core.Vertx;
import io.vertx.ext.web.RoutingContext;

public class EdgeInvocation extends AbstractRestInvocation {
  public static final String EDGE_INVOCATION_CONTEXT = "edgeInvocationContext";

  protected String microserviceName;

  protected MicroserviceVersionRule microserviceVersionRule;

  protected MicroserviceVersionMeta latestMicroserviceVersionMeta;

  protected ReferenceConfig referenceConfig;

  protected String versionRule = DefinitionConst.VERSION_RULE_ALL;

  public void init(String microserviceName, RoutingContext context, String path,
      List<HttpServerFilter> httpServerFilters) {
    this.microserviceName = microserviceName;
    this.requestEx = new VertxServerRequestToHttpServletRequest(context, path);
    this.responseEx = new VertxServerResponseToHttpServletResponse(context.response());
    this.httpServerFilters = httpServerFilters;
    requestEx.setAttribute(RestConst.REST_REQUEST, requestEx);
  }

  public void edgeInvoke() {
    findMicroserviceVersionMeta();
    findRestOperation(latestMicroserviceVersionMeta.getMicroserviceMeta());

    scheduleInvocation();
  }

  protected void findMicroserviceVersionMeta() {
    String versionRule = chooseVersionRule();

    String appId = RegistryUtils.getAppId();
    int idxAt = microserviceName.indexOf(org.apache.servicecomb.serviceregistry.api.Const.APP_SERVICE_SEPARATOR);
    if (idxAt != -1) {
      appId = microserviceName.substring(0, idxAt);
    }

    microserviceVersionRule = RegistryUtils.getServiceRegistry()
        .getAppManager()
        .getOrCreateMicroserviceVersionRule(appId, microserviceName, versionRule);
    latestMicroserviceVersionMeta = microserviceVersionRule.getLatestMicroserviceVersion();

    if (latestMicroserviceVersionMeta == null) {
      throw new ServiceCombException(
          String.format("Failed to find latest MicroserviceVersionMeta, appId=%s, microserviceName=%s, versionRule=%s.",
              appId,
              microserviceName,
              versionRule));
    }
  }

  public void setVersionRule(String versionRule) {
    this.versionRule = versionRule;
  }

  // another possible rule:
  // path is: /msName/version/.....
  // version in path is v1 or v2 and so on
  // map version to VersionRule:
  //   v1->1.0.0-2.0.0
  //   v2->2.0.0-3.0.0
  // that means if a(1.x.x) bigger then b(1.y.y), then a compatible to b
  //        but a(2.x.x) not compatible to b
  protected String chooseVersionRule() {
    // this will use all instance of the microservice
    // and this required all new version compatible to old version
    return versionRule;
  }

  @Override
  protected OperationLocator locateOperation(ServicePathManager servicePathManager) {
    return servicePathManager.consumerLocateOperation(requestEx.getRequestURI(), requestEx.getMethod());
  }

  @Override
  protected void createInvocation() {
    ReferenceConfig referenceConfig = new ReferenceConfig();
    referenceConfig.setMicroserviceMeta(latestMicroserviceVersionMeta.getMicroserviceMeta());
    referenceConfig.setMicroserviceVersionRule(microserviceVersionRule.getVersionRule().getVersionRule());
    referenceConfig.setTransport(Const.ANY_TRANSPORT);

    this.invocation = InvocationFactory.forConsumer(referenceConfig,
        restOperationMeta.getOperationMeta(),
        null);
    this.invocation.setSync(false);
    this.invocation.getHandlerContext().put(EDGE_INVOCATION_CONTEXT, Vertx.currentContext());
    this.invocation.setResponseExecutor(new ReactiveResponseExecutor());
  }
}

if just need to do something after createInvocation just override and call super first is enough?


@@ -17,11 +17,12 @@

 package org.apache.servicecomb.metrics.core.monitor;

+import java.util.HashMap;
+import java.util.Map;

-import org.apache.servicecomb.metrics.common.ConsumerInvocationMetric;
-import org.apache.servicecomb.metrics.common.MetricsConst;
+import org.apache.servicecomb.foundation.metrics.MetricsConst;

-public class ConsumerInvocationMonitor extends InvocationMonitor {
+public class ConsumerInvocationMonitor {
   private final TimerMonitor consumerLatency;

   private final CallMonitor consumerCall;

/*
 * 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.servicecomb.metrics.core.monitor;

import org.apache.servicecomb.metrics.common.ConsumerInvocationMetric;
import org.apache.servicecomb.metrics.common.MetricsConst;

public class ConsumerInvocationMonitor extends InvocationMonitor {
  private final TimerMonitor consumerLatency;

  private final CallMonitor consumerCall;

  public TimerMonitor getConsumerLatency() {
    return consumerLatency;
  }

  public CallMonitor getConsumerCall() {
    return consumerCall;
  }

  public ConsumerInvocationMonitor(String operationName) {
    super(operationName, String.format(MetricsConst.CONSUMER_PREFIX_TEMPLATE, operationName));
    this.consumerLatency = new TimerMonitor(this.getPrefix() + ".consumerLatency");
    this.consumerCall = new CallMonitor(this.getPrefix() + ".consumerCall");
  }

  public ConsumerInvocationMetric toMetric(int windowTimeIndex) {
    return new ConsumerInvocationMetric(this.getOperationName(), this.getPrefix(),
        consumerLatency.toMetric(windowTimeIndex), consumerCall.toMetric(windowTimeIndex));
  }
}

What we should do if we want to change the ConsumerInvocationMonitor into ProducerInvocationMonitor?We don't need to write lots Classes here, please use abstraction to reduce the number of the class.


@@ -63,6 +63,14 @@ class UpdateManager {
                 UserPreferences.enableSonic();
             }
         }
+
+        if(oldVersionCode < 1070196) {
+            // migrate episode cleanup value (unit changed from days to hours)
+            int oldValueInDays = UserPreferences.getEpisodeCleanupValue();
+            if (oldValueInDays > 0) {
+                UserPreferences.setEpisodeCleanupValue(oldValueInDays * 24);
+            } // else 0 or special negative values, no change needed
+        }
     }

 }

package de.danoeh.antennapod.core;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.util.Log;

import org.antennapod.audio.MediaPlayer;

import de.danoeh.antennapod.core.preferences.UserPreferences;

/*
 * This class's job is do perform maintenance tasks whenever the app has been updated
 */
class UpdateManager {

    private UpdateManager(){}

    private static final String TAG = UpdateManager.class.getSimpleName();

    private static final String PREF_NAME = "app_version";
    private static final String KEY_VERSION_CODE = "version_code";

    private static int currentVersionCode;

    private static Context context;
    private static SharedPreferences prefs;

    public static void init(Context context) {
        UpdateManager.context = context;
        prefs = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(context.getPackageName(), 0);
            currentVersionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Failed to obtain package info for package name: " + context.getPackageName(), e);
            currentVersionCode = 0;
            return;
        }
        final int oldVersionCode = getStoredVersionCode();
        Log.d(TAG, "old: " + oldVersionCode + ", current: " + currentVersionCode);
        if(oldVersionCode < currentVersionCode) {
            onUpgrade(oldVersionCode, currentVersionCode);
            setCurrentVersionCode();
        }
    }

    private static int getStoredVersionCode() {
        return prefs.getInt(KEY_VERSION_CODE, -1);
    }

    private static void setCurrentVersionCode() {
        prefs.edit().putInt(KEY_VERSION_CODE, currentVersionCode).apply();
    }

    private static void onUpgrade(final int oldVersionCode, final int newVersionCode) {
        if(oldVersionCode < 1050004) {
            if(MediaPlayer.isPrestoLibraryInstalled(context) && Build.VERSION.SDK_INT >= 16) {
                UserPreferences.enableSonic();
            }
        }
    }

}


@@ -65,6 +65,7 @@ public final class BaselineErrorProne implements Plugin<Project> {
                                 .configure(ErrorProneOptions.class, errorProneOptions -> {
                                     errorProneOptions.check("Slf4jLogsafeArgs", CheckSeverity.OFF);
                                     errorProneOptions.check("PreferSafeLoggableExceptions", CheckSeverity.OFF);
+                                    errorProneOptions.check("Slf4jConstantLogMessage", CheckSeverity.OFF);
                                 }));
             });

/*
 * (c) Copyright 2017 Palantir Technologies Inc. All rights reserved.
 *
 * 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.palantir.baseline.plugins;

import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import java.io.File;
import java.util.AbstractList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import net.ltgt.gradle.errorprone.CheckSeverity;
import net.ltgt.gradle.errorprone.ErrorProneOptions;
import net.ltgt.gradle.errorprone.ErrorPronePlugin;
import org.gradle.api.JavaVersion;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.file.FileCollection;
import org.gradle.api.plugins.ExtensionAware;
import org.gradle.api.tasks.compile.JavaCompile;
import org.gradle.api.tasks.javadoc.Javadoc;
import org.gradle.api.tasks.testing.Test;

public final class BaselineErrorProne implements Plugin<Project> {

    private static final String ERROR_PRONE_JAVAC_VERSION = "9+181-r4173-1";

    @Override
    public void apply(Project project) {
        project.getPluginManager().withPlugin("java", plugin -> {
            project.getPluginManager().apply(ErrorPronePlugin.class);
            String version = Optional.ofNullable(getClass().getPackage().getImplementationVersion())
                    .orElse("latest.release");
            project.getDependencies().add(
                    ErrorPronePlugin.CONFIGURATION_NAME,
                    "com.palantir.baseline:baseline-error-prone:" + version);

            project.getTasks().withType(JavaCompile.class).configureEach(javaCompile ->
                    ((ExtensionAware) javaCompile.getOptions()).getExtensions()
                            .configure(ErrorProneOptions.class, errorProneOptions -> {
                                errorProneOptions.setEnabled(true);
                                errorProneOptions.setDisableWarningsInGeneratedCode(true);
                                errorProneOptions.check("EqualsHashCode", CheckSeverity.ERROR);
                                errorProneOptions.check("EqualsIncompatibleType", CheckSeverity.ERROR);
                                errorProneOptions.check("StreamResourceLeak", CheckSeverity.ERROR);
                            }));

            project.getPluginManager().withPlugin("java-gradle-plugin", appliedPlugin -> {
                project.getTasks().withType(JavaCompile.class).configureEach(javaCompile ->
                        ((ExtensionAware) javaCompile.getOptions()).getExtensions()
                                .configure(ErrorProneOptions.class, errorProneOptions -> {
                                    errorProneOptions.check("Slf4jLogsafeArgs", CheckSeverity.OFF);
                                    errorProneOptions.check("PreferSafeLoggableExceptions", CheckSeverity.OFF);
                                }));
            });

            // In case of java 8 we need to add errorprone javac compiler to bootstrap classpath of tasks that perform
            // compilation or code analysis. ErrorProneJavacPluginPlugin handles JavaCompile cases via errorproneJavac
            // configuration and we do similar thing for Test and Javadoc type tasks
            if (!JavaVersion.current().isJava9Compatible()) {
                project.getDependencies().add(ErrorPronePlugin.JAVAC_CONFIGURATION_NAME,
                        "com.google.errorprone:javac:" + ERROR_PRONE_JAVAC_VERSION);
                project.getConfigurations()
                        .named(ErrorPronePlugin.JAVAC_CONFIGURATION_NAME)
                        .configure(conf -> {
                            List<File> bootstrapClasspath = Splitter.on(File.pathSeparator)
                                    .splitToList(System.getProperty("sun.boot.class.path"))
                                    .stream()
                                    .map(File::new)
                                    .collect(Collectors.toList());
                            FileCollection errorProneFiles = conf.plus(project.files(bootstrapClasspath));
                            project.getTasks().withType(Test.class)
                                    .configureEach(test -> test.setBootstrapClasspath(errorProneFiles));
                            project.getTasks().withType(Javadoc.class)
                                    .configureEach(javadoc -> javadoc.getOptions()
                                            .setBootClasspath(new LazyConfigurationList(errorProneFiles)));
                        });
            }
        });
    }

    private static final class LazyConfigurationList extends AbstractList<File> {
        private final FileCollection files;
        private List<File> fileList;

        private LazyConfigurationList(FileCollection files) {
            this.files = files;
        }

        @Override
        public File get(int index) {
            if (fileList == null) {
                fileList = ImmutableList.copyOf(files.getFiles());
            }
            return fileList.get(index);
        }

        @Override
        public int size() {
            if (fileList == null) {
                fileList = ImmutableList.copyOf(files.getFiles());
            }
            return fileList.size();
        }
    }

}

Arguably this is actually still valuable for perf, maybe it should just be a warning?


@@ -69,7 +69,6 @@ public class HttpAccess {
      * Initializes HttpAccess. Should be called from the application.
      */
     public static void init(Context app) {
-        assert DEFAULT == null : "HttpAccess.init should be called once per process";
         DEFAULT = new HttpAccess(app, null /* user agent will be calculated at request time */);
     }

/*
 * Copyright (c) 2011-present, salesforce.com, inc.
 * All rights reserved.
 * Redistribution and use of this software in source and binary forms, with or
 * without modification, are permitted provided that the following conditions
 * are met:
 * - Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * - Neither the name of salesforce.com, inc. nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission of salesforce.com, inc.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package com.salesforce.androidsdk.auth;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.salesforce.androidsdk.app.SalesforceSDKManager;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import okhttp3.ConnectionSpec;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.TlsVersion;

/**
 * Generic HTTP Access layer - used internally by {@link com.salesforce.androidsdk.rest.RestClient}
 * and {@link OAuth2}. This class watches network changes as well.
 */
public class HttpAccess {

    // Timeouts.
    public static final int CONNECT_TIMEOUT = 60;
    public static final int READ_TIMEOUT = 20;

    // User agent header name.
	private static final String USER_AGENT = "User-Agent";

    private String userAgent;
    private OkHttpClient okHttpClient;

    // Connection manager.
    private final ConnectivityManager conMgr;

    // Singleton instance.
    public static HttpAccess DEFAULT;

    /**
     * Initializes HttpAccess. Should be called from the application.
     */
    public static void init(Context app) {
        assert DEFAULT == null : "HttpAccess.init should be called once per process";
        DEFAULT = new HttpAccess(app, null /* user agent will be calculated at request time */);
    }

    /**
     * Parameterized constructor.
     *
     * @param app Reference to the application.
     * @param userAgent The user agent to be used with requests.
     */
    public HttpAccess(Context app, String userAgent) {
        this.userAgent = userAgent;

        // Only null in tests.
        if (app == null) {
            conMgr = null;
        } else {

            // Gets the connectivity manager and current network type.
            conMgr = (ConnectivityManager) app.getSystemService(Context.CONNECTIVITY_SERVICE);
        }

    }

    /**
     *
     * @return okHttpClient.Builder with appropriate connection spec and user agent interceptor
     */
    public OkHttpClient.Builder getOkHttpClientBuilder() {
        ConnectionSpec connectionSpec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_1, TlsVersion.TLS_1_2)
                .build();
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectionSpecs(Collections.singletonList(connectionSpec))
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .addNetworkInterceptor(new UserAgentInterceptor());
        return builder;
    }

    /**
     *
     * @return okHttpClient tied to this HttpAccess - builds one if needed
     */
    public synchronized OkHttpClient getOkHttpClient() {
        if (okHttpClient == null) {
            okHttpClient = getOkHttpClientBuilder().build();
        }
        return okHttpClient;
    }

    /**
     * Returns the status of network connectivity.
     *
     * @return True - if network connectivity is available, False - otherwise.
     */
    public synchronized boolean hasNetwork() {
        boolean isConnected = true;
        if (conMgr != null) {
            final NetworkInfo activeInfo = conMgr.getActiveNetworkInfo();
            if (activeInfo == null || !activeInfo.isConnected()) {
                isConnected = false;
            }
        }
        return isConnected;
    }

    /**
     * Returns the current user agent.
     *
     * @return User agent.
     */
    public String getUserAgent() {
    	return userAgent;
    }

    /**
     * Exception thrown if the device is offline, during an attempted HTTP call.
     */
    public static class NoNetworkException extends IOException {

        private static final long serialVersionUID = 1L;

        public NoNetworkException(String msg) {
            super(msg);
        }
    }

    /**
     * Interceptor that adds user agent header
     */
    public static class UserAgentInterceptor implements Interceptor {

        private String userAgent;

        public UserAgentInterceptor() {
            // User this constructor to have the user agent computed for each call
        }

        public UserAgentInterceptor(String userAgent) {
            this.userAgent = userAgent;
        }

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request originalRequest = chain.request();
            Request requestWithUserAgent = originalRequest.newBuilder()
                    .header(HttpAccess.USER_AGENT, userAgent == null ? SalesforceSDKManager.getInstance().getUserAgent() : userAgent)
                    .build();
            return chain.proceed(requestWithUserAgent);
        }
    }
}

This now throws when running tests (maybe the move to java 11??). Do we want to keep it?


@@ -92,6 +92,11 @@ public class ClickhouseSQLDialect extends GenericSQLDialect {
         return true;
     }

+    @Override
+    public boolean supportsGroupBy() {
+        return false;
+    }
+
     @Override
     public String getColumnTypeModifiers(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject column, @NotNull String typeName, @NotNull DBPDataKind dataKind) {
         if (typeName.equals("String")) {

/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2022 DBeaver Corp and others
 *
 * 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.jkiss.dbeaver.ext.clickhouse.model;

import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.ext.generic.model.GenericSQLDialect;
import org.jkiss.dbeaver.model.DBPDataKind;
import org.jkiss.dbeaver.model.DBPDataSource;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCDatabaseMetaData;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
import org.jkiss.dbeaver.model.impl.jdbc.JDBCDataSource;
import org.jkiss.dbeaver.model.struct.DBSTypedObject;

import java.util.Arrays;

public class ClickhouseSQLDialect extends GenericSQLDialect {

    private static final String[] CLICKHOUSE_FUNCTIONS = {
        "quantile",
        "quantileExact",
        "uniq",
        "concat",
        "replaceOne",
        "replaceAll",
        "toStartOfFifteenMinutes",
        "toStartOfFiveMinute",
        "toStartOfInterval",
        "toTimezone",
        "formatDateTime",
        "now",
        "multiIf",
        "geoToS2",
        "s2ToGeo",
        "greatCircleDistance",
        "greatCircleAngle",
        "plus",
        "minus",
        "multiply",
        "divide",
        "arrayConcat",
        "hasAll",
        "hasAny",
        "indexOf",
        "mapKeys",
        "mapValues",
        "UUIDNumToString",
        "UUIDStringToNum",
        "visitParamHas",
        "IPv4StringToNum",
        "randConstant",
        "javaHash",
        "bitmapBuild",
        "bitCount",
        "splitByChar",
        "splitByWhitespace",
        "toLowCardinality",
        "formatRow"
    };

    public ClickhouseSQLDialect() {
        super("Clickhouse SQL", "clickhouse");
    }

    @Override
    public boolean supportsOrderByIndex() {
        return false;
    }

    public void initDriverSettings(JDBCSession session, JDBCDataSource dataSource, JDBCDatabaseMetaData metaData) {
        super.initDriverSettings(session, dataSource, metaData);
        removeSQLKeyword("DEFAULT");
        removeSQLKeyword("SYSTEM");
        addFunctions(Arrays.asList(CLICKHOUSE_FUNCTIONS));
    }

    @Override
    public boolean supportsAliasInSelect() {
        return true;
    }

    @Override
    public String getColumnTypeModifiers(@NotNull DBPDataSource dataSource, @NotNull DBSTypedObject column, @NotNull String typeName, @NotNull DBPDataKind dataKind) {
        if (typeName.equals("String")) {
            return null;
        }
        return super.getColumnTypeModifiers(dataSource, column, typeName, dataKind);
    }

    @Override
    public boolean supportsNestedComments() {
        return true;
    }
}

It doesn't seem to me that it's Couchbase. It's ClickHouse.


@@ -43,10 +43,19 @@ public class LibrarySidebarToggleGroupSkin extends
     protected ToggleButton convertToToggleButton(ShortcutCategoryDTO category) {
         final ToggleButton categoryButton = createSidebarToggleButton(category.getName());
         // TODO: store category ID in shortcut.info?
-        categoryButton.setId(
-                String.format("applications-%s", SidebarToggleGroupBaseSkin.getToggleButtonId(category.getId())));
+        categoryButton.setId(LibrarySidebarToggleGroupSkin.getToggleButtonId(category.getId()));
         categoryButton.setOnMouseClicked(event -> getControl().setSelectedElement(category));

         return categoryButton;
     }
+
+    /**
+     * Creates a button ID which can be used e.g. to assign icons via CSS based on the category ID
+     *
+     * @param categoryId The category ID which should be used
+     * @return The created button ID
+     */
+    public static String getToggleButtonId(String categoryId) {
+        return String.format("library-%s", SidebarToggleGroupBaseSkin.getToggleButtonId(categoryId));
+    }
 }

package org.phoenicis.javafx.components.library.skin;

import javafx.scene.control.ToggleButton;
import org.phoenicis.javafx.components.library.control.LibrarySidebarToggleGroup;
import org.phoenicis.javafx.components.common.skin.SidebarToggleGroupBaseSkin;
import org.phoenicis.library.dto.ShortcutCategoryDTO;

import java.util.Optional;

import static org.phoenicis.configuration.localisation.Localisation.tr;

/**
 * A {@link SidebarToggleGroupBaseSkin} implementation class used inside the {@link LibrarySidebar}
 */
public class LibrarySidebarToggleGroupSkin extends
        SidebarToggleGroupBaseSkin<ShortcutCategoryDTO, LibrarySidebarToggleGroup, LibrarySidebarToggleGroupSkin> {
    /**
     * Constructor
     *
     * @param control The control belonging to the skin
     */
    public LibrarySidebarToggleGroupSkin(LibrarySidebarToggleGroup control) {
        super(control);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Optional<ToggleButton> createAllButton() {
        final ToggleButton allCategoryButton = createSidebarToggleButton(tr("All"));

        allCategoryButton.setId("all-button");
        allCategoryButton.setOnMouseClicked(event -> getControl().setNothingSelected());

        return Optional.of(allCategoryButton);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected ToggleButton convertToToggleButton(ShortcutCategoryDTO category) {
        final ToggleButton categoryButton = createSidebarToggleButton(category.getName());
        // TODO: store category ID in shortcut.info?
        categoryButton.setId(
                String.format("applications-%s", SidebarToggleGroupBaseSkin.getToggleButtonId(category.getId())));
        categoryButton.setOnMouseClicked(event -> getControl().setSelectedElement(category));

        return categoryButton;
    }
}

@plata does it make sense to include the content of this TODO in this PR as well?


@@ -40,4 +40,10 @@ public class FlinkConfigOptions {
           .intType()
           .defaultValue(100)
           .withDescription("Sets max infer parallelism for source operator.");
+
+  public static final ConfigOption<Integer> SOURCE_READER_FETCH_BATCH_SIZE = ConfigOptions
+      .key("source.iceberg.reader.fetch-batch-size")
+      .intType()
+      .defaultValue(2048)
+      .withDescription("The target batch size for split reader fetch.");
 }

/*
 * 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.iceberg.flink;

import org.apache.flink.configuration.ConfigOption;
import org.apache.flink.configuration.ConfigOptions;

public class FlinkConfigOptions {

  private FlinkConfigOptions() {
  }

  public static final ConfigOption<Boolean> TABLE_EXEC_ICEBERG_INFER_SOURCE_PARALLELISM =
      ConfigOptions.key("table.exec.iceberg.infer-source-parallelism")
          .booleanType()
          .defaultValue(true)
          .withDescription("If is false, parallelism of source are set by config.\n" +
              "If is true, source parallelism is inferred according to splits number.\n");

  public static final ConfigOption<Integer> TABLE_EXEC_ICEBERG_INFER_SOURCE_PARALLELISM_MAX =
      ConfigOptions.key("table.exec.iceberg.infer-source-parallelism.max")
          .intType()
          .defaultValue(100)
          .withDescription("Sets max infer parallelism for source operator.");
}


@@ -76,6 +76,11 @@ public class WriteResult implements Serializable {
       return this;
     }

+    public Builder add(Iterable<WriteResult> results) {
+      results.forEach(this::add);
+      return this;
+    }
+
     public Builder addDataFiles(DataFile... files) {
       Collections.addAll(dataFiles, files);
       return this;

/*
 * 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.iceberg.io;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.apache.iceberg.DataFile;
import org.apache.iceberg.DeleteFile;
import org.apache.iceberg.relocated.com.google.common.collect.Iterables;
import org.apache.iceberg.relocated.com.google.common.collect.Lists;
import org.apache.iceberg.util.CharSequenceSet;

public class WriteResult implements Serializable {
  private DataFile[] dataFiles;
  private DeleteFile[] deleteFiles;
  private CharSequence[] referencedDataFiles;

  private WriteResult(List<DataFile> dataFiles,
                      List<DeleteFile> deleteFiles,
                      Set<CharSequence> referencedDataFiles) {
    this.dataFiles = dataFiles.toArray(new DataFile[0]);
    this.deleteFiles = deleteFiles.toArray(new DeleteFile[0]);
    this.referencedDataFiles = referencedDataFiles.toArray(new CharSequence[0]);
  }

  public DataFile[] dataFiles() {
    return dataFiles;
  }

  public DeleteFile[] deleteFiles() {
    return deleteFiles;
  }

  public CharSequence[] referencedDataFiles() {
    return referencedDataFiles;
  }

  public static Builder builder() {
    return new Builder();
  }

  public static class Builder {
    private final List<DataFile> dataFiles;
    private final List<DeleteFile> deleteFiles;
    private final Set<CharSequence> referencedDataFiles;

    private Builder() {
      this.dataFiles = Lists.newArrayList();
      this.deleteFiles = Lists.newArrayList();
      this.referencedDataFiles = CharSequenceSet.empty();
    }

    public Builder add(WriteResult result) {
      addDataFiles(result.dataFiles);
      addDeleteFiles(result.deleteFiles);

      return this;
    }

    public Builder addDataFiles(DataFile... files) {
      Collections.addAll(dataFiles, files);
      return this;
    }

    public Builder addDataFiles(Iterable<DataFile> files) {
      Iterables.addAll(dataFiles, files);
      return this;
    }

    public Builder addDeleteFiles(DeleteFile... files) {
      Collections.addAll(deleteFiles, files);
      return this;
    }

    public Builder addDeleteFiles(Iterable<DeleteFile> files) {
      Iterables.addAll(deleteFiles, files);
      return this;
    }

    public Builder addReferencedDataFiles(CharSequence... files) {
      Collections.addAll(referencedDataFiles, files);
      return this;
    }

    public Builder addReferencedDataFiles(Iterable<CharSequence> files) {
      Iterables.addAll(referencedDataFiles, files);
      return this;
    }

    public WriteResult build() {
      return new WriteResult(dataFiles, deleteFiles, referencedDataFiles);
    }
  }
}

Typically, we would follow the Java collection convention and use `addAll`.


@@ -28,10 +28,8 @@ public class MainnetProtocolSchedule {

   public static final BigInteger DEFAULT_CHAIN_ID = BigInteger.ONE;

-  public static ProtocolSchedule create() {
-    return fromConfig(
-        GenesisConfigFile.mainnet().getConfigOptions(), PrivacyParameters.DEFAULT, false);
-  }
+  public static final ProtocolSchedule DEFAULT =
+      fromConfig(GenesisConfigFile.getMainnetConfigOptions(), PrivacyParameters.DEFAULT, false);

   /**
    * Create a Mainnet protocol schedule from a config object

/*
 * Copyright ConsenSys AG.
 *
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
package org.hyperledger.besu.ethereum.mainnet;

import org.hyperledger.besu.config.GenesisConfigFile;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyCalculators;
import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule;

import java.math.BigInteger;
import java.util.function.Function;

/** Provides {@link ProtocolSpec} lookups for mainnet hard forks. */
public class MainnetProtocolSchedule {

  public static final BigInteger DEFAULT_CHAIN_ID = BigInteger.ONE;

  public static ProtocolSchedule create() {
    return fromConfig(
        GenesisConfigFile.mainnet().getConfigOptions(), PrivacyParameters.DEFAULT, false);
  }

  /**
   * Create a Mainnet protocol schedule from a config object
   *
   * @param config {@link GenesisConfigOptions} containing the config options for the milestone
   *     starting points
   * @param privacyParameters the parameters set for private transactions
   * @param isRevertReasonEnabled whether storing the revert reason is for failed transactions
   * @return A configured mainnet protocol schedule
   */
  public static ProtocolSchedule fromConfig(
      final GenesisConfigOptions config,
      final PrivacyParameters privacyParameters,
      final boolean isRevertReasonEnabled) {
    if (FixedDifficultyCalculators.isFixedDifficultyInConfig(config)) {
      return FixedDifficultyProtocolSchedule.create(
          config, privacyParameters, isRevertReasonEnabled);
    }
    return new ProtocolScheduleBuilder(
            config,
            DEFAULT_CHAIN_ID,
            Function.identity(),
            privacyParameters,
            isRevertReasonEnabled,
            config.isQuorum())
        .createProtocolSchedule();
  }

  /**
   * Create a Mainnet protocol schedule from a config object
   *
   * @param config {@link GenesisConfigOptions} containing the config options for the milestone
   *     starting points
   * @param isRevertReasonEnabled whether storing the revert reason is for failed transactions
   * @return A configured mainnet protocol schedule
   */
  public static ProtocolSchedule fromConfig(
      final GenesisConfigOptions config, final boolean isRevertReasonEnabled) {
    return fromConfig(config, PrivacyParameters.DEFAULT, isRevertReasonEnabled);
  }

  /**
   * Create a Mainnet protocol schedule from a config object
   *
   * @param config {@link GenesisConfigOptions} containing the config options for the milestone
   *     starting points
   * @return A configured mainnet protocol schedule
   */
  public static ProtocolSchedule fromConfig(final GenesisConfigOptions config) {
    return fromConfig(config, PrivacyParameters.DEFAULT, false);
  }
}

Changing from a static method to a constant is inessential to Type Transactions and has a long reach, adding many unneeded files and diff lines.


@@ -41,6 +41,21 @@ public class GoDiscoveryContext extends DiscoveryContext implements GoContext {
           .put(Field.Kind.TYPE_DOUBLE, "0.0")
           .build();

+  @Override
+  protected String arrayTypeName(String elementName) {
+    return String.format("%sArray", elementName);
+  }
+
+  @Override
+  protected String mapTypeName(String keyName, String valueName) {
+    return String.format("%sTo%sMap", keyName, valueName);
+  }
+
+  @Override
+  protected String objectTypeName(String typeName) {
+    return upperCamelToLowerCamel(typeName);
+  }
+
   public String typeDefaultValue(Type type, Field field) {
     if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
       return typeName(type, field) + "{}";

/* Copyright 2016 Google Inc
 *
 * 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.google.api.codegen.go;

import com.google.api.codegen.ApiaryConfig;
import com.google.api.codegen.DiscoveryContext;
import com.google.api.codegen.DiscoveryImporter;
import com.google.api.Service;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableTable;
import com.google.protobuf.Field;
import com.google.protobuf.Method;
import com.google.protobuf.Type;

public class GoDiscoveryContext extends DiscoveryContext implements GoContext {
  public GoDiscoveryContext(Service service, ApiaryConfig apiaryConfig) {
    super(service, apiaryConfig);
  }

  private static final ImmutableMap<Field.Kind, String> DEFAULT_VALUES =
      ImmutableMap.<Field.Kind, String>builder()
          .put(Field.Kind.TYPE_BOOL, "false")
          .put(Field.Kind.TYPE_INT32, "int64(0)")
          .put(Field.Kind.TYPE_UINT32, "uint64(0)")
          .put(Field.Kind.TYPE_INT64, "int64(0)")
          .put(Field.Kind.TYPE_UINT64, "uint64(0)")
          .put(Field.Kind.TYPE_FLOAT, "float32(0.0)")
          .put(Field.Kind.TYPE_DOUBLE, "0.0")
          .build();

  public String typeDefaultValue(Type type, Field field) {
    if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
      return typeName(type, field) + "{}";
    }
    if (DEFAULT_VALUES.containsKey(field.getKind())) {
      return DEFAULT_VALUES.get(field.getKind());
    }
    if (field.getKind() == Field.Kind.TYPE_STRING || field.getKind() == Field.Kind.TYPE_ENUM) {
      return getDefaultString(type, field);
    }
    throw new IllegalArgumentException(
        String.format("not implemented: typeDefaultValue(%s, %s)", type, field));
  }

  @Override
  public String lineEnding(String value) {
    return value;
  }

  private static final ImmutableMap<Field.Kind, String> PRIMITIVE_TYPE =
      ImmutableMap.<Field.Kind, String>builder()
          .put(Field.Kind.TYPE_BOOL, "bool")
          .put(Field.Kind.TYPE_INT32, "int64")
          .put(Field.Kind.TYPE_UINT32, "uint64")
          .put(Field.Kind.TYPE_INT64, "int64")
          .put(Field.Kind.TYPE_UINT64, "uint64")
          .put(Field.Kind.TYPE_FLOAT, "float32")
          .put(Field.Kind.TYPE_DOUBLE, "float64")
          .put(Field.Kind.TYPE_STRING, "string")
          .put(Field.Kind.TYPE_ENUM, "string")
          .build();

  /**
   * Returns the Go representation of a type's field's type.
   */
  private String typeName(Type type, Field field) {
    String fieldName = field.getName();
    String fieldTypeName = field.getTypeUrl();
    String arrayPrefix = "";

    if (field.getCardinality() == Field.Cardinality.CARDINALITY_REPEATED) {
      Type items = this.getApiaryConfig().getType(fieldTypeName);
      if (isMapField(type, fieldName)) {
        return String.format(
            "map[%s]%s",
            typeName(items, this.getField(items, "key")),
            typeName(items, this.getField(items, "value")));
      }
      Field elements = this.getField(items, "elements");
      if (elements != null) {
        return "[]" + typeName(items, elements);
      }
      arrayPrefix = "[]";
    }
    if (field.getKind() == Field.Kind.TYPE_MESSAGE) {
      return arrayPrefix + fieldTypeName;
    }
    if (PRIMITIVE_TYPE.containsKey(field.getKind())) {
      return arrayPrefix + PRIMITIVE_TYPE.get(field.getKind());
    }
    throw new IllegalArgumentException(
        String.format("cannot find suitable type for %s %s", type.getName(), field.getName()));
  }

  @Override
  /**
   * Most languages ignore return type "Empty". However, Go cannot since the client library will
   * return an empty struct, and we have to assign it to something. Consequently, the only time the
   * response is truly "empty" for Go is when DiscoveryImporter says EMPTY_TYPE_NAME, which
   * signifies complete absence of return value.
   */
  public boolean isResponseEmpty(Method method) {
    return method.getResponseTypeUrl().equals(DiscoveryImporter.EMPTY_TYPE_NAME);
  }

  @Override
  public boolean isPageStreaming(Method method) {
    if (isResponseEmpty(method) || hasRequestField(method)) {
      return false;
    }
    boolean hasNextPageToken = false;
    for (Field field : getApiaryConfig().getType(method.getResponseTypeUrl()).getFieldsList()) {
      if (field.getName().equals("nextPageToken")) {
        hasNextPageToken = true;
        break;
      }
    }

    boolean hasPageToken = false;
    for (Field field : getApiaryConfig().getType(method.getRequestTypeUrl()).getFieldsList()) {
      if (field.getName().equals("pageToken")) {
        hasPageToken = true;
        break;
      }
    }
    return hasPageToken && hasNextPageToken;
  }

  private static final ImmutableTable<String, String, String> API_VERSION_RENAME =
      ImmutableTable.<String, String, String>builder()
          .put("clouduseraccounts", "beta", "v0.beta")
          .build();

  /**
   * We need this because in some cases there is a mismatch between discovery doc and import path
   * version numbers. API_VERSION_RENAME is a table of API name and versions as found in discovery
   * doc to the renamed versions as found in the import path.
   *
   * TODO(pongad): Find a more sustainable solution to this.
   */
  public String getApiVersion() {
    String rename = API_VERSION_RENAME.get(getApi().getName(), getApi().getVersion());
    return rename == null ? getApi().getVersion() : rename;
  }

  /*
   * Returns an empty or singleton list of auth scopes for the method. If the method has no scope,
   * returns an empty list; otherwise returns the first scope. We return an empty list instead of
   * null to denote absence of scope since the snippet cannot handle null values. If the scope
   * exists, it is stripped to its last path-element and converted to camel case, eg
   * "https://www.googleapis.com/auth/cloud-platform" becomes "CloudPlatform".
   */
  public ImmutableList<String> getAuthScopes(Method method) {
    if (!getApiaryConfig().getAuthScopes().containsKey(method.getName())) {
      return ImmutableList.<String>of();
    }
    String scope = getApiaryConfig().getAuthScopes().get(method.getName()).get(0);
    int slash = scope.lastIndexOf('/');
    if (slash < 0) {
      throw new IllegalArgumentException(
          String.format("malformed scope, cannot find slash: %s", scope));
    }
    scope = scope.substring(slash + 1);
    scope = scope.replace('.', '_');
    scope = scope.replace('-', '_');
    scope = lowerUnderscoreToUpperCamel(scope);
    return ImmutableList.<String>of(scope);
  }
}

Where is this used? Go's array of ints is `[]int` not `intArray`. I also don't see this reflected in baseline test for any language. (I ran git diff and regexp `^\+.*Array`).


@@ -34,7 +34,7 @@ module Selenium
           driver.manage.timeouts.implicit_wait = 6

           driver.find_element(id: 'adder').click
-          driver.find_element(id: 'box0')
+          expect { driver.find_element(id: 'box0') }.not_to raise_error(WebDriver::Error::NoSuchElementError)
         end

         it 'should still fail to find an element with implicit waits enabled' do

# frozen_string_literal: true

# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The SFC 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.

require_relative 'spec_helper'

module Selenium
  module WebDriver
    describe Timeouts do
      context 'implicit waits' do
        before do
          driver.manage.timeouts.implicit_wait = 0
          driver.navigate.to url_for('dynamic.html')
        end

        after { driver.manage.timeouts.implicit_wait = 0 }

        it 'should implicitly wait for a single element', except: {browser: :safari_preview} do
          driver.manage.timeouts.implicit_wait = 6

          driver.find_element(id: 'adder').click
          driver.find_element(id: 'box0')
        end

        it 'should still fail to find an element with implicit waits enabled' do
          driver.manage.timeouts.implicit_wait = 0.5
          expect { driver.find_element(id: 'box0') }.to raise_error(WebDriver::Error::NoSuchElementError)
        end

        it 'should return after first attempt to find one after disabling implicit waits' do
          driver.manage.timeouts.implicit_wait = 3
          driver.manage.timeouts.implicit_wait = 0

          expect { driver.find_element(id: 'box0') }.to raise_error(WebDriver::Error::NoSuchElementError)
        end

        it 'should implicitly wait until at least one element is found when searching for many' do
          add = driver.find_element(id: 'adder')

          driver.manage.timeouts.implicit_wait = 6
          add.click
          add.click

          expect(driver.find_elements(class_name: 'redbox')).not_to be_empty
        end

        it 'should still fail to find elements when implicit waits are enabled' do
          driver.manage.timeouts.implicit_wait = 0.5
          expect(driver.find_elements(class_name: 'redbox')).to be_empty
        end

        it 'should return after first attempt to find many after disabling implicit waits', except: {browser: :firefox, platform: :windows} do
          add = driver.find_element(id: 'adder')

          driver.manage.timeouts.implicit_wait = 3
          driver.manage.timeouts.implicit_wait = 0
          add.click

          expect(driver.find_elements(class_name: 'redbox')).to be_empty
        end
      end

      context 'page loads' do
        # w3c default is 300,000
        after { driver.manage.timeouts.page_load = 300000 }

        it 'should be able to set the page load timeout' do
          expect { driver.manage.timeouts.page_load = 2 }.not_to raise_exception
        end
      end
    end
  end # WebDriver
end # Selenium

This should just be `.not_to raise_error` otherwise it potentially hides errors


@@ -78,6 +78,32 @@ public final class TestObjects {
           .build()
   ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());

+
+  // this object simulates
+  public static final List<Span> TRACEWITHSAMEIDANDSAMEPARENTID = asList(
+    Span.builder().traceId(WEB_SPAN_ID+1).id(WEB_SPAN_ID).name("get")
+      .addAnnotation(Annotation.create(TODAY * 1000, SERVER_RECV, WEB_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 350) * 1000, SERVER_SEND, WEB_ENDPOINT))
+      .build(),
+    Span.builder().traceId(WEB_SPAN_ID+1).parentId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("get")
+      .addAnnotation(Annotation.create((TODAY + 50) * 1000, CLIENT_SEND, WEB_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 100) * 1000, SERVER_RECV, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 250) * 1000, SERVER_SEND, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 300) * 1000, CLIENT_RECV, WEB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, WEB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, APP_ENDPOINT))
+      .build(),
+    Span.builder().traceId(WEB_SPAN_ID+1).parentId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("query")
+      .addAnnotation(Annotation.create((TODAY + 150) * 1000, CLIENT_SEND, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 200) * 1000, CLIENT_RECV, APP_ENDPOINT))
+      .addAnnotation(Annotation.create((TODAY + 190) * 1000, "⻩", NO_IP_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, APP_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, DB_ENDPOINT))
+      .addBinaryAnnotation(BinaryAnnotation.create(ERROR, "\uD83D\uDCA9", NO_IP_ENDPOINT))
+      .build()
+  ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());
+
+
   public static final List<DependencyLink> LINKS = asList(
       DependencyLink.builder().parent("web").child("app").callCount(1).build(),
       DependencyLink.builder().parent("app").child("db").callCount(1).build()

/**
 * Copyright 2015-2016 The OpenZipkin Authors
 *
 * 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 zipkin;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import zipkin.internal.ApplyTimestampAndDuration;
import zipkin.internal.Dependencies;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static zipkin.Constants.CLIENT_ADDR;
import static zipkin.Constants.CLIENT_RECV;
import static zipkin.Constants.CLIENT_SEND;
import static zipkin.Constants.ERROR;
import static zipkin.Constants.SERVER_ADDR;
import static zipkin.Constants.SERVER_RECV;
import static zipkin.Constants.SERVER_SEND;
import static zipkin.internal.Util.UTF_8;
import static zipkin.internal.Util.midnightUTC;

public final class TestObjects {

  /** Notably, the cassandra implementation has day granularity */
  public static final long DAY = TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS);

  // Use real time, as most span-stores have TTL logic which looks back several days.
  public static final long TODAY = midnightUTC(System.currentTimeMillis());

  public static final Endpoint WEB_ENDPOINT = Endpoint.builder()
      .serviceName("web")
      .ipv4(124 << 24 | 13 << 16 | 90 << 8 | 3)
      // Cheat so we don't have to catch an exception here
      .ipv6(sun.net.util.IPAddressUtil.textToNumericFormatV6("2001:db8::c001"))
      .port((short) 80).build();
  public static final Endpoint APP_ENDPOINT =
      Endpoint.builder().serviceName("app").ipv4(172 << 24 | 17 << 16 | 2).port(8080).build();
  public static final Endpoint DB_ENDPOINT =
      Endpoint.builder().serviceName("db").ipv4(172 << 24 | 17 << 16 | 2).port(3306).build();
  public static final Endpoint NO_IP_ENDPOINT = Endpoint.builder().serviceName("no_ip").build();

  static final long WEB_SPAN_ID = -692101025335252320L;
  static final long APP_SPAN_ID = -7842865617155193778L;
  static final long DB_SPAN_ID = 8207293009014896295L;

  public static final List<Span> TRACE = asList(
      Span.builder().traceId(WEB_SPAN_ID).id(WEB_SPAN_ID).name("get")
          .addAnnotation(Annotation.create(TODAY * 1000, SERVER_RECV, WEB_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 350) * 1000, SERVER_SEND, WEB_ENDPOINT))
          .build(),
      Span.builder().traceId(WEB_SPAN_ID).parentId(WEB_SPAN_ID).id(APP_SPAN_ID).name("get")
          .addAnnotation(Annotation.create((TODAY + 50) * 1000, CLIENT_SEND, WEB_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 100) * 1000, SERVER_RECV, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 250) * 1000, SERVER_SEND, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 300) * 1000, CLIENT_RECV, WEB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, WEB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, APP_ENDPOINT))
          .build(),
      Span.builder().traceId(WEB_SPAN_ID).parentId(APP_SPAN_ID).id(DB_SPAN_ID).name("query")
          .addAnnotation(Annotation.create((TODAY + 150) * 1000, CLIENT_SEND, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 200) * 1000, CLIENT_RECV, APP_ENDPOINT))
          .addAnnotation(Annotation.create((TODAY + 190) * 1000, "⻩", NO_IP_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(CLIENT_ADDR, APP_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.address(SERVER_ADDR, DB_ENDPOINT))
          .addBinaryAnnotation(BinaryAnnotation.create(ERROR, "\uD83D\uDCA9", NO_IP_ENDPOINT))
          .build()
  ).stream().map(ApplyTimestampAndDuration::apply).collect(toList());

  public static final List<DependencyLink> LINKS = asList(
      DependencyLink.builder().parent("web").child("app").callCount(1).build(),
      DependencyLink.builder().parent("app").child("db").callCount(1).build()
  );
  public static final Dependencies DEPENDENCIES = Dependencies.create(TODAY, TODAY + 1000, LINKS);

  static final Span.Builder spanBuilder = spanBuilder();

  /** Reuse a builder as it is significantly slows tests to create 100000 of these! */
  static Span.Builder spanBuilder() {
    Endpoint e = Endpoint.builder().serviceName("service").ipv4(127 << 24 | 1).port(8080).build();
    Annotation sr = Annotation.create(System.currentTimeMillis() * 1000, SERVER_RECV, e);
    Annotation ss = Annotation.create(sr.timestamp + 1000, SERVER_SEND, e);
    BinaryAnnotation ba = BinaryAnnotation.create(TraceKeys.HTTP_METHOD, "GET", e);
    return Span.builder().name("get").addAnnotation(sr).addAnnotation(ss).addBinaryAnnotation(ba);
  }

  /**
   * Zipkin trace ids are random 64bit numbers. This creates a relatively large input to avoid
   * flaking out due to PRNG nuance.
   */
  public static final Span[] LOTS_OF_SPANS =
      new Random().longs(100_000).mapToObj(t -> span(t)).toArray(Span[]::new);

  public static Span span(long traceId) {
    return spanBuilder.traceId(traceId).id(traceId).build();
  }
}

please move this into a local variable in its only caller: DependencyLinkerTest.linksSpansShouldHandleNullSpans() also please don't concatenate words like this as it is not readable. Once a local variable use lower-camel


@@ -16,17 +16,13 @@

 package org.springframework.security.oauth2.server.resource.authentication;

-import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.stream.Collectors;

 import org.springframework.core.convert.converter.Converter;
 import org.springframework.security.authentication.AbstractAuthenticationToken;
 import org.springframework.security.core.GrantedAuthority;
-import org.springframework.security.core.authority.SimpleGrantedAuthority;
 import org.springframework.security.oauth2.jwt.Jwt;
-import org.springframework.util.StringUtils;
+import org.springframework.util.Assert;

 /**
  * @author Rob Winch

/*
 * Copyright 2002-2018 the original author or authors.
 *
 * 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.springframework.security.oauth2.server.resource.authentication;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;

import org.springframework.core.convert.converter.Converter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.util.StringUtils;

/**
 * @author Rob Winch
 * @author Josh Cummings
 * @since 5.1
 */
public class JwtAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
	private static final String SCOPE_AUTHORITY_PREFIX = "SCOPE_";

	private static final Collection<String> WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES =
			Arrays.asList("scope", "scp");

	public final AbstractAuthenticationToken convert(Jwt jwt) {
		Collection<GrantedAuthority> authorities = extractAuthorities(jwt);
		return new JwtAuthenticationToken(jwt, authorities);
	}

	protected Collection<GrantedAuthority> extractAuthorities(Jwt jwt) {
		return this.getScopes(jwt)
						.stream()
						.map(authority -> SCOPE_AUTHORITY_PREFIX + authority)
						.map(SimpleGrantedAuthority::new)
						.collect(Collectors.toList());
	}

	private Collection<String> getScopes(Jwt jwt) {
		for ( String attributeName : WELL_KNOWN_SCOPE_ATTRIBUTE_NAMES ) {
			Object scopes = jwt.getClaims().get(attributeName);
			if (scopes instanceof String) {
				if (StringUtils.hasText((String) scopes)) {
					return Arrays.asList(((String) scopes).split(" "));
				} else {
					return Collections.emptyList();
				}
			} else if (scopes instanceof Collection) {
				return (Collection<String>) scopes;
			}
		}

		return Collections.emptyList();
	}
}

Allow injecting the `Converter<Jwt, Collection<GrantedAuthority>>`