package arez.integration.dagger.codegen;

import arez.integration.AbstractArezIntegrationTest;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

public class AbstractCodegenIntegrationTest
  extends AbstractArezIntegrationTest
{
  final void assertClassNotPresent( @Nonnull final String className )
  {
    assertThrows( ClassNotFoundException.class, () -> Class.forName( "arez.integration.dagger.codegen." + className ) );
  }

  final void assertClassPresent( @Nonnull final String className )
    throws ClassNotFoundException
  {
    assertNotNull( Class.forName( "arez.integration.dagger.codegen." + className ) );
  }
}

package arez.integration.dagger.codegen;

import arez.integration.AbstractArezIntegrationTest;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

public class AbstractCodegenIntegrationTest
  extends AbstractArezIntegrationTest
{
  protected final void assertClassNotPresent( @Nonnull final String className )
  {
    assertThrows( ClassNotFoundException.class, () -> Class.forName( getPackagePrefix() + className ) );
  }

  protected final void assertClassPresent( @Nonnull final String className )
    throws ClassNotFoundException
  {
    assertNotNull( Class.forName( getPackagePrefix() + className ) );
  }

  @Nonnull
  private String getPackagePrefix()
  {
    return getClass().getCanonicalName().replaceAll( "^(.*\\.)[^.]+$", "$1" );
  }
}

Make assertions work in other packages


package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;

/**
 * Main Robot Class.
 */
public class RobotMain extends IterativeRobot {

    private ImageProcess ip;

    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        //ip = new ImageProcess();
        // Initialize all subsystems
        CommandBase.init();
    }

    public void autonomousInit() {
        ip.start();
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {
        Scheduler.getInstance().run();
    }

    public void teleopInit() {
    }

    /**
     * This function is called periodically during operator control.
     */
    public void teleopPeriodic() {
        Scheduler.getInstance().run();
    }

    /**
     * This function is called periodically during test mode.
     */
    public void testPeriodic() {
        LiveWindow.run();
    }

    public void disabledPeriodic() {
    }

    public void disabledInit() {
        System.out.println("Robot Main disabledInit(): Called");
    }

}

package edu.wpi.first.wpilibj.templates;

import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.templates.commands.*;

/**
 * Main Robot Class.
 */
public class RobotMain extends IterativeRobot {

    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        // Initialize all subsystems
        CommandBase.init();
    }

    public void autonomousInit() {
        ImageProcess ip = new ImageProcess();
        ip.start();
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {
        Scheduler.getInstance().run();
    }

    public void teleopInit() {
    }

    /**
     * This function is called periodically during operator control.
     */
    public void teleopPeriodic() {
        Scheduler.getInstance().run();
    }

    /**
     * This function is called periodically during test mode.
     */
    public void testPeriodic() {
        LiveWindow.run();
    }

    public void disabledPeriodic() {
    }

    public void disabledInit() {
        System.out.println("Robot Main disabledInit(): Called");
    }
}

Move this out of RobotInit so we can use the robot for other things. Swap to "autonomous" mode to trigger the ImageProcess event.


package net.glowstone.block.data;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@SuppressWarnings("unchecked")
public class BlockDataStoreTest {
    @Test
    public void testGetBlockDataById() {
        SingletonBlockData<Waterlogged> signNoWl = BlockDataStore.getBlockDataById(0);
        SingletonBlockData<Waterlogged> signYesWl = BlockDataStore.getBlockDataById(1);

        assertThat(signNoWl.mutate().isWaterlogged(), is(false));
        assertThat(signYesWl.mutate().isWaterlogged(), is(true));
        assertThat(signNoWl.getGlobalPaletteId(), is(0));
        assertThat(signYesWl.getGlobalPaletteId(), is(1));
    }

    @Test
    public void testGetIdForBlockData() {
        SingletonBlockData<Waterlogged> signNoWl = BlockDataStore.getBlockDataById(0);
        SingletonBlockData<Waterlogged> signYesWl = BlockDataStore.getBlockDataById(1);

        Waterlogged mutatedNoWl = signNoWl.mutate();
        Waterlogged mutatedYesWl = signYesWl.mutate();

        assertThat(BlockDataStore.getBlockDataPaletteId(mutatedNoWl), is(0));
        assertThat(BlockDataStore.getBlockDataPaletteId(mutatedYesWl), is(1));
    }
}

package net.glowstone.block.data;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@SuppressWarnings("unchecked")
public class BlockDataStoreTest {
    @Test
    public void testGetBlockDataById() {
        SingletonBlockData<Waterlogged> signNoWl = BlockDataStore.getBlockDataById(0);
        SingletonBlockData<Waterlogged> signYesWl = BlockDataStore.getBlockDataById(1);

        assertThat(signNoWl.mutate().isWaterlogged(), is(false));
        assertThat(signYesWl.mutate().isWaterlogged(), is(true));
        assertThat(signNoWl.getGlobalPaletteId(), is(0));
        assertThat(signYesWl.getGlobalPaletteId(), is(1));
    }

    @Test
    public void testGetIdForBlockData() {
        SingletonBlockData<Waterlogged> signNoWl = BlockDataStore.getBlockDataById(0);
        SingletonBlockData<Waterlogged> signYesWl = BlockDataStore.getBlockDataById(1);

        Waterlogged mutatedNoWl = signNoWl.mutate();
        Waterlogged mutatedYesWl = signYesWl.mutate();

        assertThat(BlockDataStore.getBlockDataPaletteId(mutatedNoWl), is(0));
        assertThat(BlockDataStore.getBlockDataPaletteId(mutatedYesWl), is(1));
    }

    @Test
    public void testMutatedBlockData() {
        SingletonBlockData<Waterlogged> singleton = BlockDataStore.getBlockDataById(0);
        Waterlogged mutable = singleton.mutate();
        assertThat(mutable.isWaterlogged(), is(false));

        mutable.setWaterlogged(true);
        int newId = BlockDataStore.getBlockDataPaletteId(mutable);
        assertThat(newId, is(1));
    }
}

Add test for mutated state changing IDs


/*
 *  Copyright (C) 2016 VSCT
 *
 *  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.vsct.dt.strowgr.admin.template.template;

import java.util.StringJoiner;

public class DefaultTemplates {
    public static final String SYSLOG_DEFAULT_TEMPLATE = new StringJoiner("\n")
            .add("source s_{{application}}_{{platform}} { udp(ip(127.0.0.1) port({{syslog_port}})); };")
            .add("destination d_{{application}}_{{platform}} { file(\"/HOME/hapadm/{{application}}/logs/{{application}}{{platform}}/haproxy.log\", perm(0664)); };")
            .add("log { source(s_{{application}}_{{platform}}); filter(f_local0); destination(d_{{application}}_{{platform}}); };")
            .add("\n")
            .toString();
}

/*
 *  Copyright (C) 2016 VSCT
 *
 *  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.vsct.dt.strowgr.admin.template.template;

import java.util.StringJoiner;

public class DefaultTemplates {
    public static final String SYSLOG_DEFAULT_TEMPLATE = new StringJoiner("\n")
            .add("source s_{{application}}_{{platform}} { udp(ip(127.0.0.1) port({{syslog_port}})); };")
            .add("destination d_{{application}}_{{platform}} { file(\"/HOME/hapadm/{{application}}/logs/{{application}}{{platform}}/haproxy{{application}}{{platform}}.log\", perm(0664)); };")
            .add("log { source(s_{{application}}_{{platform}}); filter(f_local0); destination(d_{{application}}_{{platform}}); };")
            .add("\n")
            .toString();
}

Add {{application}}{{platform}} to log filename


package com.thoughtworks.acceptance.someobjects;

import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

public class ZConverter extends AbstractSingleValueConverter {

    public boolean canConvert(Class type) {
        return type.equals(Z.class);
    }

    public Object fromString(String str) {
        return new Z("z");
    }

}

package com.thoughtworks.acceptance.someobjects;

import com.thoughtworks.xstream.converters.basic.AbstractBasicConverter;

public class ZConverter extends AbstractBasicConverter {

    public boolean canConvert(Class type) {
        return type.equals(Z.class);
    }

    protected Object fromString(String str) {
        return new Z("z");
    }

}

Revert to 1.1.1 converter ... it is part of compatibility test.


package openblocks.api;

import java.lang.annotation.*;

/**
 * Static variables marked with this annotation will be filled with instance
 * of requested API (defined by type of variable).
 *
 * All variables must have type that implements {@link IApiInterface}.
 * If requested type is not provided by OpenPeripheralAddons, variable will not be set.
 *
 * All variables should be filled in 'init'. Value in 'preInit' is undefined.
 *
 */
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiHolder {}

package openblocks.api;

import java.lang.annotation.*;

/**
 * Static variables marked with this annotation will be filled with instance
 * of requested API (defined by type of variable).
 *
 * Static methods marked with this annotation will be called with instance of requested API.
 * Methods must have single argument, which will be used to select API.
 *
 * All used types must implements {@link IApiInterface}.
 * If requested type is not provided by OpenPeripheralAddons, variable will not be set.
 *
 * All variables should be filled in 'init'. Value in 'preInit' is undefined.
 *
 */
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiHolder {}

Allow API annotation to be placed on methods, expand docs


package de.fau.amos.virtualledger.server.banking.adorsys.api;

import org.springframework.stereotype.Component;

/**
 * Class that holds all configuration required for the banking api access
 * examples: URL of the banking api, dummy configuration, ...
 */
@Component

public class BankingApiConfiguration {

    private final String bankingApiUrlAbsolute = "https://multibanking-service.dev.adorsys.de:443/api/v1/";
    private final String bankAccessApiUrlRelative = "users/{userId}/bankaccesses";
    private final String bankAccountApiUrlRelative = "users/{userId}/bankaccesses/{accessId}/accounts";
    private final String bankAccountSyncApiUrlRelative = "users/{userId}/bankaccesses/{accessId}/accounts/{accountId}/sync";

    /**
     * username of the test user that does not use adorsys api but dummies
     */
    private final String testUserName = "test@user.de";

    public String getBankingApiUrlAbsolute() {
        return bankingApiUrlAbsolute;
    }

    public String getBankAccessApiUrlRelative() {
        return bankAccessApiUrlRelative;
    }

    public String getBankAccountApiUrlRelative() {
        return bankAccountApiUrlRelative;
    }

    public String getBankAccountSyncApiUrlRelative() {
        return bankAccountSyncApiUrlRelative;
    }

    public String getTestUserName() {
        return testUserName;
    }
}

package de.fau.amos.virtualledger.server.banking.adorsys.api;

import org.springframework.stereotype.Component;

/**
 * Class that holds all configuration required for the banking api access
 * examples: URL of the banking api, dummy configuration, ...
 */
@Component

public class BankingApiConfiguration {

    private final String bankingApiUrlAbsolute = "https://multibanking-service.dev.adorsys.de:443/api/v1/";
    private final String bankAccessApiUrlRelative = "bankaccesses";
    private final String bankAccountApiUrlRelative = "bankaccesses/{accessId}/accounts";
    private final String bankAccountSyncApiUrlRelative = "bankaccesses/{accessId}/accounts/{accountId}/sync";

    /**
     * username of the test user that does not use adorsys api but dummies
     */
    private final String testUserName = "test@user.de";

    public String getBankingApiUrlAbsolute() {
        return bankingApiUrlAbsolute;
    }

    public String getBankAccessApiUrlRelative() {
        return bankAccessApiUrlRelative;
    }

    public String getBankAccountApiUrlRelative() {
        return bankAccountApiUrlRelative;
    }

    public String getBankAccountSyncApiUrlRelative() {
        return bankAccountSyncApiUrlRelative;
    }

    public String getTestUserName() {
        return testUserName;
    }
}

Remove old user from adorsys url paths


package devopsdistilled.operp.client.stock.panes.controllers;

import devopsdistilled.operp.client.abstracts.SubTaskPaneController;
import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.server.data.entity.stock.Warehouse;

public interface TransferStockPaneController extends SubTaskPaneController {

	public void validate(Warehouse fromWarehouse, Warehouse toWarehouse,
			Long quantity) throws EntityValidationException;

	public void transfer(Warehouse fromWarehouse, Warehouse toWarehouse,
			Long quantity);

}

package devopsdistilled.operp.client.stock.panes.controllers;

import devopsdistilled.operp.client.abstracts.SubTaskPaneController;
import devopsdistilled.operp.client.exceptions.EntityValidationException;
import devopsdistilled.operp.client.stock.panes.models.TransferStockPaneModel;

public interface TransferStockPaneController extends SubTaskPaneController {

	public void validate() throws EntityValidationException;

	public void transfer();

	public TransferStockPaneModel getModel();

}

Declare validate(), transfer() and getModel()


/*
 * Copyright 2013 Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>.
 *
 * 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 ca.corefacility.bioinformatics.irida.model.enums;

/**
 * When sorting a collection of generic objects you should be able to specify
 * the order of the sort.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public enum Order {

    ASCENDING("ASCENDING"),
    DESCENDING("DESCENDING");
    private String code;

    private Order(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return code;
    }

    public static Order fromString(String code) {
        switch (code.toUpperCase()) {
            case "ASCENDING":
                return ASCENDING;
            case "DESCENDING":
                return DESCENDING;
            default:
                throw new IllegalArgumentException("[" + code + "] is not a valid type of Order.");
        }
    }
}

/*
 * Copyright 2013 Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>.
 *
 * 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 ca.corefacility.bioinformatics.irida.model.enums;

/**
 * When sorting a collection of generic objects you should be able to specify
 * the order of the sort.
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public enum Order {

    ASCENDING("ASCENDING"),
    DESCENDING("DESCENDING"),
    NONE("NONE");
    private String code;

    private Order(String code) {
        this.code = code;
    }

    @Override
    public String toString() {
        return code;
    }

    public static Order fromString(String code) {
        switch (code.toUpperCase()) {
            case "ASCENDING":
                return ASCENDING;
            case "DESCENDING":
                return DESCENDING;
            default:
                return NONE;
        }
    }
}

Add a NONE order option to sort order.


/*
 * 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.jmeter.report.processor;

/**
 * The interface ResultData represents a result from samples processing.
 *
 * @since 3.0
 */
public interface ResultData {

    /**
     * Accepts the specified visitor.
     *
     * @param visitor
     *            the visitor (must not be {@code null})
     * @paran <T> type of the results of the {@link ResultDataVisitor}
     */
    <T> T accept(ResultDataVisitor<T> visitor);
}

/*
 * 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.jmeter.report.processor;

/**
 * The interface ResultData represents a result from samples processing.
 *
 * @since 3.0
 */
public interface ResultData {

    /**
     * Accepts the specified visitor.
     *
     * @param visitor
     *            the visitor (must not be {@code null})
     * @param <T>
     *            type of the results of the {@link ResultDataVisitor}
     * @return result of the vist
     */
    <T> T accept(ResultDataVisitor<T> visitor);
}

Correct typo and add missing return description


package Reaction;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class ReactionParserTest {

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testReadReactant() throws Exception {

    }
}

package Reaction;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class ReactionParserTest {

    ReactionParser reactionParser;

    @Before
    public void setUp() throws Exception {
        String DESKTOP_PATH = System.getProperty("user.dir");
        String FILE_NAME = DESKTOP_PATH + "\\assets\\react.txt";

        File file = new File(FILE_NAME);
        reactionParser = new ReactionParser(file);
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testReadReactant() throws Exception {
        Reaction reaction;
        while ((reaction = reactionParser.readReaction()) != null) {
            if (reactionParser.isEndOfBlock()) {
                break;
            }
        }
        assertNotNull(reaction);
        assertEquals(reaction.getUniqueId(), "[RXN0-6375]");
    }
}

Add and Pass ReactionParser Test


package org.aac.average.java.impl;

import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;

public class Average {
    public static void main(String[] args) {
        Function<Integer> average;

        average = new Function<>().addParameter(new FunctionParameter<Integer>("a"))
                                  .addParameter(new FunctionParameter<Integer>("b"));

        ConcreteInteger firstNumber = new ConcreteInteger.Builder()
                                                         .addDigit(ConcreteInteger.Digit.TWO)
                                                         .build();
        ConcreteInteger secondNumber = new ConcreteInteger.Builder()
                                                          .addDigit(ConcreteInteger.Digit.ONE)
                                                          .addDigit(ConcreteInteger.Digit.EIGHT)
                                                          .build();
    }
}

package org.aac.average.java.impl;

import org.aac.average.java.impl.function.Function;
import org.aac.average.java.impl.function.FunctionParameter;
import org.aac.average.java.impl.datatypes.ConcreteInteger;

public class Average {
    public static void main(String[] args) {
        Function<ConcreteInteger> averageTwoIntegers;

        averageTwoIntegers = new Function<>().addParameter(new FunctionParameter<ConcreteInteger>("a"))
                                             .addParameter(new FunctionParameter<ConcreteInteger>("b"));

        ConcreteInteger firstNumber = new ConcreteInteger.Builder()
                                                         .addDigit(ConcreteInteger.Digit.TWO)
                                                         .build();
        ConcreteInteger secondNumber = new ConcreteInteger.Builder()
                                                          .addDigit(ConcreteInteger.Digit.ONE)
                                                          .addDigit(ConcreteInteger.Digit.EIGHT)
                                                          .build();
    }
}

Change function to take ConcreteIntegers


package yokohama.unit.ast_junit;

import lombok.Value;

@Value
public class ClassType implements NonArrayType {
    private String name;
    private Span span;

    @Override
    public <T> T accept(NonArrayTypeVisitor<T> visitor) {
        return visitor.visitClassType(this);
    }
}

package yokohama.unit.ast_junit;

import lombok.Value;

@Value
public class ClassType implements NonArrayType {
    private String name;
    private Span span;

    public ClassType(String name, Span span) {
        this.name = name;
        this.span = span;
    }

    public ClassType(String name) {
        this.name = name;
        this.span = Span.dummySpan();
    }

    @Override
    public <T> T accept(NonArrayTypeVisitor<T> visitor) {
        return visitor.visitClassType(this);
    }
}

Add utility constructor that sets dummy span


package fi.helsinki.cs.tmc.cli.io;

import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class TerminalIoTest {

    Io io = new TerminalIo();
    OutputStream os;

    @Before
    public void setUp() {
        os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        System.setOut(ps);
    }

    @Test
    public void printlnWorksRight() {
        io.println("foo");
        assertTrue(os.toString().equals("foo\n"));
    }
}

package fi.helsinki.cs.tmc.cli.io;

import static org.junit.Assert.assertTrue;

import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class TerminalIoTest {

    Io io = new TerminalIo();
    OutputStream os;

    @Before
    public void setUp() {
        os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        System.setOut(ps);
    }

    @Test
    public void printWord() {
        io.print("foo");
        assertTrue(os.toString().equals("foo"));
    }

    @Test
    public void printLineWithNewLine() {
        io.println("foo");
        assertTrue(os.toString().equals("foo\n"));
    }

    @Test
    public void printNull() {
        io.print(null);
        assertTrue(os.toString().equals("null"));
    }

    @Test
    public void printInteger() {
        io.print(5);
        assertTrue(os.toString().equals("5"));
    }
}

Add more terminal io tests.


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.io.IOException;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * Abstraction of a remote JavaScript virtual machine which is embedded into
 * some application and accessed via TCP/IP connection to a port opened by
 * DebuggerAgent. Clients can use it to conduct debugging process.
 */
public interface StandaloneVm extends JavascriptVm {
  /**
   * Connects to the target VM.
   *
   * @param listener to report the debug events to
   * @throws IOException if there was a transport layer error
   * @throws UnsupportedVersionException if the SDK protocol version is not
   *         compatible with that supported by the browser
     * @throws MethodIsBlockingException because initialization implies couple of remote calls
     *     (to request version etc)
   */
  void attach(DebugEventListener listener)
      throws IOException, UnsupportedVersionException, MethodIsBlockingException;

  /**
   * @return name of embedding application as it wished to name itself; might be null
   */
  String getEmbedderName();

  /**
   * @return version of V8 implementation, format is unspecified; must not be null if
   *         {@link StandaloneVm} has been attached
   */
  // TODO: align this with {@link JavascriptVm#getVersion()} method.
  String getVmVersion();

  /**
   * @return message explaining why VM is detached; may be null
   */
  String getDisconnectReason();
}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.io.IOException;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * Abstraction of a remote JavaScript virtual machine which is embedded into
 * some application and accessed via TCP/IP connection to a port opened by
 * DebuggerAgent. Clients can use it to conduct debugging process.
 */
public interface StandaloneVm extends JavascriptVm {
  /**
   * Connects to the target VM.
   *
   * @param listener to report the debug events to
   * @throws IOException if there was a transport layer error
   * @throws UnsupportedVersionException if the SDK protocol version is not
   *         compatible with that supported by the browser
     * @throws MethodIsBlockingException because initialization implies couple of remote calls
     *     (to request version etc)
   */
  void attach(DebugEventListener listener)
      throws IOException, UnsupportedVersionException, MethodIsBlockingException;

  /**
   * @return name of embedding application as it wished to name itself; might be null
   */
  String getEmbedderName();

  /**
   * This version should correspond to {@link JavascriptVm#getVersion()}. However it gets available
   * earlier, at the transport handshake stage.
   * @return version of V8 implementation, format is unspecified; must not be null if
   *         {@link StandaloneVm} has been attached
   */
  String getVmVersion();

  /**
   * @return message explaining why VM is detached; may be null
   */
  String getDisconnectReason();
}

Drop TODO for getVmVersion method


package co.phoenixlab.discord.api;

/**
 * Contains various useful API URLs and paths
 */
public class ApiConst {

    /**
     * Utility class
     */
    private ApiConst() {
    }

    /**
     * The base URL from which Discord runs
     */
    public static final String BASE_URL = "https://discordapp.com/";
    /**
     * Base API path
     */
    public static final String API_BASE_PATH = "api";
    /**
     * The endpoint for accessing user information
     */
    public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
    /**
     * The endpoint for logging in
     */
    public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
    /**
     * The endpoint for logging out
     */
    public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
    /**
     * The endpoint for accessing server information
     */
    public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
    /**
     * The endpoint for accessing channel information
     */
    public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
    /**
     * The endpoint for accepting invites
     */
    public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
    /**
     * The format string for avatar URLs
     */
    public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";

}

package co.phoenixlab.discord.api;

/**
 * Contains various useful API URLs and paths
 */
public class ApiConst {

    /**
     * Utility class
     */
    private ApiConst() {
    }

    /**
     * The base URL from which Discord runs
     */
    public static final String BASE_URL = "https://discordapp.com/";
    /**
     * Base API path
     */
    public static final String API_BASE_PATH = BASE_URL + "api";
    /**
     * The endpoint for accessing user information
     */
    public static final String USERS_ENDPOINT = API_BASE_PATH + "/users/";
    /**
     * The endpoint for logging in
     */
    public static final String LOGIN_ENDPOINT = API_BASE_PATH + "/auth/login";
    /**
     * The endpoint for logging out
     */
    public static final String LOGOUT_ENDPOINT = API_BASE_PATH + "/auth/logout";
    /**
     * The endpoint for accessing server information
     */
    public static final String SERVERS_ENDPOINT = API_BASE_PATH + "/guilds/";
    /**
     * The endpoint for accessing channel information
     */
    public static final String CHANNELS_ENDPOINT = API_BASE_PATH + "/channels/";
    /**
     * The endpoint for accepting invites
     */
    public static final String INVITE_ENDPOINT = API_BASE_PATH + "/invite";
    /**
     * The format string for avatar URLs
     */
    public static final String AVATAR_URL_PATTERN = "https://cdn.discordapp.com/avatars/%1$s/%2$s.jpg";

}

Prepend the base URL to all endpoints


/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.project.taskfactory;

import org.gradle.api.Task;
import org.gradle.internal.Cast;

import java.util.Map;

/**
 * Class for easy access to task property validation from the validator task.
 */
public class TaskPropertyValidationAccess {
    @SuppressWarnings("unused")
    public static void collectTaskValidationProblems(Class<?> task, Map<String, Boolean> problems) {
        TaskClassInfoStore infoStore = new DefaultTaskClassInfoStore(new DefaultTaskClassValidatorExtractor(new ClasspathPropertyAnnotationHandler()));
        TaskClassInfo info = infoStore.getTaskClassInfo(Cast.<Class<? extends Task>>uncheckedCast(task));
        for (String nonAnnotatedPropertyName : info.getNonAnnotatedPropertyNames()) {
            problems.put(String.format("Task type '%s' declares property that is not annotated: '%s'.", task.getName(), nonAnnotatedPropertyName), Boolean.FALSE);
        }
    }
}

/*
 * Copyright 2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.gradle.api.internal.project.taskfactory;

import org.gradle.api.Task;
import org.gradle.internal.Cast;

import java.util.Map;

/**
 * Class for easy access to task property validation from the validator task.
 */
public class TaskPropertyValidationAccess {
    @SuppressWarnings("unused")
    public static void collectTaskValidationProblems(Class<?> task, Map<String, Boolean> problems) {
        TaskClassInfoStore infoStore = new DefaultTaskClassInfoStore(new DefaultTaskClassValidatorExtractor(new ClasspathPropertyAnnotationHandler(), new CompileClasspathPropertyAnnotationHandler()));
        TaskClassInfo info = infoStore.getTaskClassInfo(Cast.<Class<? extends Task>>uncheckedCast(task));
        for (String nonAnnotatedPropertyName : info.getNonAnnotatedPropertyNames()) {
            problems.put(String.format("Task type '%s' declares property that is not annotated: '%s'.", task.getName(), nonAnnotatedPropertyName), Boolean.FALSE);
        }
    }
}

Fix task validation to recognize `@CompileClasspath`


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

/**
 * Decodes a String into a String.
 *
 * @author Apache Software Foundation
 * @version $Id$
 */
public interface StringDecoder extends Decoder {

    /**
     * Decodes a String and returns a String.
     *
     * @param pString a String to encode
     *
     * @return the encoded String
     *
     * @throws DecoderException thrown if there is
     *  an error conidition during the Encoding process.
     */
    String decode(String pString) throws DecoderException;
}

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

/**
 * Decodes a String into a String.
 *
 * @author Apache Software Foundation
 * @version $Id$
 */
public interface StringDecoder extends Decoder {

    /**
     * Decodes a String and returns a String.
     *
     * @param source the String to decode
     *
     * @return the encoded String
     *
     * @throws DecoderException thrown if there is
     *  an error condition during the Encoding process.
     */
    String decode(String source) throws DecoderException;
}

Fix typos and use a better parameter name.


package org.realityforge.tarrabah;

import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;
import org.apache.deltaspike.cdise.api.ContextControl;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.realityforge.tarrabah.cdi.ext.pipeline.Pipeline;
import org.realityforge.tarrabah.cdi.ext.pipeline.PipelineScoped;

public class MainApp
{
  public static void main( final String[] args )
  {
    final CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();

    // Starting the application-context allows to use @PipelineScoped beans
    final ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext( PipelineScoped.class );
    contextControl.startContexts();

    Pipeline.activate( new Pipeline( "foo" ) );

    final SyslogUDPServer udpServer = BeanProvider.getContextualReference( SyslogUDPServer.class );

    System.out.println( "Active" );

    /*
    for ( int i = 0; i < 2; i++ )
    {
      try
      {
        Thread.sleep( 1000 );
      }
      catch ( final InterruptedException ie )
      {
        //ignored
      }
    }
    */

    contextControl.stopContext( PipelineScoped.class );
    Pipeline.deactivate();

    //contextControl.stopContexts();
    cdiContainer.shutdown();
    System.out.println( "Inactive" );
  }
}

package org.realityforge.tarrabah;

import org.apache.deltaspike.cdise.api.CdiContainer;
import org.apache.deltaspike.cdise.api.CdiContainerLoader;
import org.apache.deltaspike.cdise.api.ContextControl;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.realityforge.tarrabah.cdi.ext.pipeline.Pipeline;
import org.realityforge.tarrabah.cdi.ext.pipeline.PipelineScoped;

public class MainApp
{
  public static void main( final String[] args )
  {
    final CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();

    // Starting the application-context allows to use @PipelineScoped beans
    final ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext( PipelineScoped.class );
    contextControl.startContexts();

    Pipeline.activate( new Pipeline( "foo" ) );

    final SyslogUDPServer udpServer = BeanProvider.getContextualReference( SyslogUDPServer.class );

    System.err.println( "Active" );

    /*
    for ( int i = 0; i < 2; i++ )
    {
      try
      {
        Thread.sleep( 1000 );
      }
      catch ( final InterruptedException ie )
      {
        //ignored
      }
    }
    */

    contextControl.stopContext( PipelineScoped.class );
    Pipeline.deactivate();

    //contextControl.stopContexts();
    cdiContainer.shutdown();
    System.err.println( "Inactive" );
  }
}

Convert stdout to stderr so it is flushed immediately


import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

public class RobotTest {

    private static final String EXPECTED_ROBOT_NAME_PATTERN = "\\w{2}\\d{3}";
    private final Robot robot = new Robot();

    @Test
    public void hasName() {
        assertIsValidName(robot.getName());
    }

    @Test
    public void differentRobotsHaveDifferentNames() {
        assertThat(robot.getName(), not(equalTo(new Robot().getName())));
    }

    @Test
    public void resetName() {
        final String name = robot.getName();
        robot.reset();
        final String name2 = robot.getName();
        assertThat(name, not(equalTo(name2)));
        assertIsValidName(name2);
    }

    private static void assertIsValidName(String name) {
        assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
    }
}

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertThat;

public class RobotTest {

    private static final String EXPECTED_ROBOT_NAME_PATTERN = "[A-Z]{2}\\d{3}";
    private final Robot robot = new Robot();

    @Test
    public void hasName() {
        assertIsValidName(robot.getName());
    }

    @Test
    public void differentRobotsHaveDifferentNames() {
        assertThat(robot.getName(), not(equalTo(new Robot().getName())));
    }

    @Test
    public void resetName() {
        final String name = robot.getName();
        robot.reset();
        final String name2 = robot.getName();
        assertThat(name, not(equalTo(name2)));
        assertIsValidName(name2);
    }

    private static void assertIsValidName(String name) {
        assertThat(name.matches(EXPECTED_ROBOT_NAME_PATTERN), is(true));
    }
}

Fix regex to only allow uppercased letters for the the first 2 characters.


package com.feedblocker.integrations;

import com.feedblocker.model.FeedApplication;

public class Facebook extends FeedApplication
{
    @Override
    public String[] getAppResumeLogIndicators()
    {
        // AppStateLogger to the rescue
        return new String[]{
                "Activity activity.FbMainTabActivity changed state to Started"
        };
    }

    @Override
    public String[] getAppPauseLogIndicators()
    {
        // AppStateLogger to the rescue
        return new String[]{
                "Activity activity.FbMainTabActivity changed state to Paused"
        };
    }
}

package com.feedblocker.integrations;

import com.feedblocker.model.FeedApplication;

public class Facebook extends FeedApplication
{
    @Override
    public String[] getAppResumeLogIndicators()
    {
        return new String[]{
                "LocalFbBroadcastManager: Called registerBroadcastReceiver twice"
        };
    }

    @Override
    public String[] getAppPauseLogIndicators()
    {
        return new String[]{
                "moveTaskToBack: TaskRecord",
                "START u0 {act=com.android.systemui.recents.SHOW_RECENTS",
                "START u0 {act=android.intent.action.MAIN cat=[android.intent.category.HOME]"

        };
    }
}

Update logcat strings to identify FB app resume/pause


package joliex.wsdl;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Francesco
 */
public enum NameSpacesEnum {

	//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
	//TNS_SCH("tnsxs","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.xsd"),
	XML_SCH("xs","http://www.w3.org/2001/XMLSchema"),
	SOAP("soap","http://schemas.xmlsoap.org/wsdl/soap/"),
	SOAPoverHTTP("soapOhttp","http://schemas.xmlsoap.org/soap/http/"),
	WSDL("wsdl","http://schemas.xmlsoap.org/wsdl/");

	private String prefix;
        private String nameSpaceURI;

	NameSpacesEnum(String prefix,String nameSpaceURI){
            this.prefix=prefix;
            this.nameSpaceURI=nameSpaceURI;
	}

	/**
	 * @return the nameSpace
	 */ public String getNameSpaceURI()
	{
		return nameSpaceURI;
	}

	/**
	 * @return the prefix
	 */ public String getNameSpacePrefix()
	{
		return prefix;
	}

}

package joliex.wsdl;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Francesco
 */
public enum NameSpacesEnum {

	//TNS("tns","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.wsdl"),
	//TNS_SCH("tnsxs","http://www.italianasoftware.com/wsdl/FirstServiceByWSDL4J.xsd"),
	XML_SCH("xs","http://www.w3.org/2001/XMLSchema"),
	SOAP("soap","http://schemas.xmlsoap.org/wsdl/soap/"),
	SOAPoverHTTP("soapOhttp","http://schemas.xmlsoap.org/soap/http"),
	WSDL("wsdl","http://schemas.xmlsoap.org/wsdl/");

	private String prefix;
        private String nameSpaceURI;

	NameSpacesEnum(String prefix,String nameSpaceURI){
            this.prefix=prefix;
            this.nameSpaceURI=nameSpaceURI;
	}

	/**
	 * @return the nameSpace
	 */ public String getNameSpaceURI()
	{
		return nameSpaceURI;
	}

	/**
	 * @return the prefix
	 */ public String getNameSpacePrefix()
	{
		return prefix;
	}

}

Fix namespace of HTTP binding for jolie2wsdl.


package org.bndtools.builder;

import org.osgi.framework.BundleContext;

public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {

	private static BuilderPlugin instance = null;

	public static BuilderPlugin getInstance() {
		synchronized (BuilderPlugin.class) {
			return instance;
		}
	}

	public void start(BundleContext context) throws Exception {
		super.start(context);
		synchronized (BuilderPlugin.class) {
			instance = this;
		}
	}

	public void stop(BundleContext context) throws Exception {
		synchronized (BuilderPlugin.class) {
			instance = null;
		}
		super.stop(context);
	}

}

package org.bndtools.builder;

import org.osgi.framework.BundleContext;

public class BuilderPlugin extends org.eclipse.core.runtime.Plugin {

    private static BuilderPlugin instance = null;

    public static BuilderPlugin getInstance() {
        synchronized (BuilderPlugin.class) {
            return instance;
        }
    }

    @Override
    public void start(BundleContext context) throws Exception {
        super.start(context);
        synchronized (BuilderPlugin.class) {
            instance = this;
        }
    }

    @Override
    public void stop(BundleContext context) throws Exception {
        synchronized (BuilderPlugin.class) {
            instance = null;
        }
        super.stop(context);
    }

}

Add 2 missing @Override annotations


package seedu.address.logic.parser;

import static seedu.address.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT_LIST;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;

import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.ListCommand;

/**
 * Parses input arguments and creates a new ListCommand object
 */
public class ListCommandParser {

    private ListCommandParser() {
    }
    /**
     * Parses the given {@code String} of arguments in the context of the FindCommand
     * and returns an FindCommand object for execution.
     */
    public static Command parse(String args) {
        if (args == null) {
            return new ListCommand();
        }

        // if not match, show all the unfinished task
        final Matcher matcher = KEYWORDS_ARGS_FORMAT_LIST.matcher(args.trim());
        if (!matcher.matches()) {
            return new ListCommand();
        }

        // keywords delimited by whitespace
        final String[] keywords = matcher.group("keywords").split("\\s+");
        final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
        return new ListCommand(keywordSet);
    }

}

package seedu.address.logic.parser;

import static seedu.address.logic.parser.CliSyntax.KEYWORDS_ARGS_FORMAT_LIST;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;

import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.ListCommand;

/**
 * Parses input arguments and creates a new ListCommand object
 */
public class ListCommandParser {

    private ListCommandParser() {
    }

    private static final String LIST_SEPARATOR = "\\s+";
    /**
     * Parses the given {@code String} of arguments in the context of the FindCommand
     * and returns an FindCommand object for execution.
     */
    public static Command parse(String args) {
        if (args == null) {
            return new ListCommand();
        }

        // if not match, show all the unfinished task
        final Matcher matcher = KEYWORDS_ARGS_FORMAT_LIST.matcher(args.trim());
        if (!matcher.matches()) {
            return new ListCommand();
        }

        // keywords delimited by whitespace
        final String[] keywords = matcher.group("keywords").split(LIST_SEPARATOR);
        final Set<String> keywordSet = new HashSet<>(Arrays.asList(keywords));
        return new ListCommand(keywordSet);
    }

}

Refactor - remove magic string


/**
 * Copyright 2019 The CloudEvents Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.cloudevents.fun;

import java.util.Map;

import io.cloudevents.format.Format;

/**
 *
 * @author fabiojose
 *
 */
@FunctionalInterface
public interface FormatBuilder<P> {

	/**
	 * Builds a format to be used for the wire serialization
	 */
	Format<P> build(P payload, Map<String, Object> headers);

}

/**
 * Copyright 2019 The CloudEvents Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.cloudevents.fun;

import java.util.Map;

import io.cloudevents.format.Wire;

/**
 *
 * @author fabiojose
 *
 */
@FunctionalInterface
public interface WireBuilder<P, K, V> {

	/**
	 * Builds a wire format
	 */
	Wire<P, K, V> build(P payload, Map<K, V> headers);

}

Rename to wire instead of format


package io.github.lukehutch.fastclasspathscanner.classloaderhandler;

import io.github.lukehutch.fastclasspathscanner.classloaderhandler.ClassLoaderHandler;
import io.github.lukehutch.fastclasspathscanner.scanner.ClasspathFinder;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.ReflectionUtils;

public class WebsphereTraditionalClassLoaderHandler implements ClassLoaderHandler {

    public boolean handle(ClassLoader classloader, ClasspathFinder classpathFinder, LogNode log) throws Exception {
        for (Class<?> c = classloader.getClass(); c != null; c = c.getSuperclass()) {
            if (!"com.ibm.ws.classloader.CompoundClassLoader".equals(c.getName())) {
                continue;
            }
            String classpath = (String) ReflectionUtils.invokeMethod(classloader, "getClassPath");
            return classpathFinder.addClasspathElements(classpath, classloader, log);
        }
        return false;
    }

}

/*
 * This file is part of FastClasspathScanner.
 *
 * Author: Sergey Bespalov
 *
 * Hosted at: https://github.com/lukehutch/fast-classpath-scanner
 *
 * --
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2017 Sergey Bespalov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
 * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
 * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
 * OR OTHER DEALINGS IN THE SOFTWARE.
 */
package io.github.lukehutch.fastclasspathscanner.classloaderhandler;

import io.github.lukehutch.fastclasspathscanner.scanner.ClasspathFinder;
import io.github.lukehutch.fastclasspathscanner.utils.LogNode;
import io.github.lukehutch.fastclasspathscanner.utils.ReflectionUtils;

public class WebsphereTraditionalClassLoaderHandler implements ClassLoaderHandler {

    @Override
    public boolean handle(final ClassLoader classloader, final ClasspathFinder classpathFinder, final LogNode log)
            throws Exception {
        for (Class<?> c = classloader.getClass(); c != null; c = c.getSuperclass()) {
            if (!"com.ibm.ws.classloader.CompoundClassLoader".equals(c.getName())) {
                continue;
            }
            final String classpath = (String) ReflectionUtils.invokeMethod(classloader, "getClassPath");
            return classpathFinder.addClasspathElements(classpath, classloader, log);
        }
        return false;
    }

}

Add copyright and license info


package org.owasp.appsensor.analysis;

import javax.inject.Inject;
import javax.inject.Named;

import org.owasp.appsensor.AppSensorClient;
import org.owasp.appsensor.Response;
import org.owasp.appsensor.logging.Loggable;
import org.owasp.appsensor.response.ResponseHandler;
import org.owasp.appsensor.storage.ResponseStore;
import org.slf4j.Logger;

/**
 * This is a reference {@link Response} analysis engine,
 * and is an implementation of the Observer pattern.
 *
 * It is notified with implementations of the {@link Response} class.
 *
 * The implementation is trivial and simply delegates the work to the configured
 * {@link ResponseHandler} for processing.
 *
 * @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
 */
@Named
@Loggable
public class ReferenceResponseAnalysisEngine extends ResponseAnalysisEngine {

	private Logger logger;

	@Inject
	private AppSensorClient appSensorClient;

	/**
	 * This method simply catches responses and calls the
	 * configured {@link ResponseHandler} to process them.
	 *
	 * @param response {@link Response} that has been added to the {@link ResponseStore}.
	 */
	@Override
	public void analyze(Response response) {
		if (response != null) {
			logger.info("Response executed for user <" + response.getUser().getUsername() + "> - executing response action " + response.getAction());

			appSensorClient.getResponseHandler().handle(response);
		}
	}

}

package org.owasp.appsensor.analysis;

import javax.inject.Named;

import org.owasp.appsensor.Response;
import org.owasp.appsensor.logging.Loggable;
import org.owasp.appsensor.storage.ResponseStore;
import org.slf4j.Logger;

/**
 * This is a reference {@link Response} analysis engine,
 * and is an implementation of the Observer pattern.
 *
 * It is notified with implementations of the {@link Response} class.
 *
 * The implementation is trivial and simply logs the {@link Response}
 *
 * @author John Melton (jtmelton@gmail.com) http://www.jtmelton.com/
 */
@Named
@Loggable
public class ReferenceResponseAnalysisEngine extends ResponseAnalysisEngine {

	private Logger logger;

	/**
	 * This method simply logs responses.
	 *
	 * @param response {@link Response} that has been added to the {@link ResponseStore}.
	 */
	@Override
	public void analyze(Response response) {
		if (response != null) {
			logger.info("NO-OP Response for user <" + response.getUser().getUsername() + "> - should be executing response action " + response.getAction());
		}
	}

}

Remove execution of response from analysis engine. This should be done client-side, not server side.


package com.sap.cloud.lm.sl.cf.process.actions;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.sap.cloud.lm.sl.cf.core.flowable.AdditionalProcessAction;
import com.sap.cloud.lm.sl.cf.core.flowable.FlowableFacade;
import com.sap.cloud.lm.sl.cf.core.flowable.RetryProcessAction;
import com.sap.cloud.lm.sl.cf.process.Constants;
import com.sap.cloud.lm.sl.cf.process.steps.StepPhase;

@Component
public class SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction {

    private FlowableFacade flowableFacade;

    @Inject
    public SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade) {
        this.flowableFacade = flowableFacade;
    }

    @Override
    public void executeAdditionalProcessAction(String processInstanceId) {
        flowableFacade.getActiveProcessExecutions(processInstanceId)
            .stream()
            .map(execution -> execution.getProcessInstanceId())
            .forEach(executionProcessId -> flowableFacade.getProcessEngine()
                .getRuntimeService()
                .setVariable(executionProcessId, Constants.VAR_STEP_PHASE, StepPhase.RETRY));
    }

    @Override
    public String getApplicableActionId() {
        return RetryProcessAction.ACTION_ID_RETRY;
    }

}

package com.sap.cloud.lm.sl.cf.process.actions;

import javax.inject.Inject;

import org.springframework.stereotype.Component;

import com.sap.cloud.lm.sl.cf.core.flowable.AdditionalProcessAction;
import com.sap.cloud.lm.sl.cf.core.flowable.FlowableFacade;
import com.sap.cloud.lm.sl.cf.core.flowable.RetryProcessAction;
import com.sap.cloud.lm.sl.cf.process.Constants;
import com.sap.cloud.lm.sl.cf.process.steps.StepPhase;

@Component
public class SetRetryPhaseAdditionalProcessAction implements AdditionalProcessAction {

    private FlowableFacade flowableFacade;

    @Inject
    public SetRetryPhaseAdditionalProcessAction(FlowableFacade flowableFacade) {
        this.flowableFacade = flowableFacade;
    }

    @Override
    public void executeAdditionalProcessAction(String processInstanceId) {
        flowableFacade.getActiveProcessExecutions(processInstanceId)
            .stream()
            .map(execution -> execution.getProcessInstanceId())
            .forEach(executionProcessId -> flowableFacade.getProcessEngine()
                .getRuntimeService()
                .setVariable(executionProcessId, Constants.VAR_STEP_PHASE, StepPhase.RETRY.toString()));
    }

    @Override
    public String getApplicableActionId() {
        return RetryProcessAction.ACTION_ID_RETRY;
    }

}

Fix setting of StepPhase in the Retry action


package zero.zd.zquestionnaire;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class QnaBuilderActivity extends AppCompatActivity {

    public static Intent getStartIntent(Context context) {
        return new Intent(context, QnaBuilderActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qna_builder);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_qna_builder, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.action_save:
                // @TODO add action to write to a file
                break;

            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onClickAdd(View view) {
        // @TODO add action to add QnA
        Toast.makeText(QnaBuilderActivity.this, "ADD!!!", Toast.LENGTH_SHORT).show();
    }
}

package zero.zd.zquestionnaire;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

public class QnaBuilderActivity extends AppCompatActivity {

    public static Intent getStartIntent(Context context) {
        return new Intent(context, QnaBuilderActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qna_builder);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle("QnA Builder");
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_qna_builder, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.action_save:
                // @TODO add action to write to a file
                break;

            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void onClickAdd(View view) {
        // @TODO add action to add QnA
        Toast.makeText(QnaBuilderActivity.this, "ADD!!!", Toast.LENGTH_SHORT).show();
    }
}

Add ActionBar title on QnaBuilder


package util;

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

/**
 * Created by neiro on 22.05.17.
 */
public class CommandChecker {

    private static Map<String, ParseType> supportedCommandsMap;

    static {
        supportedCommandsMap = new HashMap<>();

        supportedCommandsMap.put("grep", ParseType.GREP);
        supportedCommandsMap.put("regex", ParseType.REGEX);
    }

    public static boolean isCommandSupported(String command) {
        return supportedCommandsMap.containsKey(command);
    }

}

package util;

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

/**
 * Created by neiro on 22.05.17.
 */
public class CommandChecker {

    private static Map<String, ParseType> supportedCommandsMap;

    static {
        supportedCommandsMap = new HashMap<>();

        // Supported
        supportedCommandsMap.put("grep", ParseType.GREP);

        // May supported in future (see implementation in ParseHandler.handle)
//        supportedCommandsMap.put("regex", ParseType.REGEX);
    }

    public static boolean isCommandSupported(String command) {
        return supportedCommandsMap.containsKey(command);
    }

}

Mark "regex" command as unsupported


/**
 * Provides the classes necessary to create requests
 * and responses between nodes .
 *

 * There are several ways of creating requests:
 *

 *
 The default request does not imply an answer from the destination node.
 *      It is therefore asynchronous by default. (@see simizer.app.Application.sendOneWay)
 *

 *
 *
 the second method demands a response from the destination node.
 * the responding node must therefore create a Response object
 * with the originating request as parent parameter, and call the sendResponse method
 * Upon reception a ResponseReceived event will be signaled to the VM and propagated to the Application,
 * which will the call the handle method of the corresponding Application.
 *
 * @since 0.4
 * @see simizer.VM
 * @see  simizer.app
 */
package simizer.requests;

/**
 * Provides the necessary classes to simulate sending requests.
 *

 * There are two main ways to create and send requests:
 *

The default request does not require an answer from the destination
 *         node.  It can therefore be considered asynchronous.  See {@link
 *         Application#sendOneWay(Node,Request)}.
 *
 *
The second way requires a response from the destination node.  The
 *         responding node must therefore send the request back to the caller.
 *         (See {@link Application#sendResponse(Node,Request)}.

 *
 * @since 0.4
 */
package simizer.requests;

Update the documentation for the requests package.


package org.springframework.cloud.service.relational;

import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;

/**
 * Common implementation that assumes DBCP connection pool properties.
 *
 * @author Ramnivas Laddad
 *
 * @param <SI>
 */
public abstract class DbcpLikePooledDataSourceCreator<SI extends RelationalServiceInfo> implements PooledDataSourceCreator<SI> {

	protected static Logger logger = Logger.getLogger(PooledDataSourceCreator.class.getName());

	private DataSourceConfigurer configurer = new DataSourceConfigurer();

	protected void setBasicDataSourceProperties(DataSource basicDataSource, RelationalServiceInfo serviceInfo,
											   ServiceConnectorConfig serviceConnectorConfig,
  											   String driverClassName, String validationQuery) {
		BeanWrapper target = new BeanWrapperImpl(basicDataSource);
		target.setPropertyValue("driverClassName", driverClassName);
		target.setPropertyValue("url", serviceInfo.getJdbcUrl());
		if (validationQuery != null) {
			target.setPropertyValue("validationQuery", validationQuery);
			target.setPropertyValue("testOnBorrow", true);
		}
		configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
	}

}

package org.springframework.cloud.service.relational;

import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.cloud.service.PooledServiceConnectorConfig.PoolConfig;
import org.springframework.cloud.service.ServiceConnectorConfig;
import org.springframework.cloud.service.common.RelationalServiceInfo;

/**
 * Common implementation that assumes DBCP connection pool properties.
 *
 * @author Ramnivas Laddad
 *
 * @param <SI>
 */
public abstract class DbcpLikePooledDataSourceCreator<SI extends RelationalServiceInfo> implements PooledDataSourceCreator<SI> {

	protected static Logger logger = Logger.getLogger(PooledDataSourceCreator.class.getName());

	private DataSourceConfigurer configurer = new DataSourceConfigurer();

	protected void setBasicDataSourceProperties(DataSource basicDataSource, RelationalServiceInfo serviceInfo,
											   ServiceConnectorConfig serviceConnectorConfig,
  											   String driverClassName, String validationQuery) {
		BeanWrapper target = new BeanWrapperImpl(basicDataSource);
		target.setPropertyValue("driverClassName", driverClassName);
		target.setPropertyValue("url", serviceInfo.getJdbcUrl());
		if (validationQuery != null) {
			target.setPropertyValue("validationQuery", validationQuery);
			target.setPropertyValue("testOnBorrow", true);
		}

		if (serviceConnectorConfig == null) {
		    // choose sensible values so that we set max connection pool size to what
		    // free tier services on Cloud Foundry and Heroku allow
		    serviceConnectorConfig = new DataSourceConfig(new PoolConfig(4, 30000), null);
		}
		configurer.configure(basicDataSource, (DataSourceConfig)serviceConnectorConfig);
	}

}

Choose sensible values for pool config by default


package io.quarkus.hibernate.search.orm.elasticsearch.runtime.devconsole;

import java.time.Duration;
import java.util.stream.Collectors;

import org.hibernate.search.mapper.orm.entity.SearchIndexedEntity;
import org.hibernate.search.mapper.orm.mapping.SearchMapping;

import io.quarkus.devconsole.runtime.spi.DevConsolePostHandler;
import io.quarkus.devconsole.runtime.spi.FlashScopeUtil;
import io.quarkus.runtime.annotations.Recorder;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.ext.web.RoutingContext;

@Recorder
public class HibernateSearchDevConsoleRecorder {

    public Handler<RoutingContext> indexEntity() {
        return new DevConsolePostHandler() {
            @Override
            protected void handlePostAsync(RoutingContext event, MultiMap form) throws Exception {
                if (form.isEmpty()) {
                    return;
                }
                SearchMapping mapping = HibernateSearchSupplier.searchMapping();
                if (mapping == null) {
                    flashMessage(event, "There aren't any indexed entity types!", FlashScopeUtil.FlashMessageStatus.ERROR);
                    return;
                }
                mapping.scope(Object.class,
                        mapping.allIndexedEntities().stream()
                                .map(SearchIndexedEntity::jpaName)
                                .filter(form::contains)
                                .collect(Collectors.toList()))
                        .massIndexer()
                        .startAndWait();
                flashMessage(event, "Entities successfully reindexed", Duration.ofSeconds(10));
            }
        };
    }
}

package io.quarkus.hibernate.search.orm.elasticsearch.runtime.devconsole;

import java.time.Duration;
import java.util.stream.Collectors;

import org.hibernate.search.mapper.orm.entity.SearchIndexedEntity;
import org.hibernate.search.mapper.orm.mapping.SearchMapping;

import io.quarkus.devconsole.runtime.spi.DevConsolePostHandler;
import io.quarkus.devconsole.runtime.spi.FlashScopeUtil;
import io.quarkus.runtime.annotations.Recorder;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.ext.web.RoutingContext;

@Recorder
public class HibernateSearchDevConsoleRecorder {

    public Handler<RoutingContext> indexEntity() {
        return new DevConsolePostHandler() {
            @Override
            protected void handlePostAsync(RoutingContext event, MultiMap form) throws Exception {
                if (form.isEmpty()) {
                    return;
                }
                SearchMapping mapping = HibernateSearchSupplier.searchMapping();
                if (mapping == null) {
                    flashMessage(event, "There are no indexed entity types.", FlashScopeUtil.FlashMessageStatus.ERROR);
                    return;
                }
                mapping.scope(Object.class,
                        mapping.allIndexedEntities().stream()
                                .map(SearchIndexedEntity::jpaName)
                                .filter(form::contains)
                                .collect(Collectors.toList()))
                        .massIndexer()
                        .startAndWait();
                flashMessage(event, "Entities successfully reindexed", Duration.ofSeconds(10));
            }
        };
    }
}

Make error message a bit more neutral


package com.poco.PoCoRuntime;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Single unit for matching a PoCo event or result.
 */
public class Match implements Matchable {
    private String matchString;

    private boolean isWildcard;

    private boolean isAction;
    private boolean isResult;

    public Match(String matchString) {
        // This constructor creates an Action match
        isAction = true;
        isResult = false;

        isWildcard = (matchString == "%");
        this.matchString = matchString;
    }

    @Override
    public boolean accepts(Event event) {
        if (isWildcard) {
            return true;
        }

        Pattern pattern = Pattern.compile(matchString);
        Matcher matcher = pattern.matcher(event.getSignature());

        return matcher.find();
    }
}

package com.poco.PoCoRuntime;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Single unit for matching a PoCo event or result.
 */
public class Match implements Matchable {
    private String matchString;

    private boolean isWildcard;

    private boolean isAction;
    private boolean isResult;

    /**
     * This constructor creates an Action match
     * @param matchString
     */
    public Match(String matchString) {
        // This constructor creates an Action match
        isAction = true;
        isResult = false;

        isWildcard = (matchString == "%");
        this.matchString = matchString;
    }

    /**
     * Constructor for Match when it is result instead of action
     * @param matchString
     */
    public Match(String matchString, boolean isaction, boolean isresult) {

        isAction = isaction;
        isResult = isresult;

        isWildcard = (matchString == "%");
        this.matchString = matchString;
    }

    @Override
    public boolean accepts(Event event) {
        if (isWildcard) {
            return true;
        }

        Pattern pattern = Pattern.compile(matchString);
        Matcher matcher = pattern.matcher(event.getSignature());

        return matcher.find();
    }
}

Add a constructor for result


package org.cru.godtools.domain;

import com.googlecode.flyway.core.Flyway;
import com.googlecode.flyway.core.api.MigrationVersion;
import org.cru.godtools.domain.properties.GodToolsProperties;
import org.cru.godtools.domain.properties.GodToolsPropertiesFactory;

/**
 * Created by ryancarlson on 7/18/14.
 */
public class DatabaseMigration
{
	static GodToolsProperties properties = new GodToolsPropertiesFactory().get();

	public static void main(String[] args)
	{
		new DatabaseMigration().build();
	}

	public void build()
	{
		Flyway flyway = new Flyway();
		flyway.setDataSource(properties.getProperty("databaseUrl"), properties.getProperty("databaseUsername") ,properties.getProperty("databasePassword"));
		flyway.setInitVersion("0");
		flyway.migrate();
	}
}

package org.cru.godtools.domain;

import com.googlecode.flyway.core.Flyway;
import com.googlecode.flyway.core.api.MigrationVersion;
import org.cru.godtools.domain.properties.GodToolsProperties;
import org.cru.godtools.domain.properties.GodToolsPropertiesFactory;

/**
 * Created by ryancarlson on 7/18/14.
 */
public class DatabaseMigration
{
	static GodToolsProperties properties = new GodToolsPropertiesFactory().get();

	public static void main(String[] args)
	{
		// i chose an OR here to allow for the process to be invoked from the IDE w/o having to set CLI args.  Jenkins will always pass true or false
		if(args.length == 0 || doDeploy(args[0]))
		{
			String environmentPrefix = args.length > 1 ? (getEnvironmentPrefix(args[1])) : "";

			new DatabaseMigration().build(environmentPrefix);
		}
	}

	public void build(String environmentPrefix)
	{
		Flyway flyway = new Flyway();
		flyway.setDataSource(properties.getProperty(environmentPrefix + "databaseUrl"),
				properties.getProperty(environmentPrefix + "databaseUsername"),
				properties.getProperty(environmentPrefix + "databasePassword"));
		flyway.setInitVersion("0");
		flyway.migrate();
	}

	static boolean doDeploy(String commandLineArg)
	{
		return Boolean.parseBoolean(commandLineArg);
	}

	static String getEnvironmentPrefix(String commandLineArg)
	{
		return  commandLineArg + "_";
	}
}

Add logic to accept command line args to enable migration and set environment prefix


package j2html.tags;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import j2html.Config;
import j2html.utils.CSSMin;
import j2html.utils.JSMin;

import static j2html.TagCreator.*;

public class InlineStaticResource {

    public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS}

    public static ContainerTag get(String path, TargetFormat format) {
        String fileString = getFileAsString(path);
        switch (format) {
            case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString)));
            case JS_MIN  : return script().with(rawHtml(Config.jsMinifier.minify((fileString))));
            case CSS     : return style().with(rawHtml(fileString));
            case JS      : return script().with(rawHtml(fileString));
            default      : throw new RuntimeException("Invalid target format");
        }
    }

    public static String getFileAsString(String path) {
        try {
            return readFileAsString(InlineStaticResource.class.getResource(path).getPath());
        } catch (Exception e1) {
            try {
                return readFileAsString(path);
            } catch (Exception e2) {
                throw new RuntimeException("Couldn't find file with path='" + path + "'");
            }
        }
    }

    /**
     * @author kjheimark <3
     */
    private static String readFileAsString(String path) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = bufferedReader.read()) >= 0 && c >= 0) {
            sb.append((char) c);
        }
        return sb.toString();
    }

}

package j2html.tags;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Scanner;

import j2html.Config;

import static j2html.TagCreator.*;

public class InlineStaticResource {

    public enum TargetFormat {CSS_MIN, CSS, JS_MIN, JS}

    public static ContainerTag get(String path, TargetFormat format) {
        String fileString = getFileAsString(path);
        switch (format) {
            case CSS_MIN : return style().with(rawHtml(Config.cssMinifier.minify(fileString)));
            case JS_MIN  : return script().with(rawHtml(Config.jsMinifier.minify((fileString))));
            case CSS     : return style().with(rawHtml(fileString));
            case JS      : return script().with(rawHtml(fileString));
            default      : throw new RuntimeException("Invalid target format");
        }
    }

    public static String getFileAsString(String path) {
        try {
            return streamToString(InlineStaticResource.class.getResourceAsStream(path));
        } catch (Exception expected) { // we don't ask users to specify classpath or file-system
            try {
                return streamToString(new FileInputStream(path));
            } catch (Exception exception) {
                throw new RuntimeException("Couldn't find file with path='" + path + "'");
            }
        }
    }

    private static String streamToString(InputStream inputStream) {
        Scanner s = new Scanner(inputStream).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
    }

}

Allow reading static resources from jars


/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2018 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.studio.db.repo;

import com.axelor.meta.db.MetaJsonField;
import com.axelor.meta.db.repo.MetaJsonFieldRepository;
import com.axelor.studio.db.AppBuilder;

public class MetaJsonFieldRepo extends MetaJsonFieldRepository {

  @Override
  public MetaJsonField save(MetaJsonField metajsonField) {

    AppBuilder appBuilder = metajsonField.getAppBuilder();
    if (appBuilder != null) {
      metajsonField.setIncludeIf("__config__.app.isApp('" + appBuilder.getCode() + "')");
    }

    return metajsonField;
  }
}

/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2018 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.studio.db.repo;

import com.axelor.meta.db.MetaJsonField;
import com.axelor.meta.db.repo.MetaJsonFieldRepository;
import com.axelor.studio.db.AppBuilder;

public class MetaJsonFieldRepo extends MetaJsonFieldRepository {

  @Override
  public MetaJsonField save(MetaJsonField metajsonField) {

    AppBuilder appBuilder = metajsonField.getAppBuilder();
    if (appBuilder != null) {
      metajsonField.setIncludeIf("__config__.app.isApp('" + appBuilder.getCode() + "')");
    }

    return super.save(metajsonField);
  }
}

Fix metajson field save issue


package com.admicro.vertxlet.core.handler.impl;

import com.admicro.vertxlet.core.handler.FailureHandler;
import com.admicro.vertxlet.core.HttpServerVerticle;
import com.admicro.vertxlet.core.db.IDbConnector;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.RoutingContext;

import java.util.Map;

public class FailureHandlerImpl implements FailureHandler {

    private static final Logger _logger = LoggerFactory.getLogger(FailureHandlerImpl.class);

    @Override
    public void handle(RoutingContext rc) {
        _logger.error("Unexpected error occur", rc.failure());
        rc.fail(new Exception());

        // Guarantee db connections is closed when error occurs
        Map<String, IDbConnector> iDbAdaptorMap = rc.get(HttpServerVerticle.DATABASE_KEY);
        for (IDbConnector adaptor : iDbAdaptorMap.values()) {
            adaptor.close(v -> {
            });
        }

        rc.response().putHeader("content-type", "text/html")
                .setStatusCode(500).end("
Server internal error
");
    }
}

package com.admicro.vertxlet.core.handler.impl;

import com.admicro.vertxlet.core.handler.FailureHandler;
import com.admicro.vertxlet.core.HttpServerVerticle;
import com.admicro.vertxlet.core.db.IDbConnector;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.RoutingContext;

import java.util.Map;

public class FailureHandlerImpl implements FailureHandler {

    private static final Logger _logger = LoggerFactory.getLogger(FailureHandlerImpl.class);

    @Override
    public void handle(RoutingContext rc) {
        _logger.error("Unexpected error occur", rc.failure());
        // Guarantee db connections is closed when error occurs
        Map<String, IDbConnector> iDbAdaptorMap = rc.get(HttpServerVerticle.DATABASE_KEY);
        for (IDbConnector adaptor : iDbAdaptorMap.values()) {
            adaptor.close(v -> {
            });
        }

        rc.response().putHeader("content-type", "text/html")
                .setStatusCode(500).end("
Server internal error
");
    }
}

Fix failure handler alway throw exception


package io.collap.bryg.compiler.helper;

import io.collap.bryg.compiler.ast.expression.Expression;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.type.Type;
import io.collap.bryg.compiler.type.TypeHelper;

public class StringBuilderCompileHelper extends ObjectCompileHelper {

    public StringBuilderCompileHelper (BrygMethodVisitor method) {
        super (method, new Type (StringBuilder.class));
    }

    public void compileAppend (Expression expression) {
        compileAppend (expression, true);
    }

    /**
     * StringBuilder -> StringBuilder
     */
    public void compileAppend (Expression expression, boolean compileExpression) {
        Type argumentType = expression.getType ();
        if (!argumentType.getJavaType ().isPrimitive ()) { /* All objects are supplied as either String or Object. */
            if (!argumentType.equals (String.class)) {
                argumentType = new Type (Object.class);
            }
        }else {
            /* Byte and Short primitives need to be appended as integers. */
            if (argumentType.equals (Byte.TYPE) || argumentType.equals (Short.TYPE)) {
                argumentType = new Type (Integer.TYPE);
            }
        }

        if (compileExpression) {
            expression.compile ();
            // -> T
        }

        compileInvokeVirtual ("append", TypeHelper.generateMethodDesc (
                new Type[] { argumentType },
                type
        ));
        // StringBuilder, T -> StringBuilder
    }

    public void compileToString () {
        compileInvokeVirtual ("toString", TypeHelper.generateMethodDesc (null, String.class));
        // StringBuilder -> String
    }

}

package io.collap.bryg.compiler.helper;

import io.collap.bryg.compiler.ast.expression.Expression;
import io.collap.bryg.compiler.parser.BrygMethodVisitor;
import io.collap.bryg.compiler.type.Type;
import io.collap.bryg.compiler.type.TypeHelper;

public class StringBuilderCompileHelper extends ObjectCompileHelper {

    public StringBuilderCompileHelper (BrygMethodVisitor method) {
        super (method, new Type (StringBuilder.class));
    }

    /**
     * Compiles the expression by default!
     */
    public void compileAppend (Expression expression) {
        compileAppend (expression, true);
    }

    /**
     * StringBuilder -> StringBuilder
     */
    public void compileAppend (Expression expression, boolean compileExpression) {
        Type argumentType = expression.getType ();
        if (!argumentType.getJavaType ().isPrimitive ()) { /* All objects are supplied as either String or Object. */
            if (!argumentType.equals (String.class)) {
                argumentType = new Type (Object.class);
            }
        }else {
            /* Byte and Short primitives need to be appended as integers. */
            if (argumentType.equals (Byte.TYPE) || argumentType.equals (Short.TYPE)) {
                argumentType = new Type (Integer.TYPE);
            }
        }

        if (compileExpression) {
            expression.compile ();
            // -> T
        }

        compileInvokeVirtual ("append", TypeHelper.generateMethodDesc (
                new Type[] { argumentType },
                type
        ));
        // StringBuilder, T -> StringBuilder
    }

    public void compileToString () {
        compileInvokeVirtual ("toString", TypeHelper.generateMethodDesc (null, String.class));
        // StringBuilder -> String
    }

}

Clarify compileAppend's handling of expressions.


package com.unidev.zerostorage;

import com.unidev.zerostorage.index.IndexStorage;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;

/**
 * Storage index tests
 */
public class TestIndexStorage {

    @Rule
    public TemporaryFolder folder= new TemporaryFolder();

    @Test
    public void testBlankIndexStorageSave() {
        IndexStorage indexStorage = new IndexStorage();

        Storage blankIndex = new Storage();
        indexStorage.index(blankIndex);

        File root = folder.getRoot();

        indexStorage.storageRoot(root);
        indexStorage.save();

    }

    @Test
    public void testIndexStorageSave() {
        IndexStorage indexStorage = new IndexStorage();

        Storage index = new Storage();
        index.details().put("Potato", "Tomato");
        index.details().put("Tomato", null);
        indexStorage.index(index);

        File root = folder.getRoot();

        indexStorage.storageRoot(root);
        indexStorage.save();

    }

}

package com.unidev.zerostorage;

import com.unidev.zerostorage.index.IndexStorage;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

/**
 * Storage index tests
 */
public class TestIndexStorage {

    @Rule
    public TemporaryFolder folder= new TemporaryFolder();

    @Test
    public void testBlankIndexStorageSave() {
        IndexStorage indexStorage = new IndexStorage();

        Storage blankIndex = new Storage();
        indexStorage.index(blankIndex);

        File root = folder.getRoot();

        indexStorage.storageRoot(root);
        indexStorage.save();

    }

    @Test
    public void testIndexStorageSave() {
        IndexStorage indexStorage = new IndexStorage();

        Storage index = new Storage();
        index.details().put("Potato", "Tomato");
        index.details().put("Tomato", null);
        indexStorage.index(index);

        File root = folder.getRoot();

        indexStorage.storageRoot(root);
        indexStorage.save();

    }

    @Test
    public void testLoadIndexStorage() throws IOException {
        InputStream inputStream = TestStorage.class.getResourceAsStream("/blankIndex.json");
        File root = folder.getRoot();

        File index = new File(root, IndexStorage.INDEX_FILE);
        Files.copy(inputStream, index.toPath());

        IndexStorage indexStorage = new IndexStorage();
        indexStorage.storageRoot(root);
        indexStorage.load();
    }

}

Test loading of blank index file


/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.internal.selenesedriver;

import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;

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

public class NewSession implements SeleneseFunction<Map<String, Object>> {
  public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) {
    selenium.start();
    Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
    Map<String, Object> seenCapabilities = new HashMap<String, Object>();
    seenCapabilities.put("browserName", capabilities.getBrowserName());
    seenCapabilities.put("version", capabilities.getVersion());
    seenCapabilities.put("platform", Platform.getCurrent().toString());
    seenCapabilities.put("javascriptEnabled", true);
    return seenCapabilities;
  }
}

/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 Google Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.openqa.selenium.internal.selenesedriver;

import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.Platform;

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

public class NewSession implements SeleneseFunction<Map<String, Object>> {
  public Map<String, Object> apply(Selenium selenium, Map<String, ?> args) {
    selenium.start();

    // Emulate behaviour of webdriver
    selenium.useXpathLibrary("javascript-xpath");
    selenium.allowNativeXpath("true");

    Capabilities capabilities = (Capabilities) args.get("desiredCapabilities");
    Map<String, Object> seenCapabilities = new HashMap<String, Object>();
    seenCapabilities.put("browserName", capabilities.getBrowserName());
    seenCapabilities.put("version", capabilities.getVersion());
    seenCapabilities.put("platform", Platform.getCurrent().toString());
    seenCapabilities.put("javascriptEnabled", true);
    return seenCapabilities;
  }
}

Make the selenium-backed webdriver emulate the normal webdriver's xpath mode


package io.github.bonigarcia;

/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.
 *
 */
public class Address {

    public String firstName;
    public String lastName;

    public Address(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia;

public class Address {

    public String firstName;
    public String lastName;

    public Address(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

Move package declaration to top of class