package org.jrebirth.af.core.command.basic.multi;

import org.jrebirth.af.core.command.basic.BasicCommandTest;

import org.junit.Test;

//@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {

    @Test
    public void sequentialTest1() {
        System.out.println("Sequential Test default");
        runCommand(DefaultSequentialCommand.class);
    }

    @Test
    public void sequentialTest2() {
        System.out.println("Sequential Test annotation");
        runCommand(AnnotatedSequentialCommand.class);
    }

    @Test
    public void sequentialTest3() {
        System.out.println("Sequential Test constructor");
        runCommand(ConstructorSequentialCommand.class);
    }

    @Test
    public void parallelTest1() {
        System.out.println("Parallel Test default");
        runCommand(DefaultParallelCommand.class);
    }

    @Test
    public void parallelTest2() {
        System.out.println("Parallel Test annotation");
        runCommand(AnnotatedParallelCommand.class);
    }

    @Test
    public void parallelTest3() {
        System.out.println("Parallel Test constructor");
        runCommand(ConstructorParallelCommand.class);
    }
}

package org.jrebirth.af.core.command.basic.multi;

import org.jrebirth.af.core.command.basic.BasicCommandTest;

import org.junit.Ignore;
import org.junit.Test;

@Ignore("JavaFX can't be run in headless mode yet")
public class MultiCommandTest extends BasicCommandTest {

    @Test
    public void sequentialTest1() {
        System.out.println("Sequential Test default");
        runCommand(DefaultSequentialCommand.class);
    }

    @Test
    public void sequentialTest2() {
        System.out.println("Sequential Test annotation");
        runCommand(AnnotatedSequentialCommand.class);
    }

    @Test
    public void sequentialTest3() {
        System.out.println("Sequential Test constructor");
        runCommand(ConstructorSequentialCommand.class);
    }

    @Test
    public void parallelTest1() {
        System.out.println("Parallel Test default");
        runCommand(DefaultParallelCommand.class);
    }

    @Test
    public void parallelTest2() {
        System.out.println("Parallel Test annotation");
        runCommand(AnnotatedParallelCommand.class);
    }

    @Test
    public void parallelTest3() {
        System.out.println("Parallel Test constructor");
        runCommand(ConstructorParallelCommand.class);
    }
}

Disable test untestable without x server


/*******************************************************************************
 * Copyright (c) 2014 Felix Kutzner.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Felix Kutzner - initial implementation.
 ******************************************************************************/

package tools.vitruv.domains.emf.monitorededitor.test.utils;

import java.net.URL;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.URI;

public class BasicTestCase {
    public static final String PLUGIN_NAME = "tools.vitruv.extensions.emf.monitorededitor.tests";

    private static boolean hasLoggerBeenInitialized = false;
    protected Logger LOGGER = Logger.getLogger(BasicTestCase.class);

    public BasicTestCase() {
        synchronized (BasicTestCase.class) {
            if (!hasLoggerBeenInitialized) {
                org.apache.log4j.BasicConfigurator.configure();
                hasLoggerBeenInitialized = true;
                Logger.getRootLogger().setLevel(Level.ALL);
            }
        }
    }

    public static URI getURI(URL modelURL) {
        return URI.createPlatformPluginURI(PLUGIN_NAME + modelURL.getFile(), true);
    }

}

/*******************************************************************************
 * Copyright (c) 2014 Felix Kutzner.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Felix Kutzner - initial implementation.
 ******************************************************************************/

package tools.vitruv.domains.emf.monitorededitor.test.utils;

import java.net.URL;

import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.URI;

public class BasicTestCase {
    public static final String PLUGIN_NAME = "tools.vitruv.extensions.emf.monitorededitor.tests";

    private static boolean hasLoggerBeenInitialized = false;
    protected Logger LOGGER = Logger.getLogger(BasicTestCase.class);

    public BasicTestCase() {
        synchronized (BasicTestCase.class) {
            if (!hasLoggerBeenInitialized) {
                org.apache.log4j.BasicConfigurator.configure();
                hasLoggerBeenInitialized = true;
            }
        }
    }

    public static URI getURI(URL modelURL) {
        return URI.createPlatformPluginURI(PLUGIN_NAME + modelURL.getFile(), true);
    }

}

Disable debug output in EMF monitored editor tests


package floobits.common.protocol.send;

import com.intellij.openapi.application.ApplicationInfo;
import floobits.common.protocol.Base;

public abstract class InitialBase implements Base {
    public String platform = System.getProperty("os.name");
    public String version = "0.10";
    String client = ApplicationInfo.getInstance().getVersionName();
}

package floobits.common.protocol.send;

import com.intellij.openapi.application.ApplicationInfo;
import floobits.common.Constants;
import floobits.common.protocol.Base;

public abstract class InitialBase implements Base {
    public String platform = System.getProperty("os.name");
    public String version = Constants.version;
    String client = ApplicationInfo.getInstance().getVersionName();
}

Use constants for version. Updates version.


package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.bll.host.provider.HostProviderProxy;
import org.ovirt.engine.core.bll.provider.ProviderProxyFactory;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.queries.HostErratumQueryParameters;

public class GetErratumByIdForHostQuery<P extends HostErratumQueryParameters> extends QueriesCommandBase<P> {

    public GetErratumByIdForHostQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        VdsStatic host = getDbFacade().getVdsStaticDao().get(getParameters().getId());
        if (host == null || host.getHostProviderId() == null) {
            return;
        }

        Provider<?> provider = getDbFacade().getProviderDao().get(host.getHostProviderId());
        if (provider != null) {
            HostProviderProxy proxy = ProviderProxyFactory.getInstance().create(provider);
            getQueryReturnValue().setReturnValue(proxy.getErratumForHost(host.getHostName(),
                    getParameters().getErratumId()));
        }
    }
}

package org.ovirt.engine.core.bll;

import javax.inject.Inject;

import org.ovirt.engine.core.bll.host.provider.HostProviderProxy;
import org.ovirt.engine.core.bll.provider.ProviderProxyFactory;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.queries.HostErratumQueryParameters;
import org.ovirt.engine.core.dao.VdsStaticDao;
import org.ovirt.engine.core.dao.provider.ProviderDao;

public class GetErratumByIdForHostQuery<P extends HostErratumQueryParameters> extends QueriesCommandBase<P> {

    @Inject
    private VdsStaticDao hostStaticDao;

    @Inject
    private ProviderDao providerDao;

    public GetErratumByIdForHostQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        VdsStatic host = hostStaticDao.get(getParameters().getId());
        if (host == null || host.getHostProviderId() == null) {
            return;
        }

        Provider<?> provider = providerDao.get(host.getHostProviderId());
        if (provider != null) {
            HostProviderProxy proxy = ProviderProxyFactory.getInstance().create(provider);
            getQueryReturnValue().setReturnValue(proxy.getErratumForHost(host.getHostName(),
                    getParameters().getErratumId()));
        }
    }
}

Use injection instead of static access


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

import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;

/**
 * Allow direct specification of property editors.
 */
public enum TypeEditor {
    FileEditor     {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new FileEditor(descriptor); }},
    PasswordEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new PasswordEditor(); }},
    TableEditor    {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TableEditor(); }},
    TextAreaEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TextAreaEditor(); }},
    ;
    // Some editors may need the descriptor
    abstract PropertyEditor getInstance(PropertyDescriptor descriptor);
}

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

import java.beans.PropertyDescriptor;
import java.beans.PropertyEditor;

/**
 * Allow direct specification of property editors.
 */
public enum TypeEditor {
    FileEditor     {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new FileEditor(descriptor); }},
    PasswordEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new PasswordEditor(); }},
    TableEditor    {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TableEditor(); }},
    TextAreaEditor {@Override PropertyEditor getInstance(PropertyDescriptor descriptor) { return new TextAreaEditor(descriptor); }},
    ;
    // Some editors may need the descriptor
    abstract PropertyEditor getInstance(PropertyDescriptor descriptor);
}

Allow descriptor to be passed to TextAreaEditor (for eventual use in SyntaxTextArea setup)


package com.auth0.net;

import com.auth0.exception.APIException;
import com.auth0.exception.Auth0Exception;

import java.util.concurrent.CompletableFuture;

/**
 * Class that represents an HTTP Request that can be executed.
 *
 * @param <T> the type of payload expected in the response after the execution.
 */
public interface Request<T> {

    /**
     * Executes this request synchronously.
     *
     * @return the response body JSON decoded as T
     * @throws APIException   if the request was executed but the response wasn't successful.
     * @throws Auth0Exception if the request couldn't be created or executed successfully.
     */
    T execute() throws Auth0Exception;

    /**
     * Executes this request asynchronously.
     *
     * @apiNote This method was added after the interface was released in version 1.0.
     *          It is defined as a default method for compatibility reasons.
     *          From version 2.0 on, the method will be abstract and all implementations of this interface
     *          will have to provide their own implementation.
     *
     * @implSpec The default implementation throws an {@linkplain UnsupportedOperationException}.
     *
     * @return a {@linkplain CompletableFuture} representing the specified request.
     */
    default CompletableFuture<T> executeAsync() {
        throw new UnsupportedOperationException("executeAsync");
    }
}

package com.auth0.net;

import com.auth0.exception.APIException;
import com.auth0.exception.Auth0Exception;

import java.util.concurrent.CompletableFuture;

/**
 * Class that represents an HTTP Request that can be executed.
 *
 * @param <T> the type of payload expected in the response after the execution.
 */
public interface Request<T> {

    /**
     * Executes this request synchronously.
     *
     * @return the response body JSON decoded as T
     * @throws APIException   if the request was executed but the response wasn't successful.
     * @throws Auth0Exception if the request couldn't be created or executed successfully.
     */
    T execute() throws Auth0Exception;

    /**
     * Executes this request asynchronously.
     *
     * Note: This method was added after the interface was released in version 1.0.
     * It is defined as a default method for compatibility reasons.
     * From version 2.0 on, the method will be abstract and all implementations of this interface
     * will have to provide their own implementation.
     *
     * The default implementation throws an {@linkplain UnsupportedOperationException}.
     *
     * @return a {@linkplain CompletableFuture} representing the specified request.
     */
    default CompletableFuture<T> executeAsync() {
        throw new UnsupportedOperationException("executeAsync");
    }
}

Fix JavaDoc tags for Java8


package ee.tuleva.onboarding.config;

import java.io.IOException;
import java.security.Principal;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@Component
public class MDCFilter extends GenericFilterBean {

  private final String PERSONAL_ID = "personalId";

  @Override
  public void destroy() {}

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    boolean successfulRegistration = false;

    HttpServletRequest req = (HttpServletRequest) request;
    Principal principal = req.getUserPrincipal();

    if (principal != null) {
      String personalId = principal.getName();
      successfulRegistration = registerPersonalId(personalId);
    }

    try {
      chain.doFilter(request, response);
    } finally {
      if (successfulRegistration) {
        MDC.remove(PERSONAL_ID);
      }
    }
  }

  private boolean registerPersonalId(String personalId) {
    if (personalId != null && personalId.trim().length() > 0) {
      MDC.put(PERSONAL_ID, personalId);
      return true;
    }
    return false;
  }
}

package ee.tuleva.onboarding.config;

import io.sentry.Sentry;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@Component
public class MDCFilter extends GenericFilterBean {

  private final String PERSONAL_ID = "personalId";

  @Override
  public void destroy() {}

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {

    boolean successfulRegistration = false;

    HttpServletRequest req = (HttpServletRequest) request;
    Principal principal = req.getUserPrincipal();

    if (principal != null) {
      String personalId = principal.getName();
      successfulRegistration = registerPersonalId(personalId);
    }

    try {
      chain.doFilter(request, response);
    } finally {
      if (successfulRegistration) clearPersonalId();
    }
  }

  private void clearPersonalId() {
    MDC.remove(PERSONAL_ID);
    Sentry.configureScope(scope -> scope.removeTag(PERSONAL_ID));
  }

  private boolean registerPersonalId(String personalId) {
    if (personalId != null && personalId.trim().length() > 0) {
      Sentry.configureScope(scope -> scope.setTag(PERSONAL_ID, personalId));
      MDC.put(PERSONAL_ID, personalId);
      return true;
    }
    return false;
  }
}

Add personal id as a Sentry scope tag so its searchable


package it.sk.alfresco.clojure;

import java.io.BufferedReader;
import java.io.StringReader;

import clojure.lang.Compiler;

/**
 * Created by IntelliJ IDEA.
 * User: sku
 * Date: Apr 7, 2010
 * Time: 12:20:19 AM
 * To change this template use File | Settings | File Templates.
 */
public class RunSwankServer {
    public void init() throws Exception {
        Runnable cljRunner = new Runnable() {
            public void run() {
                Thread thisThread = Thread.currentThread();
                ClassLoader savedCL = thisThread.getContextClassLoader();

                ClassLoader newCL = this.getClass().getClassLoader();

                thisThread.setContextClassLoader(newCL);

                try {
                    clojure.lang.Compiler.load(
                            new java.io.StringReader(
                                    "(require 'clojure.main)\n" +
                                            "(require 'swank.swank)\n" +
                                            "(clojure.main/with-bindings\n" +
                                            "    (swank.swank/start-server \"nul\" :encoding \"utf-8\" :port 4005))"
                            ));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                thisThread.setContextClassLoader(savedCL);
            }
        };

        Thread cljThread = new Thread(cljRunner);
        cljThread.start();

    }
}

Reformat to normal code style


package com.wolkabout.wolk;

/**
 * All supported reading types.
 */
public enum ReadingType {

    ACCELERATION("ACL"),
    GYRO("GYR"),
    MAGNET("MAG"),
    LIGHT("LT"),
    TEMPERATURE("T"),
    HUMIDITY("H"),
    PRESSURE("P"),
    BATTERY("B"),
    HEARTRATE("BPM"),
    STEPS("STP"),
    CALORIES("KCA");

    private final String prefix;

    ReadingType(final String prefix) {
        this.prefix = prefix;
    }

    String getPrefix() {
        return prefix;
    }
}

package com.wolkabout.wolk;

/**
 * All supported reading types.
 */
public enum ReadingType {

    ACCELERATION("ACL"),
    GYRO("GYR"),
    MAGNET("MAG"),
    LIGHT("LT"),
    TEMPERATURE("T"),
    HUMIDITY("H"),
    PRESSURE("P"),
    BATTERY("B"),
    HEARTRATE("BPM"),
    STEPS("STP"),
    CALORIES("KCAL");

    private final String prefix;

    ReadingType(final String prefix) {
        this.prefix = prefix;
    }

    String getPrefix() {
        return prefix;
    }
}

Fix for calories reading type


package node.company;

import org.joda.time.DateTime;

import data.trainnetwork.BookableSection;
import transaction.FailedTransactionException;
import transaction.TransactionContent;
import transaction.Vault;

public abstract class TransactionContentGenerator extends TransactionContent<String, Vault<BookableSection>> {

	/**
	 *
	 */
	private static final long serialVersionUID = 3685066724312335230L;

	public static TransactionContent<String, Vault<BookableSection>> getTestContent() {
		TransactionContent<String, Vault<BookableSection>> c
			= new TransactionContent<String, Vault<BookableSection>>() {
			private static final long serialVersionUID = -8167406104784795108L;
			@Override
			public void run() throws FailedTransactionException {
				BookableSection s = new BookableSection("section", 1, DateTime.now(), 10, 10);
				System.out.println("EXECUTING");
				data.put(s.getID(), new Vault<BookableSection>(s));
			}
		};

		return c;
	}

}

package node.company;

import java.util.Map;

import org.joda.time.DateTime;

import data.trainnetwork.BookableSection;
import transaction.FailedTransactionException;
import transaction.TransactionContent;
import transaction.Vault;

public abstract class TransactionContentGenerator extends TransactionContent<String, Vault<BookableSection>> {

	/**
	 *
	 */
	private static final long serialVersionUID = 3685066724312335230L;

	public static TransactionContent<String, Vault<BookableSection>> getTestContent() {
		TransactionContent<String, Vault<BookableSection>> c
			= new TransactionContent<String, Vault<BookableSection>>() {
			private static final long serialVersionUID = -8167406104784795108L;
			@Override
			public void run() throws FailedTransactionException {
				BookableSection s = new BookableSection("section", 1, DateTime.now(), 10, 10);
				System.out.println("EXECUTING");

				Map <String, Vault<BookableSection>> _data = (Map<String, Vault<BookableSection>>) manager.writeLock(new Vault(data));
				_data.put(s.getID(), new Vault<BookableSection>(s));

			}
		};

		return c;
	}

}

Extend test code to verify behaviour of vaults with transactions


package org.jvirtanen.parity.reporter;

import static org.jvirtanen.lang.Strings.*;

import org.jvirtanen.parity.net.ptr.PTR;
import org.jvirtanen.parity.net.ptr.PTRListener;
import java.util.Locale;

class Display implements PTRListener {

    private static final double PRICE_FACTOR = 10000.0;

    private static final String HEADER = "" +
        "Timestamp    Inst     Quantity   Price     Buyer    Seller\n" +
        "------------ -------- ---------- --------- -------- --------";

    public Display() {
        printf("\n%s\n", HEADER);
    }

    @Override
    public void trade(PTR.Trade message) {
        printf("%12s %8s %10d %9.2f %8s %8s\n", Timestamps.format(message.timestamp),
                decodeLong(message.instrument), message.quantity, message.price / PRICE_FACTOR,
                decodeLong(message.buyer), decodeLong(message.seller));
    }

    private void printf(String format, Object... args) {
        System.out.printf(Locale.US, format, args);
    }

}

package org.jvirtanen.parity.reporter;

import static org.jvirtanen.lang.Strings.*;

import java.util.Locale;
import org.jvirtanen.parity.net.ptr.PTR;
import org.jvirtanen.parity.net.ptr.PTRListener;

class Display implements PTRListener {

    private static final double PRICE_FACTOR = 10000.0;

    private static final String HEADER = "" +
        "Timestamp    Inst     Quantity   Price     Buyer    Seller\n" +
        "------------ -------- ---------- --------- -------- --------";

    public Display() {
        printf("\n%s\n", HEADER);
    }

    @Override
    public void trade(PTR.Trade message) {
        printf("%12s %8s %10d %9.2f %8s %8s\n", Timestamps.format(message.timestamp),
                decodeLong(message.instrument), message.quantity, message.price / PRICE_FACTOR,
                decodeLong(message.buyer), decodeLong(message.seller));
    }

    private void printf(String format, Object... args) {
        System.out.printf(Locale.US, format, args);
    }

}

Clean up imports in trade reporter


package fitnesse.slim.instructions;

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

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

public class MakeInstructionTest {
  private static final String ID = "id_1";
  private static final String RESULT = "OK";

  private InstructionExecutor executor;

  @Before
  public void setUp() throws Exception {
    executor = mock(InstructionExecutor.class);
  }

  @Test
  public void shouldDelegateCallToExecutor() throws Exception {
    MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"});

    instruction.execute(executor);

    verify(executor, times(1)).create("instance", "class", "arg1", "arg2");
  }

  @Test
  public void shouldFormatReturnValues() {
    MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"});

    InstructionResult result = instruction.execute(executor);

    assertEquals(ID, result.getId());
    assertTrue(result.hasResult());
    assertFalse(result.hasError());
    assertEquals("OK", result.getResult());
  }
}

package fitnesse.slim.instructions;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;

public class MakeInstructionTest {
  private static final String ID = "id_1";

  private final InstructionExecutor executor = mock(InstructionExecutor.class);

  @Test
  public void shouldDelegateCallToExecutor() throws Exception {
    MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"});

    instruction.execute(executor);

    verify(executor, times(1)).create("instance", "class", "arg1", "arg2");
  }

  @Test
  public void shouldFormatReturnValues() {
    MakeInstruction instruction = new MakeInstruction(ID, "instance", "class", new Object[]{"arg1", "arg2"});

    InstructionResult result = instruction.execute(executor);

    assertEquals(ID, result.getId());
    assertTrue(result.hasResult());
    assertFalse(result.hasError());
    assertEquals("OK", result.getResult());
  }
}

Simplify test setup a bit


package se.raddo.raddose3D;

/**
 * WriterString writes all received data to a string.
 */
public class WriterString extends Writer {
  /** All received data is kept in a Stringbuffer. */
  private final StringBuffer data     = new StringBuffer();
  /** After close() is called further data results in RuntimeExceptions. */
  private Boolean            readonly = false;

  @Override
  public void write(final String s) {
    if (readonly) {
      throw new IllegalStateException("Writer has been closed");
    }
    data.append(s);
  }

  @Override
  public void write(final StringBuffer b) {
    if (readonly) {
      throw new IllegalStateException("Writer has been closed");
    }
    data.append(b);
  }

  @Override
  public void close() {
    readonly = true;
  }

  /**
   * Retrieve all encountered data.
   *
   * @return
   *         one String containing all encountered data
   */
  public String getDataString() {
    return new String(data);
  }

  /**
   * Retrieve all encountered data.
   *
   * @return
   *         StringBuffer object containing all encountered data
   */
  public StringBuffer getDataStringBuffer() {
    return data;
  }
}

package se.raddo.raddose3D;

/**
 * WriterString writes all received data to a string.
 */
public class WriterString extends Writer {
  /** All received data is kept in a Stringbuffer. */
  private final StringBuffer data     = new StringBuffer();
  /** After close() is called further data results in RuntimeExceptions. */
  private Boolean            readonly = false;

  @Override
  public void write(final String s) {
    if (readonly) {
      throw new IllegalStateException("Writer has been closed");
    }
    data.append(s);
  }

  @Override
  public void write(final StringBuffer b) {
    if (readonly) {
      throw new IllegalStateException("Writer has been closed");
    }
    data.append(b);
  }

  @Override
  public void close() {
    readonly = true;
    data.trimToSize();
  }

  /**
   * Retrieve all encountered data.
   *
   * @return
   *         one String containing all encountered data
   */
  public String getDataString() {
    return new String(data);
  }

  /**
   * Retrieve all encountered data.
   *
   * @return
   *         StringBuffer object containing all encountered data
   */
  public StringBuffer getDataStringBuffer() {
    return data;
  }
}

Optimize StringBuffer if string is final.


package org.realityforge.replicant.client.runtime.gwt;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Timer;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.realityforge.replicant.client.runtime.DataLoaderEntry;
import org.realityforge.replicant.client.runtime.ReplicantClientSystemImpl;

@Singleton
public final class GwtReplicantClientSystemImpl
  extends ReplicantClientSystemImpl
{
  private final Timer _timer;

  @SuppressWarnings( "CdiInjectionPointsInspection" )
  @Inject
  public GwtReplicantClientSystemImpl( @Nonnull final EventBus eventBus,
                                       @Nonnull final DataLoaderEntry[] dataLoaders )
  {
    setDataLoaders( dataLoaders );
    addReplicantSystemListener( new GwtReplicantSystemListenerImpl( eventBus ) );
    _timer = new Timer()
    {
      @Override
      public void run()
      {
        converge();
      }
    };
    _timer.scheduleRepeating( CONVERGE_DELAY_IN_MS );
  }

  @Override
  protected void release()
  {
    cancelTimer();
    super.release();
  }

  private void cancelTimer()
  {
    _timer.cancel();
  }
}

package org.realityforge.replicant.client.runtime.gwt;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.Timer;
import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.realityforge.replicant.client.runtime.DataLoaderEntry;
import org.realityforge.replicant.client.runtime.ReplicantClientSystemImpl;

@Singleton
public final class GwtReplicantClientSystemImpl
  extends ReplicantClientSystemImpl
{
  private final Timer _timer;

  @SuppressWarnings( "CdiInjectionPointsInspection" )
  @Inject
  public GwtReplicantClientSystemImpl( @Nonnull final EventBus eventBus,
                                       @Nonnull final DataLoaderEntry[] dataLoaders )
  {
    setDataLoaders( dataLoaders );
    _timer = new Timer()
    {
      @Override
      public void run()
      {
        converge();
      }
    };
    _timer.scheduleRepeating( CONVERGE_DELAY_IN_MS );
  }

  @Override
  protected void release()
  {
    cancelTimer();
    super.release();
  }

  private void cancelTimer()
  {
    _timer.cancel();
  }
}

Remove reference to removed class


package ${packageName};

import static org.junit.Assert.*;

public class ${testClassName} {

    private final ${productionClassName} production = new ${productionClassName}("value");

    @org.junit.Test
    public void testOne() throws Exception {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testOne - " + i);
            System.err.println("Some test error  from ${testClassName}.testOne - " + i);
        }
        assertEquals(production.getProperty(), "value");
    }

    @org.junit.Test
    public void testTwo() throws Exception {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testTwo - " + i);
            System.err.println("Some test error  from ${testClassName}.testTwo - " + i);
        }
        String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>;
        assertEquals(production.getProperty(), expected);
    }
}

package ${packageName};

import static org.junit.Assert.*;

public class ${testClassName} {

    private final ${productionClassName} production = new ${productionClassName}("value");

    @org.junit.Test
    public void testOne() throws Exception {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testOne - " + i);
            System.err.println("Some test error  from ${testClassName}.testOne - " + i);
            if (i % 50 == 0) {
                Thread.sleep(1);
            }
        }
        assertEquals(production.getProperty(), "value");
    }

    @org.junit.Test
    public void testTwo() throws Exception {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testTwo - " + i);
            System.err.println("Some test error  from ${testClassName}.testTwo - " + i);
            if (i % 50 == 0) {
                Thread.sleep(1);
            }
        }
        String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>;
        assertEquals(production.getProperty(), expected);
    }
}

Make tests more realistic by doing some “work” other than writing console output.


package ${packageName};

import static org.junit.Assert.*;

public class ${testClassName} {

    private final ${productionClassName} production = new ${productionClassName}("value");

    @org.junit.Test
    public void testOne() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Some test output from ${testClassName}.testOne - " + i);
            System.err.println("Some test error  from ${testClassName}.testOne - " + i);
        }
        assertEquals(production.getProperty(), "value");
    }

    @org.junit.Test
    public void testTwo() {
        for (int i = 0; i < 100; i++) {
            System.out.println("Some test output from ${testClassName}.testTwo - " + i);
            System.err.println("Some test error  from ${testClassName}.testTwo - " + i);
        }
        String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>;
        assertEquals(production.getProperty(), expected);
    }
}

package ${packageName};

import static org.junit.Assert.*;

public class ${testClassName} {

    private final ${productionClassName} production = new ${productionClassName}("value");

    @org.junit.Test
    public void testOne() {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testOne - " + i);
            System.err.println("Some test error  from ${testClassName}.testOne - " + i);
        }
        assertEquals(production.getProperty(), "value");
    }

    @org.junit.Test
    public void testTwo() {
        for (int i = 0; i < 500; i++) {
            System.out.println("Some test output from ${testClassName}.testTwo - " + i);
            System.err.println("Some test error  from ${testClassName}.testTwo - " + i);
        }
        String expected = <%= binding.hasVariable("halfTestsFail") && binding.halfTestsFail ? "\"foo\"" : "\"value\"" %>;
        assertEquals(production.getProperty(), expected);
    }
}

Increase the amount of output in build scan performance tests.


package redux.api.enhancer;

import redux.api.Dispatcher;
import redux.api.StateProvider;

/**
 * A middleware is an interface that composes a {@link Dispatcher} to return a new dispatch function. It often turns
 * async actions into actions.
 *
 * @see http://redux.js.org/docs/advanced/Middleware.html
 *
 * @param <S> The store type
 */
interface Middleware<S> {

    /**
     * Dispatches an action. This is the only way to trigger a state change.
     *
     * @see http://redux.js.org/docs/Glossary.html#middleware
     *
     * @param stateProvider An interface to return the current state of the store.
     * @param action The action
     * @param next The next dispatcher in the chain
     * @return The action
     */
    Object dispatch(StateProvider<S> stateProvider, Object action, Dispatcher next);

}

package redux.api.enhancer;

import redux.api.Dispatcher;
import redux.api.StateProvider;

/**
 * A middleware is an interface that composes a {@link Dispatcher} to return a new dispatch function. It often turns
 * async actions into actions.
 *
 * @see http://redux.js.org/docs/advanced/Middleware.html
 *
 * @param <S> The store type
 */
interface Middleware<S> {

    /**
     * Dispatches an action. This is the only way to trigger a state change.
     *
     * @see http://redux.js.org/docs/Glossary.html#middleware
     *
     * @param stateProvider An interface to return the current state of the store.
     * @param action The action
     * @param dispatcher The next dispatcher in the chain
     * @return The action
     */
    Object dispatch(StateProvider<S> stateProvider, Object action, Dispatcher dispatcher);

}

Rename `next` to `dispatcher` to avoid confusion from JS source.


package brooklyn.entity.trait;

import brooklyn.entity.Entity;
import brooklyn.event.basic.BasicAttributeSensor;
import brooklyn.event.basic.BasicNotificationSensor;

/**
 * A collection of entities that can change.
 */
public interface Changeable {
    BasicAttributeSensor<Integer> GROUP_SIZE = new BasicAttributeSensor<Integer>(Integer.class, "group.members.count", "Number of memebers");
    BasicNotificationSensor<Entity> MEMBER_ADDED = new BasicNotificationSensor<Entity>(Entity.class, "group.members.added", "Entity added to group members");
    BasicNotificationSensor<Entity> MEMBER_REMOVED = new BasicNotificationSensor<Entity>(Entity.class, "group.members.removed", "Entity removed from group members");
}

package brooklyn.entity.trait;

import brooklyn.entity.Entity;
import brooklyn.event.basic.BasicAttributeSensor;
import brooklyn.event.basic.BasicNotificationSensor;

/**
 * A collection of entities that can change.
 */
public interface Changeable {
    BasicAttributeSensor<Integer> GROUP_SIZE = new BasicAttributeSensor<Integer>(Integer.class, "group.members.count", "Number of members");
    BasicNotificationSensor<Entity> MEMBER_ADDED = new BasicNotificationSensor<Entity>(Entity.class, "group.members.added", "Entity added to group members");
    BasicNotificationSensor<Entity> MEMBER_REMOVED = new BasicNotificationSensor<Entity>(Entity.class, "group.members.removed", "Entity removed from group members");
}

Fix typo in GROUP_SIZE sensor description


package arez.doc.examples.at_dependency;

import arez.annotations.ArezComponent;
import arez.annotations.Dependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@ArezComponent
public abstract class PersonViewModel
{
  @Nonnull
  private final Person _person;
  //DOC ELIDE START

  public PersonViewModel( @Nonnull final Person person )
  {
    _person = person;
  }

  //DOC ELIDE END

  // Let imagine there is a lot more logic and state on the view model
  // to justify it's existence rather than just having view layer directly
  // accessing underlying entities

  @Dependency
  @Nonnull
  public Person getPerson()
  {
    // This reference is immutable and the network replication
    // layer is responsible for managing the lifecycle of person
    // component and may dispose it when the Person entity is deleted
    // on the server which should trigger this view model being disposed.
    return _person;
  }

  /**
   * The Job entity is likewise controlled by the server
   * and can be updated, removed on the server and replicated to the web
   * browser. In this scenario the current job is just removed from the
   * person view model.
   */
  @Dependency( action = Dependency.Action.SET_NULL )
  @Observable
  @Nullable
  public abstract Job getCurrentJob();
  //DOC ELIDE START

  public abstract void setCurrentJob( @Nullable final Job currentJob );
  //DOC ELIDE END
}

package arez.doc.examples.at_dependency;

import arez.annotations.ArezComponent;
import arez.annotations.Dependency;
import arez.annotations.Observable;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;

@ArezComponent
public abstract class PersonViewModel
{
  @Nonnull
  private final Person _person;
  //DOC ELIDE START

  public PersonViewModel( @Nonnull final Person person )
  {
    _person = person;
  }

  //DOC ELIDE END

  // Let imagine there is a lot more logic and state on the view model
  // to justify it's existence rather than just having view layer directly
  // accessing underlying entities

  @Dependency
  @Nonnull
  public final Person getPerson()
  {
    // This reference is immutable and the network replication
    // layer is responsible for managing the lifecycle of person
    // component and may dispose it when the Person entity is deleted
    // on the server which should trigger this view model being disposed.
    return _person;
  }

  /**
   * The Job entity is likewise controlled by the server
   * and can be updated, removed on the server and replicated to the web
   * browser. In this scenario the current job is just removed from the
   * person view model.
   */
  @Dependency( action = Dependency.Action.SET_NULL )
  @Observable
  @Nullable
  public abstract Job getCurrentJob();
  //DOC ELIDE START

  public abstract void setCurrentJob( @Nullable final Job currentJob );
  //DOC ELIDE END
}

Make sure @Dependency is marked as final


package org.ihtsdo.buildcloud.service.build.transform;

import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public class RepeatableRelationshipUUIDTransform implements LineTransformation {

	private Type5UuidFactory type5UuidFactory;

	public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
		type5UuidFactory = new Type5UuidFactory();
	}

	@Override
	public void transformLine(String[] columnValues) throws TransformationException {
		// Create repeatable UUID to ensure SCTIDs are reused.
		// (Technique lifted from workbench release process.)
		// sourceId + destinationId + typeId + relationshipGroup
		if (columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
			try {
				columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
			} catch (UnsupportedEncodingException e) {
				throw new TransformationException("Failed to create UUID.", e);
			}
		}
	}

	public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
		return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
	}

	@Override
	public int getColumnIndex() {
		return -1;
	}

}

package org.ihtsdo.buildcloud.service.build.transform;

import org.ihtsdo.buildcloud.service.build.RF2Constants;
import org.ihtsdo.buildcloud.service.helper.Type5UuidFactory;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

public class RepeatableRelationshipUUIDTransform implements LineTransformation {

	private Type5UuidFactory type5UuidFactory;

	public RepeatableRelationshipUUIDTransform() throws NoSuchAlgorithmException {
		type5UuidFactory = new Type5UuidFactory();
	}

	@Override
	public void transformLine(String[] columnValues) throws TransformationException {
		// Create repeatable UUID to ensure SCTIDs are reused.
		// (Technique lifted from workbench release process.)
		// sourceId + destinationId + typeId + relationshipGroup
		if (columnValues[0] == null || columnValues[0].equals(RF2Constants.NULL_STRING) || columnValues[0].isEmpty()) {
			try {
				columnValues[0] = getCalculatedUuidFromRelationshipValues(columnValues);
			} catch (UnsupportedEncodingException e) {
				throw new TransformationException("Failed to create UUID.", e);
			}
		}
	}

	public String getCalculatedUuidFromRelationshipValues(String[] columnValues) throws UnsupportedEncodingException {
		return type5UuidFactory.get(columnValues[4] + columnValues[5] + columnValues[7] + columnValues[6]).toString();
	}

	@Override
	public int getColumnIndex() {
		return -1;
	}

}

Allow SCTID in relationship file to be actually null, not just "null"


package org.opencode4workspace.it;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.opencode4workspace.WWClient;
import org.opencode4workspace.WWException;
import org.opencode4workspace.endpoints.WWAuthenticationEndpoint;
import org.opencode4workspace.endpoints.WWGraphQLEndpoint;
import org.opencode4workspace.graphql.SpaceWrapper;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ITgraphQL {

	@Test(enabled=false)
	@Parameters({ "appId", "appSecret" })
	public void testgetSpacesAsApp(String appId, String appSecret) throws UnsupportedEncodingException, WWException {
		WWClient client = WWClient.buildClientApplicaitonAccess(appId, appSecret, new WWAuthenticationEndpoint());
		assert !client.isAuthenticated();
		client.authenticate();
		assert client.isAuthenticated();
		WWGraphQLEndpoint ep = new WWGraphQLEndpoint(client);
		List<SpaceWrapper> spaces = ep.getSpaces();
		assert (spaces.size() > 0);
	}

}

package org.opencode4workspace.it;

import java.io.UnsupportedEncodingException;
import java.util.List;

import org.opencode4workspace.WWClient;
import org.opencode4workspace.WWException;
import org.opencode4workspace.endpoints.WWAuthenticationEndpoint;
import org.opencode4workspace.endpoints.WWGraphQLEndpoint;
import org.opencode4workspace.graphql.SpaceWrapper;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class ITgraphQL {

	@Test(enabled=false)
	@Parameters({ "appId", "appSecret" })
	public void testgetSpacesAsApp(String appId, String appSecret) throws UnsupportedEncodingException, WWException {
		WWClient client = WWClient.buildClientApplicationAccess(appId, appSecret, new WWAuthenticationEndpoint());
		assert !client.isAuthenticated();
		client.authenticate();
		assert client.isAuthenticated();
		WWGraphQLEndpoint ep = new WWGraphQLEndpoint(client);
		List<SpaceWrapper> spaces = ep.getSpaces();
		assert (spaces.size() > 0);
	}

}

Fix needed after rename of method


package org.zanata.feature.security;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * @author Patrick Huang <a
 *         href="mailto:pahuang@redhat.com">pahuang@redhat.com</a>
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({ SecurityTest.class, LoginTest.class,
        SecurityFullTest.class })
public class SecurityTestSuite {
}

/*
 * Copyright 2013, Red Hat, Inc. and individual contributors as indicated by the
 * @author tags. See the copyright.txt file in the distribution for a full
 * listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this software; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF
 * site: http://www.fsf.org.
 */
package org.zanata.feature.security;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * @author Patrick Huang <a
 *         href="mailto:pahuang@redhat.com">pahuang@redhat.com</a>
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({
        SecurityTest.class,
        /* LoginTest.class, DISABLED (RHBZ-1016937) TODO: FIX */
        SecurityFullTest.class })
public class SecurityTestSuite {
}

Disable failing Concordion Login test


package fgis.server.support.geojson;

import org.geolatte.geom.Geometry;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public final class GjGeometryTest
  extends AbstractGjElementTest
{
  @Test
  public void geometry()
    throws Exception
  {
    final Geometry geometry = fromWkT( "POINT (1 1)" );
    final GjGeometry e = new GjGeometry( geometry, null, null, null );
    assertEquals( e.getGeometry(), geometry );
    assertPropertyAllowed( e, "X" );
    assertPropertyNotAllowed( e, "coordinates" );
  }

  @SuppressWarnings( "ConstantConditions" )
  @Test
  public void nullGeometryPassedToGeometry()
    throws Exception
  {
    try
    {
      new GjGeometry( null, null, null, null );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to fail when passing null geometry" );
  }

  @SuppressWarnings( "ConstantConditions" )
  @Test
  public void geometryCollectionPassedToGeometryShouldFail()
    throws Exception
  {
    try
    {
      new GjGeometry( fromWkT( "GEOMETRYCOLLECTION(POINT (1 1))" ), null, null, null );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to fail when passing null geometry" );
  }
}

package fgis.server.support.geojson;

import org.geolatte.geom.Geometry;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public final class GjGeometryTest
  extends AbstractGjElementTest
{
  @Test
  public void basic()
    throws Exception
  {
    final Geometry geometry = fromWkT( "POINT (1 1)" );
    final GjGeometry e = new GjGeometry( geometry, null, null, null );
    assertEquals( e.getGeometry(), geometry );
    assertPropertyAllowed( e, "X" );
    assertPropertyNotAllowed( e, "coordinates" );
  }

  @SuppressWarnings( "ConstantConditions" )
  @Test
  public void nullGeometry()
    throws Exception
  {
    try
    {
      new GjGeometry( null, null, null, null );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to fail when passing null geometry" );
  }

  @SuppressWarnings( "ConstantConditions" )
  @Test
  public void geometryCollectionPassedAsGeometryShouldFail()
    throws Exception
  {
    try
    {
      new GjGeometry( fromWkT( "GEOMETRYCOLLECTION(POINT (1 1))" ), null, null, null );
    }
    catch ( final IllegalArgumentException e )
    {
      return;
    }
    fail( "Expected to fail when passing null geometry" );
  }
}

Rename tests with more sensible names


/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.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.gravitee.repository.api;

import io.gravitee.repository.model.Application;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApplicationRepository {

    Set<Application> findAll();

    Set<Application> findByUser(String username);

    Application create(Application application);

    Application update(Application application);

    Optional<Application> findByName(String applicationName);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.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.gravitee.repository.api;

import io.gravitee.repository.model.Application;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApplicationRepository {

    Set<Application> findAll();

    Set<Application> findByTeam(String teamName);

    Set<Application> findByUser(String username);

    Application create(Application application);

    Application update(Application application);

    Optional<Application> findByName(String applicationName);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

Add service to retrieve list of Applications by team


package org.jboss.shamrock.rsops;

import io.smallrye.reactive.streams.Engine;
import org.eclipse.microprofile.reactive.streams.ReactiveStreamsFactory;
import org.eclipse.microprofile.reactive.streams.core.ReactiveStreamsFactoryImpl;
import org.eclipse.microprofile.reactive.streams.spi.ReactiveStreamsEngine;
import org.jboss.shamrock.annotations.BuildProducer;
import org.jboss.shamrock.annotations.BuildStep;
import org.jboss.shamrock.deployment.builditem.substrate.ReflectiveClassBuildItem;
import org.jboss.shamrock.deployment.builditem.substrate.SubstrateResourceBuildItem;

public class ReactiveStreamsOperatorsProcessor {

    @BuildStep
    public void build(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
                      BuildProducer<SubstrateResourceBuildItem> resource) throws Exception {
        reflectiveClass.produce(new ReflectiveClassBuildItem(false, false, ReactiveStreamsFactoryImpl.class.getName(), Engine.class.getName()));

        resource.produce(new SubstrateResourceBuildItem("META-INF/services/" + ReactiveStreamsEngine.class.getName()));
        resource.produce(new SubstrateResourceBuildItem("META-INF/services/" + ReactiveStreamsFactory.class.getName()));
    }

}

package org.jboss.shamrock.rsops;

import io.smallrye.reactive.streams.Engine;
import org.eclipse.microprofile.reactive.streams.ReactiveStreamsFactory;
import org.eclipse.microprofile.reactive.streams.core.ReactiveStreamsFactoryImpl;
import org.eclipse.microprofile.reactive.streams.spi.ReactiveStreamsEngine;
import org.jboss.shamrock.annotations.BuildProducer;
import org.jboss.shamrock.annotations.BuildStep;
import org.jboss.shamrock.deployment.builditem.substrate.ServiceProviderBuildItem;

public class ReactiveStreamsOperatorsProcessor {

    @BuildStep
    public void build(BuildProducer<ServiceProviderBuildItem> serviceProvider) {
        serviceProvider.produce(new ServiceProviderBuildItem(ReactiveStreamsEngine.class.getName(), Engine.class.getName()));
        serviceProvider.produce(new ServiceProviderBuildItem(ReactiveStreamsFactory.class.getName(), ReactiveStreamsFactoryImpl.class.getName()));
    }

}

Use the new SPI support in the SmallRye Reactive Streams Operators processor


package com.kakawait.spring.security.cas.web.authentication;

import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Thibaud Leprêtre
 */
class DefaultProxyCallbackAndServiceAuthenticationDetails
        implements ProxyCallbackAndServiceAuthenticationDetails {

    private final ServiceProperties serviceProperties;

    private final transient HttpServletRequest context;

    private final String proxyCallbackPath;

    DefaultProxyCallbackAndServiceAuthenticationDetails(ServiceProperties serviceProperties, HttpServletRequest context,
            String proxyCallbackPath) {
        this.serviceProperties = serviceProperties;
        this.context = context;
        this.proxyCallbackPath = proxyCallbackPath;
    }

    @Override
    public String getProxyCallbackUrl() {
        if (proxyCallbackPath == null) {
            return null;
        }
        String path = context.getContextPath() + proxyCallbackPath;
        return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
                context.getServerPort(), path, null);
    }

    @Override
    public String getServiceUrl() {
        String query = UriComponentsBuilder
                .newInstance()
                .query(context.getQueryString())
                .replaceQueryParam(serviceProperties.getArtifactParameter(), new Object[0])
                .build()
                .toString()
                .replaceFirst("^\\?", "");
        return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
                context.getServerPort(), context.getRequestURI(), query);
    }
}

package com.kakawait.spring.security.cas.web.authentication;

import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Thibaud Leprêtre
 */
class DefaultProxyCallbackAndServiceAuthenticationDetails
        implements ProxyCallbackAndServiceAuthenticationDetails {

    private final ServiceProperties serviceProperties;

    private final transient HttpServletRequest context;

    private final String proxyCallbackPath;

    DefaultProxyCallbackAndServiceAuthenticationDetails(ServiceProperties serviceProperties, HttpServletRequest context,
            String proxyCallbackPath) {
        this.serviceProperties = serviceProperties;
        this.context = context;
        this.proxyCallbackPath = proxyCallbackPath;
    }

    @Override
    public String getProxyCallbackUrl() {
        if (proxyCallbackPath == null) {
            return null;
        }
        String path = context.getContextPath() + proxyCallbackPath;
        return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
                context.getServerPort(), path, null);
    }

    @Override
    public String getServiceUrl() {
        String query = UriComponentsBuilder
                .newInstance()
                .query(context.getQueryString())
                .replaceQueryParam(serviceProperties.getArtifactParameter(), new Object[0])
                .build()
                .toString()
                .replaceFirst("^\\?", "");
        return UrlUtils.buildFullRequestUrl(context.getScheme(), context.getServerName(),
                context.getServerPort(), context.getRequestURI(), StringUtils.hasText(query) ? query : null);
    }
}

Use null if query strings are empty


package seedu.ezdo.commons.util;

import seedu.ezdo.model.todo.ReadOnlyTask;

//@@author A0139177W
/**
 * Utility method for Recur
 */
public class RecurUtil {

    /**
     * Checks if a recurring status is valid with at least a start date and/or
     * due date present in a task. Floating tasks should not have a recurring
     * status.
     * @param task
     * @return false if the task is a floating task
     * @return true otherwise
     */
    public static boolean isRecurValid(ReadOnlyTask task) {
        assert task != null;
        String taskStartDate = task.getStartDate().toString();
        String taskDueDate = task.getDueDate().toString();

        final boolean isStartDateMissing = taskStartDate.isEmpty();
        final boolean isDueDateMissing = taskDueDate.isEmpty();
        final boolean isBothDatesMissing = isStartDateMissing && isDueDateMissing;

        final boolean recurStatus = task.getRecur().isRecur();

        final boolean recurValid = !(isBothDatesMissing && recurStatus);

        return recurValid;
    }

}

Remove trailing whitespace in line 29


package de.onyxbits.raccoon.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * A simple session log for recording the files that were downloaded. The log is
 * meant to be used as an input for shellscripts, so the logformat is dead
 * simple: every line contains the filename of one successfully downloded file.
 *
 * @author patrick
 *
 */
public class DownloadLogger {

	public static final String LOGCOMPLETE = "downloads-complete.txt";
	private File completeLog;

	/**
	 * Create a new logger
	 *
	 * @param logfile
	 *          the file to log to.
	 */
	public DownloadLogger(Archive archive) {
		completeLog = new File(new File(archive.getRoot(), Archive.LOGDIR), LOGCOMPLETE);
	}

	/**
	 * Clears the download log. This should be called when starting the session.
	 */
	public synchronized void clear() {
		if (completeLog.exists()) {
			completeLog.delete();
		}
	}

	/**
	 * Log a completed download to the logfile
	 *
	 * @param file
	 *          the file that was downloaded
	 * @throws IOException
	 *           if writing fails.
	 */
	public synchronized void addEntry(File file) throws IOException {
		completeLog.getParentFile().mkdirs();
		FileWriter fw = new FileWriter(completeLog, true);
		fw.write(file.getAbsolutePath() + "\n");
		fw.close();
	}
}

package de.onyxbits.raccoon.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * A simple session log for recording the files that were downloaded. The log is
 * meant to be used as an input for shellscripts, so the logformat is dead
 * simple: every line contains the filename of one successfully downloded file.
 *
 * @author patrick
 *
 */
public class DownloadLogger {

	public static final String LOGCOMPLETE = "downloads-complete.txt";
	private File completeLog;

	/**
	 * Create a new logger
	 *
	 * @param logfile
	 *          the file to log to.
	 */
	public DownloadLogger(Archive archive) {
		completeLog = new File(new File(archive.getRoot(), Archive.LOGDIR), LOGCOMPLETE);
	}

	/**
	 * Clears the download log. This should be called when starting the session.
	 */
	public synchronized void clear() {
		if (completeLog.exists()) {
			completeLog.delete();
		}
	}

	/**
	 * Log a completed download to the logfile
	 *
	 * @param file
	 *          the file that was downloaded
	 * @throws IOException
	 *           if writing fails.
	 */
	public synchronized void addEntry(File file) throws IOException {
		completeLog.getParentFile().mkdirs();
		FileWriter fw = new FileWriter(completeLog, true);
		fw.write(completeLog.getAbsolutePath() + "\n");
		fw.close();
	}
}

Use the right file object


package fr.esiea.unique.binome.name.dictionary;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 *
 * @author Florent
 *
 */

public class PiocheTest {
	private Pioche pioche = new Pioche();

	@Test
	public void testMeilleurLettre() {
		char l1 = 'a';
		char l2 = 'b';
		assertTrue(pioche.meilleurLettre(l1, l2));
		assertFalse(pioche.meilleurLettre(l2, l1));
		assertTrue(pioche.meilleurLettre(l1, l1));
	}

	@Test
	public void testLetterRandom() {

	}
}

package fr.esiea.unique.binome.name.dictionary;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

/**
 *
 * @author Florent
 *
 */

public class PiocheTest {
	private Pioche pioche = new Pioche();

	@Test
	public void testMeilleurLettre() {
		char l1 = 'a';
		char l2 = 'b';
		assertTrue(pioche.meilleurLettre(l1, l2));
		assertFalse(pioche.meilleurLettre(l2, l1));
		assertTrue(pioche.meilleurLettre(l1, l1));
	}

	@Test
	public void testLetterRandom() {
		String alphabet = "abcdefghijklmnopqrstuvwxyz";
	    char c = pioche.letterRandom();
	    assertNotEquals(alphabet.lastIndexOf(c), -1);
	}
}

Test du random de la pioche


package com.sixsq.slipstream.resource;

import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Reference;
import org.restlet.routing.Redirector;

public class MeteringRedirector extends Redirector {

	public MeteringRedirector(Context context, String targetPattern, int mode) {
		super(context, targetPattern, mode);
	}

	protected void outboundServerRedirect(Reference targetRef, Request request,
			Response response) {
		String user = request.getClientInfo().getUser().getName();
		request = addUserToQuery(request, user);
		super.outboundServerRedirect(targetRef, request,
				response);
	}

	private Request addUserToQuery(Request request, String user) {
		String query = request.getResourceRef().getQuery();
		request.getResourceRef().setQuery(query + "&user_id=" + user);
		return request;
	}

}

package com.sixsq.slipstream.resource;

import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Reference;
import org.restlet.routing.Redirector;

public class MeteringRedirector extends Redirector {

	public MeteringRedirector(Context context, String targetPattern, int mode) {
		super(context, targetPattern, mode);
	}

	protected void outboundServerRedirect(Reference targetRef, Request request,
			Response response) {
		String user = request.getClientInfo().getUser().getName();
		targetRef.addQueryParameter("user_id", user);
		super.outboundServerRedirect(targetRef, request,
				response);
	}

}

Add query fragment to target


package us.myles.ViaVersion.commands.defaultsubs;

import io.netty.util.ResourceLeakDetector;
import us.myles.ViaVersion.api.command.ViaCommandSender;
import us.myles.ViaVersion.api.command.ViaSubCommand;

public class DisplayLeaksSubCmd extends ViaSubCommand {
    @Override
    public String name() {
        return "displayleaks";
    }

    @Override
    public String description() {
        return "Try to hunt memory leaks!";
    }

    @Override
    public boolean execute(ViaCommandSender sender, String[] args) {
        if (ResourceLeakDetector.getLevel() != ResourceLeakDetector.Level.ADVANCED)
            ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.ADVANCED);
        else
            ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

        sendMessage(sender, "&6Leak detector is now %s", (ResourceLeakDetector.getLevel() == ResourceLeakDetector.Level.ADVANCED ? "&aenabled" : "&cdisabled"));
        return true;
    }
}

package us.myles.ViaVersion.commands.defaultsubs;

import io.netty.util.ResourceLeakDetector;
import us.myles.ViaVersion.api.command.ViaCommandSender;
import us.myles.ViaVersion.api.command.ViaSubCommand;

public class DisplayLeaksSubCmd extends ViaSubCommand {
    @Override
    public String name() {
        return "displayleaks";
    }

    @Override
    public String description() {
        return "Try to hunt memory leaks!";
    }

    @Override
    public boolean execute(ViaCommandSender sender, String[] args) {
        if (ResourceLeakDetector.getLevel() != ResourceLeakDetector.Level.PARANOID)
            ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID);
        else
            ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.DISABLED);

        sendMessage(sender, "&6Leak detector is now %s", (ResourceLeakDetector.getLevel() == ResourceLeakDetector.Level.PARANOID ? "&aenabled" : "&cdisabled"));
        return true;
    }
}

Change ResourceLeakDetector to PARANOID for displayleaks


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

package net.myrrix.online.partition;

import java.util.List;

import org.apache.mahout.common.Pair;

/**
 * Does nothing; not applicable in local mode.
 *
 * @author Sean Owen
 */
public final class PartitionLoaderImpl implements PartitionLoader {

  /**
   * @throws UnsupportedOperationException
   */
  @Override
  public List<List<Pair<String, Integer>>> loadPartitions(int defaultPort, String bucket, String instanceID) {
    throw new UnsupportedOperationException();
  }

}

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

package net.myrrix.online.partition;

import java.util.List;

import com.google.common.net.HostAndPort;

/**
 * Does nothing; not applicable in local mode.
 *
 * @author Sean Owen
 */
public final class PartitionLoaderImpl implements PartitionLoader {

  /**
   * @throws UnsupportedOperationException
   */
  @Override
  public List<List<HostAndPort>> loadPartitions(int defaultPort, String bucket, String instanceID) {
    throw new UnsupportedOperationException();
  }

}

Use some Guava .net classes to clean up code a little


{%- if (see is defined and see is not none) or (deprecated is defined and deprecated is not none) or (since is defined and since is not none) %}
{%- if begin is defined %}
{{spacing}}{{begin}}
{%- endif %}
{%- if deprecated is defined and deprecated is not none and since is defined and since is not none %}
{{spacing}} * @deprecated in SmartDeviceLink {{since}}
{%- elif deprecated is defined and deprecated is not none %}
{{spacing}} * @deprecated
{%- elif since is defined and since is not none %}
{{spacing}} * @since SmartDeviceLink {{since}}
{%- endif %}
{%- if see is defined %}
{{spacing}} * @see {{see}}
{%- endif %}
{%- if end is defined %}
{{spacing}} {{end}}
{%- endif %}
{%- endif %}

{%- if (see is defined and see is not none) or (deprecated is defined and deprecated is not none) or (since is defined and since is not none) %}
{%- if begin is defined %}
{{spacing}}{{begin}}
{%- endif %}
{%- if deprecated is defined and deprecated is not none %}
{{spacing}} * @since in SmartDeviceLink {{history[0].since}}
{{spacing}} * @deprecated in SmartDeviceLink {{since}}
{%- elif history is defined and history is not none %}
{{spacing}} * @since in SmartDeviceLink {{history[0].since}}
{%- else %}
{{spacing}} * @since in SmartDeviceLink {{since}}
{%- endif %}
{%- if see is defined %}
{{spacing}} * @see {{see}}
{%- endif %}
{%- if end is defined %}
{{spacing}} {{end}}
{%- endif %}
{%- endif %}

Refactor since & deprecated generation format


/*
 * Copyright 2011 The Netty Project
 *
 * The Netty Project 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 com.sun.nio.sctp;

/**
 * TODO Document me.
 *
 * @author Trustin Lee
 */
public enum HandlerResult {
    CONTINUE, RETURN
}

/*
 * Copyright 2011 The Netty Project
 *
 * The Netty Project 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 com.sun.nio.sctp;

public enum HandlerResult {
    CONTINUE, RETURN
}

Remove bad Javadoc in SCTP classes.


package com.jmlb0003.jokes.gradlejokesproject;

public final class Joker {

    private Joker() {
    }

    public static String getJoke() {
        return "This is totally a funny joke";
    }

}

package com.jmlb0003.jokes.gradlejokesproject;

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

public final class Joker {

    private List<String> jokes;

    public Joker() {
        jokes = new ArrayList<>();
        jokes.add("This is totally a funny joke");
        jokes.add("This is another joke");
        jokes.add("This is a joke about animals");
        jokes.add("This is a joke about films");
        jokes.add("This is a bad joke");
    }

    public String getJoke() {
        if (jokes != null) {
            return jokes.get(new Random().nextInt(jokes.size()));
        }
        return null;
    }

}

Add more jokes to show and make the returned joke random


/**
 * Illustrates a simple flatMap in Java to extract the words
 */
package com.oreilly.learningsparkexamples.java;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;

public class BasicFlatMap {
  public static void main(String[] args) throws Exception {

		if (args.length != 2) {
      throw new Exception("Usage BasicFlatMap sparkMaster inputFile");
		}

    JavaSparkContext sc = new JavaSparkContext(
      args[0], "basicflatmap", System.getenv("SPARK_HOME"), System.getenv("JARS"));
    JavaRDD<String> rdd = sc.textFile(args[1]);
    JavaRDD<String> result = rdd.flatMap(
      new FlatMapFunction<String, String>() { public Iterable<String> call(String x) {
          return Arrays.asList(x.split(" "));
        }});
    System.out.println(StringUtils.join(result.collect(), ","));
  }
}

/**
 * Illustrates a simple flatMap in Java to extract the words
 */
package com.oreilly.learningsparkexamples.java;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;

import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;

public class BasicFlatMap {
  public static void main(String[] args) throws Exception {

		if (args.length != 2) {
      throw new Exception("Usage BasicFlatMap sparkMaster inputFile");
		}

    JavaSparkContext sc = new JavaSparkContext(
      args[0], "basicflatmap", System.getenv("SPARK_HOME"), System.getenv("JARS"));
    JavaRDD<String> rdd = sc.textFile(args[1]);
    JavaRDD<String> words = rdd.flatMap(
      new FlatMapFunction<String, String>() { public Iterable<String> call(String x) {
          return Arrays.asList(x.split(" "));
        }});
    Map<String, Long> result = words.countByValue();
    for (Entry<String, Long> entry: result.entrySet()) {
      System.out.println(entry.getKey() + ":" + entry.getValue());
    }
  }
}

Make the basicflatmap example be a wordcount example


package org.mtransit.parser.mt.data;

public class MServiceDate implements Comparable<MServiceDate> {

	public String serviceId;
	public int calendarDate;

	public MServiceDate(String serviceId, int calendarDate) {
		this.serviceId = serviceId;
		this.calendarDate = calendarDate;
	}

	@Override
	public int compareTo(MServiceDate otherServiceDate) {
		return calendarDate - otherServiceDate.calendarDate;
	}

	@Override
	public boolean equals(Object obj) {
		MServiceDate ts = (MServiceDate) obj;
		if (ts.serviceId != null && !ts.serviceId.equals(serviceId)) {
			return false;
		}
		if (ts.calendarDate != 0 && ts.calendarDate != calendarDate) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return new StringBuilder() //
				.append('\'').append(MSpec.escape(serviceId)).append('\'').append(',') // service ID
				.append(calendarDate) // calendar date
				.toString();
	}

}

package org.mtransit.parser.mt.data;

public class MServiceDate implements Comparable<MServiceDate> {

	public String serviceId;
	public int calendarDate;

	public MServiceDate(String serviceId, int calendarDate) {
		this.serviceId = serviceId;
		this.calendarDate = calendarDate;
	}

	@Override
	public int compareTo(MServiceDate otherServiceDate) {
		final int cd = calendarDate - otherServiceDate.calendarDate;
		if (cd != 0) {
			return cd;
		}
		return serviceId.compareToIgnoreCase(otherServiceDate.serviceId);
	}

	@Override
	public boolean equals(Object obj) {
		MServiceDate ts = (MServiceDate) obj;
		if (ts.serviceId != null && !ts.serviceId.equals(serviceId)) {
			return false;
		}
		if (ts.calendarDate != 0 && ts.calendarDate != calendarDate) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		return new StringBuilder() //
				.append('\'').append(MSpec.escape(serviceId)).append('\'').append(',') // service ID
				.append(calendarDate) // calendar date
				.toString();
	}

}

Fix service date sorting when multiple services / day.


package com.fsck.k9.account;

import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.ServerSettings.Type;

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

/**
 * Deals with logic surrounding account creation.
 * <p/>
 * TODO Move much of the code from com.fsck.k9.activity.setup.* into here
 */
public class AccountCreator {

    private static Map<Type, DeletePolicy> defaults = new HashMap<Type, DeletePolicy>();

    static {
        defaults.put(Type.IMAP, DeletePolicy.ON_DELETE);
        defaults.put(Type.POP3, DeletePolicy.NEVER);
        defaults.put(Type.WebDAV, DeletePolicy.ON_DELETE);
    }

    public static DeletePolicy calculateDefaultDeletePolicy(Type type) {
        return defaults.get(type);
    }

    public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) {
        switch (securityType) {
            case NONE:
            case STARTTLS_REQUIRED: {
                return storeType.defaultPort;
            }
            case SSL_TLS_REQUIRED: {
                return storeType.defaultTlsPort;
            }
            default: {
                throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType);
            }
        }
    }
}

package com.fsck.k9.account;

import com.fsck.k9.Account.DeletePolicy;
import com.fsck.k9.mail.ConnectionSecurity;
import com.fsck.k9.mail.ServerSettings.Type;

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

/**
 * Deals with logic surrounding account creation.
 * <p/>
 * TODO Move much of the code from com.fsck.k9.activity.setup.* into here
 */
public class AccountCreator {

    private static Map<Type, DeletePolicy> defaults = new HashMap<Type, DeletePolicy>();

    static {
        defaults.put(Type.IMAP, DeletePolicy.ON_DELETE);
        defaults.put(Type.POP3, DeletePolicy.NEVER);
        defaults.put(Type.WebDAV, DeletePolicy.ON_DELETE);
    }

    public static DeletePolicy calculateDefaultDeletePolicy(Type type) {
        return defaults.get(type);
    }

    public static int getDefaultPort(ConnectionSecurity securityType, Type storeType) {
        switch (securityType) {
            case NONE:
            case STARTTLS_REQUIRED: {
                return storeType.defaultPort;
            }
            case SSL_TLS_REQUIRED: {
                return storeType.defaultTlsPort;
            }
        }

        throw new AssertionError("Unhandled ConnectionSecurity type encountered: " + securityType);
    }
}

Move throw statement outside of switch body


package org.verapdf.model.impl;

import org.junit.Assert;
import org.junit.Test;
import org.verapdf.model.ModelHelper;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author Evgeniy Muravitskiy
 */

public abstract class BaseTest {

    protected static org.verapdf.model.baselayer.Object actual;

    protected static String TYPE;
    protected static String ID;

    @Test
    public void testTypeAndID() {
        Assert.assertEquals(TYPE, actual.getType());
        Assert.assertEquals(ID, actual.getID());
    }

	@Test
	public void testLinksMethod() {
		List<String> expectedLinks = ModelHelper.getListOfLinks(actual.getType());
		for (String link : expectedLinks) {
			Assert.assertNotNull(actual.getLinkedObjects(link));
		}
		expectedLinks.clear();
	}

	protected static String getSystemIndependentPath(String path) throws URISyntaxException {
		URL resourceUrl = ClassLoader.class.getResource(path);
		Path resourcePath = Paths.get(resourceUrl.toURI());
		return resourcePath.toString();
	}
}

package org.verapdf.model.impl;

import org.junit.Assert;
import org.junit.Test;
import org.verapdf.model.ModelHelper;

import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @author Evgeniy Muravitskiy
 */

public abstract class BaseTest {

    protected static org.verapdf.model.baselayer.Object actual;

    protected static String expectedType;
    protected static String expectedID;

    @Test
    public void testTypeAndID() {
        Assert.assertEquals(expectedType, actual.getType());
        Assert.assertEquals(expectedID, actual.getID());
    }

	@Test
	public void testLinksMethod() {
		List<String> expectedLinks = ModelHelper.getListOfLinks(actual.getType());
		for (String link : expectedLinks) {
			Assert.assertNotNull(actual.getLinkedObjects(link));
		}
		expectedLinks.clear();
	}

	@Test(expected = IllegalAccessError.class)
	public void testNonexistentParentLink() {
		actual.getLinkedObjects("Wrong link.");
	}

	protected static String getSystemIndependentPath(String path) throws URISyntaxException {
		URL resourceUrl = ClassLoader.class.getResource(path);
		Path resourcePath = Paths.get(resourceUrl.toURI());
		return resourcePath.toString();
	}
}

Add new test for all classes


package protocolsupport.injector.pe;

import io.netty.channel.Channel;
import raknetserver.pipeline.raknet.RakNetPacketConnectionEstablishHandler.PingHandler;

public class PENetServerConstants {

	public static final PingHandler PING_HANDLER = new PingHandler() {
		@Override
		public String getServerInfo(Channel channel) {
			//TODO: fake pspe packets for ping passthrough
			return String.join(";",
				"MCPE",
				"ProtocolSupportBungeePE",
				String.valueOf(CURRENT_PROTOCOL), POCKET_VERSION,
				"0", "1"
			);
		}
		@Override
		public void executeHandler(Runnable runnable) {
			runnable.run();
		}
	};

	public static final int USER_PACKET_ID = 0xFE;
	public static final int TEST_PORT = 2222;
	public static final int CURRENT_PROTOCOL = 141;
	public static final String POCKET_VERSION = "1.2.5.15";

}

package protocolsupport.injector.pe;

import io.netty.channel.Channel;
import protocolsupport.api.ProtocolVersion;
import raknetserver.pipeline.raknet.RakNetPacketConnectionEstablishHandler.PingHandler;

public class PENetServerConstants {

	public static final PingHandler PING_HANDLER = new PingHandler() {
		@Override
		public String getServerInfo(Channel channel) {
			//TODO: fake pspe packets for ping passthrough
			return String.join(";",
				"MCPE",
				"ProtocolSupportBungeePE",
				String.valueOf(ProtocolVersion.MINECRAFT_PE.getId()), POCKET_VERSION,
				"0", "1"
			);
		}
		@Override
		public void executeHandler(Runnable runnable) {
			runnable.run();
		}
	};

	public static final int USER_PACKET_ID = 0xFE;
	public static final String POCKET_VERSION = "1.2.6";

}

Update pe net server constants


package com.clxcommunications.xms;

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

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.Test;

public class ApiErrorTest {

	private final ApiObjectMapper json = new ApiObjectMapper();

	@Test
	public void canSerializeJson() throws Exception {
		String code = RandomStringUtils.randomPrint(1, 20);
		String text = RandomStringUtils.randomPrint(1, 20);
		ApiError input = ImmutableApiError.of(code, text);

		String expected = Utils.join("\n",
		        "{",
		        "  \"code\" : \"" + StringEscapeUtils.escapeJson(code) + "\",",
		        "  \"text\" : \"" + StringEscapeUtils.escapeJson(text) + "\"",
		        "}");

		String actual = json.writeValueAsString(input);

		assertThat(actual, is(TestUtils.jsonEqualTo(expected)));
	}

	@Test
	public void canDeserializeJson() throws Exception {
		String code = RandomStringUtils.randomPrint(1, 20);
		String text = RandomStringUtils.randomPrint(1, 20);
		ApiError expected = ImmutableApiError.of(code, text);

		String input = json.writeValueAsString(expected);

		ApiError actual = json.readValue(input, ApiError.class);

		assertThat(actual, is(expected));
	}

}

package com.clxcommunications.xms;

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

import org.apache.commons.lang3.StringEscapeUtils;
import org.junit.runner.RunWith;

import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.runner.JUnitQuickcheck;

@RunWith(JUnitQuickcheck.class)
public class ApiErrorTest {

	private final ApiObjectMapper json = new ApiObjectMapper();

	@Property
	public void canSerializeJson(String code, String text) throws Exception {
		ApiError input = ImmutableApiError.of(code, text);

		String expected = Utils.join("\n",
		        "{",
		        "  \"code\" : \"" + StringEscapeUtils.escapeJson(code) + "\",",
		        "  \"text\" : \"" + StringEscapeUtils.escapeJson(text) + "\"",
		        "}");

		String actual = json.writeValueAsString(input);

		assertThat(actual, is(TestUtils.jsonEqualTo(expected)));
	}

	@Property
	public void canDeserializeJson(String code, String text) throws Exception {
		ApiError expected = ImmutableApiError.of(code, text);

		String input = json.writeValueAsString(expected);

		ApiError actual = json.readValue(input, ApiError.class);

		assertThat(actual, is(expected));
	}

}

Use JUnit QuickCheck in ApiError test


package org.apache.logging.log4j.core.lookup;

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.core.config.plugins.Plugin;

/**
 * Maps JVM input arguments (but not main arguments) using JMX to acquire JVM arguments.
 *
 * @see java.lang.management.RuntimeMXBean#getInputArguments()
 * @since 2.1
 */
@Plugin(name = "jvmrunargs", category = "Lookup")
public class JmxRuntimeInputArgumentsLookup extends MapLookup {

    static {
        List<String> argsList = ManagementFactory.getRuntimeMXBean().getInputArguments();
        JMX_SINGLETON = new JmxRuntimeInputArgumentsLookup(MapLookup.toMap(argsList));
    }

    public static final JmxRuntimeInputArgumentsLookup JMX_SINGLETON;

    public JmxRuntimeInputArgumentsLookup(Map<String, String> map) {
        super(map);
    }

}

package org.apache.logging.log4j.core.lookup;

import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.core.config.plugins.Plugin;

/**
 * Maps JVM input arguments (but not main arguments) using JMX to acquire JVM arguments.
 *
 * @see java.lang.management.RuntimeMXBean#getInputArguments()
 * @since 2.1
 */
@Plugin(name = "jvmrunargs", category = "Lookup")
public class JmxRuntimeInputArgumentsLookup extends MapLookup {

    static {
        List<String> argsList = ManagementFactory.getRuntimeMXBean().getInputArguments();
        JMX_SINGLETON = new JmxRuntimeInputArgumentsLookup(MapLookup.toMap(argsList));
    }

    public static final JmxRuntimeInputArgumentsLookup JMX_SINGLETON;

    /**
     * Constructor when used directly as a plugin.
     */
    public JmxRuntimeInputArgumentsLookup() {
        super();
    }

    public JmxRuntimeInputArgumentsLookup(Map<String, String> map) {
        super(map);
    }

}

Add lookup for JVM arguments. Add missing ctor.


/*
 * Copyright 2013 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 com.gopivotal.cloudfoundry.test.buildpack;

import com.gopivotal.cloudfoundry.test.support.runner.ExcludedApplications;
import com.gopivotal.cloudfoundry.test.support.service.ServicesHolder;
import org.springframework.beans.factory.annotation.Autowired;

@ExcludedApplications({"grails", "groovy", "java-main", "java-main-with-web-inf", "spring-boot-cli", "web", "play"})
public abstract class AbstractAutoReconfigurationTest extends AbstractTest {

    @Autowired
    protected volatile ServicesHolder servicesHolder;

}

/*
 * Copyright 2013 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 com.gopivotal.cloudfoundry.test.buildpack;

import com.gopivotal.cloudfoundry.test.support.runner.ExcludedApplications;
import com.gopivotal.cloudfoundry.test.support.service.ServicesHolder;
import org.springframework.beans.factory.annotation.Autowired;

@ExcludedApplications({"groovy", "java-main", "java-main-with-web-inf", "spring-boot-cli", "web", "play"})
public abstract class AbstractAutoReconfigurationTest extends AbstractTest {

    @Autowired
    protected volatile ServicesHolder servicesHolder;

}

Test grails app with all non-relational services


/**
 *
 * Copyright © 2014-2015 Florian Schmaus
 *
 * 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.jxmpp.stringprep;

public class XmppStringprepException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = -8491853210107124624L;

	private final String causingString;

	public XmppStringprepException(String causingString, Exception exception) {
		super("XmppStringprepException caused by '" + causingString + "': " + exception, exception);
		this.causingString = causingString;
	}

	public XmppStringprepException(String causingString, String message) {
		super(message);
		this.causingString = causingString;
	}

	public String getCausingString() {
		return causingString;
	}
}

/**
 *
 * Copyright © 2014-2015 Florian Schmaus
 *
 * 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.jxmpp.stringprep;

import java.io.IOException;

public class XmppStringprepException extends IOException {

	/**
	 *
	 */
	private static final long serialVersionUID = -8491853210107124624L;

	private final String causingString;

	public XmppStringprepException(String causingString, Exception exception) {
		super("XmppStringprepException caused by '" + causingString + "': " + exception);
		initCause(exception);
		this.causingString = causingString;
	}

	public XmppStringprepException(String causingString, String message) {
		super(message);
		this.causingString = causingString;
	}

	public String getCausingString() {
		return causingString;
	}
}

Make stringprep exception extend IOException


package net.md_5.bungee.event;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeUtils {
    private UnsafeUtils() {}

    private static final Unsafe UNSAFE;
    static {
        Unsafe unsafe;
        try {
            Class c = Class.forName("sun.misc.Unsafe");
            Field f = c.getField("theUnsafe");
            f.setAccessible(true);
            unsafe = (Unsafe) f.get(null);
        } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
            unsafe = null;
        } catch (IllegalAccessException e) {
            throw new AssertionError(e);
        }
        UNSAFE = unsafe;
    }

    public static boolean isUnsafeSupported() {
        return UNSAFE != null;
    }

    public static Unsafe getUnsafe() {
        return UNSAFE;
    }
}

package net.md_5.bungee.event;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class UnsafeUtils {
    private UnsafeUtils() {}

    private static final Unsafe UNSAFE;
    static {
        Unsafe unsafe;
        try {
            Class c = Class.forName("sun.misc.Unsafe");
            Field f = c.getDeclaredField("theUnsafe");
            f.setAccessible(true);
            unsafe = (Unsafe) f.get(null);
        } catch (ClassNotFoundException | NoSuchFieldException | SecurityException e) {
            unsafe = null;
        } catch (IllegalAccessException e) {
            throw new AssertionError(e);
        }
        UNSAFE = unsafe;
    }

    public static boolean isUnsafeSupported() {
        return UNSAFE != null;
    }

    public static Unsafe getUnsafe() {
        return UNSAFE;
    }
}

Use getDeclaredField to access Unsafe


package com.jaku.core;

public enum KeypressKeyValues {
	HOME("Home"),
	REV("Rev"),
	FWD("Fwd"),
	PLAY("Play"),
	SELECT("Select"),
	LEFT("Left"),
	RIGHT("Right"),
	DOWN("Down"),
	UP("Up"),
	BACK("Back"),
	INTANT_REPLAY("IntantReplay"),
	INFO("Info"),
	BACKSPACE("Backspace"),
	SEARCH("Search"),
	ENTER("Enter"),
	FIND_REMOTE("FindRemote"),
	VOLUME_DOWN("VolumeDown"),
	VOLUME_MUTE("VolumeMute"),
	VOLUME_UP("VolumeUp"),
	POWER_OFF("PowerOff"),
	POWER_ON("PowerOn"),
	CHANNELUP("ChannelUp"),
	CHANNELDOWN("ChannelDown"),
	INPUTTUNER("InputTuner"),
	INPUTHDMI1("InputHDMI1"),
	INPUTHDMI2("InputHDMI2"),
	INPUTHDMI3("InputHDMI3"),
	INPUTHDMI4("InputHDMI4"),
	INPUTAV1("InputAV1"),
	LIT_("Lit_");

	private final String method;

	KeypressKeyValues(String method) {
		this.method = method;
	}

	public String getValue() {
		return method;
	}
}

package com.jaku.core;

public enum KeypressKeyValues {
	HOME("Home"),
	REV("Rev"),
	FWD("Fwd"),
	PLAY("Play"),
	SELECT("Select"),
	LEFT("Left"),
	RIGHT("Right"),
	DOWN("Down"),
	UP("Up"),
	BACK("Back"),
	INTANT_REPLAY("InstantReplay"),
	INFO("Info"),
	BACKSPACE("Backspace"),
	SEARCH("Search"),
	ENTER("Enter"),
	FIND_REMOTE("FindRemote"),
	VOLUME_DOWN("VolumeDown"),
	VOLUME_MUTE("VolumeMute"),
	VOLUME_UP("VolumeUp"),
	POWER_OFF("PowerOff"),
	POWER_ON("PowerOn"),
	CHANNELUP("ChannelUp"),
	CHANNELDOWN("ChannelDown"),
	INPUTTUNER("InputTuner"),
	INPUTHDMI1("InputHDMI1"),
	INPUTHDMI2("InputHDMI2"),
	INPUTHDMI3("InputHDMI3"),
	INPUTHDMI4("InputHDMI4"),
	INPUTAV1("InputAV1"),
	LIT_("Lit_");

	private final String method;

	KeypressKeyValues(String method) {
		this.method = method;
	}

	public String getValue() {
		return method;
	}
}

Fix typo in instant replay kepress enum value


import java.io.IOException;
import java.net.*;

public class ServerResponse {

	public static void response(URL url) throws IOException {

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	}

}

package com.complet;

import java.io.IOException;
import java.net.*;

public class ServerResponse {

	public static void response(URL url) throws IOException {

		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		try {

			connection.connect();

		} catch (Exception exp) {

		    System.err.println(exp.getMessage());

		}
	}

}

Call the connect method -of HttpUrlConnection Class- to initiate the connection, catch exceptions, define the package