package info.u_team.u_team_test.tileentity;

import info.u_team.u_team_core.tileentity.UTickableTileEntity;
import info.u_team.u_team_test.init.TestTileEntityTypes;

public class BasicFluidInventoryTileEntity extends UTickableTileEntity {

	public BasicFluidInventoryTileEntity() {
		super(TestTileEntityTypes.BASIC_FLUID_INVENTORY);
	}

}

package info.u_team.u_team_test.tileentity;

import info.u_team.u_team_core.inventory.*;
import info.u_team.u_team_core.tileentity.UTickableTileEntity;
import info.u_team.u_team_test.init.TestTileEntityTypes;
import net.minecraft.nbt.CompoundNBT;
import net.minecraftforge.common.util.LazyOptional;

public class BasicFluidInventoryTileEntity extends UTickableTileEntity {

	protected final UItemStackHandler itemSlots;
	protected final LazyOptional<UItemStackHandler> itemSlotsOptional;

	protected final UFluidStackHandler fluidTanks;
	protected final LazyOptional<UFluidStackHandler> fluidTanksOptional;

	public BasicFluidInventoryTileEntity() {
		super(TestTileEntityTypes.BASIC_FLUID_INVENTORY);

		itemSlots = new TileEntityUItemStackHandler(4, this);
		itemSlotsOptional = LazyOptional.of(() -> itemSlots);

		fluidTanks = new UFluidStackHandler(4); // TODO tile entity u fluid stack handler
		fluidTanksOptional = LazyOptional.of(() -> fluidTanks);
	}

	@Override
	public void writeNBT(CompoundNBT compound) {
		super.writeNBT(compound);
		compound.put("items", itemSlots.serializeNBT());
		compound.put("fluids", fluidTanks.serializeNBT());
	}

	@Override
	public void readNBT(CompoundNBT compound) {
		super.readNBT(compound);
		itemSlots.deserializeNBT(compound.getCompound("items"));
		fluidTanks.deserializeNBT(compound.getCompound("fluids"));
	}

	@Override
	public void remove() {
		super.remove();
		itemSlotsOptional.invalidate();
		fluidTanksOptional.invalidate();
	}

	public UItemStackHandler getItemSlots() {
		return itemSlots;
	}

	public UFluidStackHandler getFluidTanks() {
		return fluidTanks;
	}

}

Add basic item slots and fluid tanks to the basic fluid inventory te


package org.kepennar.aproc.complicatebusiness;

import static java.util.stream.Collectors.toList;

import java.util.List;

import javax.inject.Inject;

import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ComplicateBusinessService {

	private final TaskRepository taskRepository;

	@Inject
	public ComplicateBusinessService(TaskRepository taskRepository) {
		this.taskRepository = taskRepository;
	}

	public List<Task> getAllTransformedTasks() {
		return taskRepository.findAll().parallelStream()
			.map(t -> {
				return new Task(sort(t.getName()), sort(t.getDescription()));
			})
			.collect(toList());

	}

	private final static String sort(String word) {
		return String.join("",
				StringUtils.sortStringArray(word.split(""))
				);
	}

}

package org.kepennar.aproc.complicatebusiness;

import static java.util.Comparator.naturalOrder;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

import java.util.List;
import java.util.stream.Stream;

import javax.inject.Inject;

import org.kepennar.aproc.tasks.Task;
import org.kepennar.aproc.tasks.TaskRepository;
import org.springframework.stereotype.Service;

@Service
public class ComplicateBusinessService {

	private final TaskRepository taskRepository;

	@Inject
	public ComplicateBusinessService(TaskRepository taskRepository) {
		this.taskRepository = taskRepository;
	}

	public List<Task> getAllTransformedTasks() {
		return taskRepository.findAll().parallelStream()
			.map(t -> {
				return new Task(sort2(t.getName()), sort2(t.getDescription()));
			})
			.collect(toList());

	}
	private final static String sort2(String word) {
		return Stream.of(word.split(""))
				.sorted(naturalOrder())
				.collect(joining());

	}

}

Use Stream instead of StringUtils


/*
 * *
 *  * This file is part of whereisthat-android
 *  *
 *  * Unless otherwise stated in a separate LICENSE file for this project
 *  * or agreed via contract, all rights reserved by the author.
 *
 */

package com.michael_kuck.android.mkcommons;

import android.os.AsyncTask;

public class Dispatch {

    // TODO: Important, verify this is correct AsyncTask usage!
    public static void toBackground(final Runnable backgroundTask, final Runnable completionTask) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(final Void... params) {
                backgroundTask.run();
                return null;
            }

            @Override
            protected void onPostExecute(final Void aVoid) {
                completionTask.run();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
    }

}

/*
 * *
 *  * This file is part of whereisthat-android
 *  *
 *  * Unless otherwise stated in a separate LICENSE file for this project
 *  * or agreed via contract, all rights reserved by the author.
 *
 */

package com.michael_kuck.android.mkcommons;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;

public class Dispatch {

    // TODO: Important, verify this is correct AsyncTask usage!
    public static void toBackground(final Runnable backgroundTask, final Runnable completionTask) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(final Void... params) {
                backgroundTask.run();
                return null;
            }

            @Override
            protected void onPostExecute(final Void aVoid) {
                if (completionTask != null) {
                    completionTask.run();
                }
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, null);
    }

    public static void toMainThread(final Runnable completion) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (completion != null) {
                    completion.run();
                }
            }
        });
    }

}

Add convenience method for running tasks on main thread


package com.wavefront.agent;

import org.jboss.resteasy.resteasy_jaxrs.i18n.LogMessages;

import java.io.IOException;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;

/**
 * This RESTEasy interceptor allows disabling GZIP compression even for methods annotated with @GZIP by removing the
 * Content-Encoding header.
 * RESTEasy always adds "Content-Encoding: gzip" header when it encounters @GZIP annotation, but if the request body
 * is actually sent uncompressed, it violates section 3.1.2.2 of RFC7231.
 *
 * Created by vasily@wavefront.com on 6/9/17.
 */
public class DisableGZIPEncodingInterceptor implements WriterInterceptor {
    public DisableGZIPEncodingInterceptor() {
    }

    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
      LogMessages.LOGGER.debugf("Interceptor : %s,  Method : aroundWriteTo", this.getClass().getName());
      Object encoding = context.getHeaders().getFirst("Content-Encoding");
      if(encoding != null && encoding.toString().equalsIgnoreCase("gzip")) {
        context.getHeaders().remove("Content-Encoding");
      }
      context.proceed();
    }
  }

package com.wavefront.agent;

import java.io.IOException;
import java.util.logging.Logger;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;

/**
 * This RESTEasy interceptor allows disabling GZIP compression even for methods annotated with @GZIP by removing the
 * Content-Encoding header.
 * RESTEasy always adds "Content-Encoding: gzip" header when it encounters @GZIP annotation, but if the request body
 * is actually sent uncompressed, it violates section 3.1.2.2 of RFC7231.
 *
 * Created by vasily@wavefront.com on 6/9/17.
 */
public class DisableGZIPEncodingInterceptor implements WriterInterceptor {
  private static final Logger logger = Logger.getLogger(DisableGZIPEncodingInterceptor.class.getCanonicalName());

  public DisableGZIPEncodingInterceptor() {
  }

  public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
    logger.fine("Interceptor : " + this.getClass().getName() + ",  Method : aroundWriteTo");
    Object encoding = context.getHeaders().getFirst("Content-Encoding");
    if (encoding != null && encoding.toString().equalsIgnoreCase("gzip")) {
      context.getHeaders().remove("Content-Encoding");
    }
    context.proceed();
  }
}

Use proxy logger + fix formatting


package org.mutabilitydetector;

/*
 * #%L
 * MutabilityDetector
 * %%
 * Copyright (C) 2008 - 2015 Graham Allan
 * %%
 * 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.
 * #L%
 */

import org.junit.Test;
import org.mutabilitydetector.classpath.ClassPathScanner;

import java.util.Set;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;

public class ClassPathScannerTest {

    @Test
    public void scanClassPath() throws Exception {
        Set<Class<?>> immutableClasses = ClassPathScanner.findImmutableClasses("org.mutabilitydetector");

        assertThat(immutableClasses, notNullValue());
        assertThat(immutableClasses.size() > 0, is(true));
    }
}

package org.mutabilitydetector;

/*
 * #%L
 * MutabilityDetector
 * %%
 * Copyright (C) 2008 - 2015 Graham Allan
 * %%
 * 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.
 * #L%
 */

import org.junit.Test;
import org.mutabilitydetector.benchmarks.ImmutableExample;
import org.mutabilitydetector.benchmarks.settermethod.MutableByHavingSetterMethod;
import org.mutabilitydetector.classpath.ClassPathScanner;

import java.util.Set;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;

public class ClassPathScannerTest {

    @Test
    public void scanClassPath() throws Exception {
        Set<Class<?>> immutableClasses = ClassPathScanner.findImmutableClasses("org.mutabilitydetector");

        assertThat(immutableClasses, hasItem(ImmutableExample.class));
        assertThat(immutableClasses, not(hasItem(MutableByHavingSetterMethod.class)));
    }
}

Strengthen the unit test for ClassPathScanner.


package org.kohsuke.github;

import java.io.IOException;
import java.net.URL;

/**
 * A discussion in GitHub Team.
 *
 * @author Charles Moulliard
 * @see GitHub Team Discussions
 */
public class GHDiscussion extends GHObject {

    @JacksonInject
    private GitHub root;
    private GHOrganization organization;
    private GHTeam team;
    private String body, title, htmlUrl;

    @Override
    public URL getHtmlUrl() throws IOException {
        return GitHubClient.parseURL(html_url);
    }

    public GHDiscussion wrapUp(GHTeam team) throws IOException {
        this.organization = team.getOrganization();
        this.team = team;
        return this;
    }

    public GHDiscussion wrapUp(GitHub root) {
        this.root = root;
        return this;
    }

    public GHDiscussion wrapUp(GHOrganization owner) {
        this.organization = owner;
        return this;
    }

    /**
     * Get the title of the discussion.
     *
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * The description of this discussion.
     *
     * @return the body
     */
    public String getBody() {
        return body;
    }
}

package org.kohsuke.github;

import com.fasterxml.jackson.annotation.JacksonInject;

import java.io.IOException;
import java.net.URL;

/**
 * A discussion in GitHub Team.
 *
 * @author Charles Moulliard
 * @see GitHub Team Discussions
 */
public class GHDiscussion extends GHObject {

    @JacksonInject
    private GitHub root;
    private GHOrganization organization;
    private GHTeam team;
    private String body, title, htmlUrl;

    @Override
    public URL getHtmlUrl() throws IOException {
        return GitHubClient.parseURL(htmlUrl);
    }

    public GHDiscussion wrapUp(GHTeam team) throws IOException {
        this.organization = team.getOrganization();
        this.team = team;
        return this;
    }

    public GHDiscussion wrapUp(GitHub root) {
        this.root = root;
        return this;
    }

    public GHDiscussion wrapUp(GHOrganization owner) {
        this.organization = owner;
        return this;
    }

    /**
     * Get the title of the discussion.
     *
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * The description of this discussion.
     *
     * @return the body
     */
    public String getBody() {
        return body;
    }
}

Add missing import statement for the Jackson Annotation. Use the correct htmlUrl field


package seedu.utask.model.task;

import seedu.address.commons.exceptions.IllegalValueException;

/**
 * Represents a Person's phone number in the address book.
 * Guarantees: immutable; is valid as declared in {@link #isValidDeadline(String)}
 */
public class Deadline {

    public static final String MESSAGE_DEADLINE_CONSTRAINTS = "Deadline for tasks should in format DDMMYY";
    public static final String DEADLINE_VALIDATION_REGEX = "\\d+";

    public final String value;

    /**
     * Validates given deadline.
     *
     * @throws IllegalValueException if given phone string is invalid.
     */
    public Deadline(String deadline) throws IllegalValueException {
        assert deadline != null;
        String trimmedDeadline = deadline.trim();
        if (!isValidDeadline(trimmedDeadline)) {
            throw new IllegalValueException(MESSAGE_DEADLINE_CONSTRAINTS);
        }
        this.value = trimmedDeadline;
    }

    /**
     * Returns true if a given string is a valid task deadline.
     */
    public static boolean isValidDeadline(String test) {
        return test.matches(DEADLINE_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Deadline // instanceof handles nulls
                && this.value.equals(((Deadline) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

}

package seedu.utask.model.task;

import seedu.address.commons.exceptions.IllegalValueException;

/**
 * Represents a Person's phone number in the address book.
 * Guarantees: immutable; is valid as declared in {@link #isValidDeadline(String)}
 */
public class Deadline {

    public static final String MESSAGE_DEADLINE_CONSTRAINTS = "Deadline for tasks should in format DDMMYY";
    public static final String DEADLINE_VALIDATION_REGEX = "^(0[1-9]|[1-2][0-9]|"
            + "31(?!(?:0[2469]|11))|30(?!02))(0[1-9]|1[0-2])([1]\\d{1})";

    public final String value;

    /**
     * Validates given deadline.
     *
     * @throws IllegalValueException if given phone string is invalid.
     */
    public Deadline(String deadline) throws IllegalValueException {
        assert deadline != null;
        String trimmedDeadline = deadline.trim();
        if (!isValidDeadline(trimmedDeadline)) {
            throw new IllegalValueException(MESSAGE_DEADLINE_CONSTRAINTS);
        }
        this.value = trimmedDeadline;
    }

    /**
     * Returns true if a given string is a valid task deadline.
     */
    public static boolean isValidDeadline(String test) {
        return test.matches(DEADLINE_VALIDATION_REGEX);
    }

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

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof Deadline // instanceof handles nulls
                && this.value.equals(((Deadline) other).value)); // state check
    }

    @Override
    public int hashCode() {
        return value.hashCode();
    }

}

Use stricter regex to validate date in DDMMYY


package org.cryptomator.cryptofs.health.dirid;

import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;

import java.io.IOException;
import java.nio.file.Path;

/**
 * TODO: adjust DirIdCheck
 */
public class MissingDirIdBackup implements DiagnosticResult {

	private final Path cipherDir;
	private final String dirId;

	MissingDirIdBackup(String dirId, Path cipherDir)  {
		this.cipherDir = cipherDir;
		this.dirId = dirId;
	}

	@Override
	public Severity getSeverity() {
		return Severity.WARN; //TODO: decide severity
	}

	@Override
	public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
		DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
		dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId,cipherDir));
	}
}

package org.cryptomator.cryptofs.health.dirid;

import org.cryptomator.cryptofs.CryptoPathMapper;
import org.cryptomator.cryptofs.DirectoryIdBackup;
import org.cryptomator.cryptofs.VaultConfig;
import org.cryptomator.cryptofs.health.api.DiagnosticResult;
import org.cryptomator.cryptolib.api.Cryptor;
import org.cryptomator.cryptolib.api.Masterkey;

import java.io.IOException;
import java.nio.file.Path;

/**
 * The dir id backup file is missing.
 */
public record MissingDirIdBackup(String dirId, Path cipherDir) implements DiagnosticResult {

	@Override
	public Severity getSeverity() {
		return Severity.WARN;
	}

	@Override
	public String toString() {
		return String.format("Directory ID backup for directory %s is missing.", cipherDir);
	}

	@Override
	public void fix(Path pathToVault, VaultConfig config, Masterkey masterkey, Cryptor cryptor) throws IOException {
		DirectoryIdBackup dirIdBackup = new DirectoryIdBackup(cryptor);
		dirIdBackup.execute(new CryptoPathMapper.CiphertextDirectory(dirId, cipherDir));
	}
}

Refactor to record and add docs.


package com.foc.desc.parsers.predefinedFields;

import java.util.HashMap;

public class FocPredefinedFieldFactory {

	private HashMap<String, IFocPredefinedFieldType> map = null;

	private FocPredefinedFieldFactory(){
		map = new HashMap<String, IFocPredefinedFieldType>();

		put(new FTypeCODE());
		put(new FTypeNAME());
		put(new FTypeEXTERNAL_CODE());
		put(new FTypeDESCRIPTION());
		put(new FTypeCOMPANY());
		put(new FTypeDATE());
		put(new FTypeORDER());
		put(new FTypeNOT_COMPLETED_YET());
		put(new FTypeDEPRECATED());
		put(new FTypeIS_SYSTEM());
	}

	public void put(IFocPredefinedFieldType type) {
		map.put(type.getTypeName(), type);
	}

	public IFocPredefinedFieldType get(String typeName) {
		return map != null ? map.get(typeName) : null;
	}

	private static FocPredefinedFieldFactory instance = null;
	public static FocPredefinedFieldFactory getInstance(){
		if(instance == null){
			instance = new FocPredefinedFieldFactory();
		}
		return instance;
	};

}

package com.foc.desc.parsers.predefinedFields;

import java.util.HashMap;

public class FocPredefinedFieldFactory {

	private HashMap<String, IFocPredefinedFieldType> map = null;

	private FocPredefinedFieldFactory(){
		map = new HashMap<String, IFocPredefinedFieldType>();

		put(new FTypeCODE());
		put(new FTypeNAME());
		put(new FTypeEXTERNAL_CODE());
		put(new FTypeDESCRIPTION());
		put(new FTypeCOMPANY());
		put(new FTypeSITE());
		put(new FTypeDATE());
		put(new FTypeORDER());
		put(new FTypeNOT_COMPLETED_YET());
		put(new FTypeDEPRECATED());
		put(new FTypeIS_SYSTEM());
	}

	public void put(IFocPredefinedFieldType type) {
		map.put(type.getTypeName(), type);
	}

	public IFocPredefinedFieldType get(String typeName) {
		return map != null ? map.get(typeName) : null;
	}

	private static FocPredefinedFieldFactory instance = null;
	public static FocPredefinedFieldFactory getInstance(){
		if(instance == null){
			instance = new FocPredefinedFieldFactory();
		}
		return instance;
	};

}

Add the FocSITE annotation in the predefined fields factory


package alluxio.master.audit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public final class AsyncUserAccessAuditLogWriter {
  private static final int QUEUE_SIZE = 10000;
  private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
  private boolean mEnabled;
  private ArrayBlockingQueue<AuditContext> mAuditLogEntries;

  public AsyncUserAccessAuditLogWriter() {
    mEnabled = true;
    mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
  }

  public boolean isEnabled() { return mEnabled; }

  public boolean append(AuditContext context) {
    try {
      mAuditLogEntries.put(context);
    } catch (InterruptedException e) {
      // Reset the interrupted flag and return because some other thread has
      // told us not to wait any more.
      Thread.currentThread().interrupt();
      return false;
    }
    return true;
  }

  public void commit(AuditContext context) {
    synchronized (context) {
      context.setCommitted(true);
      context.notify();
    }

    AuditContext headContext = mAuditLogEntries.poll();
    if (headContext == null) { return; }
    synchronized (headContext) {
      while (!headContext.isCommitted()) {
        try {
          headContext.wait();
        } catch (InterruptedException e) {
          // TODO
          return;
        }
      }
    }
    LOG.info(headContext.toString());
  }
}

package alluxio.master.audit;

import alluxio.Configuration;
import alluxio.PropertyKey;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import javax.annotation.concurrent.ThreadSafe;

@ThreadSafe
public final class AsyncUserAccessAuditLogWriter {
  private static final int QUEUE_SIZE = 10000;
  private static final Logger LOG = LoggerFactory.getLogger(AsyncUserAccessAuditLogWriter.class);
  private boolean mEnabled;
  private ArrayBlockingQueue<AuditContext> mAuditLogEntries;

  public AsyncUserAccessAuditLogWriter() {
    mEnabled = Boolean.parseBoolean(Configuration.get(PropertyKey.MASTER_AUDIT_LOGGING_ENABLED));
    mAuditLogEntries = new ArrayBlockingQueue<>(QUEUE_SIZE);
  }

  public boolean isEnabled() { return mEnabled; }

  public boolean append(AuditContext context) {
    try {
      mAuditLogEntries.put(context);
    } catch (InterruptedException e) {
      // Reset the interrupted flag and return because some other thread has
      // told us not to wait any more.
      Thread.currentThread().interrupt();
      return false;
    }
    return true;
  }

  public void commit(AuditContext context) {
    synchronized (context) {
      context.setCommitted(true);
      context.notify();
    }

    AuditContext headContext = mAuditLogEntries.poll();
    if (headContext == null) { return; }
    synchronized (headContext) {
      while (!headContext.isCommitted()) {
        try {
          headContext.wait();
        } catch (InterruptedException e) {
          // TODO
          return;
        }
      }
    }
    LOG.info(headContext.toString());
  }
}

Set mEnabled using site property.


/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.livedata;

import com.opengamma.engine.value.ValueRequirement;

/**
 *
 */
public interface LiveDataSnapshotListener {

  /**
   *
   * @param requirement Not null
   */
  void subscriptionSucceeded(ValueRequirement requirement);

  /**
   *
   * @param requirement Not null
   * @param msg Not null
   */
  void subscriptionFailed(ValueRequirement requirement, String msg);

  /**
   * @param requirement Not null
   */
  void subscriptionStopped(ValueRequirement requirement);

  /**
   * @param requirement Not null
   */
  void valueChanged(ValueRequirement requirement);

}

/**
 * Copyright (C) 2009 - 2010 by OpenGamma Inc.
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.livedata;

import com.opengamma.engine.value.ValueRequirement;

/**
 *
 */
public interface LiveDataSnapshotListener {

  /**
   *
   * @param requirement Not null
   */
  void subscriptionSucceeded(ValueRequirement requirement);

  /**
   *
   * @param requirement Not null
   * @param msg Not null
   */
  void subscriptionFailed(ValueRequirement requirement, String msg);

  /**
   * @param requirement Not null
   */
  void subscriptionStopped(ValueRequirement requirement);

  /**
   * Important implementation note to listener implementors:
   * THIS METHOD MUST EXECUTE QUICKLY. The way the Live Data Client works,
   * several market data lines may be handled by the same Live Data Client
   * thread. If the execution of this method is slow, for example
   * because it uses external resources such as files or the network
   * in some way, or executes a complicated algorithm, then
   * market data updates for OTHER market data lines will not received
   * until this method returns. Thus, if you need to execute a
   * non-trivial operation when you receive new market data,
   * do it in a new thread.

   * @param requirement Not null
   */
  void valueChanged(ValueRequirement requirement);

}

Reduce number of threads created by JmsLiveDataClient


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Metrics used for autoscaling
 *
 * @author bratseth
 */
public class AutoscalingMetrics {

    public static final MetricSet autoscalingMetricSet = create();

    private static MetricSet create() {
        return new MetricSet("autoscaling",
                             metrics("cpu.util",
                                     "mem.util",
                                     "disk.util",
                                     "application_generation",
                                     "in_service"));
    }

    private static Set<Metric> metrics(String ... metrics) {
        return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet());
    }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Metrics used for autoscaling
 *
 * @author bratseth
 */
public class AutoscalingMetrics {

    public static final MetricSet autoscalingMetricSet = create();

    private static MetricSet create() {
        return new MetricSet("autoscaling",
                             metrics("cpu.util",
                                     "mem.util",
                                     "disk.util",
                                     "application_generation",
                                     "in_service",
                                     "queries.rate"));
    }

    private static Set<Metric> metrics(String ... metrics) {
        return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet());
    }

}

Add queries.rate to the 'autoscaling' consumer.


package com.pm.server;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PmServerApplication.class)
@WebAppConfiguration
public class PmServerApplicationTests {

	@Test
	public void contextLoads() {
	}

}

package com.pm.server;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = PmServerApplication.class)
@ComponentScan("com.pm.server")
@WebAppConfiguration
public class PmServerApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Add @ComponentScan to tests main class


package de.otto.jlineup.web;

import de.otto.jlineup.JLineup;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class JLineupService {

    public String startRun(String config) {
        return String.valueOf(UUID.randomUUID());
    }

}

Use RunOptions instead of CommandLineParameters in core


package com.nmakademija.nmaakademija.entity;

import java.util.List;

public class Event {

    private int id;
    private String name;

    private long startTime;

    private long endTime;

    private List<Integer> lecturers;
    private int section;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public long getStartTime() {
        return startTime;
    }

    public long getEndTime() {
        return endTime;
    }

    public List<Integer> getLecturer() {
        return lecturers;
    }

    public int getSection() {
        return section;
    }

}

package com.nmakademija.nmaakademija.entity;

import java.util.Date;
import java.util.List;

public class Event {

    private int id;
    private String name;

    private Date startTime;
    private Date endTime;

    private List<Integer> lecturers;
    private int section;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public Date getStartTime() {
        return startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public List<Integer> getLecturer() {
        return lecturers;
    }

    public int getSection() {
        return section;
    }

}

Change event startTime, endTime to Date


package com.probossgamers.turtlemod.items;

import com.probossgamers.turtlemod.TurtleMain;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;

public class ItemModFood extends ItemFood
{

	private PotionEffect[] effects;

	 public ItemModFood(String unlocalizedName, int amount, float saturation, boolean isWolfFood, PotionEffect... effects) {
	        super(amount, saturation, isWolfFood);
	        this.setUnlocalizedName(unlocalizedName);
	        this.setCreativeTab(TurtleMain.tabCustom);
	        this.effects = effects;
	    }

	 @Override
	 protected void onFoodEaten(ItemStack stack, World world, EntityPlayer player)
	 {
	     super.onFoodEaten(stack, world, player);

	     for (int i = 0; i < effects.length; i ++) {
	         effects[i].getPotion();
			if (!world.isRemote && effects[i] != null && Potion.getIdFromPotion(effects[i].getPotion()) > 0)
	             player.addPotionEffect(new PotionEffect(this.effects[i]));
	     }
	 }

}

package com.probossgamers.turtlemod.items;

import com.probossgamers.turtlemod.TurtleMain;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;

public class ItemModFood extends ItemFood
{

	private PotionEffect[] effects;

	 public ItemModFood(String unlocalizedName, int amount, float saturation, boolean isWolfFood, PotionEffect... effects) {
	        super(amount, saturation, isWolfFood);
	        this.setUnlocalizedName(unlocalizedName);
	        this.setCreativeTab(TurtleMain.tabCustom);
	        this.effects = effects;
	    }

	 @Override
	 protected void onFoodEaten(ItemStack stack, World world, EntityPlayer player)
	 {
	     super.onFoodEaten(stack, world, player);
	     if(!(effects == null))
         {
			 for (int i = 0; i < effects.length; i++)
			 {
				 effects[i].getPotion();
				 if (!world.isRemote && effects[i] != null && Potion.getIdFromPotion(effects[i].getPotion()) > 0)
				 {
					 player.addPotionEffect(new PotionEffect(this.effects[i]));
				 }
			 }
		 }
	 }

}

Check for null potion effects.


package org.synyx.urlaubsverwaltung.calendar;

import org.apache.commons.lang3.RandomStringUtils;
import org.hibernate.validator.constraints.Length;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;

@Entity
@Inheritance
abstract class Calendar {

    private static final int SECRET_LENGTH = 32;

    @Id
    @GeneratedValue
    private Long id;

    @Length(min = SECRET_LENGTH, max = SECRET_LENGTH)
    private String secret;

    public Calendar() {
        generateSecret();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSecret() {
        return secret;
    }

    public void generateSecret() {
        secret = RandomStringUtils.randomAlphanumeric(SECRET_LENGTH);
    }
}

package org.synyx.urlaubsverwaltung.calendar;

import org.apache.commons.lang3.RandomStringUtils;
import org.hibernate.validator.constraints.Length;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;

@Entity
@Inheritance
abstract class Calendar {

    private static final int SECRET_LENGTH = 32;

    @Id
    @GeneratedValue
    private Long id;

    @Length(min = SECRET_LENGTH, max = SECRET_LENGTH)
    private String secret;

    protected Calendar() {
        generateSecret();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getSecret() {
        return secret;
    }

    public void generateSecret() {
        secret = RandomStringUtils.randomAlphanumeric(SECRET_LENGTH);
    }
}

Change visibility of calendar entity constructor to protected


package nl.homesensors.sensortag;

import net.sf.expectit.Expect;
import net.sf.expectit.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static net.sf.expectit.matcher.Matchers.regexp;

abstract class AbstractSensor {

    private static final Logger LOG = LoggerFactory.getLogger(SensorTagReader.class);

    abstract void enableNotifications(Expect expect) throws IOException;

    abstract void enable(Expect expect) throws IOException;

    abstract void disable(Expect expect) throws IOException;

    String expectSuccessfulMatch(final Expect expect, final String regexp) throws IOException, SensortagException {
        final String value;
        final Result result = expect.withTimeout(25, TimeUnit.SECONDS).expect(regexp(regexp));
        if (result.isSuccessful()) {
            value = result.group(1);
        } else {
            throw new SensortagException("No match found for regexp [" + regexp + "] in [" + result.getInput() + "]");
        }
        return value;
    }

    void discardNotifications(final Expect expect, final String regexp) throws IOException {
        while(expect.withTimeout(20, TimeUnit.SECONDS).expect(regexp(regexp)).isSuccessful()) {
            LOG.debug("Discarding notification handle");
        }
    }

}

package nl.homesensors.sensortag;

import net.sf.expectit.Expect;
import net.sf.expectit.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

import static net.sf.expectit.matcher.Matchers.regexp;

abstract class AbstractSensor {

    private static final Logger LOG = LoggerFactory.getLogger(AbstractSensor.class);

    abstract void enableNotifications(Expect expect) throws IOException;

    abstract void enable(Expect expect) throws IOException;

    abstract void disable(Expect expect) throws IOException;

    String expectSuccessfulMatch(final Expect expect, final String regexp) throws IOException, SensortagException {
        final String value;
        final Result result = expect.withTimeout(25, TimeUnit.SECONDS).expect(regexp(regexp));
        if (result.isSuccessful()) {
            value = result.group(1);
        } else {
            throw new SensortagException("No match found for regexp [" + regexp + "] in [" + result.getInput() + "]");
        }
        return value;
    }

    void discardNotifications(final Expect expect, final String regexp) throws IOException {
        while(expect.withTimeout(20, TimeUnit.SECONDS).expect(regexp(regexp)).isSuccessful()) {
            LOG.debug("Discarding notification handle");
        }
    }

}

Use correct class for logger


/**
 * Copyright 2015 Red Hat, Inc, and individual contributors.
 *
 * 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.wildfly.swarm.plugin.maven;

import java.util.concurrent.TimeUnit;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.wildfly.swarm.tools.exec.SwarmProcess;

/**
 * @author Thomas Meyer
 */
@Mojo(name = "stop")
public class StopMojo extends AbstractMojo {

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        SwarmProcess process = (SwarmProcess) getPluginContext().get("swarm-process");
        if(process != null) {
            process.stop( 10, TimeUnit.SECONDS );
        }

    }
}

/**
 * Copyright 2015 Red Hat, Inc, and individual contributors.
 *
 * 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.wildfly.swarm.plugin.maven;

import java.util.concurrent.TimeUnit;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.wildfly.swarm.tools.exec.SwarmProcess;

/**
 * @author Thomas Meyer
 */
@Mojo(name = "stop")
public class StopMojo extends AbstractMojo {

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {
        SwarmProcess process = (SwarmProcess) getPluginContext().get("swarm-process");
        if(process != null) {
            try {
                process.stop( 10, TimeUnit.SECONDS );
            } catch (InterruptedException e) {
                throw new MojoFailureException( "unable to stop process", e);
            }
        }

    }
}

Throw interrupted exceptions from stop(). Make the arquillian container use the SwarmExector/SwarmProcess bits.


/*
 * 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.spark.sql.connector.read;

import org.apache.spark.annotation.Evolving;

/**
 * A mix in interface for {@link Scan}. Data sources can implement this interface to
 * report statistics to Spark.
 *
 * As of Spark 2.4, statistics are reported to the optimizer before any operator is pushed to the
 * data source. Implementations that return more accurate statistics based on pushed operators will
 * not improve query performance until the planner can push operators before getting stats.
 *
 * @since 3.0.0
 */
@Evolving
public interface SupportsReportStatistics extends Scan {

  /**
   * Returns the estimated statistics of this data source scan.
   */
  Statistics estimateStatistics();
}

/*
 * 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.spark.sql.connector.read;

import org.apache.spark.annotation.Evolving;

/**
 * A mix in interface for {@link Scan}. Data sources can implement this interface to
 * report statistics to Spark.
 *
 * As of Spark 3.0, statistics are reported to the optimizer after operators are pushed to the
 * data source. Implementations may return more accurate statistics based on pushed operators
 * which may improve query performance by providing better information to the optimizer.
 *
 * @since 3.0.0
 */
@Evolving
public interface SupportsReportStatistics extends Scan {

  /**
   * Returns the estimated statistics of this data source scan.
   */
  Statistics estimateStatistics();
}

Update documentation to reflect usage of updated statistics


package com.github.aureliano.achmed.os;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.types.OS;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public class LinuxTest {

	private Linux linux;

	public LinuxTest() {
		this.linux = this.createDefaultOs();
	}

	@Test
	public void testGetOperatingSystem() {
		assertEquals(OS.LINUX, this.linux.getOperatingSystem());
	}

	@Test
	public void testGetPsCommand() {
		final String cmd = "ps -ef";
		assertEquals(cmd, this.linux.getPsCommand());
	}

	private Linux createDefaultOs() {
		return new Linux() {

			public OperatingSystemFamily getOperatingSystemFamily() {
				return null;
			}

			public IPackageManager getDefaultPackageManager() {
				return null;
			}
		};
	}
}

package com.github.aureliano.achmed.os;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.github.aureliano.achmed.exception.ServiceResourceException;
import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.types.OS;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public class LinuxTest {

	private Linux linux;

	public LinuxTest() {
		this.linux = this.createDefaultOs();
	}

	@Test
	public void testGetOperatingSystem() {
		assertEquals(OS.LINUX, this.linux.getOperatingSystem());
	}

	@Test
	public void testGetPsCommand() {
		final String cmd = "ps -ef";
		assertEquals(cmd, this.linux.getPsCommand());
	}

	@Test(expected = ServiceResourceException.class)
	public void testGetPidWithNullPattern() {
		this.linux.getPid(null);
	}

	private Linux createDefaultOs() {
		return new Linux() {

			public OperatingSystemFamily getOperatingSystemFamily() {
				return null;
			}

			public IPackageManager getDefaultPackageManager() {
				return null;
			}
		};
	}
}

Add unit test to get pid passing null pattern.


package org.gbif.checklistbank.registry;

import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.OrganizationService;

import java.util.UUID;

import com.google.common.io.Files;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Test;

import static org.junit.Assert.assertNull;

/**
 *
 */
public class FileRegistryModuleTest {

  @Test
  public void configure() throws Exception {
    FileRegistryModule mod = new FileRegistryModule(Files.createTempDir());
    Injector inj = Guice.createInjector(mod);

    DatasetService ds = inj.getInstance(DatasetService.class);
    assertNull(ds.get(UUID.randomUUID()));

    OrganizationService os = inj.getInstance(OrganizationService.class);
    assertNull(os.get(UUID.randomUUID()));
  }

}

package org.gbif.checklistbank.registry;

import org.gbif.api.service.registry.DatasetService;
import org.gbif.api.service.registry.OrganizationService;
import org.gbif.utils.file.FileUtils;

import java.util.UUID;

import com.google.inject.Guice;
import com.google.inject.Injector;
import org.junit.Test;

import static org.junit.Assert.assertNull;

/**
 *
 */
public class FileRegistryModuleTest {

  @Test
  public void configure() throws Exception {

    FileRegistryModule mod = new FileRegistryModule(FileUtils.getClasspathFile("registry-datasets.txt"));
    Injector inj = Guice.createInjector(mod);

    DatasetService ds = inj.getInstance(DatasetService.class);
    assertNull(ds.get(UUID.randomUUID()));

    OrganizationService os = inj.getInstance(OrganizationService.class);
    assertNull(os.get(UUID.randomUUID()));
  }

}

Fix file registry module test


package ee.tuleva.onboarding.audit;

import ee.tuleva.onboarding.auth.principal.Person;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class AuditServiceMonitor {

    private final AuditEventPublisher auditEventPublisher;

    @Before("execution(* ee.tuleva.onboarding.account.AccountStatementService.getAccountStatement(..)) && args(person)")
    public void logServiceAccess(Person person) {
        auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_ACCOUNT_STATEMENT);
    }

    @Before("execution(* ee.tuleva.onboarding.comparisons.overview.EpisAccountOverviewProvider.getAccountOverview(..)) && args(person)")
    public void logCashFlowAccess(Person person) {
        auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_CASH_FLOWS);
    }
}

package ee.tuleva.onboarding.audit;

import ee.tuleva.onboarding.auth.principal.Person;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class AuditServiceMonitor {

    private final AuditEventPublisher auditEventPublisher;

    @Before("execution(* ee.tuleva.onboarding.account.AccountStatementService.getAccountStatement(..)) && args(person)")
    public void logServiceAccess(Person person) {
        auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_ACCOUNT_STATEMENT);
    }

    @Before("execution(* ee.tuleva.onboarding.comparisons.overview.EpisAccountOverviewProvider.getAccountOverview(..)) && args(person, ..)")
    public void logCashFlowAccess(Person person) {
        auditEventPublisher.publish(person.getPersonalCode(), AuditEventType.GET_CASH_FLOWS);
    }
}

Fix audit for cash flow


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.dimension.UModDimension;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.dimension.BasicDimension;
import net.minecraftforge.common.ModDimension;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestModDimensions {

	public static final ModDimension BASIC = new UModDimension("basic", BasicDimension::new);

	@SubscribeEvent
	public static void register(Register<ModDimension> event) {
		BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, ModDimension.class).forEach(event.getRegistry()::register);
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.dimension.UModDimension;
import info.u_team.u_team_core.util.registry.BaseRegistryUtil;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.dimension.BasicDimension;
import net.minecraft.potion.Effect;
import net.minecraftforge.common.ModDimension;
import net.minecraftforge.event.RegistryEvent.Register;
import net.minecraftforge.eventbus.api.*;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.registries.*;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD)
public class TestModDimensions {

	public static final DeferredRegister<ModDimension> MOD_DIMENSIONS = DeferredRegister.create(ForgeRegistries.MOD_DIMENSIONS, TestMod.MODID);

	public static final ModDimension BASIC = new UModDimension("basic", BasicDimension::new);

	public static void register(IEventBus bus) {
		MOD_DIMENSIONS.register(bus);
	}

//	@SubscribeEvent
//	public static void register(Register<ModDimension> event) {
//		BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, ModDimension.class).forEach(event.getRegistry()::register);
//	}
//
}

Add deferred register to mod dimensions


package com.mapr.drill;

/**
 * Created by tdunning on 7/22/15.
 */
public class BinaryIntConverter {
}

package com.mapr.drill;

import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.holders.IntHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;

/**
 * This is a helper UDF that converts bytes in big-endian format into an integer that
 * Drill can use.
 */
public class BinaryIntConverter {
    /**
     * Converts 4 byte big-endian values into integers.
     */
    @FunctionTemplate(isRandom = true, name = "byte2int", scope = FunctionTemplate.FunctionScope.SIMPLE, nulls = FunctionTemplate.NullHandling.NULL_IF_NULL)
    public static class BigEndianInt implements DrillSimpleFunc {
        @Param
        VarBinaryHolder raw;

        @Output
        IntHolder output;

        public void setup() {
        }

        public void eval() {
            output.value = raw.buffer.getInt(0);
        }
    }
}

Convert binary bytes to integer


package org.kohsuke.github;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kohsuke Kawaguchi
 */
public class GHIssueBuilder {
    private final GHRepository repo;
    private final Requester builder;
    private List<String> labels = new ArrayList<String>();

    GHIssueBuilder(GHRepository repo, String title) {
        this.repo = repo;
        this.builder = new Requester(repo.root);
        builder.with("title",title);
    }

    /**
     * Sets the main text of an issue, which is arbitrary multi-line text.
     */
    public GHIssueBuilder body(String str) {
        builder.with("body",str);
        return this;
    }

    public GHIssueBuilder assignee(GHUser user) {
        if (user!=null)
            builder.with("assignee",user.getLogin());
        return this;
    }

    public GHIssueBuilder assignee(String user) {
        if (user!=null)
            builder.with("assignee",user);
        return this;
    }

    public GHIssueBuilder milestone(GHMilestone milestone) {
        if (milestone!=null)
            builder.with("milestone",milestone.getNumber());
        return this;
    }

    public GHIssueBuilder label(String label) {
        if (label!=null)
            labels.add(label);
        return this;
    }

    /**
     * Creates a new issue.
     */
    public GHIssue create() throws IOException {
        return builder.with("labels",labels).to(repo.getApiTailUrl("issues"),GHIssue.class).wrap(repo);
    }
}

package org.kohsuke.github;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kohsuke Kawaguchi
 */
public class GHIssueBuilder {
    private final GHRepository repo;
    private final Requester builder;
    private List<String> labels = new ArrayList<String>();
    private List<String> assignees = new ArrayList<String>();

    GHIssueBuilder(GHRepository repo, String title) {
        this.repo = repo;
        this.builder = new Requester(repo.root);
        builder.with("title",title);
    }

    /**
     * Sets the main text of an issue, which is arbitrary multi-line text.
     */
    public GHIssueBuilder body(String str) {
        builder.with("body",str);
        return this;
    }

    public GHIssueBuilder assignee(GHUser user) {
        if (user!=null)
            assignees.add(user.getLogin());
        return this;
    }

    public GHIssueBuilder assignee(String user) {
        if (user!=null)
            assignees.add(user);
        return this;
    }

    public GHIssueBuilder milestone(GHMilestone milestone) {
        if (milestone!=null)
            builder.with("milestone",milestone.getNumber());
        return this;
    }

    public GHIssueBuilder label(String label) {
        if (label!=null)
            labels.add(label);
        return this;
    }

    /**
     * Creates a new issue.
     */
    public GHIssue create() throws IOException {
        return builder.with("labels",labels).with("assignees",assignees).to(repo.getApiTailUrl("issues"),GHIssue.class).wrap(repo);
    }
}

Support assignees when creating a new issue


package com.vaguehope.onosendai.storage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class VolatileKvStore implements KvStore {

	private final Map<String, String> m = new ConcurrentHashMap<String, String>();

	@Override
	public void storeValue (final String key, final String value) {
		this.m.put(key, value);
	}

	@Override
	public void deleteValue (final String key) {
		this.m.remove(key);
	}

	@Override
	public String getValue (final String key) {
		return this.m.get(key);
	}

}

package com.vaguehope.onosendai.storage;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class VolatileKvStore implements KvStore {

	private final Map<String, String> m = new ConcurrentHashMap<String, String>();

	@Override
	public void storeValue (final String key, final String value) {
		if (key == null) throw new IllegalArgumentException("Can not store against null key.");
		if (value != null) {
			this.m.put(key, value);
		}
		else {
			this.m.remove(key);
		}
	}

	@Override
	public void deleteValue (final String key) {
		this.m.remove(key);
	}

	@Override
	public String getValue (final String key) {
		return this.m.get(key);
	}

}

Fix NPE when refreshing SW token and using in memory cache.


package pro.jtaylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pro.jtaylor.timetracker.core.dao.TimeEntry;

import java.util.List;

/**
 * Created by Jason on 6/19/2015.
 */
@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    /**
     * Add method
     * @param TimeEntry to add to entries
     */
    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    /**
     * Remove method
     * @param TimeEntry to remove from entries
     */
    public void remove(TimeEntry entry) {
        entries.remove(entry);
    }

    /**
     * Size method
     * @param int size for entries
     */
    public int size() {
        return entries.size();
    }

    /**
     * Get method
     * @param int index for entries
     */
    public TimeEntry get(int index) {
        return entries.get(index);
    }
}

package pro.jtaylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pro.jtaylor.timetracker.core.dao.TimeEntry;

import java.util.List;

@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    public void remove(TimeEntry entry) {
        entries.remove(entry);
    }

    public int size() {
        return entries.size();
    }

    public TimeEntry get(int index) {
        return entries.get(index);
    }
}

Remove JavaDocs for CheckStyle warnings


/*
 * Copyright 2015-2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags.params;

public enum GetQueryTagValuesParams {
    AllowNonParametricFields,
    DateOffset,
    DatePeriod,
    DocumentCount,
    FieldDependence,
    FieldDependenceMultiLevel,
    FieldName,
    MaxValues,
    Merge,
    Ranges,
    RestrictedValues,
    Sort,
    Start,
    Synchronous,
    TotalValues,
    ValueDetails;

    public static GetQueryTagValuesParams fromValue(final String value) {
        for (final GetQueryTagValuesParams param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

/*
 * Copyright 2015-2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags.params;

public enum GetQueryTagValuesParams {
    AllowNonParametricFields,
    CustomWeight,
    DateOffset,
    DatePeriod,
    DocumentCount,
    FieldDependence,
    FieldDependenceMultiLevel,
    FieldName,
    MaxValues,
    Merge,
    Predict,
    Ranges,
    RestrictedValues,
    Sort,
    Start,
    Synchronous,
    TotalValues,
    ValueDetails,
    ValuePercentiles,
    ValueRestriction;

    public static GetQueryTagValuesParams fromValue(final String value) {
        for (final GetQueryTagValuesParams param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

Add support for new ValueRestriction QueryTagValues parameter in HavenSearchComponents (FIND-975)


package com.kogimobile.android.baselibrary.rest.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.util.Collection;

/**
 * Created by Julian Cardona on 5/21/15.
 */
public class CollectionTypedAdapter implements JsonSerializer<Collection<?>> {

    @Override
    public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null || src.isEmpty()) // exclusion is made here
            return null;

        JsonArray array = new JsonArray();

        for (Object child : src) {
            JsonElement element = context.serialize(child);
            array.add(element);
        }

        return array;
    }
}

package com.kogimobile.android.baselibrary.rest.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.util.Collection;

/**
 * Created by Julian Cardona on 5/21/15.
 */
public class CollectionTypedAdapter implements JsonSerializer<Collection<?>> {

    @Override
    public JsonElement serialize(Collection<?> src, Type typeOfSrc, JsonSerializationContext context) {
        if (src == null) // exclusion is made here
            return null;

        JsonArray array = new JsonArray();

        for (Object child : src) {
            JsonElement element = context.serialize(child);
            array.add(element);
        }

        return array;
    }
}

Fix empty array in rest calls.


package us.myles.ViaVersion.api.protocol;

public class ProtocolVersion {
    /* Defined protocol constants */
    public static int V1_7_1 = 4;
    public static int V1_7_6 = 5;

    public static int V1_8 = 47;

    public static int V1_9 = 107;
    public static int V1_9_1_PRE2 = 108;
}

package us.myles.ViaVersion.api.protocol;

public class ProtocolVersion {
    /* Defined protocol constants */
    public static final int V1_7_1 = 4;
    public static final int V1_7_6 = 5;

    public static final int V1_8 = 47;

    public static final int V1_9 = 107;
    public static final int V1_9_1_PRE2 = 108;
}

Change protocol constants to final fields


package org.wildfly.swarm.examples.messaging;

import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSDeployment;
import org.wildfly.swarm.messaging.MessagingFraction;
import org.wildfly.swarm.messaging.MessagingServer;
import org.wildfly.swarm.msc.ServiceActivatorDeployment;

/**
 * @author Bob McWhirter
 */
public class Main {

    public static void main(String[] args) throws Exception {
        Container container = new Container();

        container.subsystem(new MessagingFraction()
                        .server(
                                new MessagingServer()
                                        .enableInVMConnector()
                                        .topic("my-topic")
                                        .queue("my-queue")
                        )
        );

        // Start the container
        container.start();

        JAXRSDeployment appDeployment = new JAXRSDeployment(container);
        appDeployment.addResource(MyResource.class);

        // Deploy your app
        container.deploy(appDeployment);

        ServiceActivatorDeployment deployment = new ServiceActivatorDeployment(container);
        deployment.addServiceActivator( MyServiceActivator.class );
        deployment.addClass( MyService.class );

        // Deploy the services
        container.deploy( deployment );

    }
}

Remove a blank line, because.


package com.sourcegraph.javagraph;

import org.apache.commons.lang3.SystemUtils;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathUtil {

    public static final Path CWD = SystemUtils.getUserDir().toPath().toAbsolutePath().normalize();

    public static String normalize(String path) {
        if (SystemUtils.IS_OS_WINDOWS) {
            return path.replace('\\', '/');
        } else {
            return path;
        }
    }

    public static String relativizeCwd(String path) {
        Path p = Paths.get(path).toAbsolutePath();
        if (p.startsWith(CWD)) {
            return normalize(CWD.relativize(p).normalize().toString());
        } else {
            // for example, Android projects may refer to a directory on other drive
            return normalize(p.normalize().toString());
        }
    }

    public static Path concat(Path parent, Path child) {
        if (child.isAbsolute()) {
            return child;
        } else {
            return parent.resolve(child);
        }
    }

    public static File concat(File parent, File child) {
        if (child.isAbsolute()) {
            return child;
        } else {
            return new File(parent, child.getPath());
        }
    }

    public static File concat(File parent, String child) {
        return concat(parent, new File(child));
    }

}

package com.sourcegraph.javagraph;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathUtil {

    public static final Path CWD = SystemUtils.getUserDir().toPath().toAbsolutePath().normalize();

    public static String normalize(String path) {
        if (SystemUtils.IS_OS_WINDOWS) {
            return path.replace('\\', '/');
        } else {
            return path;
        }
    }

    public static String relativizeCwd(String path) {
        Path p = Paths.get(path).toAbsolutePath();
        if (p.startsWith(CWD)) {
            Path rel = CWD.relativize(p);
            if (rel.toString().isEmpty()) {
                return StringUtils.EMPTY;
            }
            return normalize(rel.normalize().toString());
        } else {
            // for example, Android projects may refer to a directory on other drive
            return normalize(p.normalize().toString());
        }
    }

    public static Path concat(Path parent, Path child) {
        if (child.isAbsolute()) {
            return child;
        } else {
            return parent.resolve(child);
        }
    }

    public static File concat(File parent, File child) {
        if (child.isAbsolute()) {
            return child;
        } else {
            return new File(parent, child.getPath());
        }
    }

    public static File concat(File parent, String child) {
        return concat(parent, new File(child));
    }

}

Fix ArrayOutOfBoundsException when relativizing path elements


package org.codehaus.xsite.extractors.sitemesh.rules;

import com.opensymphony.module.sitemesh.html.BasicRule;
import com.opensymphony.module.sitemesh.html.CustomTag;
import com.opensymphony.module.sitemesh.html.Tag;

/**
 * Rule for HTMLProcessor that adds class=""FirstChild" to the first header of the body if it is the first element.
 */
public class AddFirstChildClassToHeader extends BasicRule {
    private boolean firstChild = false;

    public AddFirstChildClassToHeader() {
    	super(new String[]{"p", "div", "h1", "h2", "h3", "h4", "h5", "h6"});
    }

    public void process(Tag tag) {
        if (!firstChild) {
            if (tag.getName().charAt(0) == 'h') {
                final CustomTag customTag = new CustomTag(tag);
                customTag.addAttribute("class", "FirstChild");
                tag = customTag;
            }
            firstChild = true;
        }
        tag.writeTo(currentBuffer());
    }
}

package org.codehaus.xsite.extractors.sitemesh.rules;

import com.opensymphony.module.sitemesh.html.BasicRule;
import com.opensymphony.module.sitemesh.html.CustomTag;
import com.opensymphony.module.sitemesh.html.Tag;

/**
 * Rule for HTMLProcessor that adds a class attribute to the first header of the body if it is the first element.
 * The attribute value is by default "FirstChild".
 */
public class AddFirstChildClassToHeader extends BasicRule {
    private boolean firstChild = false;
	private final String className;

    public AddFirstChildClassToHeader() {
    	this("FirstChild");
    }

    public AddFirstChildClassToHeader(String className) {
    	super(new String[]{"p", "div", "h1", "h2", "h3", "h4", "h5", "h6"});
		this.className = className;
    }

    public void process(Tag tag) {
        if (!firstChild) {
            if (tag.getName().charAt(0) == 'h') {
                final CustomTag customTag = new CustomTag(tag);
                customTag.addAttribute("class", className);
                tag = customTag;
            }
            firstChild = true;
        }
        tag.writeTo(currentBuffer());
    }
}

Make class attribute value configurable.


package com.gmail.nossr50.events.fake;

import java.util.ArrayList;

import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;

public class FakeBlockBreakEvent extends BlockBreakEvent {

	public FakeBlockBreakEvent(Block theBlock, Player player) {
		super(theBlock, player, new ArrayList<ItemStack>(theBlock.getDrops()));
	}
}

package com.gmail.nossr50.events.fake;

//import java.util.ArrayList;

import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
//import org.bukkit.inventory.ItemStack;

public class FakeBlockBreakEvent extends BlockBreakEvent {

	public FakeBlockBreakEvent(Block theBlock, Player player) {
		super(theBlock, player);
	}

//	   public FakeBlockBreakEvent(Block theBlock, Player player) {
//	        super(theBlock, player, new ArrayList<ItemStack>(theBlock.getDrops()));
//	    }
}

Fix my fix for the BlockBreak event changes (reverted).


package protocolsupport.protocol.typeremapper.legacy;

public class LegacyPainting {

	public static String getName(int id) {
		//TODO:
		return "Kebab";
	}

}

package protocolsupport.protocol.typeremapper.legacy;

public class LegacyPainting {

	public static String getName(int id) {
		switch (id) {
			case 0:
				return "Kebab";
			case 1:
				return "Aztec";
			case 2:
				return "Alban";
			case 3:
				return "Aztec2";
			case 4:
				return "Bomb";
			case 5:
				return "Plant";
			case 6:
				return "Wasteland";
			case 7:
				return "Pool";
			case 8:
				return "Courbet";
			case 9:
				return "Sea";
			case 10:
				return "Sunset";
			case 11:
				return "Creebet";
			case 12:
				return "Wanderer";
			case 13:
				return "Graham";
			case 14:
				return "Match";
			case 15:
				return "Bust";
			case 16:
				return "Stage";
			case 17:
				return "Void";
			case 18:
				return "SkullAndRoses";
			case 19:
				return "Wither";
			case 20:
				return "Fighters";
			case 21:
				return "Pointer";
			case 22:
				return "Pigscene";
			case 23:
				return "BurningSkull";
			case 24:
				return "Skeleton";
			case 25:
				return "DonkeyKong";
		}
		throw new UnsupportedOperationException("Trying to spawn painting with invalid id: " + id);
	}
}

Add painting remaps for legacy versions


package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.6.0";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "alpha";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

package ch.ethz.scu.obit.common.version;

public class VersionInfo {

	// Program version
	public static final String version = "0.5.1";

	// Version status: "alpha", "beta", or "" for a stable release
	public static final String status = "alpha";

	// Properties (XML) file version
	public static final int propertiesVersion = 4;

}

Set version to 0.5.1 (alpha).


package org.yamcs.studio.ui.archive;

import java.util.List;

import javax.swing.SwingUtilities;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.yamcs.studio.core.TimeCatalogue;

public class CreateReplayHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
        SwingUtilities.invokeLater(() -> {
            ArchiveView view = (ArchiveView) part;
            long missionTime = TimeCatalogue.getInstance().getMissionTime(true);
            TimeInterval interval = TimeInterval.starting(missionTime);
            List<String> packets = view.archivePanel.getSelectedPackets("tm");
            List<String> pps = view.archivePanel.getSelectedPackets("pp");
            Display.getDefault().asyncExec(() -> {
                CreateReplayDialog dialog = new CreateReplayDialog(Display.getCurrent().getActiveShell());
                dialog.initialize(interval, packets, pps);
                dialog.open();
            });
        });

        return null;
    }
}

package org.yamcs.studio.ui.archive;

import java.util.List;

import javax.swing.SwingUtilities;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.handlers.HandlerUtil;
import org.yamcs.studio.core.TimeCatalogue;

public class CreateReplayHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchPart part = HandlerUtil.getActivePartChecked(event);
        SwingUtilities.invokeLater(() -> {
            ArchiveView view = (ArchiveView) part;
            long missionTime = TimeCatalogue.getInstance().getMissionTime(true);
            missionTime -= 30 * 1000;
            TimeInterval interval = TimeInterval.starting(missionTime);
            List<String> packets = view.archivePanel.getSelectedPackets("tm");
            List<String> pps = view.archivePanel.getSelectedPackets("pp");
            Display.getDefault().asyncExec(() -> {
                CreateReplayDialog dialog = new CreateReplayDialog(Display.getCurrent().getActiveShell());
                dialog.initialize(interval, packets, pps);
                dialog.open();
            });
        });

        return null;
    }
}

Add negative delta to avoid stopping the processor immediately


package stroom.resources.query.v1;

import stroom.datasource.api.v1.DataSource;
import stroom.query.api.v1.DocRef;
import stroom.query.api.v1.QueryKey;
import stroom.query.api.v1.SearchRequest;
import stroom.query.api.v1.SearchResponse;
import stroom.resources.HasHealthCheck;
import stroom.resources.NamedResource;

public interface QueryResource extends HasHealthCheck, NamedResource {

    String DATASOURCE_ENDPOINT = "/datasource";
    String SEARCH_ENDPOINT = "/search";
    String DESTROY_ENDPOINT = "/destroy";

    DataSource getDataSource(final DocRef docRef);

    SearchResponse search(final SearchRequest request);

    Boolean destroy(final QueryKey queryKey);

}

package stroom.resources.query.v1;

import stroom.datasource.api.v1.DataSource;
import stroom.query.api.v1.DocRef;
import stroom.query.api.v1.QueryKey;
import stroom.query.api.v1.SearchRequest;
import stroom.query.api.v1.SearchResponse;
import stroom.resources.HasHealthCheck;
import stroom.resources.NamedResource;

public interface QueryResource extends HasHealthCheck, NamedResource {

    String DATASOURCE_ENDPOINT = "/dataSource";
    String SEARCH_ENDPOINT = "/search";
    String DESTROY_ENDPOINT = "/destroy";

    DataSource getDataSource(final DocRef docRef);

    SearchResponse search(final SearchRequest request);

    Boolean destroy(final QueryKey queryKey);

}

Change endpoint from /datasource to /dataSource


package zephyr.plugin.core.api.signals;

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

public class Signal<T> {

  static public interface EventInfoGenerator<T> {
    T generate();
  }

  private final List<Listener<T>> listeners = new LinkedList<Listener<T>>();

  public Signal() {
    super();
  }

  synchronized public Listener<T> connect(Listener<T> listener) {
    assert listener != null;
    assert this.listeners.indexOf(listener) == -1;
    this.listeners.add(listener);
    return listener;
  }

  synchronized public void disconnect(Listener<T> listener) {
    boolean elementFound;
    elementFound = listeners.remove(listener);
    assert elementFound;
  }

  public final void fire(T eventInfo) {
    for (Listener<T> listener : getListeners())
      listener.listen(eventInfo);
  }

  synchronized private ArrayList<Listener<T>> getListeners() {
    return new ArrayList<Listener<T>>(listeners);
  }

  public final void fireIFN(EventInfoGenerator<T> eventInfoGenerator) {
    if (listeners.isEmpty())
      return;
    fire(eventInfoGenerator.generate());
  }
}

package zephyr.plugin.core.api.signals;

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

public class Signal<T> {

  static public interface EventInfoGenerator<T> {
    T generate();
  }

  private final List<Listener<T>> listeners = new LinkedList<Listener<T>>();

  public Signal() {
    super();
  }

  synchronized public Listener<T> connect(Listener<T> listener) {
    assert listener != null;
    assert this.listeners.indexOf(listener) == -1;
    this.listeners.add(listener);
    return listener;
  }

  synchronized public void disconnect(Listener<T> listener) {
    boolean elementFound;
    elementFound = listeners.remove(listener);
    assert elementFound;
  }

  public final void fire(T eventInfo) {
    for (Listener<T> listener : getListeners())
      listener.listen(eventInfo);
  }

  synchronized private ArrayList<Listener<T>> getListeners() {
    return new ArrayList<Listener<T>>(listeners);
  }

  public final void fireIFN(EventInfoGenerator<T> eventInfoGenerator) {
    if (listeners.isEmpty())
      return;
    fire(eventInfoGenerator.generate());
  }

  public int nbListeners() {
    return listeners.size();
  }
}

Add a method to know the number of listeners


package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;

import java.util.Date;

import ca.corefacility.bioinformatics.irida.model.IridaThing;

/**
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> {
	Long id;

	private Date createdDate;

	private Date modifiedDate;

	public IdentifiableTestEntity() {

	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long identifier) {
		this.id = identifier;
	}

	@Override
	public int compareTo(IdentifiableTestEntity o) {
		return createdDate.compareTo(o.createdDate);
	}

	@Override
	public Date getTimestamp() {
		return createdDate;
	}

	@Override
	public void setTimestamp(Date timestamp) {
		this.createdDate = timestamp;
	}

	@Override
	public String getLabel() {
		return null;
	}

	public Date getModifiedDate() {
		return modifiedDate;
	}

	public void setModifiedDate(Date modifiedDate) {
		this.modifiedDate = modifiedDate;
	}
}

package ca.corefacility.bioinformatics.irida.web.controller.test.unit.support;

import java.util.Date;

import ca.corefacility.bioinformatics.irida.model.IridaThing;

/**
 *
 * @author Franklin Bristow <franklin.bristow@phac-aspc.gc.ca>
 */
public class IdentifiableTestEntity implements IridaThing, Comparable<IdentifiableTestEntity> {
	Long id;

	private Date createdDate;

	private Date modifiedDate;

	public IdentifiableTestEntity() {

	}

	public Long getId() {
		return this.id;
	}

	public void setId(Long identifier) {
		this.id = identifier;
	}

	@Override
	public int compareTo(IdentifiableTestEntity o) {
		return createdDate.compareTo(o.createdDate);
	}

	@Override
	public Date getTimestamp() {
		return createdDate;
	}

	@Override
	public void setTimestamp(Date timestamp) {
		this.createdDate = timestamp;
	}

	@Override
	public String getLabel() {
		return null;
	}

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

	@Override
	public void setEnabled(boolean valid) {

	}

	public Date getModifiedDate() {
		return modifiedDate;
	}

	public void setModifiedDate(Date modifiedDate) {
		this.modifiedDate = modifiedDate;
	}
}

Revert "Removed the "enabled" property since we're doing real deletes now"


package com.fenixinfotech.jmx.playpen;

import com.fenixinfotech.jmx.playpen.MbeanMonitor;

import static org.junit.Assert.*;

public class MbeanMonitorTest
{

    @org.junit.Test
    public void testConnect() throws Exception
    {
        new MbeanMonitor();
        assertTrue(true); // TODO add real test
    }
}

package com.fenixinfotech.jmx.playpen;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class MbeanMonitorTest
{
    @Test
    public void testConnect() throws Exception
    {
        MbeanMonitor mbeanMonitor = new MbeanMonitor();
        mbeanMonitor.connect("localhost", "4444");
        assertTrue(true); // TODO add real test
    }
}

Connect to local JMX for unit test


/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package itest.io.joynr.jeeintegration.preprocessor;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.joynr.messaging.RawMessagingPreprocessor;

public class TestRawMessagingProcessor extends RawMessagingPreprocessor {
    private static final Logger logger = LoggerFactory.getLogger(RawMessagingPreprocessor.class);

    @Override
    public byte[] process(byte[] rawMessage, Map<String, Serializable> context) {
        logger.info("raw message received: " + new String(rawMessage, StandardCharsets.UTF_8));
        return rawMessage;
    }
}

/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2017 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package itest.io.joynr.jeeintegration.preprocessor;

import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.joynr.messaging.RawMessagingPreprocessor;

public class TestRawMessagingProcessor extends RawMessagingPreprocessor {
    private static final Logger logger = LoggerFactory.getLogger(TestRawMessagingProcessor.class);

    @Override
    public byte[] process(byte[] rawMessage, Map<String, Serializable> context) {
        logger.info("raw message received: " + new String(rawMessage, StandardCharsets.UTF_8));
        return rawMessage;
    }
}

Fix class used for logging


package no.deichman.services.service;

import java.io.UnsupportedEncodingException;

import com.hp.hpl.jena.rdf.model.Model;

import no.deichman.services.error.PatchException;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;

public interface Service {

    void setRepository(Repository repository);
    void updateWork(String work);
    Model retrieveWorkById(String id);
    Model retrieveWorkItemsById(String id);
    String createWork(String work);
    String createPublication(String publication);
    void deleteWork(Model work);
    void deletePublication(Model publication);
    Model patchWork(String work, String requestBody) throws UnsupportedEncodingException, PatchException, PatchParserException;
    Model retrievePublicationById(String publicationId);
    Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
    boolean resourceExists(String resourceUri);
}

package no.deichman.services.service;

import com.hp.hpl.jena.rdf.model.Model;
import no.deichman.services.error.PatchParserException;
import no.deichman.services.repository.Repository;

public interface Service {

    void setRepository(Repository repository);
    void updateWork(String work);
    Model retrieveWorkById(String id);
    Model retrieveWorkItemsById(String id);
    String createWork(String work);
    String createPublication(String publication);
    void deleteWork(Model work);
    void deletePublication(Model publication);
    Model patchWork(String work, String requestBody) throws PatchParserException;
    Model retrievePublicationById(String publicationId);
    Model patchPublication(String publicationId, String requestBody) throws PatchParserException;
    boolean resourceExists(String resourceUri);
}

Remove unused exceptions from signature.


package org.deviceconnect.android.deviceplugin.theta.core;

/**
 * THETA Device Manager.
 */
public class ThetaDeviceManager {

    /**
     * Get a THETA device which is connected currently to the host device via WiFi.
     *
     * @return an instance of {@link ThetaDevice}
     */
    public ThetaDevice getConnectedDevice() {
        // TODO Implement.
        return null;
    }

    /**
     * Register {@link ThetaDeviceEventListener}.
     * @param listener an instance of {@link ThetaDeviceEventListener}
     */
    public void registerDeviceEventListener(final ThetaDeviceEventListener listener) {
        // TODO Implement.
    }

    /**
     * Unregister {@link ThetaDeviceEventListener}.
     * @param listener an instance of {@link ThetaDeviceEventListener}
     */
    public void unregisterDeviceEventListener(final ThetaDeviceEventListener listener) {
        // TODO Implement.
    }

}

package org.deviceconnect.android.deviceplugin.theta.core;

/**
 * THETA Device Manager.
 *
 *
Overview

 *

 * THETA Device Manager manages a THETA devices which is connected to the Android host device.
 *

 *
 *
Usage

 *
 *     // Obtain the Theta Device Manager.
 *     ThetaDeviceApplication app = (ThetaDeviceApplication) getApplication();
 *     ThetaDeviceManager deviceMgr = app.getDeviceManager();
 *
 *     ThetaDevice device = deviceMgr.getConnectedDevice();
 *     if (device != null) {
 *       // Codes for case that a THETA device is connected.
 *     } else {
 *       // Codes for case that a THETA device is not connected.
 *     }
 *
 */
public class ThetaDeviceManager {

    /**
     * Get a THETA device which is connected currently to the host device via WiFi.
     *
     * @return an instance of {@link ThetaDevice}
     */
    public ThetaDevice getConnectedDevice() {
        // TODO Implement.
        return null;
    }

    /**
     * Register {@link ThetaDeviceEventListener}.
     * @param listener an instance of {@link ThetaDeviceEventListener}
     */
    public void registerDeviceEventListener(final ThetaDeviceEventListener listener) {
        // TODO Implement.
    }

    /**
     * Unregister {@link ThetaDeviceEventListener}.
     * @param listener an instance of {@link ThetaDeviceEventListener}
     */
    public void unregisterDeviceEventListener(final ThetaDeviceEventListener listener) {
        // TODO Implement.
    }

}

Add JavaDoc of THETA Device Manager.


/**
 * 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.Member;
import io.gravitee.repository.model.TeamRole;

import java.util.Set;

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

    void addMember(String teamName, String username, TeamRole role);

    void updateMember(String teamName, String username, TeamRole role);

    void deleteMember(String teamName, String username);

    Set<Member> listMembers(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.Member;
import io.gravitee.repository.model.Team;
import io.gravitee.repository.model.TeamRole;

import java.util.Set;

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

    void addMember(String teamName, String username, TeamRole role);

    void updateMember(String teamName, String username, TeamRole role);

    void deleteMember(String teamName, String username);

    Set<Member> listMembers(String teamName);

    /**
     * List {@link Team} where the user is a member.
     *
     * @param username The name used to identify a user.
     * @return List of {@link Team}
     */
    Set<Team> findByUser(String username);
}

Add service to retrieve list of team for a user


package org.jbake.render.support;

import org.apache.commons.configuration.CompositeConfiguration;

public class MockCompositeConfiguration extends CompositeConfiguration {

    private boolean _bool = false;
    private String _string = "random string";

    public MockCompositeConfiguration withDefaultBoolean(boolean bool) {
        _bool = bool;
        return this;
    }

    public MockCompositeConfiguration withInnerString(String string) {
        _string = string;
        return this;
    }

    @Override
    public boolean getBoolean(String key) {

        if ( super.containsKey(key) ) {
            return super.getBoolean(key);
        }
        return _bool;
    }

    @Override
    public String getString(String string) {
        return _string;
    }
}

package org.jbake.render.support;

import org.apache.commons.configuration.CompositeConfiguration;

public class MockCompositeConfiguration extends CompositeConfiguration {

    private boolean _bool = false;
    private String _string = "random string";

    public MockCompositeConfiguration withDefaultBoolean(boolean bool) {
        _bool = bool;
        return this;
    }

    public MockCompositeConfiguration withInnerString(String string) {
        _string = string;
        return this;
    }

    @Override
    public boolean getBoolean(String key) {

        if ( super.containsKey(key) ) {
            return super.getBoolean(key);
        }
        return _bool;
    }

    @Override
    public String getString(String key) {
    	 if ( super.containsKey(key) ) {
             return super.getString(key);
         }
        return _string;
    }
}

Allow to pull value from parent configuration, if set.


package com.github.pedrovgs.app.problem3;

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SumBinaryNumberTest {

  private SumBinaryNumbers sumBinaryNumbers;

  @Before public void setUp() {
    this.sumBinaryNumbers = new SumBinaryNumbers();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInputs() {
    sumBinaryNumbers.sumBinaryNumbersCheating(null, null);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptMalformedBinaryNumbers() {
    String n1 = "10";
    String n2 = "2";

    sumBinaryNumbers.sumBinaryNumbersCheating(null, null);
  }

  @Test public void zeroPlusZeroEqualsZero() {
    String n1 = "0";
    String n2 = "0";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals(0, result);
  }

  @Test public void zeroPlusTwoEqualsTwo() {
    String n1 = "0";
    String n2 = "10";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals("10", result);
  }

  @Test public void fivePlusSevenEqualsTwelve() {
    String n1 = "101";
    String n2 = "111";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals("1100", result);
  }
}

package com.github.pedrovgs.app.problem3;

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SumBinaryNumberTest {

  private SumBinaryNumbers sumBinaryNumbers;

  @Before public void setUp() {
    this.sumBinaryNumbers = new SumBinaryNumbers();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInputs() {
    sumBinaryNumbers.sumBinaryNumbersCheating(null, null);
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldNotAcceptMalformedBinaryNumbers() {
    String n1 = "10";
    String n2 = "2";

    sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);
  }

  @Test public void zeroPlusZeroEqualsZero() {
    String n1 = "0";
    String n2 = "0";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals(0, result);
  }

  @Test public void zeroPlusTwoEqualsTwo() {
    String n1 = "0";
    String n2 = "10";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals("10", result);
  }

  @Test public void fivePlusSevenEqualsTwelve() {
    String n1 = "101";
    String n2 = "111";

    String result = sumBinaryNumbers.sumBinaryNumbersCheating(n1, n2);

    assertEquals("1100", result);
  }
}

Fix test for malformed binary numbers


package arez.doc.examples.tracker;

import arez.Arez;
import arez.Observer;
import arez.Procedure;

public class TrackerExample
{
  public static void main( String[] args )
    throws Throwable
  {
    final Procedure trackedFunction = () -> {
      // Interact with arez observable state (or computed values) here
      // and any time these changed the rescheduleRender function will
      // be run which will somehow reschedule this function.
      //DOC ELIDE START
      //DOC ELIDE END
    };
    final Observer tracker = Arez.context().tracker( () -> rescheduleRender() );
    //DOC ELIDE START
    //DOC ELIDE END
    // The rescheduleRender should ultimately result in the following
    // invocation. This call will need to be run at least once so that
    // the Arez runtime can determine the dependencies and reschedule
    // when the dependencies are changed.
    Arez.context().track( tracker, trackedFunction );
  }

  static void rescheduleRender()
  {

  }
}

package arez.doc.examples.tracker;

import arez.Arez;
import arez.Observer;
import arez.Procedure;

public class TrackerExample
{
  public static void main( String[] args )
    throws Throwable
  {
    final Procedure observedFunction = () -> {
      // Interact with arez observable state (or computed values) here
      // and any time these changed the rescheduleRender function will
      // be run which will somehow reschedule this function.
      //DOC ELIDE START
      //DOC ELIDE END
    };
    final Observer tracker = Arez.context().tracker( () -> rescheduleRender() );
    //DOC ELIDE START
    //DOC ELIDE END
    // The rescheduleRender should ultimately result in the following
    // invocation. This call will need to be run at least once so that
    // the Arez runtime can determine the dependencies and reschedule
    // when the dependencies are changed.
    Arez.context().track( tracker, observedFunction );
  }

  static void rescheduleRender()
  {
  }
}

Rename variable to reflect current terminology