@@ -102,4 +102,19 @@ public class Invoker implements InvocationHandler {

     throw ExceptionFactory.convertConsumerException(response.getResult());
   }
+
+  protected CompletableFuture<Object> completableFutureInvoke(Invocation invocation,
+      SwaggerConsumerOperation consumerOperation) {
+    CompletableFuture<Object> future = new CompletableFuture<>();
+    InvokerUtils.reactiveInvoke(invocation, response -> {
+      if (response.isSuccessed()) {
+        Object result = consumerOperation.getResponseMapper().mapResponse(response);
+        future.complete(result);
+        return;
+      }
+
+      future.completeExceptionally(response.getResult());
+    });
+    return future;
+  }
 }

/*
 * 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 io.servicecomb.provider.pojo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.springframework.util.StringUtils;

import io.servicecomb.core.CseContext;
import io.servicecomb.core.Invocation;
import io.servicecomb.core.definition.MicroserviceMeta;
import io.servicecomb.core.definition.SchemaMeta;
import io.servicecomb.core.invocation.InvocationFactory;
import io.servicecomb.core.provider.consumer.InvokerUtils;
import io.servicecomb.core.provider.consumer.ReferenceConfig;
import io.servicecomb.core.provider.consumer.ReferenceConfigUtils;
import io.servicecomb.swagger.engine.SwaggerConsumer;
import io.servicecomb.swagger.engine.SwaggerConsumerOperation;
import io.servicecomb.swagger.invocation.Response;
import io.servicecomb.swagger.invocation.exception.ExceptionFactory;

public class Invoker implements InvocationHandler {
  // 原始数据
  private String microserviceName;

  private String schemaId;

  private Class<?> consumerIntf;

  // 生成的数据
  private SchemaMeta schemaMeta;

  private ReferenceConfig referenceConfig;

  private SwaggerConsumer swaggerConsumer;

  @SuppressWarnings("unchecked")
  public static <T> T createProxy(String microserviceName, String schemaId, Class<?> consumerIntf) {
    Invoker invoker = new Invoker(microserviceName, schemaId, consumerIntf);
    return (T) Proxy.newProxyInstance(consumerIntf.getClassLoader(), new Class<?>[] {consumerIntf}, invoker);
  }

  public Invoker(String microserviceName, String schemaId, Class<?> consumerIntf) {
    this.microserviceName = microserviceName;
    this.schemaId = schemaId;
    this.consumerIntf = consumerIntf;
  }

  protected void prepare() {
    referenceConfig = ReferenceConfigUtils.getForInvoke(microserviceName);
    MicroserviceMeta microserviceMeta = referenceConfig.getMicroserviceMeta();

    if (StringUtils.isEmpty(schemaId)) {
      // 未指定schemaId，看看consumer接口是否等于契约接口
      schemaMeta = microserviceMeta.findSchemaMeta(consumerIntf);
      if (schemaMeta == null) {
        // 尝试用consumer接口名作为schemaId
        schemaId = consumerIntf.getName();
        schemaMeta = microserviceMeta.ensureFindSchemaMeta(schemaId);
      }
    } else {
      schemaMeta = microserviceMeta.ensureFindSchemaMeta(schemaId);
    }

    this.swaggerConsumer = CseContext.getInstance().getSwaggerEnvironment().createConsumer(consumerIntf,
        schemaMeta.getSwaggerIntf());
  }

  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (swaggerConsumer == null) {
      prepare();
    }

    Invocation invocation =
        InvocationFactory.forConsumer(referenceConfig, schemaMeta, method.getName(), null);

    SwaggerConsumerOperation consumerOperation = swaggerConsumer.findOperation(method.getName());
    consumerOperation.getArgumentsMapper().toInvocation(args, invocation);

    Response response = InvokerUtils.innerSyncInvoke(invocation);
    if (response.isSuccessed()) {
      return consumerOperation.getResponseMapper().mapResponse(response);
    }

    throw ExceptionFactory.convertConsumerException(response.getResult());
  }
}


@@ -7,9 +7,12 @@ package net.sourceforge.pmd.lang.ecmascript.rule;
 import net.sourceforge.pmd.Rule;
 import net.sourceforge.pmd.RuleContext;
 import net.sourceforge.pmd.RuleViolation;
+import net.sourceforge.pmd.autofix.AutoFixableRuleViolation;
+import net.sourceforge.pmd.autofix.RuleViolationFix;
 import net.sourceforge.pmd.lang.ast.Node;
 import net.sourceforge.pmd.lang.ecmascript.ast.EcmascriptNode;
 import net.sourceforge.pmd.lang.rule.AbstractRuleViolationFactory;
+import net.sourceforge.pmd.lang.rule.AutoFixableParametricRuleViolation;
 import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;

 public final class EcmascriptRuleViolationFactory extends AbstractRuleViolationFactory {

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

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

import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleContext;
import net.sourceforge.pmd.RuleViolation;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ecmascript.ast.EcmascriptNode;
import net.sourceforge.pmd.lang.rule.AbstractRuleViolationFactory;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;

public final class EcmascriptRuleViolationFactory extends AbstractRuleViolationFactory {

    public static final EcmascriptRuleViolationFactory INSTANCE = new EcmascriptRuleViolationFactory();

    private EcmascriptRuleViolationFactory() {
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected RuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message) {
        return new ParametricRuleViolation<>(rule, ruleContext, (EcmascriptNode) node, message);
    }

    protected RuleViolation createRuleViolation(Rule rule, RuleContext ruleContext, Node node, String message,
            int beginLine, int endLine) {
        return null; // FIXME
    }
}


@@ -1,6 +1,7 @@
 package com.fsck.k9.mail.ssl;

 import com.fsck.k9.mail.MessagingException;
+import com.fsck.k9.mail.ProxySettings;

 import java.io.IOException;
 import java.net.Socket;

package com.fsck.k9.mail.ssl;

import com.fsck.k9.mail.MessagingException;

import java.io.IOException;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

public interface TrustedSocketFactory {
    Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias)
            throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException;
}


@@ -102,25 +102,20 @@ public final class BaselineVersions implements Plugin<Project> {
             if (project.file("versions.props").exists()) {
                 extension.propertiesFile(ImmutableMap.of("file", project.file("versions.props")));
             }
-        } else {
-            TaskProvider<CheckBomConflictTask> checkBomConflict = project.getTasks().register(
-                    "checkBomConflict", CheckBomConflictTask.class, task -> task.setPropsFile(rootVersionsPropsFile));
-            TaskProvider<CheckNoUnusedPinTask> checkNoUnusedPin = project.getTasks().register(
-                    "checkNoUnusedPin", CheckNoUnusedPinTask.class, task -> task.setPropsFile(rootVersionsPropsFile));
-
-            project.getTasks().register("checkVersionsProps", CheckVersionsPropsTask.class, task -> {
-                task.dependsOn(checkBomConflict, checkNoUnusedPin);
-                // If we just run checkVersionsProps --fix, we want to propagate its option to its dependent tasks
-                checkBomConflict.get().setShouldFix(task.getShouldFix());
-                checkNoUnusedPin.get().setShouldFix(task.getShouldFix());
-            });
-            // If we run with --parallel --fix, both checkNoUnusedPin and checkBomConflict will try to overwrite the
-            // versions file at the same time. Therefore, make sure checkBomConflict runs first.
-            checkNoUnusedPin.configure(task -> task.mustRunAfter(checkBomConflict));
-
-            project.getPluginManager().apply(BasePlugin.class);
-            project.getTasks().named("check").configure(task -> task.dependsOn("checkVersionsProps"));
         }
+
+        TaskProvider<CheckBomConflictTask> checkBomConflict = project.getTasks().register(
+                "checkBomConflict", CheckBomConflictTask.class, task -> {
+                    task.setPropsFile(rootVersionsPropsFile);
+                    // If we run with --parallel --fix, both checkNoUnusedPin and checkBomConflict will try to overwrite
+                    // the versions file at the same time. Therefore, make sure checkNoUnusedPin runs first.
+                    task.mustRunAfter(checkNoUnusedPin);
+                });
+
+        checkVersionsProps.configure(task -> {
+            task.dependsOn(checkBomConflict);
+            checkBomConflict.get().setShouldFix(task.getShouldFix());
+        });
     }

     private static File rootVersionsPropsFile(Project project) {

/*
 * (c) Copyright 2018 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.versions;

import com.google.common.base.CharMatcher;
import com.google.common.collect.ImmutableMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Comparator;
import java.util.Set;
import java.util.stream.Collectors;
import netflix.nebula.dependency.recommender.DependencyRecommendationsPlugin;
import netflix.nebula.dependency.recommender.RecommendationStrategies;
import netflix.nebula.dependency.recommender.provider.FuzzyVersionResolver;
import netflix.nebula.dependency.recommender.provider.RecommendationProviderContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.artifacts.result.ResolutionResult;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.plugins.BasePlugin;
import org.gradle.api.tasks.TaskProvider;

/**
 * Transitively applies nebula.dependency recommender to replace the following common gradle snippet.
 *
 *

 * buildscript {
 *     dependencies {
 *         classpath 'com.netflix.nebula:nebula-dependency-recommender:5.2.0'
 *     }
 * }
 *
 * allprojects {
 *     apply plugin: 'nebula.dependency-recommender'
 *
 *     dependencyRecommendations {
 *         strategy OverrideTransitives
 *         propertiesFile file: project.rootProject.file('versions.props')
 *         if (file('versions.props').exists()) {
 *             propertiesFile file: project.file('versions.props')
 *         }
 *     }
 * }
 *

 */
public final class BaselineVersions implements Plugin<Project> {

    private static final Logger log = Logging.getLogger(BaselineVersions.class);
    static final String GROUP = "com.palantir.baseline-versions";
    /**
     * System property which, when true, instructs {@code nebula.dependency-recommender} to only support sourcing
     * constraints from a BOM. In that case, nebula doesn't support sourcing recommendations from
     * {@code versions.props} anymore.
     */
    public static final boolean IS_CORE_BOM_ENABLED = Boolean.getBoolean("nebula.features.coreBomSupport");
    public static final String DISABLE_PROPERTY = "com.palantir.baseline-versions.disable";

    @Override
    public void apply(Project project) {
        if (project.hasProperty(DISABLE_PROPERTY)) {
            log.info("Not configuring com.palantir.baseline-versions because " + DISABLE_PROPERTY + " was set");
            return;
        }
        // apply plugin: "nebula.dependency-recommender"
        project.getPluginManager().apply(DependencyRecommendationsPlugin.class);

        if (IS_CORE_BOM_ENABLED) {
            log.info("Not configuring nebula.dependency-recommender because coreBomSupport is enabled");
            return;
        }

        // get dependencyRecommendations extension
        RecommendationProviderContainer extension = project
                .getExtensions()
                .getByType(RecommendationProviderContainer.class);

        extension.setStrategy(RecommendationStrategies.OverrideTransitives); // default is 'ConflictResolved'

        File rootVersionsPropsFile = rootVersionsPropsFile(project);
        extension.propertiesFile(ImmutableMap.of("file", rootVersionsPropsFile));

        if (project != project.getRootProject()) {
            // allow nested projects to specify their own nested versions.props file
            if (project.file("versions.props").exists()) {
                extension.propertiesFile(ImmutableMap.of("file", project.file("versions.props")));
            }
        } else {
            TaskProvider<CheckBomConflictTask> checkBomConflict = project.getTasks().register(
                    "checkBomConflict", CheckBomConflictTask.class, task -> task.setPropsFile(rootVersionsPropsFile));
            TaskProvider<CheckNoUnusedPinTask> checkNoUnusedPin = project.getTasks().register(
                    "checkNoUnusedPin", CheckNoUnusedPinTask.class, task -> task.setPropsFile(rootVersionsPropsFile));

            project.getTasks().register("checkVersionsProps", CheckVersionsPropsTask.class, task -> {
                task.dependsOn(checkBomConflict, checkNoUnusedPin);
                // If we just run checkVersionsProps --fix, we want to propagate its option to its dependent tasks
                checkBomConflict.get().setShouldFix(task.getShouldFix());
                checkNoUnusedPin.get().setShouldFix(task.getShouldFix());
            });
            // If we run with --parallel --fix, both checkNoUnusedPin and checkBomConflict will try to overwrite the
            // versions file at the same time. Therefore, make sure checkBomConflict runs first.
            checkNoUnusedPin.configure(task -> task.mustRunAfter(checkBomConflict));

            project.getPluginManager().apply(BasePlugin.class);
            project.getTasks().named("check").configure(task -> task.dependsOn("checkVersionsProps"));
        }
    }

    private static File rootVersionsPropsFile(Project project) {
        File file = project.getRootProject().file("versions.props");
        if (!file.canRead()) {
            try {
                log.info("Could not find 'versions.props' file, creating...");
                Files.createFile(file.toPath());
            } catch (IOException e) {
                log.warn("Unable to create empty versions.props file, please create this manually", e);
            }
        }
        return file;
    }

    static Set<String> getAllProjectsResolvedModuleIdentifiers(Project project) {
        return project.getRootProject().getAllprojects()
                .stream()
                .flatMap(project2 -> getResolvedModuleIdentifiers(project2).stream())
                .collect(Collectors.toSet());
    }

    static Set<String> getResolvedModuleIdentifiers(Project project) {
        return project.getConfigurations().stream()
                .filter(Configuration::isCanBeResolved)
                .flatMap(configuration -> {
                    try {
                        ResolutionResult resolutionResult = configuration.getIncoming().getResolutionResult();
                        return resolutionResult
                                .getAllComponents()
                                .stream()
                                .map(result -> result.getId())
                                .filter(cid -> !cid.equals(resolutionResult.getRoot().getId())) // remove the project
                                .filter(cid -> cid instanceof ModuleComponentIdentifier)
                                .map(mcid -> ((ModuleComponentIdentifier) mcid).getModuleIdentifier())
                                .map(mid -> mid.getGroup() + ":" + mid.getName());
                    } catch (Exception e) {
                        throw new RuntimeException(String.format("Error during resolution of the dependency graph of "
                                + "configuration %s", configuration), e);
                    }
                })
                .collect(Collectors.toSet());
    }

    /**
     * Compares {@code versions.props} matchers by weight. Higher weight means the matcher is more specific.
     * For example,
     *

     *     com.google.guava:guava
     *

     * is more specific than
     *

     *     com.google.guava:*
     *

     */
    static final Comparator<String> VERSIONS_PROPS_ENTRY_SPECIFIC_COMPARATOR =
            Comparator.comparing(BaselineVersions::versionsPropsMatcherWeight);

    /**
     * The weight of a matcher in {@code versions.props} according to the disambiguation logic defined in
     * {@code nebula.dependency-recommender}.
     *
     * This matches the logic in {@link FuzzyVersionResolver}.
     */
    private static int versionsPropsMatcherWeight(String matcher) {
        return CharMatcher.isNot('*').countIn(matcher);
    }
}


@@ -14,6 +14,8 @@ import org.junit.jupiter.api.Test;
 import java.io.IOException;

 import static com.github.javaparser.ast.Modifier.Keyword.STATIC;
+import static com.github.javaparser.utils.TestUtils.assertEqualsNoEol;
+import static com.github.javaparser.utils.Utils.EOL;

 /**
  * These tests are more "high level" than the ones in LexicalPreservingPrinterTest.

package com.github.javaparser.printer.lexicalpreservation;

import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.VariableDeclarator;
import com.github.javaparser.ast.expr.Expression;
import com.github.javaparser.ast.expr.NameExpr;
import com.github.javaparser.ast.expr.NullLiteralExpr;
import com.github.javaparser.ast.stmt.ReturnStmt;
import com.github.javaparser.ast.type.ArrayType;
import com.github.javaparser.ast.type.PrimitiveType;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static com.github.javaparser.ast.Modifier.Keyword.STATIC;

/**
 * These tests are more "high level" than the ones in LexicalPreservingPrinterTest.
 * The idea is to perform some transformations on the code, print it back and see if the generated code
 * is the expected one. We do not care about the internal state of LexicalPreservingPrinter, just the visible result.
 */
class TransformationsTest extends  AbstractLexicalPreservingTest {

    @Test
    void unchangedSimpleClasses() throws IOException {
        assertUnchanged("Example1");
        assertUnchanged("Example2");
    }

    @Test
    void unchangedComplexFile() throws IOException {
        assertUnchanged("Example4");
    }

    @Test
    void example1() throws IOException {
        considerExample("Example1_original");
        cu.getClassByName("A").get().getFieldByName("a").get().setModifiers(STATIC);
        assertTransformed("Example1", cu);
    }

    @Test
    void example2() throws IOException {
        considerExample("Example2_original");
        cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer("10");
        assertTransformed("Example2", cu);
    }

    @Test
    void example3() throws IOException {
        considerExample("Example3_original");
        cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer((Expression) null);
        assertTransformed("Example3", cu);
    }

    @Test
    void example5() throws IOException {
        considerExample("Example5_original");
        cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setInitializer(new NullLiteralExpr());
        assertTransformed("Example5", cu);
    }

    @Test
    void example6() throws IOException {
        considerExample("Example6_original");
        cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setName("someOtherName");
        assertTransformed("Example6", cu);
    }

    @Test
    void example7() throws IOException {
        considerExample("Example7_original");
        cu.getClassByName("A").get().getFieldByName("a").get().getVariable(0).setType(new ArrayType(PrimitiveType.intType()));
        assertTransformed("Example7", cu);
    }

    @Test
    void example8() throws IOException {
        considerExample("Example8_original");
        FieldDeclaration fd = cu.getClassByName("A").get().getMember(0).asFieldDeclaration();
        fd.addVariable(new VariableDeclarator(PrimitiveType.intType(), "b"));
        assertTransformed("Example8", cu);
    }

    @Test
    void example9() throws IOException {
        considerExample("Example9_original");
        FieldDeclaration fd = cu.getClassByName("A").get().getMember(0).asFieldDeclaration();
        fd.addVariable(new VariableDeclarator(new ArrayType(PrimitiveType.intType()), "b"));
        assertTransformed("Example9", cu);
    }

    @Test
    void example10() throws IOException {
        considerExample("Example10_original");
        cu.getClassByName("A").get().getMembers().remove(0);
        assertTransformed("Example10", cu);
    }

    @Test
    void exampleParam1() throws IOException {
        considerExample("Example_param1_original");
        MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
        md.addParameter("int", "p1");
        assertTransformed("Example_param1", cu);
    }

    @Test
    void exampleParam2() throws IOException {
        considerExample("Example_param1_original");
        MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
        md.addParameter(new ArrayType(PrimitiveType.intType()), "p1");
        md.addParameter("char", "p2");
        assertTransformed("Example_param2", cu);
    }

    @Test
    void exampleParam3() throws IOException {
        considerExample("Example_param3_original");
        MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
        md.getParameters().remove(0);
        assertTransformed("Example_param3", cu);
    }

    @Test
    void exampleParam4() throws IOException {
        considerExample("Example_param3_original");
        MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
        md.getParameters().remove(1);
        assertTransformed("Example_param4", cu);
    }

    @Test
    void exampleParam5() throws IOException {
        considerExample("Example_param3_original");
        MethodDeclaration md = cu.getClassByName("A").get().getMember(0).asMethodDeclaration();
        md.setType(PrimitiveType.intType());
        assertTransformed("Example_param5b", cu);
        md.getBody().get().getStatements().add(new ReturnStmt(new NameExpr("p1")));
        assertTransformed("Example_param5", cu);
    }
}


@@ -31,17 +31,25 @@ import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

+import java.io.File;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.List;
+
 @Configuration
 public class RepositoryConfiguration {
-    @Value("${application.repository.configuration}")
-    private String repositoryConfiguration;
-
     @Value("${application.repository.forceIncompatibleOperatingSystems:false}")
     private boolean enforceUncompatibleOperatingSystems;

     @Value("${application.user.cache}")
     private String cacheDirectoryPath;

+    @Value("${application.repository.list}")
+    private String repositoryListPath;
+
     @Autowired
     private MultithreadingConfiguration multithreadingConfiguration;

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

import com.fasterxml.jackson.databind.ObjectMapper;
import org.phoenicis.repository.repositoryTypes.BackgroundRepository;
import org.phoenicis.repository.repositoryTypes.ClasspathRepository;
import org.phoenicis.repository.repositoryTypes.LocalRepository;
import org.phoenicis.multithreading.MultithreadingConfiguration;
import org.phoenicis.tools.ToolsConfiguration;
import org.phoenicis.tools.files.FileUtilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

@Configuration
public class RepositoryConfiguration {
    @Value("${application.repository.configuration}")
    private String repositoryConfiguration;

    @Value("${application.repository.forceIncompatibleOperatingSystems:false}")
    private boolean enforceUncompatibleOperatingSystems;

    @Value("${application.user.cache}")
    private String cacheDirectoryPath;

    @Autowired
    private MultithreadingConfiguration multithreadingConfiguration;

    @Autowired
    private ToolsConfiguration toolsConfiguration;

    @Autowired
    private FileUtilities fileUtilities;

    @Bean
    public RepositoryManager repositoryManager() {
        RepositoryManager repositoryManager = new DefaultRepositoryManager(
                multithreadingConfiguration.appsExecutorService(), enforceUncompatibleOperatingSystems,
                toolsConfiguration, cacheDirectoryPath, fileUtilities, localRepositoryFactory(),
                classPathRepositoryFactory(), backgroundRepositoryFactory());

        // set initial repositories
        repositoryManager.addRepositories(this.repositoryConfiguration.split(";"));

        return repositoryManager;
    }

    @Bean
    ClasspathRepository.Factory classPathRepositoryFactory() {
        return new ClasspathRepository.Factory(objectMapper(), new PathMatchingResourcePatternResolver());
    }

    @Bean
    LocalRepository.Factory localRepositoryFactory() {
        return new LocalRepository.Factory(objectMapper());
    }

    @Bean
    BackgroundRepository.Factory backgroundRepositoryFactory() {
        return new BackgroundRepository.Factory();
    }

    @Bean
    ObjectMapper objectMapper() {
        return new ObjectMapper();
    }

}


@@ -24,6 +24,7 @@ import java.io.File;
 import java.io.IOException;
 import java.time.LocalDateTime;
 import java.time.OffsetDateTime;
+import java.util.Collections;
 import java.util.List;
 import java.util.TimeZone;
 import org.apache.iceberg.Files;

/*
 * 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.data.orc;

import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.TimeZone;
import org.apache.iceberg.Files;
import org.apache.iceberg.Schema;
import org.apache.iceberg.data.DataTest;
import org.apache.iceberg.data.DataTestHelpers;
import org.apache.iceberg.data.GenericRecord;
import org.apache.iceberg.data.RandomGenericData;
import org.apache.iceberg.data.Record;
import org.apache.iceberg.io.CloseableIterable;
import org.apache.iceberg.io.FileAppender;
import org.apache.iceberg.orc.ORC;
import org.apache.iceberg.types.Types;
import org.junit.Assert;
import org.junit.Test;

import static org.apache.iceberg.types.Types.NestedField.required;

public class TestGenericData extends DataTest {

  @Override
  protected void writeAndValidate(Schema schema) throws IOException {
    List<Record> expected = RandomGenericData.generate(schema, 100, 0L);

    File testFile = temp.newFile();
    Assert.assertTrue("Delete should succeed", testFile.delete());

    try (FileAppender<Record> writer = ORC.write(Files.localOutput(testFile))
        .schema(schema)
        .createWriterFunc(GenericOrcWriter::buildWriter)
        .build()) {
      for (Record rec : expected) {
        writer.add(rec);
      }
    }

    List<Record> rows;
    try (CloseableIterable<Record> reader = ORC.read(Files.localInput(testFile))
        .project(schema)
        .createReaderFunc(fileSchema -> GenericOrcReader.buildReader(schema, fileSchema))
        .build()) {
      rows = Lists.newArrayList(reader);
    }

    for (int i = 0; i < expected.size(); i += 1) {
      DataTestHelpers.assertEquals(schema.asStruct(), expected.get(i), rows.get(i));
    }
  }

  @Test
  public void writeAndValidateTimestamps() throws IOException {
    Schema timestampSchema = new Schema(
        required(1, "tsTzCol", Types.TimestampType.withZone()),
        required(2, "tsCol", Types.TimestampType.withoutZone())
    );

    // Write using America/New_York timezone
    TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
    GenericRecord record1 = GenericRecord.create(timestampSchema);
    record1.setField("tsTzCol", OffsetDateTime.parse("2017-01-16T17:10:34-08:00"));
    record1.setField("tsCol", LocalDateTime.parse("1970-01-01T00:01:00"));
    GenericRecord record2 = GenericRecord.create(timestampSchema);
    record2.setField("tsTzCol", OffsetDateTime.parse("2017-05-16T17:10:34-08:00"));
    record2.setField("tsCol", LocalDateTime.parse("1970-05-01T00:01:00"));
    GenericRecord record3 = GenericRecord.create(timestampSchema);
    record3.setField("tsTzCol", OffsetDateTime.parse("1935-01-16T17:10:34-08:00"));
    record3.setField("tsCol", LocalDateTime.parse("1935-01-01T00:01:00"));
    GenericRecord record4 = GenericRecord.create(timestampSchema);
    record4.setField("tsTzCol", OffsetDateTime.parse("1935-05-16T17:10:34-08:00"));
    record4.setField("tsCol", LocalDateTime.parse("1935-05-01T00:01:00"));

    File testFile = temp.newFile();
    Assert.assertTrue("Delete should succeed", testFile.delete());

    try (FileAppender<Record> writer = ORC.write(Files.localOutput(testFile))
        .schema(timestampSchema)
        .createWriterFunc(GenericOrcWriter::buildWriter)
        .build()) {
      writer.add(record1);
      writer.add(record2);
      writer.add(record3);
      writer.add(record4);
    }

    // Read using Asia/Kolkata timezone
    TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata"));
    List<Record> rows;
    try (CloseableIterable<Record> reader = ORC.read(Files.localInput(testFile))
        .project(timestampSchema)
        .createReaderFunc(fileSchema -> GenericOrcReader.buildReader(timestampSchema, fileSchema))
        .build()) {
      rows = Lists.newArrayList(reader);
    }

    Assert.assertEquals(OffsetDateTime.parse("2017-01-17T01:10:34Z"), rows.get(0).getField("tsTzCol"));
    Assert.assertEquals(LocalDateTime.parse("1970-01-01T00:01:00"), rows.get(0).getField("tsCol"));
    Assert.assertEquals(OffsetDateTime.parse("2017-05-17T01:10:34Z"), rows.get(1).getField("tsTzCol"));
    Assert.assertEquals(LocalDateTime.parse("1970-05-01T00:01:00"), rows.get(1).getField("tsCol"));
    Assert.assertEquals(OffsetDateTime.parse("1935-01-17T01:10:34Z"), rows.get(2).getField("tsTzCol"));
    Assert.assertEquals(LocalDateTime.parse("1935-01-01T00:01:00"), rows.get(2).getField("tsCol"));
    Assert.assertEquals(OffsetDateTime.parse("1935-05-17T01:10:34Z"), rows.get(3).getField("tsTzCol"));
    Assert.assertEquals(LocalDateTime.parse("1935-05-01T00:01:00"), rows.get(3).getField("tsCol"));
  }
}


@@ -57,6 +57,9 @@ public class AzkabanCommonModule extends AbstractModule {
     bind(ProjectLoader.class).to(JdbcProjectLoader.class).in(Scopes.SINGLETON);
     bind(Props.class).toInstance(props);
     bind(Storage.class).to(resolveStorageClassType()).in(Scopes.SINGLETON);
+    bind(AzDBOperator.class).to(AzDBOperatorImpl.class).in(Scopes.SINGLETON);
+    //todo kunkun-tang : Consider both H2 DataSource and MysqlDatasource case.
+    bind(AzkabanDataSource.class).toInstance(dataSource);
   }

   public Class<? extends Storage> resolveStorageClassType() {

/*
 * Copyright 2017 LinkedIn Corp.
 *
 * 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 azkaban;

import azkaban.project.JdbcProjectLoader;
import azkaban.project.ProjectLoader;
import azkaban.spi.Storage;
import azkaban.spi.StorageException;
import azkaban.storage.LocalStorage;
import azkaban.storage.StorageConfig;
import azkaban.storage.StorageImplementationType;
import azkaban.utils.Props;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import java.io.File;

import static azkaban.storage.StorageImplementationType.*;

public class AzkabanCommonModule extends AbstractModule {
  private final Props props;
  /**
   * Storage Implementation
   * This can be any of the {@link StorageImplementationType} values in which case {@link StorageFactory} will create
   * the appropriate storage instance. Or one can feed in a custom implementation class using the full qualified
   * path required by a classloader.
   *
   * examples: LOCAL, DATABASE, azkaban.storage.MyFavStorage
   *
   */
  private final String storageImplementation;

  public AzkabanCommonModule(Props props) {
    this.props = props;
    this.storageImplementation = props.getString(Constants.ConfigurationKeys.AZKABAN_STORAGE_TYPE, LOCAL.name());
  }

  @Override
  protected void configure() {
    bind(ProjectLoader.class).to(JdbcProjectLoader.class).in(Scopes.SINGLETON);
    bind(Props.class).toInstance(props);
    bind(Storage.class).to(resolveStorageClassType()).in(Scopes.SINGLETON);
  }

  public Class<? extends Storage> resolveStorageClassType() {
    final StorageImplementationType type = StorageImplementationType.from(storageImplementation);
    if (type != null) {
      return type.getImplementationClass();
    } else {
      return loadCustomStorageClass(storageImplementation);
    }
  }

  private Class<? extends Storage> loadCustomStorageClass(String storageImplementation) {
    try {
      return (Class<? extends Storage>) Class.forName(storageImplementation);
    } catch (ClassNotFoundException e) {
      throw new StorageException(e);
    }
  }

  @Inject
  public @Provides
  LocalStorage createLocalStorage(StorageConfig config) {
    return new LocalStorage(new File(config.getBaseDirectoryPath()));
  }
}


@@ -89,11 +89,11 @@ public class PkiKeyStoreConfiguration {

     private String keyStoreType = DEFAULT_KEYSTORE_TYPE;
     private Path keyStorePath;
-    private Supplier<String> keyStorePasswordSupplier;
+    private Path keyStorePasswordPath;
     private String certificateAlias = DEFAULT_CERTIFICATE_ALIAS;
     private String trustStoreType = DEFAULT_KEYSTORE_TYPE;
     private Path trustStorePath;
-    private Supplier<String> trustStorePasswordSupplier;
+    private Path trustStorePasswordPath;
     private Path crlFilePath;

     public Builder() {}

/*
 * 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.pki.config;

import static java.util.Objects.requireNonNull;

import java.nio.file.Path;
import java.util.Optional;
import java.util.function.Supplier;

public class PkiKeyStoreConfiguration {

  public static String DEFAULT_KEYSTORE_TYPE = "PKCS12";
  public static String DEFAULT_CERTIFICATE_ALIAS = "validator";

  private final String keyStoreType;
  private final Path keyStorePath;
  private final Supplier<String> keyStorePasswordSupplier;
  private final String certificateAlias;
  private final String trustStoreType;
  private final Path trustStorePath;
  private final Supplier<String> trustStorePasswordSupplier;
  private final Optional<Path> crlFilePath;

  public PkiKeyStoreConfiguration(
      final String keyStoreType,
      final Path keyStorePath,
      final Supplier<String> keyStorePasswordSupplier,
      final String certificateAlias,
      final String trustStoreType,
      final Path trustStorePath,
      final Supplier<String> trustStorePasswordSupplier,
      final Optional<Path> crlFilePath) {
    this.keyStoreType = keyStoreType;
    this.keyStorePath = keyStorePath;
    this.keyStorePasswordSupplier = keyStorePasswordSupplier;
    this.certificateAlias = certificateAlias;
    this.trustStoreType = trustStoreType;
    this.trustStorePath = trustStorePath;
    this.trustStorePasswordSupplier = trustStorePasswordSupplier;
    this.crlFilePath = crlFilePath;
  }

  public String getKeyStoreType() {
    return keyStoreType;
  }

  public Path getKeyStorePath() {
    return keyStorePath;
  }

  public String getKeyStorePassword() {
    return null == keyStorePasswordSupplier ? null : keyStorePasswordSupplier.get();
  }

  public String getCertificateAlias() {
    return certificateAlias;
  }

  public String getTrustStoreType() {
    return trustStoreType;
  }

  public Path getTrustStorePath() {
    return trustStorePath;
  }

  public String getTrustStorePassword() {
    return trustStorePasswordSupplier.get();
  }

  public Optional<Path> getCrlFilePath() {
    return crlFilePath;
  }

  public static final class Builder {

    private String keyStoreType = DEFAULT_KEYSTORE_TYPE;
    private Path keyStorePath;
    private Supplier<String> keyStorePasswordSupplier;
    private String certificateAlias = DEFAULT_CERTIFICATE_ALIAS;
    private String trustStoreType = DEFAULT_KEYSTORE_TYPE;
    private Path trustStorePath;
    private Supplier<String> trustStorePasswordSupplier;
    private Path crlFilePath;

    public Builder() {}

    public Builder withKeyStoreType(final String keyStoreType) {
      this.keyStoreType = keyStoreType;
      return this;
    }

    public Builder withKeyStorePath(final Path keyStorePath) {
      this.keyStorePath = keyStorePath;
      return this;
    }

    public Builder withKeyStorePasswordSupplier(final Supplier<String> keyStorePasswordSupplier) {
      this.keyStorePasswordSupplier = keyStorePasswordSupplier;
      return this;
    }

    public Builder withCertificateAlias(final String certificateAlias) {
      this.certificateAlias = certificateAlias;
      return this;
    }

    public Builder withTrustStoreType(final String trustStoreType) {
      this.trustStoreType = trustStoreType;
      return this;
    }

    public Builder withTrustStorePath(final Path trustStorePath) {
      this.trustStorePath = trustStorePath;
      return this;
    }

    public Builder withTrustStorePasswordSupplier(
        final Supplier<String> trustStorePasswordSupplier) {
      this.trustStorePasswordSupplier = trustStorePasswordSupplier;
      return this;
    }

    public Builder withCrlFilePath(final Path filePath) {
      this.crlFilePath = filePath;
      return this;
    }

    public PkiKeyStoreConfiguration build() {
      requireNonNull(keyStoreType, "Key Store Type must not be null");
      requireNonNull(keyStorePasswordSupplier, "Key Store password supplier must not be null");
      return new PkiKeyStoreConfiguration(
          keyStoreType,
          keyStorePath,
          keyStorePasswordSupplier,
          certificateAlias,
          trustStoreType,
          trustStorePath,
          trustStorePasswordSupplier,
          Optional.ofNullable(crlFilePath));
    }
  }
}


@@ -136,7 +136,7 @@ public class TestLoadBalancer {
     List<Server> servers = new ArrayList<Server>();
     Server server = Mockito.mock(Server.class);
     servers.add(server);
-    Mockito.when(serverList.getInitialListOfServers()).thenReturn(servers);
+    loadBalancer.setServerList(servers);

     TransactionControlFilter filter = Mockito.mock(TransactionControlFilter.class);
     Mockito.when(filter.getFilteredListOfServers(servers)).thenReturn(servers);

/*
 * Copyright 2017 Huawei Technologies Co., Ltd
 *
 * 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 io.servicecomb.loadbalance;

import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

import com.netflix.loadbalancer.AbstractLoadBalancer.ServerGroup;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.Server;

import io.servicecomb.loadbalance.filter.SimpleTransactionControlFilter;
import io.servicecomb.loadbalance.filter.TransactionControlFilter;

public class TestLoadBalancer {

  private CseServerList serverList = Mockito.mock(CseServerList.class);

  private IRule rule = Mockito.mock(IRule.class);

  private LoadBalancer loadBalancer = new LoadBalancer(serverList, rule);

  @Test
  public void testLoadBalancerFullOperationWithoutException() {

    List<Server> newServers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);
    newServers.add(server);

    loadBalancer.chooseServer();

    Object key = Mockito.mock(Object.class);

    loadBalancer.chooseServer(key);
    loadBalancer.getAllServers();
    loadBalancer.getLoadBalancerStats();
    loadBalancer.getReachableServers();

    assertNotNull(loadBalancer.getAllServers());
  }

  @Test
  public void testAddServerException() {
    boolean status = true;
    List<Server> newServers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);

    newServers.add(server);

    try {

      loadBalancer.addServers(newServers);
    } catch (Exception e) {

      status = false;

      Assert.assertEquals("Not implemented.", e.getMessage());
    }

    Assert.assertFalse(status);
  }

  @Test
  public void testServerListException() {
    boolean status = true;
    List<Server> newServers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);

    newServers.add(server);

    try {

      loadBalancer.getServerList(ServerGroup.ALL);
    } catch (Exception e) {

      status = false;

      Assert.assertEquals("Not implemented.", e.getMessage());
    }

    Assert.assertFalse(status);
  }

  @Test
  public void testMarkServerDownException() {
    boolean status = true;
    List<Server> newServers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);

    newServers.add(server);

    try {

      loadBalancer.markServerDown(server);
    } catch (Exception e) {

      status = false;

      Assert.assertEquals("Not implemented.", e.getMessage());
    }

    Assert.assertFalse(status);
  }

  @Test
  public void testFilter() {
    Assert.assertEquals(0, loadBalancer.getFilterSize());

    TransactionControlFilter filter = new SimpleTransactionControlFilter();
    loadBalancer.putFilter("test", filter);
    Assert.assertEquals(1, loadBalancer.getFilterSize());
  }

  @Test
  public void testGetAllServers() {
    List<Server> servers = new ArrayList<Server>();
    Server server = Mockito.mock(Server.class);
    servers.add(server);
    Mockito.when(serverList.getInitialListOfServers()).thenReturn(servers);

    TransactionControlFilter filter = Mockito.mock(TransactionControlFilter.class);
    Mockito.when(filter.getFilteredListOfServers(servers)).thenReturn(servers);
    Assert.assertEquals(servers, loadBalancer.getAllServers());
  }
}


@@ -1,35 +1,10 @@
 #include "flatbuffers/grpc.h"
 #include "monster_test_generated.h"
+#include "test_assert.h"
+#include "test_builder.h"

-static int builder_test_error = 0;
-
-#define test_assert(condition) do { \
-  if(!(condition)) { \
-    fprintf(stderr, "%s:%d: %s failed.\n", __FILE__, __LINE__, #condition);\
-    builder_test_error = 1;\
-  } \
-} while(0)
-
-using namespace MyGame::Example;
-
-const std::string m1_name = "Cyberdemon";
-const Color m1_color = Color_Red;
-const std::string m2_name = "Imp";
-const Color m2_color = Color_Green;
-
-flatbuffers::Offset<Monster> populate1(flatbuffers::FlatBufferBuilder &builder) {
-  auto name_offset = builder.CreateString(m1_name);
-  return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color);
-}
-
-flatbuffers::Offset<Monster> populate2(flatbuffers::FlatBufferBuilder &builder) {
-  auto name_offset = builder.CreateString(m2_name);
-  return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color);
-}
-
-bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, const std::string &expected_name, Color color) {
-  flatbuffers::DetachedBuffer buf = fbb.Release();
-  const Monster *monster = flatbuffers::GetRoot<Monster>(buf.data());
+bool verify(flatbuffers::grpc::Message<Monster> &msg, const std::string &expected_name, Color color) {
+  const Monster *monster = msg.GetRoot();
   return (monster->name()->str() == expected_name) && (monster->color() == color);
 }

#include "flatbuffers/grpc.h"
#include "monster_test_generated.h"

static int builder_test_error = 0;

#define test_assert(condition) do { \
  if(!(condition)) { \
    fprintf(stderr, "%s:%d: %s failed.\n", __FILE__, __LINE__, #condition);\
    builder_test_error = 1;\
  } \
} while(0)

using namespace MyGame::Example;

const std::string m1_name = "Cyberdemon";
const Color m1_color = Color_Red;
const std::string m2_name = "Imp";
const Color m2_color = Color_Green;

flatbuffers::Offset<Monster> populate1(flatbuffers::FlatBufferBuilder &builder) {
  auto name_offset = builder.CreateString(m1_name);
  return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color);
}

flatbuffers::Offset<Monster> populate2(flatbuffers::FlatBufferBuilder &builder) {
  auto name_offset = builder.CreateString(m2_name);
  return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color);
}

bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, const std::string &expected_name, Color color) {
  flatbuffers::DetachedBuffer buf = fbb.Release();
  const Monster *monster = flatbuffers::GetRoot<Monster>(buf.data());
  return (monster->name()->str() == expected_name) && (monster->color() == color);
}

bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, const std::string &expected_name, Color color) {
  flatbuffers::grpc::Message<Monster> msg = mbb.ReleaseMessage<Monster>();
  const Monster *monster = msg.GetRoot();
  return (monster->name()->str() == expected_name) && (monster->color() == color);
}

struct OwnedAllocator : public flatbuffers::DefaultAllocator {};

struct TestHeapMessageBuilder : public flatbuffers::FlatBufferBuilder {
  TestHeapMessageBuilder()
    : flatbuffers::FlatBufferBuilder(2048, new OwnedAllocator(), true) {}
};

template <class Builder>
struct BuilderTests {
  static void empty_builder_movector_test() {
    Builder b1;
    size_t b1_size = b1.GetSize();
    Builder b2(std::move(b1));
    size_t b2_size = b2.GetSize();
    test_assert(b1_size == 0);
    test_assert(b1_size == b2_size);
  }

  static void nonempty_builder_movector_test() {
    Builder b1;
    populate1(b1);
    size_t b1_size = b1.GetSize();
    Builder b2(std::move(b1));
    test_assert(b1_size == b2.GetSize());
    test_assert(0 == b1.GetSize());
  }

  static void builder_movector_before_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    Builder b2(std::move(b1));
    b2.Finish(root_offset1);
    test_assert(release_n_verify(b2, m1_name, m1_color));
    test_assert(0 == b1.GetSize());
  }

  static void builder_movector_after_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    b1.Finish(root_offset1);
    Builder b2(std::move(b1));
    test_assert(release_n_verify(b2, m1_name, m1_color));
    test_assert(0 == b1.GetSize());
  }

  static void builder_move_assign_before_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    Builder b2;
    populate2(b2);
    b2 = std::move(b1);
    b2.Finish(root_offset1);
    test_assert(release_n_verify(b2, m1_name, m1_color));
    test_assert(0 == b1.GetSize());
  }

  static void builder_move_assign_after_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    b1.Finish(root_offset1);
    Builder b2;
    auto root_offset2 = populate2(b2);
    b2.Finish(root_offset2);
    b2 = std::move(b1);
    test_assert(release_n_verify(b2, m1_name, m1_color));
    test_assert(0 == b1.GetSize());
  }

  static void builder_swap_before_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    auto size1 = b1.GetSize();
    Builder b2;
    auto root_offset2 = populate2(b2);
    auto size2 = b2.GetSize();
    b1.Swap(b2);
    b1.Finish(root_offset2);
    b2.Finish(root_offset1);
    test_assert(b1.GetSize() > size2);
    test_assert(b2.GetSize() > size1);
    test_assert(release_n_verify(b1, m2_name, m2_color));
    test_assert(release_n_verify(b2, m1_name, m1_color));
  }

  static void builder_swap_after_finish_test() {
    Builder b1;
    auto root_offset1 = populate1(b1);
    b1.Finish(root_offset1);
    auto size1 = b1.GetSize();
    Builder b2;
    auto root_offset2 = populate2(b2);
    b2.Finish(root_offset2);
    auto size2 = b2.GetSize();
    b1.Swap(b2);
    test_assert(b1.GetSize() == size2);
    test_assert(b2.GetSize() == size1);
    test_assert(release_n_verify(b1, m2_name, m2_color));
    test_assert(release_n_verify(b2, m1_name, m1_color));
  }

  static void all_tests() {
    empty_builder_movector_test();
    nonempty_builder_movector_test();
    builder_movector_before_finish_test();
    builder_movector_after_finish_test();
    builder_move_assign_before_finish_test();
    builder_move_assign_after_finish_test();
    builder_swap_before_finish_test();
    builder_swap_after_finish_test();
  }
};

int builder_tests() {
  BuilderTests<flatbuffers::grpc::MessageBuilder>::all_tests();
  BuilderTests<flatbuffers::FlatBufferBuilder>::all_tests();
  BuilderTests<TestHeapMessageBuilder>::all_tests();
  return builder_test_error;
}


@@ -14,6 +14,8 @@
  */
 package org.hyperledger.besu.ethereum.core.encoding;

+import static org.hyperledger.besu.ethereum.core.Transaction.GO_QUORUM_PRIVATE_TRANSACTION_V_VALUE_MAX;
+import static org.hyperledger.besu.ethereum.core.Transaction.GO_QUORUM_PRIVATE_TRANSACTION_V_VALUE_MIN;
 import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_PROTECTED_V_BASE;
 import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_PROTECTED_V_MIN;
 import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_UNPROTECTED_V_BASE;

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

import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_PROTECTED_V_BASE;
import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_PROTECTED_V_MIN;
import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_UNPROTECTED_V_BASE;
import static org.hyperledger.besu.ethereum.core.Transaction.REPLAY_UNPROTECTED_V_BASE_PLUS_1;
import static org.hyperledger.besu.ethereum.core.Transaction.TWO;

import org.hyperledger.besu.config.experimental.ExperimentalEIPs;
import org.hyperledger.besu.crypto.SECP256K1;
import org.hyperledger.besu.ethereum.core.Address;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.Wei;
import org.hyperledger.besu.ethereum.rlp.RLPInput;

import java.math.BigInteger;
import java.util.Optional;

import org.apache.tuweni.bytes.Bytes;

@FunctionalInterface
public interface TransactionRLPDecoder {

  TransactionRLPDecoder FRONTIER = frontierDecoder();
  TransactionRLPDecoder EIP1559 = eip1559Decoder();

  static Transaction decodeTransaction(final RLPInput input) {
    return (ExperimentalEIPs.eip1559Enabled ? EIP1559 : FRONTIER).decode(input);
  }

  Transaction decode(RLPInput input);

  static TransactionRLPDecoder frontierDecoder() {
    return input -> {
      input.enterList();
      final Transaction.Builder builder =
          Transaction.builder()
              .nonce(input.readLongScalar())
              .gasPrice(Wei.of(input.readUInt256Scalar()))
              .gasLimit(input.readLongScalar())
              .to(input.readBytes(v -> v.size() == 0 ? null : Address.wrap(v)))
              .value(Wei.of(input.readUInt256Scalar()))
              .payload(input.readBytes());

      final BigInteger v = input.readBigIntegerScalar();
      final byte recId;
      Optional<BigInteger> chainId = Optional.empty();
      if (v.equals(REPLAY_UNPROTECTED_V_BASE) || v.equals(REPLAY_UNPROTECTED_V_BASE_PLUS_1)) {
        recId = v.subtract(REPLAY_UNPROTECTED_V_BASE).byteValueExact();
      } else if (v.compareTo(REPLAY_PROTECTED_V_MIN) > 0) {
        chainId = Optional.of(v.subtract(REPLAY_PROTECTED_V_BASE).divide(TWO));
        recId =
            v.subtract(TWO.multiply(chainId.get()).add(REPLAY_PROTECTED_V_BASE)).byteValueExact();
      } else {
        throw new RuntimeException(
            String.format("An unsupported encoded `v` value of %s was found", v));
      }
      final BigInteger r = input.readUInt256Scalar().toBytes().toUnsignedBigInteger();
      final BigInteger s = input.readUInt256Scalar().toBytes().toUnsignedBigInteger();
      final SECP256K1.Signature signature = SECP256K1.Signature.create(r, s, recId);

      input.leaveList();

      chainId.ifPresent(builder::chainId);
      return builder.signature(signature).build();
    };
  }

  static TransactionRLPDecoder eip1559Decoder() {
    return input -> {
      input.enterList();

      final Transaction.Builder builder =
          Transaction.builder()
              .nonce(input.readLongScalar())
              .gasPrice(Wei.of(input.readUInt256Scalar()))
              .gasLimit(input.readLongScalar())
              .to(input.readBytes(v -> v.size() == 0 ? null : Address.wrap(v)))
              .value(Wei.of(input.readUInt256Scalar()))
              .payload(input.readBytes());

      final Bytes maybeGasPremiumOrV = input.readBytes();
      final Bytes maybeFeeCapOrR = input.readBytes();
      final Bytes maybeVOrS = input.readBytes();
      final BigInteger v, r, s;
      // if this is the end of the list we are processing a legacy transaction
      if (input.isEndOfCurrentList()) {
        v = maybeGasPremiumOrV.toUnsignedBigInteger();
        r = maybeFeeCapOrR.toUnsignedBigInteger();
        s = maybeVOrS.toUnsignedBigInteger();
      } else {
        // otherwise this is an EIP-1559 transaction
        builder
            .gasPremium(Wei.of(maybeGasPremiumOrV.toBigInteger()))
            .feeCap(Wei.of(maybeFeeCapOrR.toBigInteger()));
        v = maybeVOrS.toBigInteger();
        r = input.readUInt256Scalar().toBytes().toUnsignedBigInteger();
        s = input.readUInt256Scalar().toBytes().toUnsignedBigInteger();
      }
      final byte recId;
      Optional<BigInteger> chainId = Optional.empty();
      if (v.equals(REPLAY_UNPROTECTED_V_BASE) || v.equals(REPLAY_UNPROTECTED_V_BASE_PLUS_1)) {
        recId = v.subtract(REPLAY_UNPROTECTED_V_BASE).byteValueExact();
      } else if (v.compareTo(REPLAY_PROTECTED_V_MIN) > 0) {
        chainId = Optional.of(v.subtract(REPLAY_PROTECTED_V_BASE).divide(TWO));
        recId =
            v.subtract(TWO.multiply(chainId.get()).add(REPLAY_PROTECTED_V_BASE)).byteValueExact();
      } else {
        throw new RuntimeException(
            String.format("An unsupported encoded `v` value of %s was found", v));
      }
      final SECP256K1.Signature signature = SECP256K1.Signature.create(r, s, recId);
      input.leaveList();
      chainId.ifPresent(builder::chainId);
      return builder.signature(signature).build();
    };
  }
}


@@ -133,8 +133,20 @@ public class StorageCallbacksImpl implements StorageCallbacks {
                     + " FROM " + PodDBAdapter.TABLE_NAME_FEEDS
                     + " WHERE " + PodDBAdapter.TABLE_NAME_FEEDS + "." + PodDBAdapter.KEY_ID
                     + " = " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_FEED + ")");
+
             db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                     + " ADD COLUMN " + PodDBAdapter.KEY_HIDE + " TEXT");
+
+
+            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
+                    + " ADD COLUMN " + PodDBAdapter.KEY_LAST_UPDATE_FAILED + " INTEGER DEFAULT 0");
+
+            // create indexes
+            db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDITEMS_FEED);
+            db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDITEMS_IMAGE);
+            db.execSQL(PodDBAdapter.CREATE_INDEX_FEEDMEDIA_FEEDITEM);
+            db.execSQL(PodDBAdapter.CREATE_INDEX_QUEUE_FEEDITEM);
+            db.execSQL(PodDBAdapter.CREATE_INDEX_SIMPLECHAPTERS_FEEDITEM);
         }
     }
 }

package de.danoeh.antennapod.config;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import de.danoeh.antennapod.core.StorageCallbacks;
import de.danoeh.antennapod.core.storage.PodDBAdapter;

public class StorageCallbacksImpl implements StorageCallbacks {

    @Override
    public int getDatabaseVersion() {
        return 15;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w("DBAdapter", "Upgrading from version " + oldVersion + " to "
                + newVersion + ".");
        if (oldVersion <= 1) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS + " ADD COLUMN "
                    + PodDBAdapter.KEY_TYPE + " TEXT");
        }
        if (oldVersion <= 2) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS
                    + " ADD COLUMN " + PodDBAdapter.KEY_LINK + " TEXT");
        }
        if (oldVersion <= 3) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
                    + " ADD COLUMN " + PodDBAdapter.KEY_ITEM_IDENTIFIER + " TEXT");
        }
        if (oldVersion <= 4) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS + " ADD COLUMN "
                    + PodDBAdapter.KEY_FEED_IDENTIFIER + " TEXT");
        }
        if (oldVersion <= 5) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_DOWNLOAD_LOG
                    + " ADD COLUMN " + PodDBAdapter.KEY_REASON_DETAILED + " TEXT");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_DOWNLOAD_LOG
                    + " ADD COLUMN " + PodDBAdapter.KEY_DOWNLOADSTATUS_TITLE + " TEXT");
        }
        if (oldVersion <= 6) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS
                    + " ADD COLUMN " + PodDBAdapter.KEY_CHAPTER_TYPE + " INTEGER");
        }
        if (oldVersion <= 7) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
                    + " ADD COLUMN " + PodDBAdapter.KEY_PLAYBACK_COMPLETION_DATE
                    + " INTEGER");
        }
        if (oldVersion <= 8) {
            final int KEY_ID_POSITION = 0;
            final int KEY_MEDIA_POSITION = 1;

            // Add feeditem column to feedmedia table
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
                    + " ADD COLUMN " + PodDBAdapter.KEY_FEEDITEM
                    + " INTEGER");
            Cursor feeditemCursor = db.query(PodDBAdapter.TABLE_NAME_FEED_ITEMS,
                    new String[]{PodDBAdapter.KEY_ID, PodDBAdapter.KEY_MEDIA}, "? > 0",
                    new String[]{PodDBAdapter.KEY_MEDIA}, null, null, null);
            if (feeditemCursor.moveToFirst()) {
                db.beginTransaction();
                ContentValues contentValues = new ContentValues();
                do {
                    long mediaId = feeditemCursor.getLong(KEY_MEDIA_POSITION);
                    contentValues.put(PodDBAdapter.KEY_FEEDITEM, feeditemCursor.getLong(KEY_ID_POSITION));
                    db.update(PodDBAdapter.TABLE_NAME_FEED_MEDIA, contentValues, PodDBAdapter.KEY_ID + "=?", new String[]{String.valueOf(mediaId)});
                    contentValues.clear();
                } while (feeditemCursor.moveToNext());
                db.setTransactionSuccessful();
                db.endTransaction();
            }
            feeditemCursor.close();
        }
        if (oldVersion <= 9) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_AUTO_DOWNLOAD
                    + " INTEGER DEFAULT 1");
        }
        if (oldVersion <= 10) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_FLATTR_STATUS
                    + " INTEGER");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
                    + " ADD COLUMN " + PodDBAdapter.KEY_FLATTR_STATUS
                    + " INTEGER");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_MEDIA
                    + " ADD COLUMN " + PodDBAdapter.KEY_PLAYED_DURATION
                    + " INTEGER");
        }
        if (oldVersion <= 11) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_USERNAME
                    + " TEXT");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_PASSWORD
                    + " TEXT");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
                    + " ADD COLUMN " + PodDBAdapter.KEY_IMAGE
                    + " INTEGER");
        }
        if (oldVersion <= 12) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_IS_PAGED + " INTEGER DEFAULT 0");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_NEXT_PAGE_LINK + " TEXT");
        }
        if (oldVersion <= 13) {
            // remove duplicate rows in "Chapters" table that were created because of a bug.
            db.execSQL(String.format("DELETE FROM %s WHERE %s NOT IN " +
                            "(SELECT MIN(%s) as %s FROM %s GROUP BY %s,%s,%s,%s,%s)",
                    PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS,
                    PodDBAdapter.KEY_ID,
                    PodDBAdapter.KEY_ID,
                    PodDBAdapter.KEY_ID,
                    PodDBAdapter.TABLE_NAME_SIMPLECHAPTERS,
                    PodDBAdapter.KEY_TITLE,
                    PodDBAdapter.KEY_START,
                    PodDBAdapter.KEY_FEEDITEM,
                    PodDBAdapter.KEY_LINK,
                    PodDBAdapter.KEY_CHAPTER_TYPE));
        }
        if(oldVersion <= 14) {
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
                    + " ADD COLUMN " + PodDBAdapter.KEY_AUTO_DOWNLOAD + " INTEGER");
            db.execSQL("UPDATE " + PodDBAdapter.TABLE_NAME_FEED_ITEMS
                    + " SET " + PodDBAdapter.KEY_AUTO_DOWNLOAD + " = "
                    + "(SELECT " + PodDBAdapter.KEY_AUTO_DOWNLOAD
                    + " FROM " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " WHERE " + PodDBAdapter.TABLE_NAME_FEEDS + "." + PodDBAdapter.KEY_ID
                    + " = " + PodDBAdapter.TABLE_NAME_FEED_ITEMS + "." + PodDBAdapter.KEY_FEED + ")");
            db.execSQL("ALTER TABLE " + PodDBAdapter.TABLE_NAME_FEEDS
                    + " ADD COLUMN " + PodDBAdapter.KEY_HIDE + " TEXT");
        }
    }
}


@@ -65,7 +65,7 @@ public class FileAnalyser {

         try {
             byte[] data = Files.readAllBytes(path);
-            return Magic.getMagicMatch(data);
+            return Magic.getMagicMatch(data, true);
         } catch (MagicException | MagicParseException | IOException e) {
             throw new IllegalStateException("Unable to detect mimetype of the file", e);
         }

/*
 * 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.tools.files;

import net.sf.jmimemagic.*;
import org.apache.commons.io.FileUtils;
import org.phoenicis.configuration.security.Safe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Safe
public class FileAnalyser {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileAnalyser.class);

    /**
     * Identify which line delimiter is used in a file
     *
     * @param fileContent
     *            string to analyse
     * @return the line separator as a string. Null if the file has no line
     *         separator
     */
    public static String identifyLineDelimiter(String fileContent) {
        if (fileContent.matches("(?s).*(\\r\\n).*")) { // Windows //$NON-NLS-1$
            return "\r\n"; //$NON-NLS-1$
        } else if (fileContent.matches("(?s).*(\\n).*")) { // Unix/Linux //$NON-NLS-1$
            return "\n"; //$NON-NLS-1$
        } else if (fileContent.matches("(?s).*(\\r).*")) { // Legacy mac os 9. Newer OS X use \n //$NON-NLS-1$
            return "\r"; //$NON-NLS-1$
        } else {
            return "\n"; // fallback onto '\n' if nothing matches. //$NON-NLS-1$
        }
    }

    public static String identifyLineDelimiter(File fileToAnalyse) throws IOException {
        final String fileContent = FileUtils.readFileToString(fileToAnalyse);
        return identifyLineDelimiter(fileContent);
    }

    private MagicMatch getMatch(File inputFile) throws MagicMatchNotFoundException {
        final Path path = Paths.get(inputFile.getAbsolutePath());

        try {
            byte[] data = Files.readAllBytes(path);
            return Magic.getMagicMatch(data);
        } catch (MagicException | MagicParseException | IOException e) {
            throw new IllegalStateException("Unable to detect mimetype of the file", e);
        }
    }

    public String getDescription(File inputFile) {
        try {
            return getMatch(inputFile).getDescription();
        } catch (MagicMatchNotFoundException e) {
            throw new IllegalStateException("Unable to detect mimetype of the file", e);
        }
    }

    public String getMimetype(File inputFile) {
        try {
            return getMatch(inputFile).getMimeType();
        } catch (MagicMatchNotFoundException e) {
            LOGGER.debug("Failed to get Mime Type", e);
            final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            return mimeTypesMap.getContentType(inputFile);
        }
    }
}


@@ -119,6 +119,8 @@ public class V2Request extends SolrRequest<V2Response> implements MapWriter {
     private boolean useBinary = false;

     private boolean forceV2EndPoint = false;
+    private ResponseParser parser;
+    private String mimeType;

     /**
      * Create a Builder object based on the provided resource.

/*
 * 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.solr.client.solrj.request;

import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.response.V2Response;
import org.apache.solr.common.MapWriter;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.JavaBinCodec;
import org.apache.solr.common.util.Utils;

import static org.apache.solr.common.params.CommonParams.JAVABIN_MIME;
import static org.apache.solr.common.params.CommonParams.JSON_MIME;

public class V2Request extends SolrRequest<V2Response> implements MapWriter {
  //only for debugging purposes
  public static final ThreadLocal<AtomicLong> v2Calls = new ThreadLocal<>();
  static final Pattern COLL_REQ_PATTERN = Pattern.compile("/(c|collections)/([^/])+/(?!shards)");
  private Object payload;
  private SolrParams solrParams;
  public final boolean useBinary;
  private String collection;
  private boolean forceV2 = false;
  private boolean isPerCollectionRequest = false;

  private V2Request(METHOD m, String resource, boolean useBinary) {
    super(m, resource);
    Matcher matcher = COLL_REQ_PATTERN.matcher(getPath());
    if (matcher.find()) {
      this.collection = matcher.group(2);
      isPerCollectionRequest = true;
    }
    this.useBinary = useBinary;

  }

  public boolean isForceV2(){
    return forceV2;
  }

  @Override
  public SolrParams getParams() {
    return solrParams;
  }

  @Override
  public RequestWriter.ContentWriter getContentWriter(String s) {
    if (v2Calls.get() != null) v2Calls.get().incrementAndGet();
    if (payload == null) return null;
    if (payload instanceof String) {
      return new RequestWriter.StringPayloadContentWriter((String) payload, JSON_MIME);
    }
    return new RequestWriter.ContentWriter() {
      @Override
      public void write(OutputStream os) throws IOException {
        if (useBinary) {
          new JavaBinCodec().marshal(payload, os);
        } else {
          Utils.writeJson(payload, os, false);
        }
      }

      @Override
      public String getContentType() {
        return useBinary ? JAVABIN_MIME : JSON_MIME;
      }
    };
  }

  public boolean isPerCollectionRequest() {
    return isPerCollectionRequest;
  }

  @Override
  public String getCollection() {
    return collection;
  }

  @Override
  protected V2Response createResponse(SolrClient client) {
    return new V2Response();
  }

  @Override
  public void writeMap(EntryWriter ew) throws IOException {
    ew.put("method", getMethod().toString());
    ew.put("path", getPath());
    ew.putIfNotNull("params", solrParams);
    ew.putIfNotNull("command", payload);
  }

  public static class Builder {
    private String resource;
    private METHOD method = METHOD.GET;
    private Object payload;
    private SolrParams params;
    private boolean useBinary = false;

    private boolean forceV2EndPoint = false;

    /**
     * Create a Builder object based on the provided resource.
     * The default method is GET.
     *
     * @param resource resource of the request for example "/collections" or "/cores/core-name"
     */
    public Builder(String resource) {
      if (!resource.startsWith("/")) resource = "/" + resource;
      this.resource = resource;
    }

    public Builder withMethod(METHOD m) {
      this.method = m;
      return this;
    }

    /**
     * Only for testing. It's always true otherwise
     */
    public Builder forceV2(boolean flag) {
      forceV2EndPoint = flag;
      return this;
    }

    /**
     * Set payload for request.
     *
     * @param payload as UTF-8 String
     * @return builder object
     */
    public Builder withPayload(String payload) {
      if (payload != null) {
        this.payload = payload;
      }
      return this;
    }

    public Builder withPayload(Object payload) {
      this.payload = payload;
      return this;
    }

    public Builder withParams(SolrParams params) {
      this.params = params;
      return this;
    }

    public Builder useBinary(boolean flag) {
      this.useBinary = flag;
      return this;
    }

    public V2Request build() {
      V2Request v2Request = new V2Request(method, resource, useBinary);
      v2Request.solrParams = params;
      v2Request.payload = payload;
      v2Request.forceV2 = forceV2EndPoint;
      return v2Request;
    }
  }
}


@@ -27,7 +27,10 @@
 package com.salesforce.androidsdk.rest;

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

+import org.apache.http.Header;
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;

/*
 * Copyright (c) 2012, 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.rest;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;

/**
 * RestResponse: Class to represent any REST response.
 *
 */
public class RestResponse {

	private final int statusCode;
	private final HttpResponse response;

	// Populated when "consume" is called
	private byte[] responseAsBytes;
	private String responseCharSet;

	// Lazily computed
	private String responseAsString;
	private JSONObject responseAsJSONObject;
	private JSONArray responseAsJSONArray;

	/**
	 * Constructor
	 * @param response
	 */
	public RestResponse(HttpResponse response) {
		this.response = response;
		this.statusCode = response.getStatusLine().getStatusCode();
	}

	/**
	 * Constructor
	 * @param response
	 */
	public RestResponse(NetworkResponse response) {
		this.response = null;
		this.statusCode = response.statusCode;
		this.responseAsBytes = response.data;

	}

	/**
	 * @return HTTP status code of the response
	 */
	public int getStatusCode() {
		return statusCode;
	}

	/**
	 * @return the base HTTP response of the response. The can be useful for response that are not JSON, such as binary payloads.
	 */
	/**
	 * @return true for response with 2xx status codes
	 */
	public boolean isSuccess() {
		// 2xx success
		return (statusCode >= HttpStatus.SC_OK && statusCode < HttpStatus.SC_MULTIPLE_CHOICES);
	}

	/**
	 * Fully consume response entity content and closes content stream
	 * Must be called before returning control to the UI thread
	 * @throws IOException
	 */
	public void consume() throws IOException {
		if (responseAsBytes != null) {
			// already consumed
			return;
		}

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			responseCharSet = EntityUtils.getContentCharSet(entity);
			responseAsBytes = EntityUtils.toByteArray(entity);
		}
		else {
			responseAsBytes = new byte[0];
		}
	}

	/**
	 * @return byte[] for entire response
	 * @throws IOException
	 */
	public byte[] asBytes() throws IOException {
		if (responseAsBytes == null) {
			consume();
		}
		return responseAsBytes;
	}

	/**
	 * String is built the first time the method is called.
	 *
	 * @return string for entire response
	 * @throws ParseException
	 * @throws IOException
	 */
	public String asString() throws ParseException, IOException {
		if (responseAsString == null) {
			responseAsString = new String(asBytes(), (responseCharSet == null ? HTTP.UTF_8 : responseCharSet));
		}
		return responseAsString;
	}

	/**
	 * JSONObject is built the first time the method is called.
	 *
	 * @return JSONObject for response
	 * @throws ParseException
	 * @throws JSONException
	 * @throws IOException
	 */
	public JSONObject asJSONObject() throws ParseException, JSONException, IOException {
		if (responseAsJSONObject == null) {
			responseAsJSONObject = new JSONObject(asString());
		}
		return responseAsJSONObject;
	}

	/**
	 * JSONArray is built the first time the method is called.
	 *
	 * @return JSONObject for response
	 * @throws ParseException
	 * @throws JSONException
	 * @throws IOException
	 */
	public JSONArray asJSONArray() throws ParseException, JSONException, IOException {
		if (responseAsJSONArray == null) {
			responseAsJSONArray = new JSONArray(asString());
		}
		return responseAsJSONArray;
	}

	@Override
	public String toString() {
		try {
			return asString();
		} catch (Exception e) {
			return response.toString();
		}
	}
}


@@ -83,7 +83,11 @@ public class MetricsRestServiceImpl extends AbstractRestProcessEngineAware imple
       metrics = query.interval();
     }

-    return convertToDtos(metrics);
+    final List<MetricsIntervalResultDto> dtoList = convertToDtos(metrics);
+    if (name != null) {
+      dtoList.forEach(dto -> dto.setName(name));
+    }
+    return dtoList;
   }

   @Override

/*
 * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
 * under one or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership. Camunda licenses this file to you under the Apache License,
 * Version 2.0; 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.camunda.bpm.engine.rest.impl;

import org.camunda.bpm.engine.rest.MetricsRestService;
import org.camunda.bpm.engine.rest.sub.metrics.MetricsResource;
import org.camunda.bpm.engine.rest.sub.metrics.MetricsResourceImpl;

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.camunda.bpm.engine.management.MetricsQuery;
import org.camunda.bpm.engine.rest.dto.metrics.MetricsIntervalResultDto;
import org.camunda.bpm.engine.management.MetricIntervalValue;
import org.camunda.bpm.engine.rest.dto.converter.DateConverter;
import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter;
import org.camunda.bpm.engine.rest.dto.converter.LongConverter;

/**
 * @author Daniel Meyer
 *
 */
public class MetricsRestServiceImpl extends AbstractRestProcessEngineAware implements MetricsRestService {

  public static final String QUERY_PARAM_NAME = "name";
  public static final String QUERY_PARAM_REPORTER = "reporter";
  public static final String QUERY_PARAM_START_DATE = "startDate";
  public static final String QUERY_PARAM_END_DATE = "endDate";
  public static final String QUERY_PARAM_FIRST_RESULT = "firstResult";
  public static final String QUERY_PARAM_MAX_RESULTS = "maxResults";
  public static final String QUERY_PARAM_INTERVAL = "interval";
  public static final String QUERY_PARAM_DATE = "date";
  public static final String QUERY_PARAM_AGG_BY_REPORTER = "aggregateByReporter";

  protected final DateConverter dateConverter;

  public MetricsRestServiceImpl(String engineName, ObjectMapper objectMapper) {
    super(engineName, objectMapper);
    dateConverter = new DateConverter();
    dateConverter.setObjectMapper(objectMapper);
  }

  @Override
  public MetricsResource getMetrics(String name) {
    return new MetricsResourceImpl(name, processEngine, objectMapper);
  }

  @Override
  public List<MetricsIntervalResultDto> interval(UriInfo uriInfo) {
    MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
    MetricsQuery query = processEngine.getManagementService()
      .createMetricsQuery()
      .name(queryParameters.getFirst(QUERY_PARAM_NAME))
      .reporter(queryParameters.getFirst(QUERY_PARAM_REPORTER));

    applyQueryParams(query, queryParameters);

    List<MetricIntervalValue> metrics;
    LongConverter longConverter = new LongConverter();
    longConverter.setObjectMapper(objectMapper);
    if (queryParameters.getFirst(QUERY_PARAM_INTERVAL) != null) {
      long interval = longConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_INTERVAL));
      metrics = query.interval(interval);
    } else {
      metrics = query.interval();
    }

    return convertToDtos(metrics);
  }

  @Override
  public Response deleteTaskMetrics(String dateString) {
    Date date = dateConverter.convertQueryParameterToType(dateString);
    processEngine.getManagementService().deleteTaskMetrics(date);

    // return no content (204) since resource is deleted
    return Response.noContent().build();
  }

  protected void applyQueryParams(MetricsQuery query, MultivaluedMap<String, String> queryParameters) {
    if(queryParameters.getFirst(QUERY_PARAM_START_DATE) != null) {
      Date startDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_START_DATE));
      query.startDate(startDate);
    }

    if(queryParameters.getFirst(QUERY_PARAM_END_DATE) != null) {
      Date endDate = dateConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_END_DATE));
      query.endDate(endDate);
    }

    IntegerConverter intConverter = new IntegerConverter();
    intConverter.setObjectMapper(objectMapper);

    if (queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT) != null) {
      int firstResult = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_FIRST_RESULT));
      query.offset(firstResult);
    }

    if (queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS) != null) {
      int maxResults = intConverter.convertQueryParameterToType(queryParameters.getFirst(QUERY_PARAM_MAX_RESULTS));
      query.limit(maxResults);
    }

    if(queryParameters.getFirst(QUERY_PARAM_AGG_BY_REPORTER) != null) {
      query.aggregateByReporter();
    }
  }

  protected List<MetricsIntervalResultDto> convertToDtos(List<MetricIntervalValue> metrics) {
    List<MetricsIntervalResultDto> intervalMetrics = new ArrayList<>();
    for (MetricIntervalValue m : metrics) {
      intervalMetrics.add(new MetricsIntervalResultDto(m));
    }
    return intervalMetrics;
  }
}


@@ -52,6 +52,9 @@ public class JobTypePluginSet {
     this.pluginJobPropsProcessor = new HashMap<>();
     this.jobToClassName = new HashMap<>();
     this.jobToClassLoaderURLs = new HashMap<>();
+    this.jobToDefaultProxyUser = new HashMap<>();
+    this.defaultProxyUsersJobTypeClasses = new HashSet<>();
+    this.defaultProxyUsersFilter = new HashSet<>();
   }

   /**

/*
 * Copyright 2014 LinkedIn Corp.
 *
 * 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 azkaban.jobtype;

import azkaban.utils.Props;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Container for job type plugins
 *
 * This contains the jobClass objects, the properties for loading plugins, and the properties given
 * by default to the plugin.
 *
 * This class is not thread safe, so adding to this class should only be populated and controlled by
 * the JobTypeManager
 */
public class JobTypePluginSet {
  private static final URL[] EMPTY_URLS = new URL[0];
  private final Map<String, Props> pluginJobPropsMap;
  private final Map<String, Props> pluginLoadPropsMap;
  private final Map<String, Props> pluginPrivatePropsMap;
  private final Map<String, JobPropsProcessor> pluginJobPropsProcessor;
  private final Map<String, String> jobToClassName;
  private final Map<String, URL[]> jobToClassLoaderURLs;

  private Props commonJobProps;
  private Props commonLoadProps;

  /**
   * Base constructor
   */
  public JobTypePluginSet() {
    this.pluginJobPropsMap = new HashMap<>();
    this.pluginLoadPropsMap = new HashMap<>();
    this.pluginPrivatePropsMap = new HashMap<>();
    this.pluginJobPropsProcessor = new HashMap<>();
    this.jobToClassName = new HashMap<>();
    this.jobToClassLoaderURLs = new HashMap<>();
  }

  /**
   * Copy constructor
   */
  public JobTypePluginSet(final JobTypePluginSet clone) {
    this.pluginJobPropsMap = new HashMap<>(clone.pluginJobPropsMap);
    this.pluginLoadPropsMap = new HashMap<>(clone.pluginLoadPropsMap);
    this.pluginPrivatePropsMap = new HashMap<>(clone.pluginPrivatePropsMap);
    this.commonJobProps = clone.commonJobProps;
    this.commonLoadProps = clone.commonLoadProps;
    this.pluginJobPropsProcessor = clone.pluginJobPropsProcessor;
    this.jobToClassName = clone.jobToClassName;
    this.jobToClassLoaderURLs = clone.jobToClassLoaderURLs;
  }

  /**
   * Gets common properties for every jobtype
   */
  public Props getCommonPluginJobProps() {
    return this.commonJobProps;
  }

  /**
   * Sets the common properties shared in every jobtype
   */
  public void setCommonPluginJobProps(final Props commonJobProps) {
    this.commonJobProps = commonJobProps;
  }

  /**
   * Gets the common properties used to load a plugin
   */
  public Props getCommonPluginLoadProps() {
    return this.commonLoadProps;
  }

  /**
   * Sets the common properties used to load every plugin
   */
  public void setCommonPluginLoadProps(final Props commonLoadProps) {
    this.commonLoadProps = commonLoadProps;
  }

  /**
   * Get the properties for a jobtype used to setup and load a plugin
   */
  public Props getPluginLoaderProps(final String jobTypeName) {
    return this.pluginLoadPropsMap.get(jobTypeName);
  }

  /**
   * Get the plugin private properties for the jobtype
   */
  public Props getPluginPrivateProps(final String jobTypeName) {
    return this.pluginPrivatePropsMap.get(jobTypeName);
  }
  /**
   * Get the properties that will be given to the plugin as default job properties.
   */
  public Props getPluginJobProps(final String jobTypeName) {
    return this.pluginJobPropsMap.get(jobTypeName);
  }

  public void addPluginClassName(final String jobTypeName, final String jobTypeClassName) {
    this.jobToClassName.put(jobTypeName, jobTypeClassName);
  }

  /**
   * Gets the plugin job class name
   */
  public String getPluginClassName(final String jobTypeName) {
    return this.jobToClassName.get(jobTypeName);
  }

  /**
   * Get the resource URLs that should be added to its associated job ClassLoader.
   */
  public URL[] getPluginClassLoaderURLs(final String jobTypeName) {
    return this.jobToClassLoaderURLs.getOrDefault(jobTypeName, EMPTY_URLS);
  }

  /**
   * Adds plugin job properties used as default runtime properties
   */
  public void addPluginJobProps(final String jobTypeName, final Props props) {
    this.pluginJobPropsMap.put(jobTypeName, props);
  }

  /**
   * Add resource URLs that should be made available to ClassLoader of all jobs of the given jobtype.
   */
  public void addPluginClassLoaderURLs(final String jobTypeName, final URL[] urls) {
    this.jobToClassLoaderURLs.put(jobTypeName, urls);
  }

  /**
   * Adds plugin load properties used to load the plugin
   */
  public void addPluginLoadProps(final String jobTypeName, final Props props) {
    this.pluginLoadPropsMap.put(jobTypeName, props);
  }

  /**
   * Adds plugins private properties used by the plugin
   */
  public void addPluginPrivateProps(final String jobTypeName, final Props props) {
    this.pluginPrivatePropsMap.put(jobTypeName, props);
  }

  public JobPropsProcessor getPluginJobPropsProcessor(
      final String jobTypeName) {
    return this.pluginJobPropsProcessor.get(jobTypeName);
  }

  public void addPluginJobPropsProcessor(final String jobTypeName,
      JobPropsProcessor jobPropsProcessor) {
    this.pluginJobPropsProcessor.put(jobTypeName, jobPropsProcessor);
  }
}