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

package com.google.android.as.oss.fl.federatedcompute.config;

/** Interface to add and override PCS-specific flags. */
public abstract class PcsFcFlags {

  /** Whether to read FC flags from DeviceConfig. */
  public abstract boolean enableDeviceConfigOverrides();

  /** Percentage of messages to be logged. */
  public int logSamplingPercentage() {
    return 0;
  }

  /** Maximum size of serialized atoms logged by PCS. */
  public int maxSerializedAtomSize() {
    return 0;
  }

  /** Whether or not PCS should log error message strings from federated compute. */
  public boolean allowLoggingErrorMessage() {
    return false;
  }

  /** Whether or not SecAggClientLogEvents should be logged. */
  public boolean allowLoggingSecAggClientEvent() {
    return false;
  }

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

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

package com.google.android.as.oss.fl.federatedcompute.config;

/** Interface to add and override PCS-specific flags. */
public abstract class PcsFcFlags {

  /** Whether to read FC flags from DeviceConfig. */
  public abstract boolean enableDeviceConfigOverrides();

  /** Percentage of messages to be logged. */
  public int logSamplingPercentage() {
    return 0;
  }

  /** Maximum size of serialized atoms logged by PCS. */
  public int maxSerializedAtomSize() {
    return 0;
  }

  /** Whether or not PCS should log error message strings from federated compute. */
  public boolean allowLoggingErrorMessage() {
    return false;
  }

  /** Whether or not SecAggClientLogEvents should be logged. */
  public boolean allowLoggingSecAggClientEvent() {
    return false;
  }
}

Delete cleaned up default true selectorContextIncludeRunId flag


package org.helioviewer.jhv.data.container;

import java.util.List;

import org.helioviewer.jhv.data.datatype.JHVEvent;

/**
 * Interface should be implemented by a class that handles received events by
 * the JHVEventContainer.
 *
 * @author Bram Bourgoignie (Bram.Bourgoignie)
 */
public interface JHVEventHandler {
    /**
     * New Events were received by the JHVEventContainer.
     *
     * @param eventList
     *            the list of events that were received
     */
    public abstract void newEventsReceived(List<JHVEvent> eventList);
}

package org.helioviewer.jhv.data.container;

import java.util.List;

import org.helioviewer.jhv.data.datatype.JHVEvent;

/**
 * Interface should be implemented by a class that handles received events by
 * the JHVEventContainer.
 *
 * @author Bram Bourgoignie (Bram.Bourgoignie)
 */
public interface JHVEventHandler {
    /**
     * New Events were received by the JHVEventContainer.
     *
     * @param eventList
     *            the list of events that were received
     */
    public abstract void newEventsReceived(List<JHVEvent> eventList);

    /**
     * Informs the JHVEventHandler the cache was changed.
     *
     */
    public abstract void cacheUpdated();
}

Extend the JHVEventHandelr with a cacheUpdate function


package sagan.docs.support;

import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {

    private ProjectMetadataService service;

    @Autowired
    public DocsController(ProjectMetadataService service) {
        this.service = service;
    }

    @RequestMapping(value = "", method = { GET, HEAD })
    public String listProjects(Model model) {
        model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
        model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
        model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
        return "docs/index";
    }

    private List<Project> nonAggregatorsForCategory(String category) {
        return service.getProjectsForCategory(category).stream()
                .filter(project -> !project.isAggregator())
                .sorted((p1, p2) -> p1.getId().compareToIgnoreCase(p2.getId()))
                .collect(Collectors.toList());
    }
}

package sagan.docs.support;

import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {

    private ProjectMetadataService service;

    @Autowired
    public DocsController(ProjectMetadataService service) {
        this.service = service;
    }

    @RequestMapping(value = "", method = { GET, HEAD })
    public String listProjects(Model model) {
        model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
        model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
        model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
        return "docs/index";
    }

    private List<Project> nonAggregatorsForCategory(String category) {
        return service.getProjectsForCategory(category).stream()
                .filter(project -> !project.isAggregator())
                .sorted((p1, p2) -> p1.getName().compareToIgnoreCase(p2.getName()))
                .collect(Collectors.toList());
    }
}

Sort projects on /docs page by name vs. id


/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 androidx.test.core.os;

import static com.google.common.truth.Truth.assertThat;

import android.net.Uri;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public final class ParcelablesTest {

  @Test
  public void testForceParcel() throws Exception {
    Uri value = Uri.parse("content://foo/bar");
    Uri newValue = Parcelables.forceParcel(value, Uri.CREATOR);
    assertThat(newValue).isNotSameAs(value);
    assertThat(newValue).isEqualTo(value);
  }
}

/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * 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 androidx.test.core.os;

import static com.google.common.truth.Truth.assertThat;

import android.net.Uri;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public final class ParcelablesTest {

  @Test
  public void testForceParcel() throws Exception {
    Uri value = Uri.parse("content://foo/bar");
    Uri newValue = Parcelables.forceParcel(value, Uri.CREATOR);
    assertThat(newValue).isNotSameInstanceAs(value);
    assertThat(newValue).isEqualTo(value);
  }
}

Migrate from isNotSameAs to isNotSameInstanceAs.


package com.github.alexvictoor.proxy;

import java.io.File;

public class FileSystemRoute {

    private final String uriPrefix;
    private final File directory;

    private FileSystemRoute(String uriPrefix, File directory) {
        this.uriPrefix = uriPrefix;
        this.directory = directory;
    }

    public static FileSystemRoute create(String uriPrefix, String path) {
        File directory = new File(path);
        if (!directory.exists() || !directory.canRead() || !directory.isDirectory()) {
            throw new RuntimeException(path + " is not a path to a readable directory");
        }
        return new FileSystemRoute(uriPrefix, directory);
    }

    public static FileSystemRoute parse(String input) {
        String[] tokens = input.split("\\|");
        return create(tokens[0], tokens[1]);
    }

    public File findFile(String uri) {
        if (uri ==null || !uri.startsWith(uriPrefix)) {
            return null;
        }
        String relativePath = uri.substring(uriPrefix.length() + 1).replace('/', File.separatorChar);
        File file = new File(directory, relativePath);
        return file;
    }
}

package com.github.alexvictoor.proxy;

import java.io.File;

public class FileSystemRoute {

    private final String uriPrefix;
    private final File directory;

    private FileSystemRoute(String uriPrefix, File directory) {
        this.uriPrefix = uriPrefix;
        this.directory = directory;
    }

    public static FileSystemRoute create(String uriPrefix, String path) {
        File directory = new File(path);
        if (!directory.exists() || !directory.canRead() || !directory.isDirectory()) {
            throw new RuntimeException(path + " is not a path to a readable directory");
        }
        return new FileSystemRoute(uriPrefix, directory);
    }

    public static FileSystemRoute parse(String input) {
        String[] tokens = input.split("\\|");
        String prefix = tokens[0].trim();
        String path = tokens[1].trim();
        return create(prefix, path);
    }

    public File findFile(String uri) {
        if (uri ==null || !uri.startsWith(uriPrefix)) {
            return null;
        }
        String relativePath = uri.substring(uriPrefix.length() + 1).replace('/', File.separatorChar);
        File file = new File(directory, relativePath);
        return file;
    }
}

Fix conf parsing on linux


package org.mustangproject.ZUGFeRD;

public class CustomXMLProvider implements IXMLProvider {

	protected byte[] zugferdData;

	@Override
	public byte[] getXML() {
		return zugferdData;
	}

	public void setXML(byte[] newData) {
		zugferdData=newData;
	}

	@Override
	public void generateXML(IZUGFeRDExportableTransaction trans) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setTest() {
		// TODO Auto-generated method stub

	}

}

package org.mustangproject.ZUGFeRD;

public class CustomXMLProvider implements IXMLProvider {

	protected byte[] zugferdData;

	@Override
	public byte[] getXML() {
		return zugferdData;
	}

	public void setXML(byte[] newData) {
		String zf=new String(newData);
		if (!zf.contains("<rsm:CrossIndustry")) {
			throw new RuntimeException("ZUGFeRD XML does not contain <rsm:CrossIndustry and can thus not be valid");
		}

		zugferdData=newData;
	}

	@Override
	public void generateXML(IZUGFeRDExportableTransaction trans) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setTest() {
		// TODO Auto-generated method stub

	}

}

Make sure custom XML provided by some anonymous developer is at least halfway valid ;-)


package se.jaitco.queueticketapi.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import se.jaitco.queueticketapi.model.Roles;
import se.jaitco.queueticketapi.model.User;

import java.util.Arrays;
import java.util.Optional;

@Slf4j
@Component
public class UserService {

    public Optional<User> getUser(String username) {
        Optional<User> user = Optional.empty();
        if ("Aschan".equals(username)) {
            User aschan = User.builder()
                    .username("Aschan")
                    .password("Fotboll")
                    .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN))
                    .build();
            user = Optional.of(aschan);
        } else if ("Lmar".equals(username)) {
            User lmar = User.builder()
                    .username("Lmar")
                    .password("Book")
                    .grantedRoles(Arrays.asList(Roles.ADMIN))
                    .build();
            user = Optional.of(lmar);
        }
        return user;
    }
}

package se.jaitco.queueticketapi.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import se.jaitco.queueticketapi.model.Roles;
import se.jaitco.queueticketapi.model.User;

import java.util.Arrays;
import java.util.Optional;

@Slf4j
@Component
public class UserService {

    public Optional<User> getUser(String username) {
        Optional<User> user = Optional.empty();
        if ("Aschan".equals(username)) {
            User aschan = User.builder()
                    .username("Aschan")
                    .password("{noop}Fotboll")
                    .grantedRoles(Arrays.asList(Roles.CUSTOMER, Roles.ADMIN))
                    .build();
            user = Optional.of(aschan);
        } else if ("Lmar".equals(username)) {
            User lmar = User.builder()
                    .username("Lmar")
                    .password("{noop}Book")
                    .grantedRoles(Arrays.asList(Roles.ADMIN))
                    .build();
            user = Optional.of(lmar);
        }
        return user;
    }
}

Upgrade to spring boot 2 and java 9


package arez.integration;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.Observable;
import java.lang.reflect.Modifier;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TypeVisibilityTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent( dagger = Feature.ENABLE )
  public static abstract class PersonModel
  {
    PersonModel()
    {
    }

    @Observable
    @Nonnull
    String getFirstName()
    {
      return "";
    }

    void setFirstName( @Nonnull final String firstName )
    {
    }
  }

  @ArezComponent( dagger = Feature.ENABLE )
  public static abstract class PersonModel2
  {
    @Observable
    @Nonnull
    String getFirstName()
    {
      return "";
    }

    void setFirstName( @Nonnull final String firstName )
    {
    }
  }

  @Test
  public void typeVisibilities()
  {
    assertFalse( Modifier.isPublic( TypeVisibilityTest_Arez_PersonModel.class.getModifiers() ) );
    assertTrue( Modifier.isPublic( TypeVisibilityTest_Arez_PersonModel2.class.getModifiers() ) );
    assertTrue( Modifier.isPublic( TypeVisibilityTest_PersonModelDaggerModule.class.getModifiers() ) );
    assertTrue( Modifier.isPublic( TypeVisibilityTest_PersonModel2DaggerModule.class.getModifiers() ) );
  }
}

package arez.integration;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.Observable;
import java.lang.reflect.Modifier;
import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TypeVisibilityTest
  extends AbstractArezIntegrationTest
{
  @ArezComponent( dagger = Feature.ENABLE )
  public static abstract class PersonModel
  {
    PersonModel()
    {
    }

    @Observable
    @Nonnull
    String getFirstName()
    {
      return "";
    }

    void setFirstName( @Nonnull final String firstName )
    {
    }
  }

  @ArezComponent( dagger = Feature.ENABLE )
  public static abstract class PersonModel2
  {
    @Observable
    @Nonnull
    String getFirstName()
    {
      return "";
    }

    void setFirstName( @Nonnull final String firstName )
    {
    }
  }

  @Test
  public void typeVisibilities()
  {
    assertFalse( Modifier.isPublic( TypeVisibilityTest_Arez_PersonModel.class.getModifiers() ) );
    assertFalse( Modifier.isPublic( TypeVisibilityTest_Arez_PersonModel2.class.getModifiers() ) );
    assertTrue( Modifier.isPublic( TypeVisibilityTest_PersonModelDaggerModule.class.getModifiers() ) );
    assertTrue( Modifier.isPublic( TypeVisibilityTest_PersonModel2DaggerModule.class.getModifiers() ) );
  }
}

Fix test to reflect chages in the library


package edu.northwestern.bioinformatics.studycalendar.dao;

import org.springframework.transaction.annotation.Transactional;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment;

import java.util.List;

/**
 * @author Rhett Sutphin
 */
@Transactional(readOnly = true)
public class StudyDao extends StudyCalendarGridIdentifiableDao<Study> {
    public Class<Study> domainClass() {
        return Study.class;
    }

    @Transactional(readOnly = false)
    public void save(Study study) {
        getHibernateTemplate().saveOrUpdate(study);
    }

    public List<Study> getAll() {
        return getHibernateTemplate().find("from Study");
    }

    public List<StudyParticipantAssignment> getAssignmentsForStudy(Integer studyId) {
        return getHibernateTemplate().find(
            "select a from StudyParticipantAssignment a inner join a.studySite ss inner join a.participant p where ss.study.id = ? order by p.lastName, p.firstName",
            studyId);
    }

    public Study getById(int id) {
        return (Study) getHibernateTemplate().get(Study.class, new Integer(id));
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import org.springframework.transaction.annotation.Transactional;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment;

import java.util.List;

/**
 * @author Rhett Sutphin
 */
@Transactional(readOnly = true)
public class StudyDao extends StudyCalendarGridIdentifiableDao<Study> {
    @Override
    public Class<Study> domainClass() {
        return Study.class;
    }

    @Transactional(readOnly = false)
    public void save(Study study) {
        getHibernateTemplate().saveOrUpdate(study);
    }

    @SuppressWarnings({ "unchecked" })
    public List<Study> getAll() {
        return getHibernateTemplate().find("from Study");
    }

    @SuppressWarnings({ "unchecked" })
    public List<StudyParticipantAssignment> getAssignmentsForStudy(Integer studyId) {
        return getHibernateTemplate().find(
            "select a from StudyParticipantAssignment a inner join a.studySite ss inner join a.participant p where ss.study.id = ? order by p.lastName, p.firstName",
            studyId);
    }
}

Remove unnecessary override of getById


package net.md_5.bungee.api.event;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import net.md_5.bungee.api.connection.Connection;
import net.md_5.bungee.api.plugin.Cancellable;

/**
 * Event called when a player sends a message to a server, or a server sends a
 * message to a player.
 */
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class ChatEvent extends TargetedEvent implements Cancellable
{

    /**
     * Cancelled state.
     */
    private boolean cancelled;
    /**
     * Text contained in this chat.
     */
    private String message;

    public ChatEvent(Connection sender, Connection receiver, String message)
    {
        super( sender, receiver );
        this.message = message;
    }

    /**
     * Checks whether this message is valid as a command
     *
     * @return if this message is a command
     */
    public boolean isCommand()
    {
        return message.charAt( 0 ) == '/';
    }
}

package net.md_5.bungee.api.event;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import net.md_5.bungee.api.connection.Connection;
import net.md_5.bungee.api.plugin.Cancellable;

/**
 * Event called when a player sends a message to a server, or a server sends a
 * message to a player.
 */
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class ChatEvent extends TargetedEvent implements Cancellable
{

    /**
     * Cancelled state.
     */
    private boolean cancelled;
    /**
     * Text contained in this chat.
     */
    private String message;

    public ChatEvent(Connection sender, Connection receiver, String message)
    {
        super( sender, receiver );
        this.message = message;
    }

    /**
     * Checks whether this message is valid as a command
     *
     * @return if this message is a command
     */
    public boolean isCommand()
    {
        return message.length() > 0 && message.charAt( 0 ) == '/';
    }
}

Check length before checking if command.


package totemic_commons.pokefenn.event;

import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import totemic_commons.pokefenn.ModBlocks;
import totemic_commons.pokefenn.block.tipi.BlockTipi;

/**
 * Created by Pokefenn.
 * Licensed under MIT (If this is one of my Mods)
 */
public class EntityRightClick
{

    @SubscribeEvent
    public void entityInteracti(PlayerInteractEvent event)
    {
        if(event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)
        {
            Block block = event.world.getBlock(event.x, event.y, event.z);
            if(block != null)
            {
                if(block.getMaterial() == Material.ground || block.getUnlocalizedName().contains("dirt") || block.getUnlocalizedName().contains("grass"))
                {
                    if(event.world.getBlock(event.x, event.y + 1, event.z) == ModBlocks.tipi)
                    {
                        ((BlockTipi) event.world.getBlock(event.x, event.y + 1, event.z)).tipiSleep(event.world, event.x, event.y + 1, event.z, event.entityPlayer);
                    }
                }
            }
        }
    }
}

package totemic_commons.pokefenn.event;

import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraftforge.event.entity.player.PlayerInteractEvent;
import totemic_commons.pokefenn.ModBlocks;
import totemic_commons.pokefenn.block.tipi.BlockTipi;

/**
 * Created by Pokefenn.
 * Licensed under MIT (If this is one of my Mods)
 */
public class EntityRightClick
{

    @SubscribeEvent
    public void entityInteracti(PlayerInteractEvent event)
    {
        if(event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK)
        {
            if(event.world.getBlock(event.x, event.y + 1, event.z) == ModBlocks.tipi)
            {
                Block block = event.world.getBlock(event.x, event.y, event.z);
                if(block != null)
                {
                    if(block.getMaterial() == Material.ground || block.getUnlocalizedName().contains("dirt") || block.getUnlocalizedName().contains("grass"))
                    {
                        ((BlockTipi)ModBlocks.tipi).tipiSleep(event.world, event.x, event.y + 1, event.z, event.entityPlayer);
                    }
                }
            }
        }
    }
}

Change order of checks on Tipi PlayerInteractEvent


package cvut.fit.borrowsystem.web.API;

import cvut.fit.borrowsystem.service.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by Jakub Tuček on 11.6.2016.
 */
public class UserRestController {
    private static final Logger log = LoggerFactory.getLogger(UserRestController.class);

    @Autowired
    UserManager userManager;

}

package cvut.fit.borrowsystem.web.API;

import cvut.fit.borrowsystem.service.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by Jakub Tuček on 11.6.2016.
 */

@RestController
@RequestMapping("/api/users")
public class UserRestController {
    private static final Logger log = LoggerFactory.getLogger(UserRestController.class);

    @Autowired
    UserManager userManager;

}

Add user rest api controller annotation


package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 * A Command to spin the intake motor forward or backward
 */
public class ManualVerticalIntake extends Command {

	public Direction direction; //Object for the Direction enum

	int time; //Used to set timeout

	/**
	 * Initalizes some variables
	 *
	 * @param direction  Used to initalize Direction enum
	 * @param time  Takes input for time
	 * */
    public ManualVerticalIntake(Direction direction, int time) {
    	requires(Robot.intake);
    	this.direction = direction;
    	this.time = time;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	setTimeout(time);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	if (direction == Direction.UP) {
    		Robot.intake.moveUp();
    	} else if(direction == Direction.DOWN){
    		Robot.intake.moveDown();
    	} else {
    		Robot.intake.stopVertical();
    	}
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.intake.stopVertical();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

package org.robockets.stronghold.robot.intake;

import org.robockets.stronghold.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

/**
 * A Command to spin the intake motor forward or backward
 */
public class ManualVerticalIntake extends Command {

	public Direction direction; //Object for the Direction enum

	int time; //Used to set timeout

	/**
	 * Initalizes some variables
	 *
	 * @param direction  Used to initalize Direction enum
	 * @param time  Takes input for time
	 * */
    public ManualVerticalIntake(Direction direction, int time) {
    	requires(Robot.intake);
    	this.direction = direction;
    	this.time = time;
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    	setTimeout(time);
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
    	if (direction == Direction.UP) {
    		Robot.intake.moveUp();
    	} else if(direction == Direction.DOWN){
    		Robot.intake.moveDown();
    	} else {
    		Robot.intake.stopVertical();
    	}
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
    	if(isTimedOut()){
    		return true;
    	}
    	return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    	Robot.intake.stopVertical();
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    	end();
    }
}

Set isFinished to true when timed out, end on interrupt


package com.github.ajalt.reprint.core;

import com.github.ajalt.reprint.testing.TestReprintModule;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;

public class ReprintTest {
    public TestReprintModule module;

    @Mock
    public AuthenticationListener listener;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);

        module = new TestReprintModule();
        module.listener = null;
        module.cancellationSignal = null;
        Reprint.registerModule(module);

        Reprint.authenticate(listener);
        assertThat(module.listener).isNotNull();
    }

    @Test
    public void successfulRequest() throws Exception {
        verifyZeroInteractions(listener);
        module.listener.onSuccess(module.TAG);
        verify(listener).onSuccess(anyInt());
    }

    @Test
    public void failedRequest() throws Exception {
        verifyZeroInteractions(listener);
        module.listener.onFailure(AuthenticationFailureReason.AUTHENTICATION_FAILED, false, "", module.TAG, 0);
        verify(listener).onFailure(eq(AuthenticationFailureReason.AUTHENTICATION_FAILED), eq(false), anyString(), anyInt(), anyInt());
    }
}

package com.github.ajalt.reprint.core;

import com.github.ajalt.reprint.testing.TestReprintModule;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;

import static org.assertj.core.api.Java6Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
@RunWith(MockitoJUnitRunner.class)
public class ReprintTest {
    public TestReprintModule module;

    @Mock
    public AuthenticationListener listener;

    @Before
    public void setup() {
        module = new TestReprintModule();
        module.listener = null;
        module.cancellationSignal = null;
        Reprint.registerModule(module);

        Reprint.authenticate(listener);
        assertThat(module.listener).isNotNull();
    }

    @Test
    public void successfulRequest() throws Exception {
        verifyZeroInteractions(listener);
        module.listener.onSuccess(module.TAG);
        verify(listener).onSuccess(anyInt());
    }

    @Test
    public void failedRequest() throws Exception {
        verifyZeroInteractions(listener);
        module.listener.onFailure(AuthenticationFailureReason.AUTHENTICATION_FAILED, false, "", module.TAG, 0);
        verify(listener).onFailure(eq(AuthenticationFailureReason.AUTHENTICATION_FAILED), eq(false), anyString(), anyInt(), anyInt());
    }
}

Use MockitoJUnitRunner instead of initMocks.


package <%=packageName%>.service;

import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.List;

/**
 * Service for managing audit event.
 *

 *

 * This is the default implementation to support SpringBoot Actuator AuditEventRepository
 *

 */
@Service
@Transactional
public class AuditEventService {

    @Inject
    private PersistenceAuditEventRepository persistenceAuditEventRepository;

    @Inject
    private AuditEventConverter auditEventConverter;

    public List<AuditEvent> findAll() {
        return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
    }

    public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
        final List<PersistentAuditEvent> persistentAuditEvents =
                persistenceAuditEventRepository.findByAuditEventDateBetween(fromDate, toDate);

        return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
    }

}

package <%=packageName%>.service;

import <%=packageName%>.config.audit.AuditEventConverter;
import <%=packageName%>.domain.PersistentAuditEvent;
import <%=packageName%>.repository.PersistenceAuditEventRepository;
import org.joda.time.LocalDateTime;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import java.util.List;

/**
 * Service for managing audit event.
 *

 *

 * This is the default implementation to support SpringBoot Actuator AuditEventRepository
 *

 */
@Service
@Transactional
public class AuditEventService {

    @Inject
    private PersistenceAuditEventRepository persistenceAuditEventRepository;

    @Inject
    private AuditEventConverter auditEventConverter;

    public List<AuditEvent> findAll() {
        return auditEventConverter.convertToAuditEvent(persistenceAuditEventRepository.findAll());
    }

    public List<AuditEvent> findBetweenDates(LocalDateTime fromDate, LocalDateTime toDate) {
        final List<PersistentAuditEvent> persistentAuditEvents =
                persistenceAuditEventRepository.findByDates(fromDate, toDate);

        return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
    }

}

Call the new findByDates method


package io.sigpipe.sing.graph;

public class GraphMetrics implements Cloneable {

    private long vertices;
    private long leaves;

    public GraphMetrics() {

    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        GraphMetrics that = (GraphMetrics) obj;
        return this.vertices == that.vertices
            && this.leaves == that.leaves;
    }

    public GraphMetrics(int vertices, int leaves) {
        this.vertices = vertices;
        this.leaves = leaves;
    }

    public void setVertexCount(long vertices) {
        this.vertices = vertices;
    }

    public void setLeafCount(long leaves) {
        this.leaves = leaves;
    }

    public void addVertex() {
        this.vertices++;
    }

    public void addVertices(long vertices) {
        this.vertices += vertices;
    }

    public void addLeaf() {
        this.leaves++;
    }

    public void addLeaves(long leaves) {
        this.leaves += leaves;
    }

    public long getVertexCount() {
        return this.vertices;
    }

    public long getLeafCount() {
        return this.leaves;
    }

    public String toString() {
        return "V: " + this.vertices + ", L: " + this.leaves;
    }

}

package io.sigpipe.sing.graph;

public class GraphMetrics implements Cloneable {

    private long vertices;
    private long leaves;

    public GraphMetrics() {

    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        GraphMetrics that = (GraphMetrics) obj;
        return this.vertices == that.vertices
            && this.leaves == that.leaves;
    }

    public GraphMetrics(int vertices, int leaves) {
        this.vertices = vertices;
        this.leaves = leaves;
    }

    public void setVertexCount(long vertices) {
        this.vertices = vertices;
    }

    public void setLeafCount(long leaves) {
        this.leaves = leaves;
    }

    public void addVertex() {
        this.vertices++;
    }

    public void addVertices(long vertices) {
        this.vertices += vertices;
    }

    public void addLeaf() {
        this.leaves++;
    }

    public void addLeaves(long leaves) {
        this.leaves += leaves;
    }

    public void removeVertex() {
        this.vertices--;
    }

    public void removeVertices(long vertices) {
        this.vertices -= vertices;
    }
    public long getVertexCount() {
        return this.vertices;
    }

    public long getLeafCount() {
        return this.leaves;
    }

    public String toString() {
        return "V: " + this.vertices + ", L: " + this.leaves;
    }

}

Add methods to remove vertices


package com.reason.bs;

import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;

class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {

    private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
    private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;

    BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
        super(commandLine);
        m_onProcessTerminated = onProcessTerminated;
    }

    @Override
    protected void onOSProcessTerminated(int exitCode) {
        super.onOSProcessTerminated(exitCode);
        if (m_onProcessTerminated != null) {
            m_onProcessTerminated.run();
        }
    }

    @Override
    public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
        m_ansiEscapeDecoder.escapeText(text, outputType, super::notifyTextAvailable);
    }

    @Override
    public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
        super.notifyTextAvailable(text, attributes);
    }
}

package com.reason.bs;

import com.intellij.execution.*;
import com.intellij.execution.configurations.*;
import com.intellij.execution.process.*;
import com.intellij.openapi.util.*;
import com.reason.Compiler;
import org.jetbrains.annotations.*;

class BsColoredProcessHandler extends KillableProcessHandler implements AnsiEscapeDecoder.ColoredTextAcceptor {

    private final @NotNull AnsiEscapeDecoder m_ansiEscapeDecoder = new AnsiEscapeDecoder();
    private final @Nullable Compiler.ProcessTerminated m_onProcessTerminated;

    BsColoredProcessHandler(@NotNull GeneralCommandLine commandLine, @Nullable Compiler.ProcessTerminated onProcessTerminated) throws ExecutionException {
        super(commandLine);
        m_onProcessTerminated = onProcessTerminated;
    }

    @Override
    protected void onOSProcessTerminated(int exitCode) {
        super.onOSProcessTerminated(exitCode);
        if (m_onProcessTerminated != null) {
            m_onProcessTerminated.run();
        }
    }

    @Override
    public final void notifyTextAvailable(@NotNull final String text, @NotNull final Key outputType) {
        m_ansiEscapeDecoder.escapeText(
                text,
                outputType,
                (chunk, attributes) -> {
                    if (":".equals(chunk)) {
                        // Suppose this is the separator in output: C:\xxx\xxx\File.re : 1:13-14
                        super.notifyTextAvailable(" ", attributes);
                    } else {
                        super.notifyTextAvailable(chunk, attributes);
                    }
                });
    }

    @Override
    public void coloredTextAvailable(@NotNull String text, @NotNull Key attributes) {
        super.notifyTextAvailable(text, attributes);
    }
}

Fix file pattern introduced in 8.3.0


package com.github.aureliano.edocs.app;

import javax.swing.SwingUtilities;

import com.github.aureliano.edocs.app.gui.AppFrame;

public class EdocsApp {

	private static EdocsApp instance;
	private AppFrame frame;

	public static void main(String[] args) {
		final EdocsApp application = new EdocsApp();

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				application.getFrame().showFrame();
			}
		});
	}

	public static EdocsApp instance() {
		if (instance == null) {
			instance = new EdocsApp();
		}

		return instance;
	}

	public EdocsApp() {
		this.frame = new AppFrame();
	}

	public AppFrame getFrame() {
		return this.frame;
	}
}

package com.github.aureliano.edocs.app;

import javax.swing.SwingUtilities;

import com.github.aureliano.edocs.app.gui.AppFrame;

public class EdocsApp {

	private static EdocsApp instance;
	private AppFrame frame;

	public static void main(String[] args) {
		final EdocsApp application = instance();

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				application.getFrame().showFrame();
			}
		});
	}

	public static EdocsApp instance() {
		if (instance == null) {
			instance = new EdocsApp();
		}

		return instance;
	}

	public EdocsApp() {
		this.frame = new AppFrame();
	}

	public AppFrame getFrame() {
		return this.frame;
	}
}

Fix GUI main frame instantiation.


package vooga.request.forwarder;

import vooga.request.receiver.IReceiver;

/**
 * An exception capturing when an address conflicts with a pre-existing address
 */
public class AddressConflictException extends Exception {

    private static final long serialVersionUID = -3572949740426821224L;

    private String myConflictingAddress;
    private IReceiver myConflictingReceiver;

    /**
     * Create a new address conflict exception
     *
     * @param conflictingAddress The address that conflicts with a pre-existing address
     * @param conflictingReceiver The receiver that already possesses that address
     */
    public AddressConflictException(String conflictingAddress, IReceiver conflictingReceiver){
        super(conflictingAddress + " is already in use by " + conflictingReceiver);
        myConflictingAddress = conflictingAddress;
        myConflictingReceiver = conflictingReceiver;
    }

    /**
     * The conflicting address
     *
     * @return The address that conflicts with a pre-existing address
     */
    public String conflictingAddress(){
        return myConflictingAddress;
    }

    /**
     * The conflicting receiver
     *
     * @return The receiver that already possesses that address
     */
    public IReceiver conflictingReceiver(){
        return myConflictingReceiver;
    }
}

Remove spacing between static and non static variables


/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.3 2004/11/09 08:51:22 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;

import java.sql.*;
import java.util.Map;

class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
    Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
    {
        super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
    }

    public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(i, map);
    }

    public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(s, map);
    }

}

/*-------------------------------------------------------------------------
*
* Copyright (c) 2004-2005, PostgreSQL Global Development Group
*
* IDENTIFICATION
*   $PostgreSQL: pgjdbc/org/postgresql/jdbc3g/Jdbc3gCallableStatement.java,v 1.4 2005/01/11 08:25:47 jurka Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.jdbc3g;

import java.sql.*;
import java.util.Map;

class Jdbc3gCallableStatement extends Jdbc3gPreparedStatement implements CallableStatement
{
    Jdbc3gCallableStatement(Jdbc3gConnection connection, String sql, int rsType, int rsConcurrency, int rsHoldability) throws SQLException
    {
        super(connection, sql, true, rsType, rsConcurrency, rsHoldability);
        if ( !connection.haveMinimumServerVersion("8.1") || connection.getProtocolVersion() == 2)
        {
            adjustIndex = true;
        }
    }

    public Object getObject(int i, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(i, map);
    }

    public Object getObject(String s, Map < String, Class < ? >> map) throws SQLException
    {
        return getObjectImpl(s, map);
    }

}

Make callable statements work again for JDK 1.5 builds. Any code int the jdbc3/Jdbc3 classes also needs to get into the corresponding jdbc3g/Jdbc3g class.


package org.pma.nutrifami.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;

import org.pma.nutrifami.R;
import org.pma.nutrifami.adapter.LessonPagePagerAdaptor;
import org.pma.nutrifami.lib.ModuleManager;
import org.pma.nutrifami.model.Module;

import me.crosswall.lib.coverflow.CoverFlow;

public class ModuleActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_module_carousel);

        ModuleManager moduleManager = ModuleManager.getInstance();
        // TODO: Get real module
        Module module = moduleManager.getModules()[0];

        ViewPager mPager = (ViewPager) findViewById(R.id.lesson_page_pager);
        PagerAdapter mPagerAdapter = new LessonPagePagerAdaptor(getSupportFragmentManager(), module);
        mPager.setAdapter(mPagerAdapter);

        new CoverFlow.Builder()
                .with(mPager)
                .scale(0.15f)
                .build();
    }
}

package org.pma.nutrifami.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;

import org.pma.nutrifami.R;
import org.pma.nutrifami.adapter.LessonPagePagerAdaptor;
import org.pma.nutrifami.lib.ModuleManager;
import org.pma.nutrifami.model.Module;

import me.crosswall.lib.coverflow.CoverFlow;

public class ModuleActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_module_carousel);

        ModuleManager moduleManager = ModuleManager.getInstance();
        // TODO: Get real module
        Module module = moduleManager.getModules()[0];

        ViewPager mPager = (ViewPager) findViewById(R.id.lesson_page_pager);
        mPager.setOffscreenPageLimit(2);

        PagerAdapter mPagerAdapter = new LessonPagePagerAdaptor(getSupportFragmentManager(), module);
        mPager.setAdapter(mPagerAdapter);

        new CoverFlow.Builder()
                .with(mPager)
                .scale(0.15f)
                .build();
    }
}

Fix wrong scaling of lessons in module detail view


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

/**
 * Collection of file directory paths.
 *
 * @author Ryan Gilera
 */
public enum FilePath {

    TEMP_FILE_HOLDER("/VAADIN/tempFileHolder/"),
    HTML_OUTPUT_NAME("convertedWork"),
    PDF_OUTPUT_NAME("pdfFile"),
    TEMP_PICTURE_FOLDER("pictures/");
    private final String path;

    private FilePath(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

}

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

/**
 * Collection of file directory paths.
 *
 * @author Ryan Gilera
 */
public enum FilePath {

    TEMP_FILE_HOLDER("/VAADIN/tempFileHolder/"),
    HTML_OUTPUT_NAME("convertedWork"),
    FILE_OUTPUT_NAME("pdfFile"),
    TEMP_PICTURE_FOLDER("pictures/");
    private final String path;

    private FilePath(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

}

Rename for a better term


/*******************************************************************************
 * Copyright (c) 2018 Red Hat Inc and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Dejan Bosanac - initial implementation
 *******************************************************************************/
package org.eclipse.hono.util;

/**
 * Utility used to determine type of the endpoint.
 */
public enum EndpointType {
    TELEMETRY, EVENT, UNKNOWN;

    /**
     * Gets the endpoint type from a string value.
     *
     * @param name The name of the endpoint type.
     *
     * @return The enum literal of the endpoint type. Returns {@value #UNKNOWN} if it cannot find the endpoint type.
     *         Never returns {@code null}.
     */
    public static EndpointType fromString(String name) {
        switch (name) {
        case TelemetryConstants.TELEMETRY_ENDPOINT:
        case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
            return TELEMETRY;
        case EventConstants.EVENT_ENDPOINT:
        case EventConstants.EVENT_ENDPOINT_SHORT:
            return EVENT;
        default:
            return UNKNOWN;
        }
    }
}

/*******************************************************************************
 * Copyright (c) 2018 Red Hat Inc and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Dejan Bosanac - initial implementation
 *******************************************************************************/
package org.eclipse.hono.util;

/**
 * Utility used to determine type of the endpoint.
 */
public enum EndpointType {
    TELEMETRY, EVENT, UNKNOWN;

    /**
     * Gets the endpoint type from a string value.
     *
     * @param name The name of the endpoint type.
     *
     * @return The enum literal of the endpoint type. Returns {@link #UNKNOWN} if it cannot find the endpoint type.
     *         Never returns {@code null}.
     */
    public static EndpointType fromString(String name) {
        switch (name) {
        case TelemetryConstants.TELEMETRY_ENDPOINT:
        case TelemetryConstants.TELEMETRY_ENDPOINT_SHORT:
            return TELEMETRY;
        case EventConstants.EVENT_ENDPOINT:
        case EventConstants.EVENT_ENDPOINT_SHORT:
            return EVENT;
        default:
            return UNKNOWN;
        }
    }
}

Use "link" to reference enum literal, fixing javadoc issue.


package io.spacedog.utils;

import org.joda.time.DateTimeZone;

public class DateTimeZones {
	public final static DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");
}

package io.spacedog.utils;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

public class DateTimeZones {
	public final static DateTimeZone PARIS = DateTimeZone.forID("Europe/Paris");

	public static double toEpochSeconds(DateTime date) {
		return ((double) date.getMillis()) / 1000;
	}

	public static DateTime toDateTime(double epochSeconds) {
		return new DateTime((long) (epochSeconds * 1000));
	}

}

Add converters from DateTime to Epoch double dates


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

import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import rx.Observable;

/**
 * User: michaels@netflix.com
 * Date: 5/11/15
 * Time: 3:14 PM
 */
public interface Origin {
    String getName();
    boolean isAvailable();
    boolean isWarmServerAvailable();
    Observable<HttpResponseMessage> request(HttpRequestMessage requestMsg);
}

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

import com.netflix.zuul.message.http.HttpRequestMessage;
import com.netflix.zuul.message.http.HttpResponseMessage;
import rx.Observable;

/**
 * User: michaels@netflix.com
 * Date: 5/11/15
 * Time: 3:14 PM
 */
public interface Origin {
    String getName();
    boolean isAvailable();
    boolean isCold();
    Observable<HttpResponseMessage> request(HttpRequestMessage requestMsg);
}

Rename the interface to isCold()


package etomica.simulation;

import etomica.data.meter.MeterPressureTensor;
import etomica.space3d.Space3D;
import etomica.surfacetension.LJMC;
import org.openjdk.jmh.annotations.*;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimSurfacetensionLJMC {

    @Param({"1000", "20000"})
    private int numAtoms;

    private LJMC sim;
    private MeterPressureTensor meter;

    @Setup(Level.Iteration)
    public void setUp() {
        sim = new LJMC(Space3D.getInstance(), numAtoms, 1.1, 6);

        meter = new MeterPressureTensor(sim.potentialMaster, sim.space);
        meter.setBox(sim.box);
        meter.setTemperature(1.1);

    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 1, iterations = 5)
    @Measurement(time = 1, timeUnit = TimeUnit.SECONDS)
    public void surfacetension() {
        sim.integrator.doStep();
    }
}

package etomica.simulation;

import etomica.data.AccumulatorAverageFixed;
import etomica.data.DataPumpListener;
import etomica.data.IData;
import etomica.data.meter.MeterPressureTensor;
import etomica.space3d.Space3D;
import etomica.surfacetension.LJMC;
import org.openjdk.jmh.annotations.*;

import java.util.concurrent.TimeUnit;

@State(Scope.Benchmark)
@Fork(1)
public class BenchSimSurfacetensionLJMC {

    @Param({"1000", "20000"})
    private int numAtoms;

    private LJMC sim;
    private MeterPressureTensor meter;

    @Setup(Level.Iteration)
    public void setUp() {
        sim = new LJMC(Space3D.getInstance(), numAtoms, 1.1, 6);

        meter = new MeterPressureTensor(sim.potentialMaster, sim.space);
        meter.setBox(sim.box);
        meter.setTemperature(1.1);
        DataPumpListener pumpListener = new DataPumpListener(meter, new AccumulatorAverageFixed(10), 2 * numAtoms);
        sim.integrator.getEventManager().addListener(pumpListener);
        sim.integrator.reset();
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.SECONDS)
    @Warmup(time = 1, iterations = 5)
    @Measurement(time = 5, timeUnit = TimeUnit.SECONDS, iterations = 5)
    public IData surfacetension() {
        sim.integrator.doStep();
        return meter.getData();
    }
}

Add integrator reset to Surfacetension bench


import java.io.File;

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  public static String readFile(String filePath){
      File f = new File(filePath);
      Scanner input = new Scanner();
  }

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

import java.io.File;

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  public static String readFile(String filePath){
      File f = new File(filePath);
      Scanner input = new Scanner(f);
  }

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

Set "new Scanner()" to "f" :pencil2:


package net.zero918nobita.Xemime;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * ブロック
 * Common Lisp の progn のようにブロック自体が戻り値を持つ
 * そのためブロック内に何も記述していない場合例外を投げる
 * @author Kodai Matsumoto
 */

class X_Block extends X_Object {
    private ArrayList<X_Object> list;

    X_Block(ArrayList<X_Object> l) {
        list = l;
    }

    @Override
    X_Object run() throws Exception {
        Main.loadLocalFrame(new HashMap<>());
        X_Object obj = null;
        if (list != null) for (X_Object o : list) obj = o.run();
        if (obj == null) throw new Exception("ブロックの戻り値が記述されていません");
        return obj;
    }
}

package net.zero918nobita.Xemime;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * ブロック
 * Common Lisp の progn のようにブロック自体が戻り値を持つ
 * そのためブロック内に何も記述していない場合例外を投げる
 * @author Kodai Matsumoto
 */

class X_Block extends X_Object {
    private ArrayList<X_Object> list;

    X_Block(ArrayList<X_Object> l) {
        list = l;
    }

    @Override
    X_Object run() throws Exception {
        Main.loadLocalFrame(new HashMap<>());
        X_Object obj = null;
        if (list != null) for (X_Object o : list) obj = o.run();
        if (obj == null) throw new Exception("ブロックの戻り値が記述されていません");
        Main.unloadLocalFrame();
        return obj;
    }
}

Fix the problem where blocks' local frames aren't discarded when they are used


package org.metaborg.util.log;

public enum Level {
    Trace, Debug, Info, Warn, Error
}

package org.metaborg.util.log;

public enum Level {
    Trace, Debug, Info, Warn, Error;

    public static Level parse(String name) {
        for(Level level : Level.values()) {
            if(level.name().equalsIgnoreCase(name)) {
                return level;
            }
        }
        throw new IllegalArgumentException("Unknown level: " + name);
    }

}

Add parsing function for log levels.


package devopsdistilled.operp.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);
		System.out.println(context);
	}
}

package devopsdistilled.operp.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Properties;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {
		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		Properties hibernateProperties = new Properties();
		URL hibernatePropertiesFileUrl = ServerApp.class.getClassLoader()
				.getResource("server/hibernate.properties");
		File hibernatePropertiesFile = new File(
				hibernatePropertiesFileUrl.getFile());
		try {
			InputStream in = new FileInputStream(hibernatePropertiesFile);
			hibernateProperties.load(in);
			String hbm2dllKey = "hibernate.hbm2ddl.auto";
			String hbm2ddlValue = hibernateProperties.getProperty(hbm2dllKey);

			if (hbm2ddlValue.equalsIgnoreCase("create"))
				hibernateProperties.setProperty(hbm2dllKey, "update");

			in.close();
			OutputStream out = new FileOutputStream(hibernatePropertiesFile);
			hibernateProperties.store(out, null);

		} catch (IOException e) {
			System.err.println("hibernate.properties file not found!");
		}

		System.out.println(context);
	}
}

Change hbm2dll property = update after creating schema


/*
 * 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.logging.log4j.test;

import org.apache.logging.log4j.Level;

/**
 *
 */
public class ExtendedLevels {

    public static final Level NOTE = Level.forName("NOTE", 350);
    public static final Level DETAIL = Level.forName("DETAIL", 450);
}

/*
 * 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.logging.log4j.test;

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

/**
 *
 */
@Plugin(name="ExtendedLevel", category=Level.CATEGORY)
public class ExtendedLevels {

    public static final Level NOTE = Level.forName("NOTE", 350);
    public static final Level DETAIL = Level.forName("DETAIL", 450);
}

Revert removal of @Plugin in test


package ee.tuleva.onboarding.notification.payment;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import lombok.ToString;

import javax.validation.constraints.Min;
import java.math.BigDecimal;

@Data
@JsonNaming(SnakeCaseStrategy.class)
@ToString
public class Payment {

  private static final int MIN_AMOUNT = 100;

  @Min(MIN_AMOUNT)
  private BigDecimal amount;
  private String currency;
  private String customerName;
  private String merchantData;
  private String messageTime;
  private String messageType;
  private Long reference;
  private String shop;
  private String signature;
  private String status;
  private String transaction;

}

package ee.tuleva.onboarding.notification.payment;

import com.fasterxml.jackson.databind.PropertyNamingStrategy.SnakeCaseStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.Data;
import lombok.ToString;

import javax.validation.constraints.Min;
import java.math.BigDecimal;

@Data
@JsonNaming(SnakeCaseStrategy.class)
@ToString
public class Payment {

  private static final int MIN_AMOUNT = 125;

  @Min(MIN_AMOUNT)
  private BigDecimal amount;
  private String currency;
  private String customerName;
  private String merchantData;
  private String messageTime;
  private String messageType;
  private Long reference;
  private String shop;
  private String signature;
  private String status;
  private String transaction;

}

Update min amount for incoming payments


/**
 * Copyright (C) 2013 Alexander Szczuczko
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package ca.szc.keratin.core.net;

import org.pmw.tinylog.Logger;

import net.engio.mbassy.IPublicationErrorHandler;
import net.engio.mbassy.PublicationError;

/**
 * Logs PublicationErrors at error level
 */
public class BusErrorHandler
    implements IPublicationErrorHandler
{

    @Override
    public void handleError( PublicationError error )
    {
        Logger.error( error.toString() );
    }

}

/**
 * Copyright (C) 2013 Alexander Szczuczko
 *
 * This file may be modified and distributed under the terms
 * of the MIT license. See the LICENSE file for details.
 */
package ca.szc.keratin.core.net;

import org.pmw.tinylog.Logger;

import net.engio.mbassy.IPublicationErrorHandler;
import net.engio.mbassy.PublicationError;

/**
 * Logs PublicationErrors at error level
 */
public class BusErrorHandler
    implements IPublicationErrorHandler
{

    @Override
    public void handleError( PublicationError error )
    {
        Logger.error( error.toString() );
        logAllSubCauses( error.getCause() );

    }

    private void logAllSubCauses( Throwable cause )
    {
        Throwable subcause = cause.getCause();
        if ( subcause != null )
        {
            Logger.error( subcause, "Subcause of " + cause );
            logAllSubCauses( subcause );
        }
    }
}

Add recursive logging of causes for the bus error handler.


package competitive.programming.timemanagement;

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

import org.junit.Test;

import competitive.programming.timemanagement.TimeoutException;
import competitive.programming.timemanagement.Timer;

public class TimerTest {

	@Test
	public void nonStartedTimerDoesNotTimeout() {
		Timer timer = new Timer();
		try {
			timer.timeCheck();
			sleep(1);
			timer.timeCheck();
		} catch (TimeoutException e) {
			fail();
		}
	}

	@Test
	public void doesNotTimeOutBeforeTimeoutReached() {
		Timer timer = new Timer();
		try {
			timer.startTimer(2);
			sleep(1);
			long currentTimeTaken = timer.currentTimeTakenInNanoSeconds();
			assertTrue(currentTimeTaken>1*1000*1000);
			assertTrue(currentTimeTaken<2*1000*1000);
			timer.timeCheck();
		} catch (TimeoutException e) {
			fail();
		}
	}

	@Test(expected = TimeoutException.class)
	public void timeoutReached() throws TimeoutException {
		Timer timer = new Timer();
		timer.startTimer(1);
		sleep(2);
		timer.timeCheck();
	}

	private void sleep(long milliseconds){
		//I had some difficulties to sleep precisely a number of milliseconds.
		//Thread.sleep was not fine...
		long start = System.nanoTime();
		long timeout = start+milliseconds*1000*1000;

		while (System.nanoTime()<timeout){
			//do nothing
		}
	}
}

package competitive.programming.timemanagement;

import static org.junit.Assert.fail;

import org.junit.Test;

public class TimerTest {

    @Test
    public void nonStartedTimerDoesNotTimeout() {
        Timer timer = new Timer();
        try {
            timer.timeCheck();
            sleep(1);
            timer.timeCheck();
        } catch (TimeoutException e) {
            fail();
        }
    }

    @Test
    public void doesNotTimeOutBeforeTimeoutReached() {
        Timer timer = new Timer();
        try {
            // We have a random failing test here. Try to reproduce the issue
            // more frequently.
            for (int i = 0; i < 100; i++) {
                timer.startTimer(20);
                sleep(10);
                timer.timeCheck();
            }
        } catch (TimeoutException e) {
            fail();
        }
    }

    @Test(expected = TimeoutException.class)
    public void timeoutReached() throws TimeoutException {
        Timer timer = new Timer();
        timer.startTimer(1);
        sleep(2);
        timer.timeCheck();
    }

    private void sleep(long milliseconds) {
        // I had some difficulties to sleep precisely a number of milliseconds.
        // Thread.sleep was not fine...
        long start = System.nanoTime();
        long timeout = start + milliseconds * 1000 * 1000;

        while (System.nanoTime() < timeout) {
            // do nothing
        }
    }
}

Change timer test so that we can reproduce the random issue. Change timings.


package com.openxc.messages;

import java.util.HashMap;

import junit.framework.TestCase;
import org.junit.Test;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import android.os.Parcel;

@Config(emulateSdk = 18, manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class NamedVehicleMessageTest extends TestCase {
    NamedVehicleMessage message;
    HashMap<String, Object> data;

    @Before
    public void setup() {
        data = new HashMap<String, Object>();
        data.put("value", Double.valueOf(42));
        message = new NamedVehicleMessage("foo", data);
    }

    @Test
    public void testName() {
        assertEquals("foo", message.getName());
    }

    @Test
    public void testExtractsNameFromValues() {
        data.put("name", "bar");
        message = new NamedVehicleMessage(data);
        assertEquals("bar", message.getName());
        assertFalse(message.contains("name"));
    }

    @Test
    public void testWriteAndReadFromParcel() {
        Parcel parcel = Parcel.obtain();
        message.writeToParcel(parcel, 0);

        // Reset parcel for reading
        parcel.setDataPosition(0);

        VehicleMessage createdFromParcel =
                VehicleMessage.CREATOR.createFromParcel(parcel);
        assertTrue(message instanceof NamedVehicleMessage);
        assertEquals(message, createdFromParcel);
    }
}

package com.openxc.messages;

import java.util.HashMap;

import junit.framework.TestCase;
import org.junit.Test;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import android.os.Parcel;

@Config(emulateSdk = 18, manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class NamedVehicleMessageTest extends TestCase {
    NamedVehicleMessage message;
    HashMap<String, Object> data;

    @Before
    public void setup() {
        data = new HashMap<String, Object>();
        data.put("value", Double.valueOf(42));
        message = new NamedVehicleMessage("foo", data);
    }

    @Test
    public void testName() {
        assertEquals("foo", message.getName());
    }

    @Test
    public void testExtractsNameFromValues() {
        data.put("name", "bar");
        message = new NamedVehicleMessage(data);
        assertEquals("bar", message.getName());
        assertFalse(message.contains("name"));
    }

    @Test
    public void sameEquals() {
        assertEquals(message, message);
    }

    @Test
    public void sameNameAndValueEquals() {
        NamedVehicleMessage anotherMessage = new NamedVehicleMessage("foo", data);
        assertEquals(message, anotherMessage);
    }

    @Test
    public void testWriteAndReadFromParcel() {
        Parcel parcel = Parcel.obtain();
        message.writeToParcel(parcel, 0);

        // Reset parcel for reading
        parcel.setDataPosition(0);

        VehicleMessage createdFromParcel =
                VehicleMessage.CREATOR.createFromParcel(parcel);
        assertTrue(message instanceof NamedVehicleMessage);
        assertEquals(message, createdFromParcel);
    }
}

Test equals overridden on NamedVehicleMessage.


package seedu.taskitty.logic.commands;

import java.util.Set;

/**
 * Finds and lists all tasks in task manager whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class ViewDoneCommand extends Command {

    public static final String COMMAND_WORD = "viewdone";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": view all previously marked as done tasks. "
            + "Example: " + COMMAND_WORD;

    public ViewDoneCommand() {
    }

    @Override
    public CommandResult execute() {

        model.updateFilteredDoneList();
        return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size()));
    }

    @Override
    public void saveStateIfNeeded() {
        model.saveState();
    }

}

package seedu.taskitty.logic.commands;

import java.util.Set;

/**
 * Finds and lists all tasks in task manager whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class ViewDoneCommand extends Command {

    public static final String COMMAND_WORD = "viewdone";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": view all previously marked as done tasks. "
            + "Example: " + COMMAND_WORD;

    public ViewDoneCommand() {
    }

    @Override
    public CommandResult execute() {

        model.updateFilteredDoneList();
        return new CommandResult(getMessageForTaskListShownSummary(model.getTaskList().size()));
    }

    @Override
    public void saveStateIfNeeded(String commandText) {
        model.saveState(commandText);
    }

}

Update saveStateIsNeeded parameters in viewDoneCommand


package org.ow2.chameleon.wisdom.api.bodies;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.io.IOUtils;
import org.ow2.chameleon.wisdom.api.http.Context;
import org.ow2.chameleon.wisdom.api.http.Renderable;
import org.ow2.chameleon.wisdom.api.http.Result;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * A renderable object taking a String as parameter.
 */
public class RenderableString implements Renderable {

    //TODO Support encoding

    private final String rendered;

    public RenderableString(String object) {
        rendered = object;
    }

    public RenderableString(Object object) {
        rendered = object.toString();
    }

    @Override
    public InputStream render(Context context, Result result) throws Exception {
        return new ByteArrayInputStream(rendered.getBytes());
    }

    @Override
    public long length() {
        return rendered.length();
    }
}

package org.ow2.chameleon.wisdom.api.bodies;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.io.IOUtils;
import org.ow2.chameleon.wisdom.api.http.Context;
import org.ow2.chameleon.wisdom.api.http.Renderable;
import org.ow2.chameleon.wisdom.api.http.Result;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * A renderable object taking a String as parameter.
 */
public class RenderableString implements Renderable {

    //TODO Support encoding

    private final String rendered;

    public RenderableString(String object) {
        rendered = object;
    }

    public RenderableString(StringBuilder object) {
        rendered = object.toString();
    }

    public RenderableString(StringBuffer object) {
        rendered = object.toString();
    }

    public RenderableString(Object object) {
        rendered = object.toString();
    }

    @Override
    public InputStream render(Context context, Result result) throws Exception {
        return new ByteArrayInputStream(rendered.getBytes());
    }

    @Override
    public long length() {
        return rendered.length();
    }
}

Add two new constructor to renderable string.


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

package com.google.gerrit.sshd.commands;

import com.google.common.cache.Cache;
import com.google.common.collect.Sets;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.sshd.SshCommand;
import com.google.inject.Inject;

import java.util.SortedSet;

abstract class CacheCommand extends SshCommand {
  @Inject
  protected DynamicMap<Cache<?, ?>> cacheMap;

  protected SortedSet<String> cacheNames() {
    SortedSet<String> names = Sets.newTreeSet();
    for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
      names.add(cacheNameOf(e.getPluginName(), e.getExportName()));
    }
    return names;
  }

  protected String cacheNameOf(String plugin, String name) {
    if ("gerrit".equals(plugin)) {
      return name;
    } else {
      return plugin + "." + name;
    }
  }
}

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

package com.google.gerrit.sshd.commands;

import com.google.common.cache.Cache;
import com.google.common.collect.Sets;
import com.google.gerrit.extensions.registration.DynamicMap;
import com.google.gerrit.sshd.SshCommand;
import com.google.inject.Inject;

import java.util.SortedSet;

abstract class CacheCommand extends SshCommand {
  @Inject
  protected DynamicMap<Cache<?, ?>> cacheMap;

  protected SortedSet<String> cacheNames() {
    SortedSet<String> names = Sets.newTreeSet();
    for (DynamicMap.Entry<Cache<?, ?>> e : cacheMap) {
      names.add(cacheNameOf(e.getPluginName(), e.getExportName()));
    }
    return names;
  }

  protected String cacheNameOf(String plugin, String name) {
    if ("gerrit".equals(plugin)) {
      return name;
    } else {
      return plugin + "-" + name;
    }
  }
}

Use '-' in cache name as separator between plugin name and cache name


package cuke4duke.internal.jvmclass;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

/**
 * @author Henning Jensen
 */
public class GuiceFactory implements ObjectFactory {

	private final Module module;
    private final List<Class<?>> classes = new ArrayList<Class<?>>();
    private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>();
    private Injector injector;

    public GuiceFactory() throws Throwable {
        String moduleClassName = System.getProperty("cuke4duke.guiceModule", null);
        module = (Module) Class.forName(moduleClassName).newInstance();
    }

    public void addClass(Class<?> clazz) {
        classes.add(clazz);
    }

    public void addInstance(Object instance) {
    }

    public void createObjects() {
        injector = Guice.createInjector(module);
		for(Class<?> clazz: classes) {
	        instanceMap.put(clazz, injector.getInstance(clazz));
		}
    }

    public void disposeObjects() {
    }

    public Object getComponent(Class<?> clazz) {
        return instanceMap.get(clazz);
    }

}

package cuke4duke.internal.jvmclass;

import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.List;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import cuke4duke.StepMother;

/**
 * @author Henning Jensen
 */
public class GuiceFactory implements ObjectFactory {

	private final Module module;
    private final List<Class<?>> classes = new ArrayList<Class<?>>();
    private final Map<Class<?>, Object> instanceMap = new HashMap<Class<?>, Object>();
    private Injector injector;

    public GuiceFactory() throws Throwable {
        String moduleClassName = System.getProperty("cuke4duke.guiceModule", null);
        module = (Module) Class.forName(moduleClassName).newInstance();
    }

    public void addClass(Class<?> clazz) {
        classes.add(clazz);
    }

    public void addStepMother(StepMother mother) {
        // Not supported yet.
    }

    public void createObjects() {
        injector = Guice.createInjector(module);
		for(Class<?> clazz: classes) {
	        instanceMap.put(clazz, injector.getInstance(clazz));
		}
    }

    public void disposeObjects() {
    }

    public Object getComponent(Class<?> clazz) {
        return instanceMap.get(clazz);
    }

}

Rename method to inject step mother


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package io.dropwizard.jetty;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * @see https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java
 */
public interface LocalIpFilter {

    public boolean use(NetworkInterface networkInterface,
                       InetAddress address) throws SocketException;
}

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

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * @see https://github.com/apache/curator/blob/master/curator-x-discovery/src/main/java/org/apache/curator/x/discovery/LocalIpFilter.java
 */
public interface LocalIpFilter {

    public boolean use(NetworkInterface networkInterface,
                       InetAddress address) throws SocketException;
}

Update copyright notice to reference Curator


package org.forge.text.syntax.encoder;

import java.io.OutputStream;

import org.forge.text.syntax.Encoder;
import org.forge.text.syntax.Theme;
import org.forge.text.syntax.TokenType;

public class DebugEncoder extends Encoder.AbstractEncoder implements Encoder {

   public DebugEncoder(OutputStream out, Theme theme) {
      super(out, theme);
   }

   @Override
   public void textToken(String text, TokenType type) {
      if(type == TokenType.space) {
         write(text);
      }
      else {
         String output = text;
         if(output.indexOf("\\") != -1) {
            output = output.replaceAll("\\\\", "\\\\\\\\");
         }
         if(output.indexOf(")") != -1) {
            output = output.replaceAll("\\)", "\\\\)");
         }
         write(type + "(" + output + ")");
      }
   }

   @Override
   public void beginGroup(TokenType type) {
      writeln(type + "<");
   }

   @Override
   public void endGroup(TokenType type) {
      writeln(">");
   }

   @Override
   public void beginLine(TokenType type) {
      writeln(type + "[");
   }

   @Override
   public void endLine(TokenType type) {
      writeln("]");
   }
}

package org.forge.text.syntax.encoder;

import java.io.OutputStream;

import org.forge.text.syntax.Encoder;
import org.forge.text.syntax.Theme;
import org.forge.text.syntax.TokenType;

public class DebugEncoder extends Encoder.AbstractEncoder implements Encoder {

   public DebugEncoder(OutputStream out, Theme theme) {
      super(out, theme);
   }

   @Override
   public void textToken(String text, TokenType type) {
      if(type == TokenType.space) {
         write(text);
      }
      else {
         String output = text;
         if(output.indexOf("\\") != -1) {
            output = output.replaceAll("\\\\", "\\\\\\\\");
         }
         if(output.indexOf(")") != -1) {
            output = output.replaceAll("\\)", "\\\\)");
         }
         write(fixTokeName(type) + "(" + output + ")");
      }
   }

   @Override
   public void beginGroup(TokenType type) {
      write(fixTokeName(type) + "<");
   }

   @Override
   public void endGroup(TokenType type) {
      write(">");
   }

   @Override
   public void beginLine(TokenType type) {
      write(fixTokeName(type) + "[");
   }

   @Override
   public void endLine(TokenType type) {
      write("]");
   }

   public String fixTokeName(TokenType type) {
      String name = type.name();
      if(name.endsWith("_")) {
         name = name.substring(0, name.length()-1);
      }
      return name;
   }
}

Align Debug output with Coderay to verify test suite


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

package net.myrrix.online.partition;

import java.util.List;

import org.apache.mahout.common.Pair;

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

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

}

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

package net.myrrix.online.partition;

import java.util.List;

import com.google.common.net.HostAndPort;

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

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

}

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


package com.laschuet.spark.rest.sample;

import javax.servlet.ServletContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.spark.sql.SparkSession;

@Path("info")
public class Info {
    @Context
    private ServletContext context = null;

    @Path("version")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSparkSessionVersion() {
        SparkSession sparkSession = (SparkSession) context.getAttribute("sparkSession");
        return sparkSession.version();
    }
}

package com.laschuet.spark.rest.sample;

import javax.servlet.ServletContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.apache.spark.SparkContext;
import org.apache.spark.sql.SparkSession;

@Path("info")
public class Info {
    @Context
    private ServletContext context = null;

    @Path("version")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSparkSessionVersion() {
        SparkSession sparkSession = (SparkSession) context.getAttribute("sparkSession");
        return sparkSession.version();
    }

    @Path("user")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSparkContextVersion() {
        SparkSession sparkSession = (SparkSession) context.getAttribute("sparkSession");
        SparkContext sparkContext = sparkSession.sparkContext();
        return sparkContext.sparkUser();
    }
}

Add an endpoint to query the Spark user


package hello.config.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import hello.dao.GreetingService;
import hello.entities.Greeting;

@Component
@Profile({ "default", "test" })
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {

	private final static Logger log = LoggerFactory.getLogger(InitialDataLoader.class);

	private final static String GREETING = "Hello, %s!";

	@Autowired
	private GreetingService greetingService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		if (greetingService.count() > 0) {
			log.info("Database already populated. Skipping data initialization.");
			return;
		}

		Greeting greeting = new Greeting();
		greeting.setTemplate(GREETING);

		greetingService.save(greeting);

		log.info("Added greeting (" + greeting.getId() + "): " + greeting.getTemplate());
	}
}

package hello.config.data;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import hello.dao.GreetingService;
import hello.entities.Greeting;

@Component
@Profile({ "default", "test" })
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {

	private final static Logger log = LoggerFactory.getLogger(InitialDataLoader.class);

	private final static String[] TEMPLATES = { "Hello, %s!", "Howdy, %s!" };

	@Autowired
	private GreetingService greetingService;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {

		if (greetingService.count() > 0) {
			log.info("Database already populated. Skipping data initialization.");
			return;
		}

		for (String template : TEMPLATES) {
			Greeting greeting = new Greeting();
			greeting.setTemplate(template);

			greetingService.save(greeting);
			log.info("Added greeting (" + greeting.getId() + "): " + greeting.getTemplate());
		}
	}
}

Add another greeting to the initial data.


package com.gaiagps.iburn;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by davidbrodsky on 7/8/15.
 */
public class CurrentDateProvider {

    /**
     * Date to use as "now" for Debug builds
     */
    public static Date MOCK_NOW_DATE = new GregorianCalendar(2015, Calendar.AUGUST, 30, 15, 43).getTime();

    public static Date getCurrentDate() {
        return BuildConfig.MOCK ? MOCK_NOW_DATE : new Date();
    }

    public static long getCurrentTimeMillis() {
        return BuildConfig.MOCK ? MOCK_NOW_DATE.getTime() : new Date().getTime();
    }
}

package com.gaiagps.iburn;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by davidbrodsky on 7/8/15.
 */
public class CurrentDateProvider {

    /**
     * Date to use as "now" for Debug builds
     */
    public static Date MOCK_NOW_DATE = new GregorianCalendar(2015, Calendar.AUGUST, 31, 15, 43).getTime();

    public static Date getCurrentDate() {
        return BuildConfig.MOCK ? MOCK_NOW_DATE : new Date();
    }

    public static long getCurrentTimeMillis() {
        return BuildConfig.MOCK ? MOCK_NOW_DATE.getTime() : new Date().getTime();
    }
}

Update mocked date to 8/31