package com.mocircle.cidrawing.element;

import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.RectF;

/**
 * A kind of element which is surrounded by the bounds.
 */
public abstract class BoundsElement extends DrawElement {

    protected transient RectF originalBoundingBox;
    protected transient Path boundingPath;

    @Override
    public void applyMatrixForData(Matrix matrix) {
        super.applyMatrixForData(matrix);
        boundingPath.transform(matrix);
    }

    @Override
    public void updateBoundingBox() {
        if (boundingPath != null) {
            RectF box = new RectF();
            boundingPath.computeBounds(box, true);
            setBoundingBox(box);
        }
    }

    @Override
    public RectF getOuterBoundingBox() {
        if (boundingPath != null) {
            Path path = new Path(boundingPath);
            path.transform(getDisplayMatrix());
            RectF box = new RectF();
            path.computeBounds(box, true);
            return box;
        }
        return new RectF();
    }

    @Override
    protected void cloneTo(BaseElement element) {
        super.cloneTo(element);
        if (element instanceof BoundsElement) {
            BoundsElement obj = (BoundsElement) element;
            if (originalBoundingBox != null) {
                obj.originalBoundingBox = new RectF(originalBoundingBox);
            }
            if (boundingPath != null) {
                obj.boundingPath = new Path(boundingPath);
            }
        }
    }

    protected abstract void calculateBoundingBox();

}

package com.mocircle.cidrawing.element;

import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.RectF;

/**
 * A kind of element which is surrounded by the bounds.
 */
public abstract class BoundsElement extends DrawElement {

    protected transient RectF originalBoundingBox;
    protected transient Path boundingPath;

    @Override
    public void applyMatrixForData(Matrix matrix) {
        super.applyMatrixForData(matrix);
        boundingPath.transform(matrix);
    }

    @Override
    public void updateBoundingBox() {
        if (boundingPath != null) {
            RectF box = new RectF();
            boundingPath.computeBounds(box, true);
            setBoundingBox(box);
        }
    }

    @Override
    public RectF getOuterBoundingBox() {
        if (boundingPath != null) {
            Path path = new Path(boundingPath);
            path.transform(getDisplayMatrix());
            RectF box = new RectF();
            path.computeBounds(box, true);
            return box;
        }
        return new RectF();
    }

    @Override
    public Path getTouchableArea() {
        if (boundingPath != null) {
            return boundingPath;
        } else {
            return new Path();
        }
    }

    @Override
    protected void cloneTo(BaseElement element) {
        super.cloneTo(element);
        if (element instanceof BoundsElement) {
            BoundsElement obj = (BoundsElement) element;
            if (originalBoundingBox != null) {
                obj.originalBoundingBox = new RectF(originalBoundingBox);
            }
            if (boundingPath != null) {
                obj.boundingPath = new Path(boundingPath);
            }
        }
    }

    protected abstract void calculateBoundingBox();

}

Fix bounds element touch area incorrect issue.


package fr.insee.pogues.webservice.rest;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;

/**
 * Created by acordier on 04/07/17.
 */
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    private final Status STATUS = Status.INTERNAL_SERVER_ERROR;

    public Response toResponse(Throwable error){
        RestMessage message = new RestMessage(
                STATUS.getStatusCode(),
                "An unexpected error occured", error.getMessage());
        return Response.status(STATUS)
                .entity(message)
                .type(MediaType.APPLICATION_JSON)
                .build();
    }
}

package fr.insee.pogues.webservice.rest;

import org.apache.log4j.Logger;

import javax.ws.rs.NotFoundException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.Provider;

/**
 * Created by acordier on 04/07/17.
 */
@Provider
public class GenericExceptionMapper implements ExceptionMapper<Throwable> {

    private Status STATUS = Status.INTERNAL_SERVER_ERROR;

    private Logger logger = Logger.getLogger(GenericExceptionMapper.class);

    public Response toResponse(Throwable error){
        RestMessage message = new RestMessage(
                STATUS.getStatusCode(),
                "An unexpected error occured", error.getMessage());
        if(error instanceof NotFoundException) {
            STATUS = Status.NOT_FOUND;
            message.setMessage("Not Found");
            message.setDetails("No JAX-RS resource found for this path");
        }
        return Response.status(STATUS)
                .entity(message)
                .type(MediaType.APPLICATION_JSON)
                .build();
    }
}

Make exception mapper more accurate on jax-rs internal error


package hypernova;

import javax.swing.JFrame;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

import hypernova.gui.Viewer;

public class Hypernova {
    public static final String TITLE = "Hypernova";

    public static Universe universe;
    private static Viewer viewer;

    public static boolean debug = false;
    private static Logger log = Logger.getRootLogger();

    public static void main(String[] args) {
        /* Fix for poor OpenJDK performance. */
        System.setProperty("sun.java2d.pmoffscreen", "false");

        /* Prepare logging. */
        BasicConfigurator.configure();
        if (debug)
            log.setLevel(Level.TRACE);

        universe = new Universe();
        viewer = new Viewer(universe);

        JFrame frame = new JFrame(TITLE);
        frame.add(viewer);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        viewer.requestFocusInWindow();

        Sound.init();

        universe.start();
    }
}

package hypernova;

import javax.swing.JFrame;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.BasicConfigurator;

import hypernova.gui.Viewer;

public class Hypernova {
    public static final String TITLE = "Hypernova";

    public static Universe universe;
    private static Viewer viewer;

    public static boolean debug = false;
    private static Logger log = Logger.getRootLogger();

    public static void main(String[] args) {
        /* Fix for poor OpenJDK performance. */
        System.setProperty("sun.java2d.pmoffscreen", "false");

        /* Prepare logging. */
        BasicConfigurator.configure();
        if (debug)
            log.setLevel(Level.TRACE);

        Sound.init();

        universe = new Universe();
        viewer = new Viewer(universe);

        JFrame frame = new JFrame(TITLE);
        frame.add(viewer);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        viewer.requestFocusInWindow();

        universe.start();
    }
}

Move sound initialization up before showing the window.


package info.u_team.u_team_test.enchantment;

import info.u_team.u_team_core.enchantment.UEnchantment;
import net.minecraft.enchantment.EnchantmentType;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraftforge.common.MinecraftForge;

public class AutoSmeltEnchantment extends UEnchantment {

	public AutoSmeltEnchantment(String name) {
		super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND });
		MinecraftForge.EVENT_BUS.register(this);
	}
}

package info.u_team.u_team_test.enchantment;

import info.u_team.u_team_core.enchantment.UEnchantment;
import net.minecraft.enchantment.EnchantmentType;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraftforge.common.MinecraftForge;

public class AutoSmeltEnchantment extends UEnchantment {

	public AutoSmeltEnchantment(String name) {
		super(name, Rarity.COMMON, EnchantmentType.DIGGER, new EquipmentSlotType[] { EquipmentSlotType.MAINHAND });
	}
}

Remove unused registry for the event bus


package fr.insee.eno.exception;

import net.sf.saxon.trans.XPathException;

public class Utils {

    public static String getErrorLocation(String styleSheet, Exception e){
        String errorMessage="";
        try{
            int line = ((XPathException) e).getLocator().getLineNumber();
            int column = ((XPathException) e).getLocator().getColumnNumber();
            errorMessage += String.format("Error in :%s [line :%d - column:%d]", styleSheet,line,column);
        } catch (Exception exception){
        }
        return errorMessage;
    }
}

package fr.insee.eno.exception;

import net.sf.saxon.trans.XPathException;

public class Utils {

    public static String getErrorLocation(String styleSheet, Exception e){
        String errorMessage="";
        try{
            String location = ((XPathException) e).getLocationAsString();
            errorMessage += String.format("Error in :%s %s", styleSheet, location);
        } catch (Exception exception){
        }
        return errorMessage;
    }
}

Improve utils function for xslt exception


package throwing.bridge;

import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
interface RethrowChain<X extends Throwable, Y extends Throwable> {
    public static final RethrowChain<Throwable, Throwable> START = t -> Optional.empty();
    public static final RethrowChain<Throwable, Throwable> END = t -> {
        if (t instanceof Error) {
            throw (Error) t;
        } else if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new AssertionError(t);
        }
    };

    @SuppressWarnings("unchecked")
    public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> start() {
        return (RethrowChain<X, Y>) START;
    }

    @SuppressWarnings("unchecked")
    public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> end() {
        return (RethrowChain<X, Y>) END;
    }

    public Optional<Y> handle(X t);

    default public <Z extends Throwable> RethrowChain<X, Z> rethrow(Function<? super Y, ? extends Z> mapper) {
        return t -> this.handle(t).map(mapper);
    }

    default public RethrowChain<X, Y> chain(RethrowChain<X, Y> second) {
        return this == START ? second : t -> {
            Optional<Y> o = this.handle(t);
            return o.isPresent() ? o : second.handle(t);
        };
    };

    default public Function<X, Y> finish() {
        return t -> this.chain(end()).handle(t).get();
    }
}

package throwing.bridge;

import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
interface RethrowChain<X extends Throwable, Y extends Throwable> extends Function<X, Optional<Y>> {
    public static final RethrowChain<Throwable, Throwable> START = t -> Optional.empty();
    public static final RethrowChain<Throwable, Throwable> END = t -> {
        if (t instanceof Error) {
            throw (Error) t;
        } else if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new AssertionError(t);
        }
    };

    @SuppressWarnings("unchecked")
    public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> start() {
        return (RethrowChain<X, Y>) START;
    }

    @SuppressWarnings("unchecked")
    public static <X extends Throwable, Y extends Throwable> RethrowChain<X, Y> end() {
        return (RethrowChain<X, Y>) END;
    }

    default public <Z extends Throwable> RethrowChain<X, Z> rethrow(Function<? super Y, ? extends Z> mapper) {
        return t -> apply(t).map(mapper);
    }

    default public RethrowChain<X, Y> chain(RethrowChain<X, Y> second) {
        return this == START ? second : t -> {
            Optional<Y> o = apply(t);
            return o.isPresent() ? o : second.apply(t);
        };
    };

    default public Function<X, Y> finish() {
        RethrowChain<X, Y> c = this.chain(end());
        return t -> c.apply(t).get();
    }
}

Make rethrow chain a Function


package models;

import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "actors")
public class Actor extends Model {

    @Id
    private Long id;

    @Constraints.Required
    @Column(unique = true)
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static Finder<Long, Actor> find = new Finder<>(Long.class, Actor.class);
}

package models;

import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "actors")
public class Actor extends Model {

    @Id
    private Long id;

    @Constraints.Required
    @Column(unique = true)
    private String name;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static Finder<Long, Actor> find = new Finder<>(Long.class, Actor.class);

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        Actor actor = (Actor) o;

        if (name != null ? !name.equals(actor.name) : actor.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}

Add hashCode and equals to actor model, since a show holds all actors in a HashSet


package com.irgat.rest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldEndpoint
{
    @RequestMapping("/helloWorld")
    public String helloWorld() {
        return "Hello World after redeployment!";
    }
}

package com.irgat.rest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldEndpoint
{
    @RequestMapping("/helloWorld")
    public String helloWorld() {
        return "Hello World after redeployment! Are you lucky to see me!";
    }
}

Test for sequential auto redeployment.


package info.u_team.u_team_core;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

@Mod(UCoreMain.MODID)
public class UCoreMain {

	public static final String MODID = "uteamcore";
	public static final Logger LOGGER = LogManager.getLogger("UTeamCore");

	private static final IModProxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new);

	public UCoreMain() {
		FMLJavaModLoadingContext.get().getModEventBus().register(this);
		proxy.construct();
	}

	@SubscribeEvent
	public void setup(FMLCommonSetupEvent event) {
		proxy.setup();
	}

	@SubscribeEvent
	public void ready(FMLLoadCompleteEvent event) {
		proxy.complete();
	}

}

package info.u_team.u_team_core;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

@Mod(UCoreMain.MODID)
public class UCoreMain {

	public static final String MODID = "uteamcore";
	public static final Logger LOGGER = LogManager.getLogger("UTeamCore");

	private static final IModProxy PROXY = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new);

	public UCoreMain() {
		FMLJavaModLoadingContext.get().getModEventBus().register(this);
		PROXY.construct();
	}

	@SubscribeEvent
	public void setup(FMLCommonSetupEvent event) {
		PROXY.setup();
	}

	@SubscribeEvent
	public void ready(FMLLoadCompleteEvent event) {
		PROXY.complete();
	}

}

Fix proxy variable that was not adjusted


package seedu.ezdo.commons.util;

import seedu.ezdo.model.todo.ReadOnlyTask;

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

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

}

package seedu.ezdo.commons.util;

import seedu.ezdo.model.todo.ReadOnlyTask;

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

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

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

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

        if (isBothDatesMissing && isRecurring) {
            return false;
        }

        return true;
    }

}

Fix recur bug: Not working when floating task is added


package tars.logic.commands;

/**
 * Represents the result of a command execution.
 */
public class CommandResult {

    public final String feedbackToUser;

    public CommandResult(String feedbackToUser) {
        assert feedbackToUser != null;
        this.feedbackToUser = feedbackToUser;
    }

}

package tars.logic.commands;

import java.util.ArrayList;

import tars.model.task.ReadOnlyTask;

/**
 * Represents the result of a command execution.
 */
public class CommandResult {

    public final String feedbackToUser;

    public CommandResult(String feedbackToUser) {
        assert feedbackToUser != null;
        this.feedbackToUser = feedbackToUser;
    }

    /**
     * Formats an ArrayList of tasks to return it as a string
     */
    public static String formatTasksList(ArrayList<ReadOnlyTask> taskList) {
        String toReturn = "";
        for (ReadOnlyTask t : taskList) {
            toReturn += t.toString() +"\n";
        }
        return toReturn.trim();
    }

}

Add method to format lists of tasks for commandResult


package org.c4k3.Events;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

/** Class is responsible for listening to player deaths
 * and making sure no xp is dropped in the events
 */
public class PlayerDeath implements Listener {

	@EventHandler(priority = EventPriority.NORMAL,ignoreCancelled=true)
	public void onPlayerDeath(PlayerDeathEvent event) {

		if ( Event.isPlayerActive(event.getEntity().getUniqueId()) ) {

			event.setDroppedExp(0);

		}

	}

}

package org.c4k3.Events;

import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

/** Class is responsible for listening to player deaths
 * and making sure no xp is dropped in the events
 * and that players don't keep any set gamemodes
 */
public class PlayerDeath implements Listener {

	@EventHandler(priority = EventPriority.NORMAL,ignoreCancelled=true)
	public void onPlayerDeath(PlayerDeathEvent event) {

		if ( Event.isPlayerActive(event.getEntity().getUniqueId()) ) {

			event.setDroppedExp(0);

		}

		Player player = event.getEntity();

		if ( !player.isOp() && player.getGameMode() != GameMode.SURVIVAL ) {

			player.setGameMode(GameMode.SURVIVAL);

		}

	}

}

Fix players being able to /kill after restart to leave with gm1


package com.axelmonroy;

import javax.swing.*;

/**
 * Silly  Tic-Tac-Toe - By Axel!
 *
 */
public class App
{
    public static void main(String[] args) {
        JFrame frame = new JFrame("Silly  Tic-Tac-Toe - By Axel");
        frame.setContentPane(new Client_Tic_Tac_Toe().JPanelMain);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

package com.axelmonroy;

import javax.swing.*;

/**
 * Smart  Tic-Tac-Toe - By Axel!
 *
 */
public class App
{
    public static void main(String[] args) {
        JFrame frame = new JFrame("Smart Tic-Tac-Toe - By Axel");
        frame.setContentPane(new Client_Tic_Tac_Toe().JPanelMain);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

Change Silly for Smart in comments and title


package de.innoaccel.wamp.server.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;

public class PrefixMessageConverter extends JsonParsingConverter<PrefixMessage>
{
    @Override
    public boolean canConvert(int messageCode)
    {
        return Message.PREFIX == messageCode;
    }

    @Override
    public String serialize(PrefixMessage message, Websocket socket) throws InvalidMessageCodeException
    {
        try {
            return this.objectMapper.writeValueAsString(new Object[] {
                Message.PREFIX,
                message.getPrefix(),
                message.getURI()
            });
        } catch (JsonProcessingException ex) {
            throw new InvalidMessageCodeException(Message.EVENT);
        }
    }

    @Override
    protected PrefixMessage deserialize(JsonNode message, Websocket socket) throws MessageParseException, InvalidMessageCodeException
    {
        this.assertMessageCode(message, Message.PREFIX);

        String prefix = this.readStringAt(message, 1);
        if (0 == prefix.length()) {
            throw new MessageParseException("Prefix may not be empty");
        }

        String uri = this.readStringAt(message, 2);
        if (0 == uri.length()) {
            throw new MessageParseException("URI may not be empty");
        }

        return new PrefixMessage(prefix, uri);
    }
}

package de.innoaccel.wamp.server.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import de.innoaccel.wamp.server.Websocket;
import de.innoaccel.wamp.server.message.Message;
import de.innoaccel.wamp.server.message.PrefixMessage;

public class PrefixMessageConverter extends JsonParsingConverter<PrefixMessage>
{
    @Override
    public boolean canConvert(int messageCode)
    {
        return Message.PREFIX == messageCode;
    }

    @Override
    public String serialize(PrefixMessage message, Websocket socket) throws InvalidMessageCodeException
    {
        try {
            return this.objectMapper.writeValueAsString(new Object[] {
                Message.PREFIX,
                message.getPrefix(),
                message.getURI()
            });
        } catch (JsonProcessingException ex) {
            throw new InvalidMessageCodeException(Message.PREFIX);
        }
    }

    @Override
    protected PrefixMessage deserialize(JsonNode message, Websocket socket) throws MessageParseException, InvalidMessageCodeException
    {
        this.assertMessageCode(message, Message.PREFIX);

        String prefix = this.readStringAt(message, 1);
        if (0 == prefix.length()) {
            throw new MessageParseException("Prefix may not be empty");
        }

        String uri = this.readStringAt(message, 2);
        if (0 == uri.length()) {
            throw new MessageParseException("URI may not be empty");
        }

        return new PrefixMessage(prefix, uri);
    }
}

Adjust message code in exception


package protocolsupport.protocol.packet.middle.clientbound.play;

import protocolsupport.api.tab.TabAPI;
import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket;
import protocolsupport.protocol.serializer.PacketDataSerializer;
import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedPlayer;

public abstract class MiddleLogin<T> extends ClientBoundMiddlePacket<T> {

	protected int playerEntityId;
	protected int gamemode;
	protected int dimension;
	protected int difficulty;
	protected int maxplayers;
	protected String leveltype;
	protected boolean reducedDebugInfo;

	@Override
	public void readFromServerData(PacketDataSerializer serializer) {
		playerEntityId = serializer.readInt();
		gamemode = serializer.readByte();
		dimension = serializer.readByte();
		difficulty = serializer.readByte();
		serializer.readByte();
		maxplayers = TabAPI.getMaxTabSize();
		leveltype = serializer.readString(16);
		reducedDebugInfo = serializer.readBoolean();
	}

	@Override
	public void handle() {
		storage.addWatchedSelfPlayer(new WatchedPlayer(playerEntityId));
		storage.setDimensionId(dimension);
	}

}

package protocolsupport.protocol.packet.middle.clientbound.play;

import protocolsupport.api.tab.TabAPI;
import protocolsupport.protocol.packet.middle.ClientBoundMiddlePacket;
import protocolsupport.protocol.serializer.PacketDataSerializer;
import protocolsupport.protocol.typeremapper.watchedentity.types.WatchedPlayer;

public abstract class MiddleLogin<T> extends ClientBoundMiddlePacket<T> {

	protected int playerEntityId;
	protected int gamemode;
	protected int dimension;
	protected int difficulty;
	protected int maxplayers;
	protected String leveltype;
	protected boolean reducedDebugInfo;

	@Override
	public void readFromServerData(PacketDataSerializer serializer) {
		playerEntityId = serializer.readInt();
		gamemode = serializer.readByte();
		dimension = serializer.readInt();
		difficulty = serializer.readByte();
		serializer.readByte();
		maxplayers = TabAPI.getMaxTabSize();
		leveltype = serializer.readString(16);
		reducedDebugInfo = serializer.readBoolean();
	}

	@Override
	public void handle() {
		storage.addWatchedSelfPlayer(new WatchedPlayer(playerEntityId));
		storage.setDimensionId(dimension);
	}

}

Fix dimension id read from login packet. This was working only because of pure luck, but that explains problems with players logging in non in overworld dimension.


package model;

import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

/**
 * @author Emmanuel Bernard
 */
@Entity
public class Customer extends User {
	private Set<Order> orders;

	public Set<Order> getOrders() {
		return orders;
	}

	@OneToMany
	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}
}

package model;

import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

/**
 * @author Emmanuel Bernard
 */
@Entity
public class Customer extends User {
	private Set<Order> orders;
	private String nonPersistent;

	public Set<Order> getOrders() {
		return orders;
	}

	@OneToMany
	public void setOrders(Set<Order> orders) {
		this.orders = orders;
	}
}

Support for access type for entity and sub entity


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

/**
 * @author prprmurakami
 */
public class DirNotFoundException extends Exception {

    private static final long serialVersionUID = 1L;

    private String dirPath;

    public DirNotFoundException(String msg, String dirPath) {
        super(msg);
        this.dirPath = dirPath;
    }

    public String getDirPath() {
        return dirPath;
    }
}

Fix classes with no copyright


package bjohnson.ResponseHandlers;

import bjohnson.Request;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class HTMLDirectoryResponseBuilderTest {
    private String filePath;
    private Request request;

    @Before
    public void setUp(){
        filePath = System.getProperty("user.dir") + "/src/test/java/bjohnson/testResource";
        request = new Request();
        request.setURL("/");
        request.setMethod("GET");
    }
    @Test
    public void testReturns200Ok() throws Exception {
        Response response = new HTMLDirectoryResponseBuilder(filePath).getResponse(request);
        assertEquals("200 OK", response.getStatus());
    }

    @Test
    public void testBodyContainsTestHtml() throws Exception {
        HTMLDirectoryResponseBuilder htmlDirectoryResponseBuilder = new HTMLDirectoryResponseBuilder(filePath);
        Response response = htmlDirectoryResponseBuilder.getResponse(request);
        String testHtml = "\n
\n" +
                "
image.png
\n" +
                "
partial_content.txt
\n" +
                "
patch-content.txt
\n" +
                "
readerFile.txt
\n" +
                "
\n\n";
        assertArrayEquals(testHtml.getBytes(), response.getBody());
    }
}

package bjohnson.ResponseHandlers;

import bjohnson.Request;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

public class HTMLDirectoryResponseBuilderTest {
    private String filePath;
    private Request request;

    @Before
    public void setUp(){
        filePath = System.getProperty("user.dir") + "/src/test/java/bjohnson/testResource";
        request = new Request();
        request.setURL("/");
        request.setMethod("GET");
    }
    @Test
    public void testReturns200Ok() throws Exception {
        Response response = new HTMLDirectoryResponseBuilder(filePath).getResponse(request);
        assertEquals("200 OK", response.getStatus());
    }

    @Test
    public void testBodyContainsTestHtml() throws Exception {
        HTMLDirectoryResponseBuilder htmlDirectoryResponseBuilder = new HTMLDirectoryResponseBuilder(filePath);
        Response response = htmlDirectoryResponseBuilder.getResponse(request);
        assertThat(new String(response.getBody()), CoreMatchers.containsString("
image.png
\n"));
        assertThat(new String(response.getBody()), CoreMatchers.containsString("
partial_content.txt
\n"));
        assertThat(new String(response.getBody()), CoreMatchers.containsString("
patch-content.txt
\n"));
        assertThat(new String(response.getBody()), CoreMatchers.containsString("
readerFile.txt
\n"));
    }
}

Change test to check for contents instead of full string


package tours.compiler;

import tours.grammar.ToursParser;

public class Type {
    public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN);
    public static final Type CHARACTER = new Type(ToursParser.CHARACTER);
    public static final Type INTEGER = new Type(ToursParser.INTEGER);
    public static final Type STRING = new Type(ToursParser.STRING);
    private final int type;

    public Type(int type) {
        this.type = type;
    }
    public Type(String type) {
        switch (type) {
            case "boolean" :
                this.type = BOOLEAN.getType();
                break;
            case "character" :
                this.type = CHARACTER.getType();
                break;
            case "integer" :
                this.type = INTEGER.getType();
                break;
            case "string" :
                this.type = STRING.getType();
                break;
            default :
                throw new UnsupportedOperationException("Type: " + type + " was undefined");
        }
    }

    public int getType() {
        return type;
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Type) {
            return this.getType() == ((Type) object).getType();
        }
        return false;
    }
}

package tours.compiler;

import tours.grammar.ToursParser;

public class Type {
    public static final Type BOOLEAN = new Type(ToursParser.BOOLEAN);
    public static final Type CHARACTER = new Type(ToursParser.CHARACTER);
    public static final Type INTEGER = new Type(ToursParser.INTEGER);
    public static final Type STRING = new Type(ToursParser.STRING);
    private final int type;

    public Type(int type) {
        this.type = type;
    }
    public Type(String type) {
        type = type.toLowerCase();
        switch (type) {
            case "boolean" :
                this.type = BOOLEAN.getType();
                break;
            case "character" :
                this.type = CHARACTER.getType();
                break;
            case "integer" :
                this.type = INTEGER.getType();
                break;
            case "string" :
                this.type = STRING.getType();
                break;
            default :
                throw new UnsupportedOperationException("Type: " + type + " was undefined");
        }
    }

    public int getType() {
        return type;
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Type) {
            return this.getType() == ((Type) object).getType();
        }
        return false;
    }
}

Normalize type before switching on it


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

package org.svetovid.demo;

import org.svetovid.Svetovid;

public class HelloWorld {

    public static void main(String[] args) {

        // Ask for a name
        String name = Svetovid.in.readString("Please enter your name:");

        // Greet the user
        Svetovid.out.println("Hello " + name + "!");

    }
}

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

package org.svetovid.demo;

import org.svetovid.Svetovid;

public class HelloWorld {

    public static void main(String[] args) {

        // Ask for a name
        String name = Svetovid.in.readLine("Please enter your name:");

        // Greet the user
        Svetovid.out.println("Hello " + name + "!");

    }
}

Fix demos to use readTokenXxx()


package protocolsupport;

import java.util.logging.Level;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;

public class ProtocolSupport extends Plugin {

	private PEProxyServer peserver;

	@Override
	public void onLoad() {
		try {
			getProxy().getPluginManager().registerCommand(this, new CommandHandler());
			BungeeNettyChannelInjector.inject();
		} catch (Throwable t) {
			t.printStackTrace();
			ProxyServer.getInstance().stop();
		}
	}

	@Override
	public void onEnable() {
		if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
			getLogger().log(Level.INFO, "Enabling MCPE support");
			(peserver = new PEProxyServer()).start();
		}
	}

	@Override
	public void onDisable() {
		peserver.stop();
	}

}

package protocolsupport;

import java.util.logging.Level;

import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.plugin.Plugin;
import protocolsupport.injector.BungeeNettyChannelInjector;
import protocolsupport.injector.pe.PEProxyServer;
import protocolsupport.utils.Utils;

public class ProtocolSupport extends Plugin {

	private PEProxyServer peserver;

	@Override
	public void onLoad() {
		try {
			getProxy().getPluginManager().registerCommand(this, new CommandHandler());
			BungeeNettyChannelInjector.inject();
		} catch (Throwable t) {
			t.printStackTrace();
			ProxyServer.getInstance().stop();
		}
	}

	@Override
	public void onEnable() {
		if (Utils.getJavaPropertyValue("enablepe", false, Boolean::parseBoolean)) {
			getLogger().log(Level.INFO, "Enabling MCPE support");
			(peserver = new PEProxyServer()).start();
		}
	}

	@Override
	public void onDisable() {
		if (peserver != null) {
			peserver.stop();
		}
	}

}

Stop PE server only if it was running


package com.pedro.fizzbuzz;

/**
 *
 * Matcher implementation created to return the "Fizz" value if the value passed as argument in the evaluate method
 * is 5 or multiple of 5.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
class BuzzMatcher implements Matcher {

    @Override
    public String evaluate(int value) {
        return "";
    }
}

package com.pedro.fizzbuzz;

/**
 *
 * Matcher implementation created to return the "Fizz" value if the value passed as argument in the evaluate method
 * is 5 or multiple of 5.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
class BuzzMatcher implements Matcher {

    /*
     * Constants
     */
    private final static String BUZZ = "BUZZ";

    /*
     * Implemented methods
     */

    @Override
    public String evaluate(int value) {
        return value % 5 == 0 ? BUZZ : "";
    }
}

Implement BUZZ matcher and all tests in green :)


package com.vite;

import com.vite.service.ViteClient;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@ComponentScan({"com.vite.service"})
@SpringBootApplication
public class Application {
    static final Logger LOGGER = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        new ViteClient();
        LOGGER.info("Starting server...");
    }
}

package com.vite;

import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@EnableWebMvc
@ComponentScan({"com.vite.service"})
@SpringBootApplication
public class Application {
    static final Logger LOGGER = Logger.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        LOGGER.info("Starting server...");
    }
}

Remove code from start up


package ch.hood;

import static ch.hood.jooq.schema1.Tables.A;
import static ch.hood.jooq.schema2.Tables.B;
import static org.jooq.impl.DSL.select;

public class App {
	public static void main(String[] args) {
		System.out.println(
			select(A.ID, A.FLAG)
				.from(A)
				.join(B).on(B.NAME.eq(A.NAME))
				.toString());
	}

}

package ch.hood;

import static ch.hood.jooq.schema1.Schema1.SCHEMA1;
import static ch.hood.jooq.schema1.Tables.A;
import static ch.hood.jooq.schema2.Schema2.SCHEMA2;
import static ch.hood.jooq.schema2.Tables.B;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.jooq.impl.DSL.select;

import ch.hood.jooq.schema1.Schema1;
import ch.hood.jooq.schema2.Schema2;
import org.jooq.Configuration;
import org.jooq.DSLContext;
import org.jooq.SQLDialect;
import org.jooq.conf.MappedSchema;
import org.jooq.conf.RenderMapping;
import org.jooq.conf.RenderNameStyle;
import org.jooq.conf.Settings;
import org.jooq.impl.DSL;
import org.jooq.impl.DefaultConfiguration;

/**
 * The main methods expects either no arguments or 2 arguments. When run without arguments, we assume a HQSLDB;
 * when run with 2 arguments, we expect the names of the schema1 and the schema2 for a Postgresql (or Oracle) instance.
 */
public class App {
	public static void main(String[] args) {
		SQLDialect sqlDialect = args.length == 0 ? SQLDialect.HSQLDB : SQLDialect.POSTGRES; // SQLDialect.ORACLE

		Settings settings = new Settings()
			.withRenderFormatted(true)
			.withRenderSchema(TRUE)
			.withRenderNameStyle(RenderNameStyle.UPPER);
		if (sqlDialect == SQLDialect.POSTGRES) {
			String schema1Name = args[0];
			String schema2Name = args[1];
			settings.withRenderMapping(new RenderMapping()
				.withSchemata(
					new MappedSchema().withInput(SCHEMA1.getName()).withOutput(schema1Name),
					new MappedSchema().withInput(SCHEMA2.getName()).withOutput(schema2Name)));
		}

		Configuration config = new DefaultConfiguration()
			.set(sqlDialect)
			.set(settings);

		Configuration configuration = config;
		DSLContext dsl = DSL.using(configuration);

		System.out.println(
			dsl.select(A.ID, A.FLAG)
				.from(A)
				.join(B).on(B.NAME.eq(A.NAME))
				.toString());
	}

}

Add Code Example with Schema Mapping.


package com.rhomobile.rhodes.webview;

import android.content.Context;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class RhoWebSettingsNew implements RhoWebSettings {

	public WebSettings setWebSettings(WebView w) {
		RhoWebSettingsOld ws = new RhoWebSettingsOld();
		WebSettings webSettings = ws.setWebSettings(w);

		webSettings.setAppCacheEnabled(true);

		webSettings.setDatabaseEnabled(true);
		webSettings.setJavaScriptEnabled(true);

		Context context = w.getContext();
		String databasePath = context.getDir("database", Context.MODE_PRIVATE).getPath();
		webSettings.setDatabasePath(databasePath);

		return webSettings;
	}

}

package com.rhomobile.rhodes.webview;

import android.content.Context;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class RhoWebSettingsNew implements RhoWebSettings {

	public WebSettings setWebSettings(WebView w) {
		RhoWebSettingsOld ws = new RhoWebSettingsOld();
		WebSettings webSettings = ws.setWebSettings(w);

		webSettings.setAppCacheEnabled(true);

		webSettings.setDatabaseEnabled(true);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setDomStorageEnabled(true);

		Context context = w.getContext();
		String databasePath = context.getDir("database", Context.MODE_PRIVATE).getPath();
		webSettings.setDatabasePath(databasePath);

		return webSettings;
	}

}

Fix localStorage access from js.


package com.iluwatar.doublechecked.locking;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * In {@link Inventory} we store the items with a given size. However, we do not store
 * more items than the inventory size. To address concurrent access problems we
 * use double checked locking to add item to inventory. In this method, the
 * thread which gets the lock first adds the item.
 *
 */
public class App {

	/**
	 * Program entry point
	 * @param args command line args
	 */
	public static void main(String[] args) {
		final Inventory inventory = new Inventory(1000);
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					while (inventory.addItem(new Item()))
						;
				}
			});
		}
	}
}

package com.iluwatar.doublechecked.locking;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *
 * Double Checked Locking is a concurrency design pattern used to reduce the overhead
 * of acquiring a lock by first testing the locking criterion (the "lock hint") without
 * actually acquiring the lock. Only if the locking criterion check indicates that
 * locking is required does the actual locking logic proceed.
 * <p>
 * In {@link Inventory} we store the items with a given size. However, we do not store
 * more items than the inventory size. To address concurrent access problems we
 * use double checked locking to add item to inventory. In this method, the
 * thread which gets the lock first adds the item.
 *
 */
public class App {

	/**
	 * Program entry point
	 * @param args command line args
	 */
	public static void main(String[] args) {
		final Inventory inventory = new Inventory(1000);
		ExecutorService executorService = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 3; i++) {
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					while (inventory.addItem(new Item()))
						;
				}
			});
		}
	}
}

Improve Double Checked Locking Javadoc


/*******************************************************************************
 * Copyright (c) 2010 itemis AG (http://www.itemis.eu) 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
 *******************************************************************************/
package org.eclipse.xtext.mwe;

/**
 * @author svenefftinge - Initial contribution and API
 */
public class EquinoxClasspathEntriesProvider implements IClasspathEntriesProvider {

	@Override
	public Iterable<String> getAllPathes(ClassLoader classloader) {

		return null;
	}

}

/*******************************************************************************
 * Copyright (c) 2010 itemis AG (http://www.itemis.eu) 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
 *******************************************************************************/
package org.eclipse.xtext.mwe;

import java.util.Collections;

/**
 * @author svenefftinge - Initial contribution and API
 */
public class EquinoxClasspathEntriesProvider implements IClasspathEntriesProvider {
	@Override
	public Iterable<String> getAllPathes(ClassLoader classloader) {
		return Collections.emptyList();
	}

}

Return empty list instead of null


package com.unidev.polydata;

import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import java.util.Optional;

/**
 * SQLite storage tests
 */
public class SQLiteStorageTest {

    @Test
    public void testStorageSaveLoad() throws SQLiteStorageException {

        SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");

        BasicPoly basicPoly = BasicPoly.newPoly("potato");
        basicPoly.put("value", "tomato");

        sqLiteStorage.save("poly", basicPoly);

        Optional<Poly> polyOptional = sqLiteStorage.fetch("poly", "potato");
        assertThat(polyOptional.isPresent(), is(true));

        Poly poly = polyOptional.get();
        assertThat(poly._id(), is("potato"));
        assertThat(poly.get("value"), is("tomato"));

        Optional<Poly> polyOptional2 = sqLiteStorage.fetch("poly", "tomato");
        assertThat(polyOptional2.isPresent(), is(false));
    }
}

package com.unidev.polydata;

import com.unidev.polydata.domain.BasicPoly;
import com.unidev.polydata.domain.Poly;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Optional;

/**
 * SQLite storage tests
 */
public class SQLiteStorageTest {

    @Test
    public void testStorageSaveLoad() throws SQLiteStorageException {

        SQLiteStorage sqLiteStorage = new SQLiteStorage("/tmp/testdb.db");
        sqLiteStorage.setPolyMigrators(Arrays.asList(new SQLitePolyMigrator() {
            @Override
            public boolean canHandle(String poly) {
                return "poly".equalsIgnoreCase(poly);
            }

            @Override
            public void handle(String poly, Connection connection) throws SQLiteStorageException {
                try {
                    Statement statement = connection.createStatement();
                    statement.executeUpdate("CREATE TABLE IF NOT EXISTS "+poly+" (_id TEXT PRIMARY KEY, value TEXT)");
                } catch (SQLException e) {
                    throw new SQLiteStorageException(e);
                }
            }
        }));

        BasicPoly basicPoly = BasicPoly.newPoly("potato");
        basicPoly.put("value", "tomato");

        sqLiteStorage.save("poly", basicPoly);

        Optional<Poly> polyOptional = sqLiteStorage.fetch("poly", "potato");
        assertThat(polyOptional.isPresent(), is(true));

        Poly poly = polyOptional.get();
        assertThat(poly._id(), is("potato"));
        assertThat(poly.get("value"), is("tomato"));

        Optional<Poly> polyOptional2 = sqLiteStorage.fetch("poly", "tomato");
        assertThat(polyOptional2.isPresent(), is(false));
    }
}

Test coverage for poly tables conversion


package io.georocket.index.generic;

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

import io.georocket.index.xml.MetaIndexer;
import io.georocket.storage.ChunkMeta;
import io.georocket.storage.IndexMeta;

/**
 * Default implementation of {@link MetaIndexer} that extracts generic
 * attributes from chunk metadata and adds it to the index.
 * @author Michel Kraemer
 */
public class DefaultMetaIndexer implements MetaIndexer {
  private final Map<String, Object> result = new HashMap<>();

  @Override
  public Map<String, Object> getResult() {
    return result;
  }

  @Override
  public void onIndexChunk(String path, ChunkMeta chunkMeta,
      IndexMeta indexMeta) {
    result.put("path", path);
    result.put("correlationId", indexMeta.getCorrelationId());
    result.put("filename", indexMeta.getFilename());
    result.put("timestamp", indexMeta.getTimestamp());
    result.put("chunkMeta", chunkMeta.toJsonObject());
    if (indexMeta.getTags() != null) {
      result.put("tags", indexMeta.getTags());
    }
  }
}

package io.georocket.index.generic;

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

import io.georocket.index.xml.MetaIndexer;
import io.georocket.storage.ChunkMeta;
import io.georocket.storage.IndexMeta;

/**
 * Default implementation of {@link MetaIndexer} that extracts generic
 * attributes from chunk metadata and adds it to the index.
 * @author Michel Kraemer
 */
public class DefaultMetaIndexer implements MetaIndexer {
  private final Map<String, Object> result = new HashMap<>();

  @Override
  public Map<String, Object> getResult() {
    return result;
  }

  @Override
  public void onIndexChunk(String path, ChunkMeta chunkMeta,
      IndexMeta indexMeta) {
    result.put("path", path);
    result.put("chunkMeta", chunkMeta.toJsonObject());
    if (indexMeta.getTags() != null) {
      result.put("tags", indexMeta.getTags());
    }
  }
}

Remove unnecessary properties from index


package org.apache.lucene.index;

/**
 * Copyright 2004 The Apache Software Foundation
 *
 * 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.
 */

import java.io.IOException;

import org.apache.lucene.store.GCJDirectory;

class GCJSegmentReader extends SegmentReader {

  /** Try to use an optimized native implementation of TermDocs.  The optimized
   * implementation can only be used when the segment's directory is a
   * GCJDirectory and it is not in compound format.  */
  public final TermDocs termDocs() throws IOException {
    if (directory() instanceof GCJDirectory       // it's a GCJ directory
        && this.cfsReader == null) {              // & not in compound format
      return new GCJTermDocs(this);               // so can use GCJTermDocs
    } else {
      return super.termDocs();
    }
  }
}

package org.apache.lucene.index;

/**
 * Copyright 2004 The Apache Software Foundation
 *
 * 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.
 */

import java.io.IOException;

import org.apache.lucene.store.GCJIndexInput;

class GCJSegmentReader extends SegmentReader {

  /** Try to use an optimized native implementation of TermDocs.  The optimized
   * implementation can only be used when the segment's directory is a
   * GCJDirectory and it is not in compound format.  */
  public final TermDocs termDocs() throws IOException {
    if (freqStream instanceof GCJIndexInput) {    // it's a GCJIndexInput
      return new GCJTermDocs(this);               // so can use GCJTermDocs
    } else {
      return super.termDocs();
    }
  }
}

Check the type of the IndexInput rather than the Directory to detect native implementation. This is a simpler and more correct test. It also permits the Directory to return a mixture of native and non-native IndexInput implementations.


package given.a.spec.with.constructor.parameters;

class Fixture {

  public static Class<?> getSpecThatRequiresAConstructorParameter() {
    class Spec {
      @SuppressWarnings("unused")
      public Spec(final String something) {}
    }

    return Spec.class;
  }

  public static class SomeException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public SomeException(final String message) {
      super(message);
    }
  }

}

package given.a.spec.with.constructor.parameters;

class Fixture {

  public static Class<?> getSpecThatRequiresAConstructorParameter() {
    class Spec {
      @SuppressWarnings("unused")
      public Spec(final String something) {}
    }

    return Spec.class;
  }

}

Remove some dead code from test suite


package com.granveaud.mysql2h2converter.converter;

import com.granveaud.mysql2h2converter.parser.ParseException;
import com.granveaud.mysql2h2converter.parser.SQLParserManager;
import com.granveaud.mysql2h2converter.sql.Statement;

import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Iterator;

public class Main {
    final static private Charset INPUT_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException, ParseException {
        if (args.length < 1) {
            System.err.println("Usage: input_file1 input_file2...");
            System.exit(1);
        }

        for (String str : args) {
            Iterator<Statement> sourceIterator = SQLParserManager.parseScript(new InputStreamReader(new FileInputStream(str), INPUT_CHARSET));

            // conversion and execution
            Iterator<Statement> it = H2Converter.convertScript(sourceIterator);
            while (it.hasNext()) {
                Statement st = it.next();

                // output to stdout
                System.out.println(st.toString() + ";");
            }
        }
    }
}

package com.granveaud.mysql2h2converter.converter;

import com.granveaud.mysql2h2converter.parser.ParseException;
import com.granveaud.mysql2h2converter.parser.SQLParserManager;
import com.granveaud.mysql2h2converter.sql.Statement;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.zip.GZIPInputStream;

public class Main {
    final static private Charset INPUT_CHARSET = Charset.forName("UTF-8");

    public static void main(String[] args) throws IOException, ParseException {
        if (args.length < 1) {
            System.err.println("Usage: input_file1 input_file2...");
            System.exit(1);
        }

        for (String str : args) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(readFile(str), INPUT_CHARSET));
            Iterator<Statement> sourceIterator = SQLParserManager.parseScript(reader);

            // conversion and execution
            Iterator<Statement> it = H2Converter.convertScript(sourceIterator);
            while (it.hasNext()) {
                Statement st = it.next();

                // output to stdout
                System.out.println(st.toString() + ";");
            }
        }

    }

    public static InputStream readFile(String name) throws IOException {
        InputStream input = new BufferedInputStream(new FileInputStream(name));
        PushbackInputStream pb = new PushbackInputStream( input, 2 );
        byte [] magicbytes = new byte[2];
        pb.read(magicbytes);
        pb.unread(magicbytes);
        ByteBuffer bb = ByteBuffer.wrap(magicbytes);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        short magic = bb.getShort();
        if( magic == (short)GZIPInputStream.GZIP_MAGIC )
            return new GZIPInputStream( pb );
        else
            return pb;
    }
}

Support reading input scripts that are gzipped


package ohtuhatut.domain;

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * The class for a list of references
 * Created by iilumme.
 */

@Entity
@Table(name = "ReferenceList")
public class ReferenceList extends AbstractPersistable<Long> {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Reference> references;

    public List<Reference> getReferences() {
        return this.references;
    }

    public void setReferences(List<Reference> references) {
        this.references = references;
    }
}

package ohtuhatut.domain;

import org.springframework.data.jpa.domain.AbstractPersistable;

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;

/**
 * The class for a list of references
 * Created by iilumme.
 */

@Entity
@Table(name = "ReferenceList")
public class ReferenceList extends AbstractPersistable<Long> {

    @OneToMany(fetch = FetchType.LAZY)
    private List<Reference> references;

    private String name;

    public ReferenceList(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Reference> getReferences() {
        return this.references;
    }

    public void setReferences(List<Reference> references) {
        this.references = references;
    }
}

Add name field for reference list


package com.geeks;

public class BinarySearchTree {
	public static void main(String[] args) {

	}

	private static class TreeNode<T> {
		TreeNode<T> left;
		TreeNode<T> right;

		T elem;
	}
}

package com.geeks;

import java.util.Arrays;

public class BinarySearchTree {
	public static void main(String[] args) {
		Character[] inOrder = { 'D', 'B', 'E', 'A', 'F', 'C' };
		Character[] preOrder = { 'A', 'B', 'D', 'E', 'C', 'F' };

		TreeNode<Character> tree = constructTreeNode(0, preOrder, inOrder);

		postOrderTraverse(tree, new TraverseCallback() {

			public <T> void callback(T t) {
				TreeNode<Character> treeNode = (TreeNode<Character>) t;
				System.out.println(treeNode.elem);
			}
		});
	}

	/**
	 *
	 * @param inOrder
	 * @param preOrder
	 * @return
	 */
	private static <T> TreeNode<T> constructTreeNode(int rootPos, T[] preOrder,
			T[] inOrder) {
		if (rootPos == preOrder.length) {
			return null;
		}

		if (inOrder == null || inOrder.length == 0)
			return null;

		T childRoot = preOrder[rootPos];

		int i = 0;
		for (; i < inOrder.length; i++) {
			if (childRoot.equals(inOrder[i]))
				break;
		}

		T[] leftChildInOrder = Arrays.copyOfRange(inOrder, 0, i);

		T[] rightChildInOrder = null;
		if (i < inOrder.length - 1) {
			rightChildInOrder = Arrays.copyOfRange(inOrder, i + 1,
					inOrder.length);
		}

		TreeNode<T> leftChild = constructTreeNode(rootPos + 1, preOrder,
				leftChildInOrder);
		TreeNode<T> rightChild = constructTreeNode(rootPos + i + 1, preOrder,
				rightChildInOrder);

		TreeNode<T> node = new TreeNode<T>();
		node.left = leftChild;
		node.right = rightChild;
		node.elem = childRoot;

		return node;
	}

	private static <T> void postOrderTraverse(TreeNode<T> tree,
			TraverseCallback callback) {
		if (tree.right != null)
			postOrderTraverse(tree.right, callback);

		if (tree.left != null)
			postOrderTraverse(tree.left, callback);

		callback.callback(tree);
		// System.out.println(tree.elem);
	}

	private static interface TraverseCallback {
		public <T> void callback(T t);
	}

	private static class TreeNode<T> {
		TreeNode<T> left;
		TreeNode<T> right;

		T elem;
	}
}

Add construct binary tree from inOrder and preOrder


/*
 * Copyright 2015 Timothy Brooks
 *
 * 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.uncontended.precipice.timeout;

public class NewTimerService {

    public void schedule(Object task, long timeMillis) {

    }
}

/*
 * Copyright 2015 Timothy Brooks
 *
 * 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.uncontended.precipice.timeout;

import java.util.concurrent.TimeUnit;

public class NewTimerService {

    private final long resolution;
    private final long startTime;

    public NewTimerService(long resolution, TimeUnit unit) {
        this.resolution = unit.toMillis(resolution);
        startTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
    }

    public void schedule(Object task, long delay, TimeUnit unit) {

    }
}

Work on laying out timeout service resolution


package org.synyx.urlaubsverwaltung.application.domain;

/**
 * Enum describing which states an {@link Application} may have.
 */
public enum ApplicationStatus {

    /**
     * After applying for the leave, the saved application for leave gets this status.
     */
    WAITING,

    /**
     * After the HeadOf has allowed the application in a two stage approval process.
     *
     * @since 2.15.0
     */
    TEMPORARY_ALLOWED,

    /**
     * Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
     * stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
     */
    ALLOWED,

    /**
     * Status after the application for leave was allowed but the applicant wants to cancel the own application.
     * The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
     */
    ALLOWED_CANCELLATION_REQUESTED,

    /**
     * Status after a boss has rejected application for leave.
     */
    REJECTED,

    /**
     * If an application for leave has been allowed and is cancelled afterwards, it gets this status.
     */
    CANCELLED,

    /**
     * If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
     *
     * @since 2.5.2
     */
    REVOKED
}

package org.synyx.urlaubsverwaltung.application.domain;

/**
 * Enum describing which states an {@link Application} may have.
 */
public enum ApplicationStatus {

    /**
     * After applying for the leave, the saved application for leave gets this status.
     */
    WAITING,

    /**
     * After the department head has allowed the application in a two stage approval process and before the
     * second stage authority has rejected or allowed the application.
     * This status is a special case of WAITING and needs to be handled as a waiting, not yet allowed, application for leave.
     *
     * @since 2.15.0
     */
    TEMPORARY_ALLOWED,

    /**
     * Status after a boss has allowed the application for leave or after HeadOf has allowed the application in a one
     * stage approval process or after a SECOND_STAGE_AUTHORITY (Role) has released a TEMPORARY_ALLOWED application.
     */
    ALLOWED,

    /**
     * Status after the application for leave was allowed but the applicant wants to cancel the own application.
     * The application for leave is at this point not cancelled and can only be approved by OFFICE Role.
     */
    ALLOWED_CANCELLATION_REQUESTED,

    /**
     * Status after a boss has rejected application for leave.
     */
    REJECTED,

    /**
     * If an application for leave has been allowed and is cancelled afterwards, it gets this status.
     */
    CANCELLED,

    /**
     * If an application for leave has **not** been allowed yet and is cancelled, it gets this status.
     *
     * @since 2.5.2
     */
    REVOKED
}

Improve javadoc of temporary allowed application status


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.jvm.java.testutil.compiler;

import org.junit.runners.Parameterized;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.TestClass;

/**
 * Parameterized test runner that enables tests to work with the Compiler Tree API implementation
 * corresponding to the compiler returned by {@link
 * javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
 * rt.jar and thus are not usually on the classpath.
 */
public class CompilerTreeApiParameterized extends Parameterized {
  public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
    super(klass);
  }

  @Override
  protected TestClass createTestClass(Class<?> testClass) {
    try {
      return new TestClass(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(testClass));
    } catch (InitializationError initializationError) {
      throw new AssertionError(initializationError);
    }
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.buck.jvm.java.testutil.compiler;

import org.junit.runners.Parameterized;

/**
 * Parameterized test runner that enables tests to work with the Compiler Tree API implementation
 * corresponding to the compiler returned by {@link
 * javax.tools.ToolProvider#getSystemJavaCompiler()}. These are public APIs that are not provided in
 * rt.jar and thus are not usually on the classpath.
 */
public class CompilerTreeApiParameterized extends Parameterized {
  public CompilerTreeApiParameterized(Class<?> klass) throws Throwable {
    super(CompilerTreeApiTestRunner.reloadFromCompilerClassLoader(klass));
  }
}

Replace deprecate code in JUnit call


/* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;

import java.util.Set;

public
class OMultExpression extends OMathExpression {

  public OMultExpression(int id) {
    super(id);
  }

  public OMultExpression(OrientSql p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  public boolean needsAliases(Set<String> aliases) {
    throw new UnsupportedOperationException();
  }
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */

/* Generated By:JJTree: Do not edit this line. OMultExpression.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=O,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package com.orientechnologies.orient.core.sql.parser;

import java.util.Set;

public
class OMultExpression extends OMathExpression {

  public OMultExpression(int id) {
    super(id);
  }

  public OMultExpression(OrientSql p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(OrientSqlVisitor visitor, Object data) {
    return visitor.visit(this, data);
  }

  public boolean needsAliases(Set<String> aliases) {
    return super.needsAliases(aliases);
  }
}
/* JavaCC - OriginalChecksum=f75b8be48dca1e0cafae0cacadc608c8 (do not edit this line) */

Fix Multiplication operation in new SQL executor


package net.interfax.rest.client.exception;

public class UnsuccessfulStatusCodeException extends Exception {

    public UnsuccessfulStatusCodeException(String message) {
        super(message);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public UnsuccessfulStatusCodeException(final Throwable cause) {
        super(cause);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

}

package net.interfax.rest.client.exception;

public class UnsuccessfulStatusCodeException extends Exception {

    private int statusCode;
    private String responseBody;

    public UnsuccessfulStatusCodeException(int statusCode) {
        this.statusCode = statusCode;
    }

    public UnsuccessfulStatusCodeException(int statusCode, String responseBody) {
        this.statusCode = statusCode;
        this.responseBody = responseBody;
    }

    public UnsuccessfulStatusCodeException(String message) {
        super(message);
    }

    public UnsuccessfulStatusCodeException(String message, int statusCode, String responseBody) {
        super(message);
        this.statusCode = statusCode;
        this.responseBody = responseBody;
    }

    public UnsuccessfulStatusCodeException(String message, int statusCode) {
        super(message);
        this.statusCode = statusCode;
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause) {
        super(message, cause);
    }

    public UnsuccessfulStatusCodeException(final Throwable cause) {
        super(cause);
    }

    public UnsuccessfulStatusCodeException(final String message, final Throwable cause, final boolean enableSuppression, final boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(final int statusCode) {
        this.statusCode = statusCode;
    }

    public String getResponseBody() {
        return responseBody;
    }

    public void setResponseBody(final String responseBody) {
        this.responseBody = responseBody;
    }

}

Add attributes to capture status code and response body in custom exception


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

package org.gradle.internal.filewatch;

import org.gradle.api.Action;
import org.gradle.api.internal.file.FileSystemSubset;

public interface FileWatcherFactory {
    FileWatcher watch(FileSystemSubset systemSubset, Action<? super Throwable> onError, FileWatcherListener listener);
}

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

package org.gradle.internal.filewatch;

import org.gradle.api.Action;
import org.gradle.api.internal.file.FileSystemSubset;

public interface FileWatcherFactory {

    /**
     * Starts watching for changes to the given subset of the file system.
     *

     * Listeners should not rely on the events being an entirely accurate journal of file system events.
     * Implementations may emit duplicate events and chronological ordering is not guaranteed.
     *

     * It can be assumed that all changes to the file system subset that occur after the return of this method will produce events.
     *

     * No events will be emitted after that watcher has been stopped.
     *
     * @param systemSubset the parts of the file system to watch
     * @param onError what to do if an error occurs while watching
     * @param listener the receiver of events
     * @return a, stoppable, handle to the watcher
     */
    FileWatcher watch(FileSystemSubset systemSubset, Action<? super Throwable> onError, FileWatcherListener listener);
}

Add some docs on the filewatcher contract.


package com.gmail.jiangyang5157.cardboard.scene.projection;

import android.util.ArrayMap;
import android.util.Log;

/**
 * @author Yang
 * @since 4/12/2016.
 */
public class IcosphereBuilder {

    private volatile static IcosphereBuilder uniqueInstance = null;

    private ArrayMap<Integer, IcosphereVertex> icosphereVertices = new ArrayMap<>();

    public static IcosphereBuilder getInstance() {
        if (uniqueInstance == null) {
            synchronized (IcosphereBuilder.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new IcosphereBuilder();
                }
            }
        }
        return uniqueInstance;
    }

    private IcosphereBuilder() {
    }

    protected IcosphereVertex build(int recursionLevel) {
        final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1;
        if (recursionLevel > MAX_RECURSION_LEVEL) {
            throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL);
        }

        Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel];
        IcosphereVertex ret = icosphereVertices.get(vertexCount);
        if (ret == null) {
            ret = new IcosphereVertex(recursionLevel);
            icosphereVertices.put(vertexCount, ret);
            Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount);
        }
        return ret;
    }
}

package com.gmail.jiangyang5157.cardboard.scene.projection;

import android.util.ArrayMap;
import android.util.Log;

/**
 * @author Yang
 * @since 4/12/2016.
 */
public class IcosphereBuilder {

    private volatile static IcosphereBuilder uniqueInstance;

    private ArrayMap<Integer, IcosphereVertex> icosphereVertices;

    public static IcosphereBuilder getInstance() {
        if (uniqueInstance == null) {
            synchronized (IcosphereBuilder.class) {
                if (uniqueInstance == null) {
                    uniqueInstance = new IcosphereBuilder();
                }
            }
        }
        return uniqueInstance;
    }

    private IcosphereBuilder() {
        icosphereVertices = new ArrayMap<>();
    }

    protected IcosphereVertex build(int recursionLevel) {
        final int MAX_RECURSION_LEVEL = IcosphereVertex.VERTEX_COUNTS.length - 1;
        if (recursionLevel > MAX_RECURSION_LEVEL) {
            throw new RuntimeException("Unable to build a Icosphere with recursion level greater than " + MAX_RECURSION_LEVEL);
        }

        Integer vertexCount = IcosphereVertex.VERTEX_COUNTS[recursionLevel];
        IcosphereVertex ret = icosphereVertices.get(vertexCount);
        if (ret == null) {
            ret = new IcosphereVertex(recursionLevel);
            icosphereVertices.put(vertexCount, ret);
            Log.d("####", "IcosphereBuilder: created IcosephereVertex object with vertexCount=" + vertexCount);
        }
        return ret;
    }
}

Add Camera and Light class. Refact.


// Copyright (C) 2012 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.client.ui;

import com.google.gerrit.client.Gerrit;
import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle;

/**
 * Suggest oracle that only provides suggestions if the user has typed at least
 * as many characters as configured by 'suggest.from'. If 'suggest.from' is set
 * to 0, suggestions will always be provided.
 */
public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle {

  @Override
  protected void onRequestSuggestions(final Request request, final Callback done) {
    final int suggestFrom = Gerrit.getConfig().getSuggestFrom();
    if (suggestFrom == 0 || request.getQuery().length() >= suggestFrom) {
      _onRequestSuggestions(request, done);
    }
  }

  protected abstract void _onRequestSuggestions(Request request, Callback done);
}

// Copyright (C) 2012 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.client.ui;

import com.google.gerrit.client.Gerrit;
import com.google.gwtexpui.safehtml.client.HighlightSuggestOracle;

import java.util.Collections;
import java.util.List;

/**
 * Suggest oracle that only provides suggestions if the user has typed at least
 * as many characters as configured by 'suggest.from'. If 'suggest.from' is set
 * to 0, suggestions will always be provided.
 */
public abstract class SuggestAfterTypingNCharsOracle extends HighlightSuggestOracle {

  @Override
  protected void onRequestSuggestions(Request req, Callback cb) {
    if (req.getQuery().length() >= Gerrit.getConfig().getSuggestFrom()) {
      _onRequestSuggestions(req, cb);
    } else {
      List<Suggestion> none = Collections.emptyList();
      cb.onSuggestionsReady(req, new Response(none));
    }
  }

  protected abstract void _onRequestSuggestions(Request request, Callback done);
}

Fix reviewer suggestions when suggestFrom > 0


package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;

public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {

    // Elements
    public static final String EPOCH = "epoch";
    public static final String PLANNDED_CALENDAR = "planned-calendar";

    private EpochDao epochDao;

    public Element createElement(Epoch epoch) {
        // Using QName is the only way to attach the namespace to the element
        QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
        Element eEpoch = DocumentHelper.createElement(qEpoch)
                .addAttribute(ID, epoch.getGridId())
                .addAttribute(NAME, epoch.getName());

        return eEpoch;
    }

    public Epoch readElement(Element element) {
        String key = element.attributeValue(ID);
        Epoch epoch = epochDao.getByGridId(key);
        if (epoch == null) {
            epoch = new Epoch();
            epoch.setGridId(key);
            epoch.setName(element.attributeValue(NAME));
        }
        return epoch;
    }

    public void setEpochDao(EpochDao epochDao) {
        this.epochDao = epochDao;
    }
}

package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.dao.EpochDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Epoch;
import edu.northwestern.bioinformatics.studycalendar.xml.AbstractStudyCalendarXmlSerializer;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.QName;

public class EpochXmlSerializer extends AbstractStudyCalendarXmlSerializer<Epoch> {

    // Elements
    public static final String EPOCH = "epoch";

    private EpochDao epochDao;

    public Element createElement(Epoch epoch) {
        // Using QName is the only way to attach the namespace to the element
        QName qEpoch = DocumentHelper.createQName(EPOCH, DEFAULT_NAMESPACE);
        Element eEpoch = DocumentHelper.createElement(qEpoch)
                .addAttribute(ID, epoch.getGridId())
                .addAttribute(NAME, epoch.getName());

        return eEpoch;
    }

    public Epoch readElement(Element element) {
        String key = element.attributeValue(ID);
        Epoch epoch = epochDao.getByGridId(key);
        if (epoch == null) {
            epoch = new Epoch();
            epoch.setGridId(key);
            epoch.setName(element.attributeValue(NAME));
        }
        return epoch;
    }

    public void setEpochDao(EpochDao epochDao) {
        this.epochDao = epochDao;
    }
}

Remove un-needed field in epoch serializer.


package net.safedata.springboot.training.d03.s01.handler;

import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class PostLogoutHandler implements LogoutHandler {

    @Override
    public void logout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse,
                       final Authentication authentication) {
        // perform any post-logout operations
    }
}

Split the parameter on the next line


/*******************************************************************************
 * Copyright (c) 2012 Symplectic Ltd. All rights reserved.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 ******************************************************************************/
package uk.co.symplectic.elements.api;

import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

class ElementsAPIConnectionManager {
    private static HttpConnectionManager connectionManager;
    private static HttpConnectionManagerParams params = null;

    static {
        params = new HttpConnectionManagerParams();
        params.setConnectionTimeout(30000);
    }

    private ElementsAPIConnectionManager() {}

    static HttpConnectionManager getInstance() {
        if (connectionManager == null) {
            ElementsAPIConnectionManager.initialize();
        }

        return connectionManager;
    }

    private static synchronized void initialize() {
        if (connectionManager == null) {
            connectionManager = new MultiThreadedHttpConnectionManager();
            if (params != null) {
                connectionManager.setParams(params);
            }
        }
    }
}

/*******************************************************************************
 * Copyright (c) 2012 Symplectic Ltd. All rights reserved.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 ******************************************************************************/
package uk.co.symplectic.elements.api;

import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

class ElementsAPIConnectionManager {
    private static HttpConnectionManager connectionManager;
    private static HttpConnectionManagerParams params = null;

    static {
        params = new HttpConnectionManagerParams();
        params.setConnectionTimeout(30000);
        params.setSoTimeout(60000);
    }

    private ElementsAPIConnectionManager() {}

    static HttpConnectionManager getInstance() {
        if (connectionManager == null) {
            ElementsAPIConnectionManager.initialize();
        }

        return connectionManager;
    }

    private static synchronized void initialize() {
        if (connectionManager == null) {
            connectionManager = new MultiThreadedHttpConnectionManager();
            if (params != null) {
                connectionManager.setParams(params);
            }
        }
    }
}

Fix timeouts on non-responsive API


/**
 *
 */
package com.gengo.client;

/**
 * @author hiroyu-n@inter-plug.co.jp
 *
 */
public final class GengoConstants {
	protected static String BASE_URL_STANDARD = "http://api.gengo.com/v2/";
	protected static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/";
	protected static String BASE_URL_STAGING = "http://api.staging.gengo.com/v2/";
}

/**
 *
 */
package com.gengo.client;

/**
 * @author hiroyu-n@inter-plug.co.jp
 *
 */
public final class GengoConstants {
	protected static String BASE_URL_STANDARD = "http://api.gengo.com/v2/";
	protected static String BASE_URL_SANDBOX = "http://api.sandbox.gengo.com/v2/";
}

Remove code for staging environment.


package org.crygier.graphql;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import graphql.language.IntValue;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;

public class JavaScalars {
    public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() {
        @Override
        public Object serialize(Object input) {
            if (input instanceof String) {
                try {
                    return DateFormat.getInstance().parse((String)input);
                } catch (ParseException e) {
                    throw new IllegalArgumentException(e.getMessage());
                }
            } else if (input instanceof Date) {
                return input;
            } else if (input instanceof Long) {
                return new Date(((Long) input));
            } else if (input instanceof Integer) {
                return new Date(((Integer) input).longValue());
            } else {
                return null;
            }
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (input instanceof StringValue) {
                try {
                    return DateFormat.getInstance().parse(((StringValue) input).getValue());
                } catch (ParseException e) {
                    throw new IllegalArgumentException(e.getMessage());
                }
            } else if (input instanceof IntValue) {
                BigInteger value = ((IntValue) input).getValue();
                return new Date(value.longValue());
            }
            return null;
        }
    });
}

package org.crygier.graphql;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

import graphql.language.IntValue;
import graphql.language.StringValue;
import graphql.schema.Coercing;
import graphql.schema.GraphQLScalarType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JavaScalars {
    static final Logger log = LoggerFactory.getLogger(JavaScalars.class);

    public static GraphQLScalarType GraphQLDate = new GraphQLScalarType("Date", "Date type", new Coercing() {
        @Override
        public Object serialize(Object input) {
            if (input instanceof String) {
                return parseStringToDate((String) input);
            } else if (input instanceof Date) {
                return input;
            } else if (input instanceof Long) {
                return new Date(((Long) input).longValue());
            } else if (input instanceof Integer) {
                return new Date(((Integer) input).longValue());
            }
            return null;
        }

        @Override
        public Object parseValue(Object input) {
            return serialize(input);
        }

        @Override
        public Object parseLiteral(Object input) {
            if (input instanceof StringValue) {
                return parseStringToDate(((StringValue) input).getValue());
            } else if (input instanceof IntValue) {
                BigInteger value = ((IntValue) input).getValue();
                return new Date(value.longValue());
            }
            return null;
        }

        private Date parseStringToDate(String input) {
            try {
                return DateFormat.getInstance().parse(input);
            } catch (ParseException e) {
                log.warn("Failed to parse Date from input: " + input, e);
                return null;
            }
        }
    });
}

Return null on parse errors as per specification; Do not throw Exception


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

package org.sablecc.sablecc.launcher;

import org.sablecc.sablecc.exception.InternalException;

public class TextArgument {

    private String text;

    public TextArgument(
            String text) {

        if (text == null) {
            throw new InternalException("text may not be null");
        }

        this.text = text;
    }

    public String getText() {

        return this.text;
    }
}

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

package org.sablecc.sablecc.launcher;

import org.sablecc.sablecc.exception.InternalException;

/**
 * A text argument puts in appendix a String at the end of another.
 */
public class TextArgument {

    /** the text to append. */
    private String text;

    /**
     * Constructs a new textArgument.
     *
     * @param text
     *            the provided text to append.
     *
     * @throws InternalException
     *             if the text is null.
     */
    public TextArgument(
            String text) {

        if (text == null) {
            throw new InternalException("text may not be null");
        }

        this.text = text;
    }

    /**
     * Returns the text of this textArgument.
     *
     * @return the text.
     */
    public String getText() {

        return this.text;
    }
}

Add javadoc comments. See ticket:56.


package wang.cloudfinger.printing.utils;

public class Constants {

	public static final String IMAGE_CACHE_PATH = "imageLoader/cache";

	public final static int NEWS_TYPE_REGISTER = 0;
	public final static int NEWS_TYPE_ADVERTISING = 1;
	public final static int NEWS_TYPE_PRINTING = 2;
	public final static int NEWS_TYPE_BID = 3;
	public final static int NEWS_TYPE_HOBBY = 4;

}

package wang.cloudfinger.printing.utils;

public final class Constants {

	public static final String IMAGE_CACHE_PATH = "imageLoader/cache";

	public final static int NEWS_TYPE_REGISTER = 0;
	public final static int NEWS_TYPE_ADVERTISING = 1;
	public final static int NEWS_TYPE_PRINTING = 2;
	public final static int NEWS_TYPE_BID = 3;
	public final static int NEWS_TYPE_HOBBY = 4;

}

Change the Class to final Class