package io.cucumber.guice;

import com.google.inject.Guice;
import com.google.inject.Stage;

import java.util.Map;

import static java.text.MessageFormat.format;

final class InjectorSourceFactory {

    static final String GUICE_INJECTOR_SOURCE_KEY = "guice.injector-source";
    private final Map<String, String> properties;

    InjectorSourceFactory(Map<String, String> properties) {
        this.properties = properties;
    }

    InjectorSource create() {
        String injectorSourceClassName = properties.get(GUICE_INJECTOR_SOURCE_KEY);
        if (injectorSourceClassName == null) {
            return createDefaultScenarioModuleInjectorSource();
        } else {
            return instantiateUserSpecifiedInjectorSource(injectorSourceClassName);
        }
    }

    private InjectorSource createDefaultScenarioModuleInjectorSource() {
        return () -> Guice.createInjector(Stage.PRODUCTION, CucumberModules.SCENARIO);
    }

    private InjectorSource instantiateUserSpecifiedInjectorSource(String injectorSourceClassName) {
        try {
            return (InjectorSource) Class.forName(injectorSourceClassName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            String message = format("Instantiation of ''{0}'' failed. Check the caused by exception and ensure your" +
                    "InjectorSource implementation is accessible and has a public zero args constructor.",
                    injectorSourceClassName);
            throw new InjectorSourceInstantiationFailed(message, e);
        }
    }

}

package io.cucumber.guice;

import com.google.inject.Guice;
import com.google.inject.Stage;

import java.util.Map;

import static java.text.MessageFormat.format;

final class InjectorSourceFactory {

    static final String GUICE_INJECTOR_SOURCE_KEY = "guice.injector-source";
    private final Map<String, String> properties;

    InjectorSourceFactory(Map<String, String> properties) {
        this.properties = properties;
    }

    InjectorSource create() {
        String injectorSourceClassName = properties.get(GUICE_INJECTOR_SOURCE_KEY);
        if (injectorSourceClassName == null) {
            return createDefaultScenarioModuleInjectorSource();
        } else {
            return instantiateUserSpecifiedInjectorSource(injectorSourceClassName);
        }
    }

    private InjectorSource createDefaultScenarioModuleInjectorSource() {
        return () -> Guice.createInjector(Stage.PRODUCTION, CucumberModules.createScenarioModule());
    }

    private InjectorSource instantiateUserSpecifiedInjectorSource(String injectorSourceClassName) {
        try {
            return (InjectorSource) Class.forName(injectorSourceClassName, true, Thread.currentThread().getContextClassLoader()).newInstance();
        } catch (Exception e) {
            String message = format("Instantiation of ''{0}'' failed. Check the caused by exception and ensure your" +
                    "InjectorSource implementation is accessible and has a public zero args constructor.",
                    injectorSourceClassName);
            throw new InjectorSourceInstantiationFailed(message, e);
        }
    }

}

Remove use of deprecated constants

[Guice] Remove use of deprecated constants


package purchase;

import common.contexts.UserContext;
import common.controllers.ControllerDependency;
import common.models.ProductDataConfig;
import common.pages.SunrisePageData;
import io.sphere.sdk.carts.Cart;
import play.i18n.Messages;
import play.libs.F;
import play.mvc.Result;

import javax.inject.Inject;

public class CheckoutPaymentController extends CartController {

    private final ProductDataConfig productDataConfig;

    @Inject
    public CheckoutPaymentController(final ControllerDependency controllerDependency, final ProductDataConfig productDataConfig) {
        super(controllerDependency);
        this.productDataConfig = productDataConfig;
    }

    public F.Promise<Result> show(final String languageTag) {
        final UserContext userContext = userContext(languageTag);
        final F.Promise<Cart> cartPromise = getOrCreateCart(userContext, session());
        return cartPromise.map(cart -> {
            final Messages messages = messages(userContext);
            final CheckoutPaymentPageContent content = new CheckoutPaymentPageContent(cart, userContext, productDataConfig, reverseRouter());
            final SunrisePageData pageData = pageData(userContext, content, ctx());
            return ok(templateService().renderToHtml("checkout-payment", pageData, userContext.locales()));
        });
    }

    public Result process(final String language) {
        return redirect(reverseRouter().showCheckoutPaymentForm(language));
    }
}

package purchase;

import common.contexts.UserContext;
import common.controllers.ControllerDependency;
import common.models.ProductDataConfig;
import common.pages.SunrisePageData;
import io.sphere.sdk.carts.Cart;
import play.i18n.Messages;
import play.libs.F;
import play.mvc.Result;

import javax.inject.Inject;

public class CheckoutPaymentController extends CartController {

    private final ProductDataConfig productDataConfig;

    @Inject
    public CheckoutPaymentController(final ControllerDependency controllerDependency, final ProductDataConfig productDataConfig) {
        super(controllerDependency);
        this.productDataConfig = productDataConfig;
    }

    public F.Promise<Result> show(final String languageTag) {
        final UserContext userContext = userContext(languageTag);
        final F.Promise<Cart> cartPromise = getOrCreateCart(userContext, session());
        return cartPromise.map(cart -> {
            final Messages messages = messages(userContext);
            final CheckoutPaymentPageContent content = new CheckoutPaymentPageContent(cart, userContext, productDataConfig, reverseRouter());
            final SunrisePageData pageData = pageData(userContext, content, ctx());
            return ok(templateService().renderToHtml("checkout-payment", pageData, userContext.locales()));
        });
    }

    public Result process(final String language) {
        return redirect(reverseRouter().showCheckoutConfirmationForm(language));
    }
}

Fix link to checkout confirmation.

Fix link to checkout confirmation.


package tools.vitruv.applications.pcmjava.tests.transformations;

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

@RunWith(Suite.class)

@SuiteClasses({ JaMoPPPCMUtilsTest.class, JaMoPPTest.class, VitruviusEMFEditorMonitorImplTestPlugin.class })
public class PCMJavaTransformationsTestSuite {

}

package tools.vitruv.applications.pcmjava.tests.transformations;

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

@RunWith(Suite.class)

@SuiteClasses({ JaMoPPPCMUtilsTest.class,
	//JaMoPPTest.class,
	VitruviusEMFEditorMonitorImplTestPlugin.class })
public class PCMJavaTransformationsTestSuite {

}

Remove badly implemented test class from test suite.


package gx.realtime.serialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import gx.realtime.operation.ValueChangedOperation;

import java.io.IOException;

public class ValueChangedOperationDeserializer extends JsonDeserializer<ValueChangedOperation>
{
    @Override
    public ValueChangedOperation deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
    {
        String objectId = jp.nextTextValue();
        String key = jp.nextTextValue();
        jp.nextToken();

        if (jp.getCurrentToken().equals(JsonToken.END_ARRAY)) {
            // This is a remove action
            return new ValueChangedOperation(objectId, key, null, null);
        }

        JsonNode valueNode = jp.readValueAsTree();
        int valueType = valueNode.get(0).asInt();
        String value = valueNode.get(1).asText();
        return new ValueChangedOperation(objectId, key, valueType, value);
    }
}

package gx.realtime.serialize;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import gx.realtime.operation.ValueChangedOperation;

import java.io.IOException;

public class ValueChangedOperationDeserializer extends JsonDeserializer<ValueChangedOperation>
{
    @Override
    public ValueChangedOperation deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException
    {
        String objectId = jp.nextTextValue();
        String key = jp.nextTextValue();
        jp.nextToken();

        if (jp.getCurrentToken().equals(JsonToken.END_ARRAY)) {
            // This is a remove action
            return new ValueChangedOperation(objectId, key, ValueChangedOperation.ValueType.COLLABORATIVE_OBJECT, null);
        }

        JsonNode valueNode = jp.readValueAsTree();
        int valueType = valueNode.get(0).asInt();
        String value = valueNode.get(1).asText();
        return new ValueChangedOperation(objectId, key, valueType, value);
    }
}

Set the type of a (deletion) ValueChangedEvent to CollaborativeObject instead of null


package mypermissions.manager;

import mypermissions.MyPermissions;
import mypermissions.api.IPermissionManager;
import mypermissions.api.command.CommandManager;
import mypermissions.command.CommandTree;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;

import java.util.UUID;

public class BukkitPermissionManager implements IPermissionManager {

    @Override
    public boolean hasPermission(UUID uuid, String permission) {
        OfflinePlayer player = Bukkit.getPlayer(uuid);
        if(player == null || player.getPlayer() == null) {
            MyPermissions.instance.LOG.error("Failed to get player with the UUID: " + uuid.toString());
            return false;
        }

        return player.getPlayer().hasPermission(trimPermission(permission));
    }

    /**
     * Bukkit permissions will only check for base permission of each tree since implementing
     * it is not important and should work as intended 99% of the time.
     */
    public String trimPermission(String permission) {
        CommandTree tree = CommandManager.getTreeFromPermission(permission);
        if(tree != null) {
            return tree.getRoot().getAnnotation().permission();
        } else {
            return permission;
        }
    }
}

package mypermissions.manager;

import mypermissions.MyPermissions;
import mypermissions.api.IPermissionManager;
import mypermissions.api.command.CommandManager;
import mypermissions.command.CommandTree;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;

import java.util.UUID;

public class BukkitPermissionManager implements IPermissionManager {

    @Override
    public boolean hasPermission(UUID uuid, String permission) {
        OfflinePlayer player = Bukkit.getPlayer(uuid);
        if(player == null || player.getPlayer() == null) {
            //MyPermissions.instance.LOG.error("Failed to get player with the UUID: " + uuid.toString());
            return false;
        }

        return player.getPlayer().hasPermission(trimPermission(permission));
    }

    /**
     * Bukkit permissions will only check for base permission of each tree since implementing
     * it is not important and should work as intended 99% of the time.
     */
    public String trimPermission(String permission) {
        CommandTree tree = CommandManager.getTreeFromPermission(permission);
        if(tree != null) {
            return tree.getRoot().getAnnotation().permission();
        } else {
            return permission;
        }
    }
}

Remove spam of failure to get UUID.

Remove spam of failure to get UUID.


package com.twotoasters.jazzylistview.effects;

import android.view.View;

import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.twotoasters.jazzylistview.JazzyEffect;
import com.twotoasters.jazzylistview.JazzyListView;

public class FadeEffect implements JazzyEffect {

    private static final int DURATION_MULTIPLIER = 5;

    @Override
    public void initView(View item, int position, int scrollDirection) {
        ViewHelper.setAlpha(item, JazzyListView.TRANSPARENT);
    }

    @Override
    public void setupAnimation(View item, int position, int scrollDirection, ViewPropertyAnimator animator) {
        animator.setDuration(animator.getDuration() * JazzyListView.DURATION * DURATION_MULTIPLIER);
        animator.alpha(JazzyListView.OPAQUE);
    }

}

package com.twotoasters.jazzylistview.effects;

import android.view.View;

import com.nineoldandroids.view.ViewHelper;
import com.nineoldandroids.view.ViewPropertyAnimator;
import com.twotoasters.jazzylistview.JazzyEffect;
import com.twotoasters.jazzylistview.JazzyListView;

public class FadeEffect implements JazzyEffect {

    private static final int DURATION_MULTIPLIER = 5;

    @Override
    public void initView(View item, int position, int scrollDirection) {
        ViewHelper.setAlpha(item, JazzyListView.TRANSPARENT);
    }

    @Override
    public void setupAnimation(View item, int position, int scrollDirection, ViewPropertyAnimator animator) {
        animator.setDuration(JazzyListView.DURATION * DURATION_MULTIPLIER);
        animator.alpha(JazzyListView.OPAQUE);
    }

}

Fix error while factoring out fade effect


package coffee;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;

import javax.inject.Inject;

import sheath.Modules;
import sheath.SheathEntryPoint;

class CoffeeApp implements EntryPoint {
  @Modules(DripCoffeeModule.class)
  interface CoffeeGagger extends SheathEntryPoint<CoffeeApp> { }

  @Inject CoffeeMaker coffeeMaker;

  @Override
  public void onModuleLoad() {
    CoffeeGagger gagger = GWT.create(CoffeeGagger.class);
    gagger.inject(this);

    Button btn = Button.wrap(Document.get().getElementById("coffeeMaker"));
    btn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
          coffeeMaker.brew();
        }
      });
    btn.setEnabled(true);
  }
}

package coffee;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.shared.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;

import javax.inject.Inject;

import sheath.Modules;
import sheath.SheathEntryPoint;

class CoffeeApp implements EntryPoint {
  @Modules(DripCoffeeModule.class)
  interface CoffeeGraph extends SheathEntryPoint<CoffeeApp> { }

  @Inject CoffeeMaker coffeeMaker;

  @Override
  public void onModuleLoad() {
    CoffeeGraph graph = GWT.create(CoffeeGraph.class);
    graph.inject(this);

    Button btn = Button.wrap(Document.get().getElementById("coffeeMaker"));
    btn.addClickHandler(new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
          coffeeMaker.brew();
        }
      });
    btn.setEnabled(true);
  }
}

Remove references to old-name _Gagger_ in the sample.


package com.btk5h.skriptmirror.skript;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.util.SimpleLiteral;
import com.btk5h.skriptmirror.Null;

public class LitNullObject extends SimpleLiteral<Null> {
  static {
    Skript.registerExpression(LitNullObject.class, Null.class, ExpressionType.SIMPLE, "null");
  }

  public LitNullObject() {
    super(Null.getInstance(), false);
  }
}

package com.btk5h.skriptmirror.skript;

import ch.njol.skript.Skript;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.ExpressionType;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleLiteral;
import ch.njol.util.Kleenean;
import com.btk5h.skriptmirror.Null;
import org.bukkit.event.Event;

public class LitNullObject extends SimpleLiteral<Null> {
  static {
    Skript.registerExpression(LitNullObject.class, Null.class, ExpressionType.SIMPLE, "null");
  }

  public LitNullObject() {
    super(Null.getInstance(), false);
  }

  @Override
  public boolean init(Expression<?>[] exprs, int matchedPattern, Kleenean isDelayed,
                      SkriptParser.ParseResult parseResult) {
    return true;
  }

  @Override
  public String toString(Event e, boolean debug) {
    return "null";
  }
}

Revert "Remove unnecessary method overrides"

This reverts commit 02c3141

Whoops, it was necessary!


package starpunk.logic.systems;

import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.EntitySystem;
import com.artemis.annotations.Mapper;
import com.artemis.managers.TagManager;
import com.artemis.utils.ImmutableBag;
import starpunk.logic.PlayerInput;
import starpunk.logic.components.Acceleration;

public final class PlayerMovementSystem
  extends EntitySystem
{
  private static final float MAX_ACCELERATION = 10;

  @Mapper
  ComponentMapper<Acceleration> _accelerationMapper;
  private Entity _player;

  public PlayerMovementSystem()
  {
    super( Aspect.getAspectForAll() );
  }

  @Override
  public void initialize()
  {
    ensurePlayerEntity();
  }

  @Override
  protected void processEntities( final ImmutableBag<Entity> entities )
  {
    ensurePlayerEntity();

    if( null != _player )
    {
      updatePlayer( _player );
    }
  }

  @Override
  protected boolean checkProcessing()
  {
    return true;
  }

  private void ensurePlayerEntity()
  {
    if( null == _player || !_player.isActive() )
    {
      _player = world.getManager( TagManager.class ).getEntity( "PLAYER" );
    }
  }

  protected void updatePlayer( Entity e )
  {
    final Acceleration acceleration = _accelerationMapper.get( e );

    final PlayerInput input = PlayerInput.getPlayerInput();
    acceleration.setVectorX( input.isLeft() ? -MAX_ACCELERATION : input.isRight() ? MAX_ACCELERATION : 0 );
    acceleration.setVectorY( input.isUp() ? MAX_ACCELERATION : input.isDown() ? -MAX_ACCELERATION : 0 );
  }
}

package starpunk.logic.systems;

import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Mapper;
import com.artemis.managers.TagManager;
import com.artemis.systems.VoidEntitySystem;
import starpunk.logic.PlayerInput;
import starpunk.logic.components.Acceleration;

public final class PlayerMovementSystem
  extends VoidEntitySystem
{
  private static final float MAX_ACCELERATION = 10;

  @Mapper
  ComponentMapper<Acceleration> _accelerationMapper;
  private Entity _player;

  @Override
  protected void processSystem()
  {
    ensurePlayerEntity();

    if( null != _player )
    {
      updatePlayer( _player );
    }
  }

  private void ensurePlayerEntity()
  {
    if( null == _player || !_player.isActive() )
    {
      _player = world.getManager( TagManager.class ).getEntity( "PLAYER" );
    }
  }

  protected void updatePlayer( Entity e )
  {
    final Acceleration acceleration = _accelerationMapper.get( e );

    final PlayerInput input = PlayerInput.getPlayerInput();
    acceleration.setVectorX( input.isLeft() ? -MAX_ACCELERATION : input.isRight() ? MAX_ACCELERATION : 0 );
    acceleration.setVectorY( input.isUp() ? MAX_ACCELERATION : input.isDown() ? -MAX_ACCELERATION : 0 );
  }
}

Simplify to use a void system instead

Simplify to use a void system instead


package rogue.creature;

import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;

public class Player extends Creature implements Camera
{
    private Terminal term;
    private ViewField fov;

    public Player(Terminal term)
    {
        super(ColoredChar.create('@'));
        this.term = term;
        fov = new RayCaster();
    }

    @Override
    public void act()
    {
        try
        {
            char key;
            key = term.getKey();
            switch(key)
            {
                case 'q':
                    expire();
                    break;
		case 'l':
		    System.out.println("Geschaeftsprozessmodelle");
		    // Do not break; here, otherwise we can't move left!
                default:
                    Direction dir = Direction.keyToDir(key);
                    if(dir != null)
                        move(dir);
                    break;
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public Collection<Coordinate> getViewField()
    {
        return fov.getViewField(world(), pos(), 5);
    }
}

package rogue.creature;

import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;

public class Player extends Creature implements Camera
{
    private Terminal term;
    private ViewField fov;

    public Player(Terminal term)
    {
        super(ColoredChar.create('@'));
        this.term = term;
        fov = new RayCaster();
    }

    @Override
    public void act()
    {
        try
        {
            char key;
            key = term.getKey();
            switch(key)
            {
                case 'q':
                    expire();
                    break;
                default:
                    Direction dir = Direction.keyToDir(key);
                    if(dir != null)
                        move(dir);
                    break;
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public Collection<Coordinate> getViewField()
    {
        return fov.getViewField(world(), pos(), 5);
    }
}

Revert "Print "Geschaeftsprozessmodelle" when 'l' has been pressed"

This reverts commit d8b19a1f8486ea6259783d2be898e11cc9ed48c4.


package jpower.core.test;

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

@RunWith(Suite.class)
@Suite.SuiteClasses({
        AlphabetTest.class,
        ConditionTest.class,
        ConfigurationTest.class,
        FactoryTest.class,
        InternalTest.class,
        IOUtilsTest.class,
        LoadTest.class,
        MultiMapTest.class,
        PowerLoaderTest.class,
        RandomTest.class,
        ThreadUtilsTest.class,
        ByteUtilsTest.class,
        WorkerTest.class,
        GenericSnifferTest.class,
        OperatingSystemTest.class,
        CallUtilsTest.class,
        ServiceTest.class,
        WrapperTest.class,
        RepeaterTest.class,
        ConditionalAdapterTest.class,
        StringUtilsTest.class
})
public class CoreTestSuite
{
}

package jpower.core.test;

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

@RunWith(Suite.class)
@Suite.SuiteClasses({
        AlphabetTest.class,
        ConditionTest.class,
        ConfigurationTest.class,
        FactoryTest.class,
        InternalTest.class,
        IOUtilsTest.class,
        LoadTest.class,
        MultiMapTest.class,
        PowerLoaderTest.class,
        RandomTest.class,
        ThreadUtilsTest.class,
        ByteUtilsTest.class,
        WorkerTest.class,
        GenericSnifferTest.class,
        OperatingSystemTest.class,
        CallUtilsTest.class,
        ServiceTest.class,
        WrapperTest.class,
        RepeaterTest.class,
        ConditionalAdapterTest.class,
        StringUtilsTest.class,
        ListUtilsTest.class
})
public class CoreTestSuite
{
}

Add ListUtilsTest to Core Suite

Add ListUtilsTest to Core Suite


package com.parrit.entities;

import javax.persistence.*;
import java.util.Collection;

@Entity
public class Space {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @OneToMany(targetEntity = Person.class)
    private Collection<Person> people;

    private String name;

    public Space() {}

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

    public long getId() {
        return id;
    }

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

    public Collection<Person> getPeople() {
        return people;
    }

    public void setPeople(Collection<Person> people) {
        this.people = people;
    }

    public String getName() {
        return name;
    }

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

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

        Space space = (Space) o;

        if (id != space.id) return false;
        if (people != null ? !people.equals(space.people) : space.people != null) return false;
        if (name != null ? !name.equals(space.name) : space.name == null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "Space{" +
                "id=" + id +
                ", people=" + people +
                ", name='" + name + '\'' +
                '}';
    }
}

package com.parrit.entities;

import javax.persistence.*;
import java.util.Collection;

@Entity
public class Space {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToMany(targetEntity = Person.class)
    private Collection<Person> people;

    private String name;

    public Space() {}

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

    public long getId() {
        return id;
    }

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

    public Collection<Person> getPeople() {
        return people;
    }

    public void setPeople(Collection<Person> people) {
        this.people = people;
    }

    public String getName() {
        return name;
    }

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

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

        Space space = (Space) o;

        if (id != space.id) return false;
        if (people != null ? !people.equals(space.people) : space.people != null) return false;
        if (name != null ? !name.equals(space.name) : space.name == null) return false;

        return true;
    }

    @Override
    public String toString() {
        return "Space{" +
                "id=" + id +
                ", people=" + people +
                ", name='" + name + '\'' +
                '}';
    }
}

Allow ManyToMany relationship sapce_people until better solution


package com.github.ferstl.depgraph;

import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;

import com.github.ferstl.depgraph.dot.DotBuilder;

@Mojo(
    name = "graph",
    aggregator = false,
    defaultPhase = LifecyclePhase.NONE,
    requiresDependencyCollection = ResolutionScope.TEST,
    requiresDirectInvocation = true,
    threadSafe = true)
public class DepGraphMojo extends AbstractDepGraphMojo {

  @Override
  protected GraphFactory createGraphFactory(
      DependencyGraphBuilder dependencyGraphBuilder, ArtifactFilter artifactFilter) {

      DotBuilder dotBuilder = new DotBuilder(NodeRenderers.VERSIONLESS_ID, NodeRenderers.ARTIFACT_ID_LABEL);
      return new AggregatingDotGraphFactory(dependencyGraphBuilder, artifactFilter, dotBuilder);
  }

}

package com.github.ferstl.depgraph;

import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.shared.dependency.graph.DependencyGraphBuilder;

import com.github.ferstl.depgraph.dot.DotBuilder;

@Mojo(
    name = "graph",
    aggregator = false,
    defaultPhase = LifecyclePhase.NONE,
    requiresDependencyCollection = ResolutionScope.TEST,
    requiresDirectInvocation = true,
    threadSafe = true)
public class DepGraphMojo extends AbstractDepGraphMojo {

  @Override
  protected GraphFactory createGraphFactory(
      DependencyGraphBuilder dependencyGraphBuilder, ArtifactFilter artifactFilter) {

      DotBuilder dotBuilder = new DotBuilder(NodeRenderers.VERSIONLESS_ID, NodeRenderers.ARTIFACT_ID_LABEL);
      return new SimpleDotGraphFactory(dependencyGraphBuilder, artifactFilter, dotBuilder);
  }

}

Use the right graph factory

Use the right graph factory


package moe.tristan.easyfxml.api;

import moe.tristan.easyfxml.util.Resources;
import moe.tristan.easyfxml.util.Stages;

import javafx.stage.Stage;

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;

/**
 * Represents a stylesheet a supplier of Path. What this means is that any protocol is acceptable. Whether it is local
 * file-based or remote URI-based.
 *

 *
 * @see Stages#setStylesheet(Stage, FxmlStylesheet)
 */
public interface FxmlStylesheet {

    /**
     * @return the CSS file that composes the stylesheet as a {@link Path}.
     *

     * See {@link Resources#getResourcePath(String)}
     */
    Path getPath();

    /**
     * @return the CSS file in external form (i.e. with the file:/, http:/...) protocol info before it.
     *

     * See {@link Resources#getResourceURL(String)} and {@link URL#toExternalForm()}
     */
    default String getExternalForm() {
        try {
            return getPath().toUri().toURL().toExternalForm();
        } catch (MalformedURLException e) {
            throw new IllegalArgumentException(e);
        }
    }

}

package moe.tristan.easyfxml.api;

import moe.tristan.easyfxml.util.Resources;
import moe.tristan.easyfxml.util.Stages;
import io.vavr.control.Try;

import javafx.stage.Stage;

import java.net.URI;
import java.net.URL;
import java.nio.file.Path;

/**
 * Represents a stylesheet a supplier of Path. What this means is that any protocol is acceptable. Whether it is local
 * file-based or remote URI-based.
 *

 *
 * @see Stages#setStylesheet(Stage, FxmlStylesheet)
 */
public interface FxmlStylesheet {

    /**
     * @return the CSS file that composes the stylesheet as a {@link Path}.
     *

     * See {@link Resources#getResourcePath(String)}
     */
    Path getPath();

    /**
     * This method is a sample implementation that should work in almost all general cases.
     * An {@link java.io.IOException} can be thrown in very rare cases.
     *
     * If you encounter them, post an issue with system details.
     *
     * @return the CSS file in external form (i.e. with the file:/, http:/...) protocol info before it.
     *

     *
     * @see Resources#getResourceURL(String)
     * @see URL#toExternalForm()
     */
    default String getExternalForm() {
        return Try.of(this::getPath)
            .map(Path::toUri)
            .mapTry(URI::toURL)
            .map(URL::toExternalForm)
            .get();
    }

}

Remove useless catch case that wouldn't happen under normal operation.


package net.shadowfacts.foodies.recipe;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.shadowfacts.foodies.item.FItems;

/**
 * A helper class for registering recipes.
 * @author shadowfacts
 */
public class FRecipes {
	public static void preInit() {
		// Shapeless
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.hamburger), new ItemStack(FItems.toast), new ItemStack(FItems.beefPattie), new ItemStack(FItems.toast));
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.cheeseburger), new ItemStack(FItems.hamburger), new ItemStack(FItems.cheese));

		// Shaped

		registerSmelting();
	}

	private static void registerSmelting() {
		// Smelting
		GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast), 0.2f);
		GameRegistry.addSmelting(Items.cooked_beef, new ItemStack(FItems.beefPattie), 0.3f);
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

package net.shadowfacts.foodies.recipe;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.shadowfacts.foodies.item.FItems;

/**
 * A helper class for registering recipes.
 * @author shadowfacts
 */
public class FRecipes {
	public static void preInit() {
		// Shapeless
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.hamburger), new ItemStack(FItems.toast), new ItemStack(FItems.beefPattie), new ItemStack(FItems.toast));
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.cheeseburger), new ItemStack(FItems.hamburger), new ItemStack(FItems.cheese));
		GameRegistry.addShapelessRecipe(new ItemStack(FItems.deluxeCheeseburger), new ItemStack(FItems.cheeseburger), new ItemStack(FItems.lettuce), new ItemStack(FItems.tomato));

		// Shaped

		registerSmelting();
	}

	private static void registerSmelting() {
		// Smelting
		GameRegistry.addSmelting(Items.bread, new ItemStack(FItems.toast), 0.2f);
		GameRegistry.addSmelting(Items.cooked_beef, new ItemStack(FItems.beefPattie), 0.3f);
	}

	public static void load() {

	}

	public static void postInit() {

	}
}

Add recipe for deluxe cheeseburger

Add recipe for deluxe cheeseburger


/**
 * Copyright (c) 2012 by Tyson Gern
 * Licensed under the MIT License
 */

import java.util.*;

/**
 * This class stores an element of a Coxeter group of rank "rank" as a
 * signed permutation, oneLine.  The methods contained in this class
 * can preform elementary operations on the element.
 * @author Tyson Gern (tygern@gmail.com)
 */
abstract class EvenElement extends Element {

}

/**
 * Copyright (c) 2012 by Tyson Gern
 * Licensed under the MIT License
 */

import java.util.*;

/**
 * This class stores an element of a Coxeter group of rank "rank" as a
 * signed permutation, oneLine.  The methods contained in this class
 * can preform elementary operations on the element.
 * @author Tyson Gern (tygern@gmail.com)
 */
abstract class EvenElement extends Element {

    protected int countNeg() {
        int count = 0;

        for (int i = 1; i <= size; i++) {
            if (mapsto(i) < 0) count ++;
        }

        return count;
    }

}

Add sign counting for future use in type B length function.


package com.flipper83.katapotter;

import java.util.List;

public class BasketCalculator {
  private static final int BOOK_PRICE = 8;
  private static final float BOOK_DISCOUNT = 0.95f;

  public float calculatePrice(List<String> books) {

    NormalizeBasket normalizeBasket = new NormalizeBasket();
    normalizeBasket.addBooks(books);

    float amount = 0.0f;
    for (SetCollection collection : normalizeBasket.getCollections()) {
      int numBooks = collection.numBooks();
      if (numBooks > 1) {
        amount += BOOK_PRICE * BOOK_DISCOUNT * numBooks;
      } else {
        amount += BOOK_PRICE * numBooks;
      }
    }
    return amount;
  }
}

package com.flipper83.katapotter;

import java.util.List;

public class BasketCalculator {
  private static final int BOOK_PRICE = 8;
  private static final float BOOK_DISCOUNT = 0.05f;

  public float calculatePrice(List<String> books) {

    NormalizeBasket normalizeBasket = new NormalizeBasket();
    normalizeBasket.addBooks(books);

    float amount = 0.0f;
    for (SetCollection collection : normalizeBasket.getCollections()) {
      int numBooks = collection.numBooks();
      float discount = calculateDiscount(numBooks);
      amount += BOOK_PRICE * discount * numBooks;
    }
    return amount;
  }

  private float calculateDiscount(int numBooks) {
    return 1.0f - ((numBooks - 1) * BOOK_DISCOUNT);
  }
}

[GREEN] Add code for check different discounts for different number of books.


package rogue.creature;

import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;

public class Player extends Creature implements Camera
{
    private Terminal term;
    private ViewField fov;

    public Player(Terminal term)
    {
        super(ColoredChar.create('@'));
        this.term = term;
        fov = new RayCaster();
    }

    @Override
    public void act()
    {
        try
        {
            char key;
            key = term.getKey();
            switch(key)
            {
                case 'q':
                    expire();
                    break;
                default:
                    Direction dir = Direction.keyToDir(key);
                    if(dir != null)
                        move(dir);
                    break;
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public Collection<Coordinate> getViewField()
    {
        return fov.getViewField(world(), pos(), 5);
    }
}

package rogue.creature;

import java.util.Collection;
import jade.fov.RayCaster;
import jade.fov.ViewField;
import jade.ui.Camera;
import jade.ui.Terminal;
import jade.util.datatype.ColoredChar;
import jade.util.datatype.Coordinate;
import jade.util.datatype.Direction;

public class Player extends Creature implements Camera
{
    private Terminal term;
    private ViewField fov;

    public Player(Terminal term)
    {
        super(ColoredChar.create('@'));
        this.term = term;
        fov = new RayCaster();
    }

    @Override
    public void act()
    {
        try
        {
            char key;
            key = term.getKey();
            System.out.println("Gesamtproduktgüte");
            switch(key)
            {
                case 'q':
                    expire();
                    break;
                default:
                    Direction dir = Direction.keyToDir(key);
                    if(dir != null)
                        move(dir);
                    break;
            }
        }
        catch(InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public Collection<Coordinate> getViewField()
    {
        return fov.getViewField(world(), pos(), 5);
    }
}

Print "Gesamtproduktgüte" on any key press.


package com.amitness.photon;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.id_about) {
            //TODO: Write intent to another activity
            return true;
        }
        return true;
    }
}

package com.amitness.photon;

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

public class MainActivity extends AppCompatActivity {

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.id_about) {
            //TODO: Write intent to another activity
            return true;
        }
        return true;
    }

    public void gotoTransmitActivity(View view) {
        Intent nextPage = new Intent(MainActivity.this, TransmitActivity.class);
        startActivity(nextPage);
    }

    public void gotoReceiveActivity(View view) {
        Intent nextPage = new Intent(MainActivity.this, ReceiveActivity.class);
        startActivity(nextPage);
    }
}

Add intents to switch to another activity


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

package com.facebook.buck.versions;

import com.facebook.buck.util.randomizedtrial.WithProbability;

/**
 * Whether to use the {@link com.facebook.buck.versions.AsyncVersionedTargetGraphBuilder} or {@link
 * com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder}
 */
public enum VersionTargetGraphMode implements WithProbability {
  ENABLED(0.5),
  DISABLED(0.5),
  EXPERIMENT(0.0),
  ;

  public static final VersionTargetGraphMode DEFAULT = DISABLED;

  private final double probability;

  VersionTargetGraphMode(double probability) {
    this.probability = probability;
  }

  @Override
  public double getProbability() {
    return probability;
  }
}

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

package com.facebook.buck.versions;

import com.facebook.buck.util.randomizedtrial.WithProbability;

/**
 * Whether to use the {@link com.facebook.buck.versions.AsyncVersionedTargetGraphBuilder} or {@link
 * com.facebook.buck.versions.ParallelVersionedTargetGraphBuilder}
 */
public enum VersionTargetGraphMode implements WithProbability {
  ENABLED(0.5),
  DISABLED(0.5),
  EXPERIMENT(0.0),
  ;

  public static final VersionTargetGraphMode DEFAULT = ENABLED;

  private final double probability;

  VersionTargetGraphMode(double probability) {
    this.probability = probability;
  }

  @Override
  public double getProbability() {
    return probability;
  }
}

Make default version target graph build with new builder

Reviewed By: philipjameson

shipit-source-id: f2103da595


/*
 * Copyright (C) 2017 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 android.support;

/**
 * The list of versions codes of all the libraries in this project.
 */
public class LibraryVersions {
    /**
     * Version code of the support library components.
     */
    public static final Version SUPPORT_LIBRARY = new Version("27.0.0-SNAPSHOT");

    /**
     * Version code of the flatfoot libraries.
     */
    public static final Version FLATFOOT = new Version("1.0.0-alpha8");

    /**
     * Version code of the lifecycles library.
     */
    public static final Version LIFECYCLES = new Version("1.0.0-SNAPSHOT");
}

/*
 * Copyright (C) 2017 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 android.support;

/**
 * The list of versions codes of all the libraries in this project.
 */
public class LibraryVersions {
    /**
     * Version code of the support library components.
     */
    public static final Version SUPPORT_LIBRARY = new Version("27.0.0-SNAPSHOT");

    /**
     * Version code of the flatfoot libraries.
     */
    public static final Version FLATFOOT = new Version("1.0.0-alpha9");

    /**
     * Version code of the lifecycles library.
     */
    public static final Version LIFECYCLES = new Version("1.0.0-SNAPSHOT");
}

Set version to alpha 9.

Set version to alpha 9.

Bug:36069458
Test: N/A
Change-Id: I094078142551d23418245aed3be3366e2fd2ad99


package gamecontrollers.commandcreator;

import gamecontrollers.Response;
import gamecontrollers.commands.GameplayActionCommand;
import models.board.Direction;
import models.board.Space;
import models.board.TileComponent;

public class TilePlacementController <A extends Space, B extends TileComponent> extends TileCommandCreator {
	private Space currentSpace;
	private TileComponent currentTile;

	public TilePlacementController(Space currentSpace, TileComponent currentTile) {
		this.currentSpace = currentSpace;
		this.currentTile = currentTile;
	}

	public Space getCurrentSpace() {
		return currentSpace;
	}

	public void setCurrentSpace(Space currentSpace) {
		this.currentSpace = currentSpace;
	}

	public TileComponent getCurrentTile() {
		return currentTile;
	}

	public void setCurrentTile(TileComponent currentTile) {
		this.currentTile = currentTile;
	}

	public void placeTileComponent() {

	}

	public void move(Direction direction) {

	}

	public void rotateCurrentTileComponent() {

	}

    /*
    This method will return the constructed command
 */
    public GameplayActionCommand getCommand(){

        // TODO implement
        return null;

    }

    /*
        This method will return the AP cost of the command that would
        be required to perform the command
     */
    public int getCost(){
        return 0;
    }

    /*

     */
    public Response checkPossible(){
        return null;
    }

}

package gamecontrollers.commandcreator;

import gamecontrollers.Response;
import gamecontrollers.commands.GameplayActionCommand;
import models.board.Direction;
import models.board.Space;
import models.board.TileComponent;

public class TilePlacementController extends TileCommandCreator {
	private Space currentSpace;
	private TileComponent currentTile;

    /*
  ========================================================================
     CONSTRUCTORS
  ========================================================================
   */
	public TilePlacementController(Space currentSpace, TileComponent currentTile) {
		this.currentSpace = currentSpace;
		this.currentTile = currentTile;
	}

    /*
   ========================================================================
      GETTERS AND SETTERS
   ========================================================================
    */

	public Space getCurrentSpace() {
		return currentSpace;
	}

	public void setCurrentSpace(Space currentSpace) {
		this.currentSpace = currentSpace;
	}

	public TileComponent getCurrentTile() {
		return currentTile;
	}

	public void setCurrentTile(TileComponent currentTile) {
		this.currentTile = currentTile;
	}

    /*
  ========================================================================
     PUBLIC METHODS
  ========================================================================
   */

	public void move(Direction direction) {
		//traverse in the space direction
        currentSpace = currentSpace.getAdjacentSpace(direction);
	}

	public void rotateCurrentTileComponent() {

	}

    /*
    This method will return the constructed command
 */
    public GameplayActionCommand getCommand(){

        // TODO implement
        return null;

    }

    /*
        This method will return the AP cost of the command that would
        be required to perform the command
     */
    public int getCost(){
        return 0;
    }

    /*

     */
    public Response checkPossible(){
        return null;
    }

}

Implement move and add some comments, getting ready for pull


package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }
}

package cpw.mods.fml.common.event;

import net.minecraft.server.MinecraftServer;
import net.minecraft.src.CommandHandler;
import net.minecraft.src.ICommand;
import cpw.mods.fml.common.LoaderState.ModState;

public class FMLServerStartingEvent extends FMLStateEvent
{

    private MinecraftServer server;

    public FMLServerStartingEvent(Object... data)
    {
        super(data);
        this.server = (MinecraftServer) data[0];
    }
    @Override
    public ModState getModState()
    {
        return ModState.AVAILABLE;
    }

    public MinecraftServer getServer()
    {
        return server;
    }

    public void registerServerCommand(ICommand command)
    {
        CommandHandler ch = (CommandHandler) getServer().func_71187_D();
        ch.func_71560_a(command);
    }
}

Add in a helper on the server start event for adding commands to the server.


package org.udg.pds.simpleapp_javaee.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class LoggingFilter implements ContainerResponseFilter {

  private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

  public void filter(ContainerRequestContext requestContext,
                     ContainerResponseContext responseContext) throws IOException {
    String method = requestContext.getMethod();

    logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType());
    // String json = IOUtils.toString(requestContext.getEntityStream());
    Object entity = responseContext.getEntity();
    if (entity != null) {
      logger.info("Response " + new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(entity));
    }

  }
}

package org.udg.pds.simpleapp_javaee.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class LoggingFilter implements ContainerResponseFilter {

  private static final Logger logger = LoggerFactory.getLogger(LoggingFilter.class);

  public void filter(ContainerRequestContext requestContext,
                     ContainerResponseContext responseContext) throws IOException {
    String method = requestContext.getMethod();

    logger.info("Requesting " + method + " for path " + requestContext.getUriInfo().getPath() + " with MIME type " + requestContext.getMediaType());
    // String json = IOUtils.toString(requestContext.getEntityStream());
    Object entity = responseContext.getEntity();
    if (entity != null) {
      String response = new ObjectMapper().writeValueAsString(entity).replace("\\\"", "\"");
      logger.info("Response: " + response);
    }

  }
}

Remove escape from double quotes

Remove escape from double quotes


package bamboo;

import bamboo.app.Bamboo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Bamboo getBamboo() throws IOException {
        return new Bamboo(false);
    }
}

package bamboo;

import bamboo.app.Bamboo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.io.IOException;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        for (int i = 0; i < args.length; i++) {
            switch (args[i]) {
                case "-h":
                case "--help":
                    System.out.println("Options:\n" +
                            "  -p port  Web server port\n" +
                            "  -b addr  Web server bind address\n" +
                            "  -c path  Web server context path");
                    return;
                case "-c":
                    System.setProperty("server.servlet.context-path", args[++i]);
                    break;
                case "-p":
                    System.setProperty("server.port", args[++i]);
                    break;
                case "-b":
                    System.setProperty("server.address", args[++i]);
                    break;
                default:
                    System.err.println("Ignoring unknown option: " + args[i]);
                    break;
            }
        }
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public Bamboo getBamboo() throws IOException {
        return new Bamboo(false);
    }
}

Add command-line options compatible with old main()


package org.logtalk.intellij;

import org.jetbrains.annotations.NotNull;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;

public class LogtalkFileTypeFactory extends FileTypeFactory {

    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "lgt");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "pl");
        //fileTypeConsumer.consume(PrologFileType.INSTANCE, "pl");
    }

}

package org.logtalk.intellij;

import org.jetbrains.annotations.NotNull;

import com.intellij.openapi.fileTypes.FileTypeConsumer;
import com.intellij.openapi.fileTypes.FileTypeFactory;

public class LogtalkFileTypeFactory extends FileTypeFactory {

    @Override
    public void createFileTypes(@NotNull FileTypeConsumer fileTypeConsumer) {
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "logtalk");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "lgt");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "prolog");
        fileTypeConsumer.consume(LogtalkFileType.INSTANCE, "pl");
        //fileTypeConsumer.consume(PrologFileType.INSTANCE, "pl");
    }

}

Update IntelliJ IDEA support to also recognize `*.logtalk` and `*.prolog` file extensions


package edu.ntnu.idi.goldfish;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class StopWatch {

	protected static HashMap<String, Long> starts = new HashMap<String,Long>();
	protected static HashMap<String, Long> timings = new HashMap<String,Long>();

	public static void start(String name) {
		timings.remove(name);
		starts.put(name, System.currentTimeMillis());
	}

	public static void stop(String name) {
		if(!starts.containsKey(name)) {
			System.err.format("have no start timing for %s\n", name);
			return;
		}
		if(!timings.containsKey(name)) {
			timings.put(name, System.currentTimeMillis() - starts.get(name));
		}
	}

	public static String str(String name) {
		stop(name);
		long time = timings.get(name);
		return String.format("%d min, %d sec",
			    TimeUnit.MILLISECONDS.toMinutes(time),
			    TimeUnit.MILLISECONDS.toSeconds(time) -
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time))
		);
	}

	public static void print(String name) {
		System.out.format("%s: %s\n", name, str(name));
	}

	public static long get(String name) {
		stop(name);
		return timings.get(name);
	}
}

package edu.ntnu.idi.goldfish;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class StopWatch {

	protected static HashMap<String, Long> starts = new HashMap<String,Long>();
	protected static HashMap<String, Long> timings = new HashMap<String,Long>();

	public static void start(String name) {
		timings.remove(name);
		starts.put(name, System.currentTimeMillis());
	}

	public static void stop(String name) {
		if(!starts.containsKey(name)) {
			System.err.format("have no start timing for %s\n", name);
			return;
		}
		if(!timings.containsKey(name)) {
			timings.put(name, System.currentTimeMillis() - starts.get(name));
		}
	}

	public static String str(String name) {
		stop(name);
		long time = timings.get(name);
		return String.format("%d min, %d sec, (%d ms)",
			    TimeUnit.MILLISECONDS.toMinutes(time),
			    TimeUnit.MILLISECONDS.toSeconds(time) -
			    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)),
			    time
		);
	}

	public static void print(String name) {
		System.out.format("%s: %s\n", name, str(name));
	}

	public static long get(String name) {
		stop(name);
		return timings.get(name);
	}
}

Include ms in stopwatch output.

Include ms in stopwatch output.


package org.oblodiff.token.text;

import org.oblodiff.token.BasicToken;

/**
 * A textual token is a token representing a text.
 *
 * @since 1.0.0
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class TextualToken<T> extends BasicToken<T> {

    public TextualToken(T ct) {
        super(ct);
    }
}

package org.oblodiff.token.text;

import org.oblodiff.token.BasicToken;

/**
 * A textual token is a token representing a text.
 *
 * XXX For what is this class good? It does not add any behavior/property to BasicToken.
 * @since 1.0.0
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class TextualToken<T> extends BasicToken<T> {

    /**
     * Dedicated constructor.
     *
     * @param content must not be {@code null}
     */
    public TextualToken(final T content) {
        super(content);
    }
}

Add XXX marker to class.

Add XXX marker to class.


package se.kits.gakusei.content.model;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "lessons", schema = "contentschema")
public class Lesson implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String description;

    @ManyToMany
    @JsonManagedReference
    @JoinTable(
            name = "lessons_nuggets",
            joinColumns = @JoinColumn(name = "lesson_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "nugget_id", referencedColumnName = "id"))
    private List<Nugget> nuggets;

    public Lesson() {
    }

    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 String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Nugget> getNuggets() {
        return nuggets;
    }

    public void setNuggets(List<Nugget> nuggets) {
        this.nuggets = nuggets;
    }
}

package se.kits.gakusei.content.model;

import com.fasterxml.jackson.annotation.JsonManagedReference;

import javax.persistence.*;
import java.io.Serializable;
import java.util.List;

@Entity
@Table(name = "lessons", schema = "contentschema")
public class Lesson implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    private String description;

    @ManyToMany
    @JsonManagedReference
    @JoinTable(
            name = "lessons_nuggets",
            schema = "contentschema",
            joinColumns = @JoinColumn(name = "lesson_id", referencedColumnName = "id"),
            inverseJoinColumns = @JoinColumn(name = "nugget_id", referencedColumnName = "id"))
    private List<Nugget> nuggets;

    public Lesson() {
    }

    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 String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<Nugget> getNuggets() {
        return nuggets;
    }

    public void setNuggets(List<Nugget> nuggets) {
        this.nuggets = nuggets;
    }
}

Add missing schema declaration to lesson/nugget relation


package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

		if (foundProject != null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

package com.example.beer.dao;

import javax.ejb.Singleton;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

	public boolean addProject(Project project) {
		Project foundProject = findProjectByName(project.getName());

		if (foundProject == null) {
			em.persist(project);
			return true;
		} else {
			// TODO: Maybe update project title or users, or tasks?
			return false;
		}
	}

	public Project findProjectByName(String name) {
		String idQueryText = "SELECT p FROM Project p WHERE p.name= :projectName";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectName", name);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	public Project findProjectById(int projectId) {
		String idQueryText = "SELECT p FROM Project p WHERE p.id= :projectId";
		TypedQuery<Project> idQuery = em.createQuery(idQueryText, Project.class);
		idQuery.setParameter("projectId", projectId);

		try {
			return idQuery.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}
}

Fix a logical error. A new project was persisted if it was already found found in the database. It should be the opposite


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Benchmark {

    private static final String PATTERN_EMAIL = "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+";
    private static final String PATTERN_URI = "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?";
    private static final String PATTERN_IP = "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}" +
                                             "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])";

    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java Benchmark <filename>");
            System.exit(1);
        }

        final String data = Files.readString(Paths.get(args[0]));

        measure(data, PATTERN_EMAIL);
        measure(data, PATTERN_URI);
        measure(data, PATTERN_IP);
    }

    private static void measure(String data, String pattern) {
        long startTime = System.nanoTime();

        final Matcher matcher = Pattern.compile(pattern).matcher(data);
        int count = 0;
        while (matcher.find()) {
            ++count;
        }

        long elapsed = System.nanoTime() - startTime;

        System.out.println(elapsed / 1e6 + " - " + count);
    }
}

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public final class Benchmark {
    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: java Benchmark <filename>");
            System.exit(1);
        }

        final String data = Files.readString(Paths.get(args[0]));

        measure(data, "[\\w.+-]+@[\\w.-]+\\.[\\w.-]+");
        measure(data, "[\\w]+://[^/\\s?#]+[^\\s?#]+(?:\\?[^\\s#]*)?(?:#[^\\s]*)?");
        measure(data, "(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])");
    }

    private static void measure(String data, String pattern) {
        long startTime = System.nanoTime();

        final Matcher matcher = Pattern.compile(pattern).matcher(data);
        int count = 0;
        while (matcher.find()) {
            ++count;
        }

        long elapsed = System.nanoTime() - startTime;

        System.out.println(elapsed / 1e6 + " - " + count);
    }
}

Java: Put patterns directly in function call to follow style of the rest of benchmarks


package org.gbif.nameparser;

import org.gbif.nameparser.api.ParsedAuthorship;
import org.gbif.nameparser.api.ParsedName;

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

public class ParserConfigs {

  private final Map<String, ParsedName> names = new HashMap<>();
  private final Map<String, ParsedAuthorship> authorships = new HashMap<>();

  public ParsedName forName(String name) {
    name = ParsingJob.preClean(name, null);
    return names.get(name);
  }

  public ParsedAuthorship forAuthorship(String authorship) {
    authorship = ParsingJob.preClean(authorship, null);
    return authorships.get(authorship);
  }
}

package org.gbif.nameparser;

import org.gbif.nameparser.api.ParsedAuthorship;
import org.gbif.nameparser.api.ParsedName;

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

public class ParserConfigs {

  private final Map<String, ParsedName> names = new HashMap<>();
  private final Map<String, ParsedAuthorship> authorships = new HashMap<>();

  public ParsedName forName(String name) {
    name = ParsingJob.preClean(name, null);
    return names.get(name);
  }

  public ParsedAuthorship forAuthorship(String authorship) {
    authorship = ParsingJob.preClean(authorship, null);
    return authorships.get(authorship);
  }

  public void setName(String sciname, ParsedName pn) {
    names.put(ParsingJob.preClean(sciname, null), pn);
  }

  public ParsedName deleteName(String name) {
    return names.remove(ParsingJob.preClean(name, null));
  }

  public void setAuthorship(String authorship, ParsedAuthorship pn) {
    authorships.put(ParsingJob.preClean(authorship, null), pn);
  }

  public ParsedAuthorship deleteAuthorship(String authorship) {
    return authorships.remove(ParsingJob.preClean(authorship, null));
  }
}

Add methods to change parser override configs


package com.amebame.triton.server;

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

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = Executors.newFixedThreadPool(
				config.getNetty().getWorker(),
				new NamedThreadFactory("triton-worker-"));
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

package com.amebame.triton.server;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;

import com.amebame.triton.config.TritonServerConfiguration;
import com.amebame.triton.util.NamedThreadFactory;

@Singleton
public class TritonServerContext {

	private TritonServerMethodMap methodMap;

	private ExecutorService executor;

	@Inject
	public TritonServerContext(TritonServerConfiguration config) {
		methodMap = new TritonServerMethodMap();
		executor = new ThreadPoolExecutor(
				1,
				config.getNetty().getWorker(),
				60L,
				TimeUnit.SECONDS,
				new SynchronousQueue<Runnable>(),
				new NamedThreadFactory("triton-worker-"));
	}

	/**
	 * Add server methods from the target object
	 * @param target
	 */
	public void addServerMethod(Object target) {
		methodMap.register(target);
	}

	/**
	 * Get server method by name
	 * @param name
	 * @return
	 */
	public TritonServerMethod getServerMethod(String name) {
		return methodMap.getMethod(name);
	}

	/**
	 * Get worker executor
	 * @return
	 */
	public ExecutorService getWorkerExecutor() {
		return executor;
	}
}

Use SynchronousQueue as executor queue to enable expanding pools.


package at.ac.tuwien.inso.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;

import at.ac.tuwien.inso.entity.*;

import java.util.*;

public interface SubjectService {

    @PreAuthorize("isAuthenticated()")
    Page<Subject> findAll(Pageable pageable);

    @PreAuthorize("isAuthenticated()")
    Subject findOne(long id);

    @PreAuthorize("isAuthenticated()")
    List<Subject> searchForSubjects(String word);

    @PreAuthorize("hasRole('ADMIN')")
    Subject create(Subject subject);

    @PreAuthorize("hasRole('ADMIN')")
    Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);

    @PreAuthorize("hasRole('ADMIN')")
    List<Lecturer> getAvailableLecturersForSubject(Long subjectId);

    @PreAuthorize("hasRole('ADMIN')")
    void removeLecturerFromSubject(Long subjectId, Long lecturerId);
}

package at.ac.tuwien.inso.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;

import at.ac.tuwien.inso.entity.*;

import java.util.*;

public interface SubjectService {

    @PreAuthorize("isAuthenticated()")
    Page<Subject> findAll(Pageable pageable);

    @PreAuthorize("isAuthenticated()")
    Subject findOne(long id);

    @PreAuthorize("isAuthenticated()")
    List<Subject> searchForSubjects(String word);

    @PreAuthorize("hasRole('ADMIN')")
    Subject create(Subject subject);

    @PreAuthorize("hasRole('ADMIN')")
    Subject addLecturerToSubject(Long subjectId, Long lecturerUisUserId);

    @PreAuthorize("hasRole('ADMIN')")
    List<Lecturer> getAvailableLecturersForSubject(Long subjectId);

    @PreAuthorize("hasRole('ADMIN')")
    Lecturer removeLecturerFromSubject(Long subjectId, Long lecturerUisUserId);
}

Add return value to removeLecturerFromSubject


package seedu.address.logic.commands;

import java.util.Set;

/**
 * Finds and lists all persons in address book whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class FindCommand extends Command {

    public static final String COMMAND_WORD = "find";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
            + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n"
            + "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
            + "Example: " + COMMAND_WORD + " CS2103";

    private final Set<String> keywords;

    public FindCommand(Set<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public CommandResult execute() {
        model.updateFilteredPersonList(keywords);
        return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()));
    }

}

package seedu.address.logic.commands;

import java.util.Set;

/**
 * Finds and lists all persons in address book whose name contains any of the argument keywords.
 * Keyword matching is case sensitive.
 */
public class FindCommand extends Command {

    public static final String COMMAND_WORD = "find";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Finds all tasks whose names contain any of "
            + "the specified keywords (case-sensitive) and displays them as a list with index numbers.\n"
            + "Parameters: KEYWORD [MORE_KEYWORDS]...\n"
            + "Example: " + COMMAND_WORD + " CS2103";

    private final Set<String> keywords;

    public FindCommand(Set<String> keywords) {
        this.keywords = keywords;
    }

    @Override
    public CommandResult execute() {
        model.updateFilteredPersonList(keywords);
        return new CommandResult(getMessageForPersonListShownSummary(model.getFilteredPersonList().size()+model.getFilteredUndatedTaskList().size()));
    }

}

Update Number of tasks listed in Find command


package com.kurento.kmf.media.repository;

import java.io.IOException;

public abstract class MediaRepository {

	/**
	 *
	 * @return the created media id
	 * @throws IOException
	 *             if the media resource cannot be created
	 */
	public abstract String create() throws IOException;

	/**
	 *
	 * @param mediaId
	 * @throws IOException
	 *             it the media resource cannot be removed
	 */
	public abstract void remove(String mediaId) throws IOException;

	/**
	 *
	 * @param mediaId
	 * @return the path of the media resource with this id
	 * @throws IOException
	 *             if the media resource does not exist
	 */
	public abstract String getPath(String mediaId) throws IOException;

}

package com.kurento.kmf.media.repository;

import java.io.IOException;

public abstract class MediaRepository {

	/**
	 *
	 * @return the created media id
	 * @throws IOException
	 *             if the media resource cannot be created
	 */
	public abstract String create() throws IOException;

	/**
	 *
	 * @param mediaId
	 * @throws IOException
	 *             it the media resource cannot be removed
	 */
	public abstract void remove(String mediaId) throws IOException;

	/**
	 *
	 * @param mediaId
	 * @return the URI of the media resource with this id
	 * @throws IOException
	 *             if the media resource does not exist
	 */
	public abstract String getUri(String mediaId) throws IOException;

}

Replace getPath method by getUri

Replace getPath method by getUri

Change-Id: I4c7aa63b092090243bad8b1429b7bbdbe5cc40d5


package com.codingchili.core.logging;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.*;
import org.junit.runner.RunWith;

import com.codingchili.core.context.SystemContext;
import com.codingchili.core.testing.ContextMock;

import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING;

/**
 * @author Robin Duda
 *
 * Verify that the remote logger is pushing events to a remote.
 */
@RunWith(VertxUnitRunner.class)
public class RemoteLoggerTest {
    private SystemContext context;

    @Before
    public void setUp() {
        context = new ContextMock(Vertx.vertx());
    }

    @After
    public void tearDown(TestContext test) {
        context.vertx().close(test.asyncAssertSuccess());
    }

    @Test
    public void testLogRemote(TestContext test) {
        mockNode(test.async());

        new RemoteLogger(context).log("text");
    }

    private void mockNode(Async async) {
        context.bus().consumer(NODE_LOGGING).handler(message -> {
            async.complete();
        });
    }
}

package com.codingchili.core.logging;

import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.*;
import org.junit.runner.RunWith;

import com.codingchili.core.context.ServiceContext;
import com.codingchili.core.testing.ContextMock;

import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING;

/**
 * @author Robin Duda
 *
 * Verify that the remote logger is pushing events to a remote.
 */
@RunWith(VertxUnitRunner.class)
public class RemoteLoggerTest {
    private ServiceContext context;

    @Before
    public void setUp() {
        context = new ContextMock(Vertx.vertx());
    }

    @After
    public void tearDown(TestContext test) {
        context.vertx().close(test.asyncAssertSuccess());
    }

    @Test
    public void testLogRemote(TestContext test) {
        mockNode(test.async());

        new RemoteLogger(context).log("text");
    }

    private void mockNode(Async async) {
        context.bus().consumer(NODE_LOGGING).handler(message -> {
            async.complete();
        });
    }
}

Fix compile error in tests.

Fix compile error in tests.


package com.cloud.flyway;

import com.cloud.legacymodel.exceptions.CloudRuntimeException;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class FlywayDB {

    private static final Logger logger = LoggerFactory.getLogger(FlywayDB.class);

    public void check() {
        logger.info("Start database migration");

        final InitialContext cxt;
        final DataSource dataSource;

        try {
            cxt = new InitialContext();
            dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic");
        } catch (final NamingException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        final Flyway flyway = new Flyway();
        flyway.setDataSource(dataSource);
        flyway.setTable("schema_version");
        flyway.setEncoding("UTF-8");

        try {
            flyway.migrate();
        } catch (final FlywayException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        logger.info("Database migration successful");
    }
}

package com.cloud.flyway;

import com.cloud.legacymodel.exceptions.CloudRuntimeException;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.FlywayException;
import org.flywaydb.core.api.configuration.FluentConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FlywayDB {

    private static final Logger logger = LoggerFactory.getLogger(FlywayDB.class);

    public void check() {
        logger.info("Start database migration");

        final InitialContext cxt;
        final DataSource dataSource;

        try {
            cxt = new InitialContext();
            dataSource = (DataSource) cxt.lookup("java:/comp/env/jdbc/cosmic");
        } catch (final NamingException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        final FluentConfiguration flywayConfig = new FluentConfiguration()
                .encoding("UTF-8")
                .dataSource(dataSource)
                .table("schema_version");
        final Flyway flyway = new Flyway(flywayConfig);

        try {
            flyway.migrate();
        } catch (final FlywayException e) {
            logger.error(e.getMessage(), e);
            throw new CloudRuntimeException(e.getMessage(), e);
        }

        logger.info("Database migration successful");
    }
}

Change deprecated flyway methods to new FluentConfiguration


package nakadi;

/**
 * Can be called by the {@link StreamObserver} to indicate a batch has been processed.
 *
 * Typically this is used to implement a checkpointer that can store the position of the
 * client in the stream to track their progress.
 */
public interface StreamOffsetObserver {

  /**
   * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally,
   * observe) progress in the stream.
   *

   * The default observer for a subscription based {@link StreamProcessor} (one which has been
   * given a subscription id via {@link StreamConfiguration#subscriptionId} is
   * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time
   * it's called. This behaviour can be replaced by supplying a different checkpointer via
   * {@link StreamProcessor.Builder#streamOffsetObserver}.
   *
   * @param streamCursorContext the batch's {@link StreamCursorContext}.
   *
   * todo: see if we need to declare checked exceptions here to force the observer to handle.
   */
  void onNext(StreamCursorContext streamCursorContext) throws NakadiException;
}

package nakadi;

/**
 * Can be called by the {@link StreamObserver} to indicate a batch has been processed.
 *
 * Typically this is used to implement a checkpointer that can store the position of the
 * client in the stream to track their progress.
 */
public interface StreamOffsetObserver {

  /**
   * Receives a {@link StreamCursorContext} that can be used to checkpoint (or more generally,
   * observe) progress in the stream.
   *

   * The default observer for a subscription based {@link StreamProcessor} (one which has been
   * given a subscription id via {@link StreamConfiguration#subscriptionId} is
   * {@link SubscriptionOffsetObserver}. This will checkpoint back to the server each time
   * it's called. This behaviour can be replaced by supplying a different checkpointer via
   * {@link StreamProcessor.Builder#streamOffsetObserver}.
   *
   * @param streamCursorContext the batch's {@link StreamCursorContext}.
   *
   */
  void onNext(StreamCursorContext streamCursorContext) throws NakadiException;
}

Remove comment, offset observer will throw runtime exceptions


/*
 * Copyright 2017 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.
 */

/**
 * Workers allow running pieces of work in the background, either
 * in-process in isolated classloaders or out-of-process in reausable
 * daemons.
 *
 * @since 3.5
 */
@org.gradle.api.Incubating
package org.gradle.workers;

/*
 * Copyright 2017 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.
 */

/**
 * Workers allow running pieces of work in the background, either
 * in-process in isolated classloaders or out-of-process in reusable
 * daemons.
 *
 * @since 3.5
 */
@org.gradle.api.Incubating
package org.gradle.workers;

Fix a typo in some Javadoc.

Fix a typo in some Javadoc.


/*
 * Copyright (c) 2015 Ushahidi.
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.domain.entity;

import com.addhen.android.raiburari.domain.entity.Entity;

/**
 * GeoJson Entity
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class GeoJson extends Entity {

    private String mGeoJson;

    public String getGeoJson() {
        return mGeoJson;
    }

    public void setGeoJson(String geoJson) {
        mGeoJson = geoJson;
    }

    @Override
    public String toString() {
        return "GeoJson{" +
                "mID='" + _id + '\'' +
                ", geojson='" + mGeoJson + '\'' +
                '}';
    }
}

/*
 * Copyright (c) 2015 Ushahidi.
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.domain.entity;

import com.addhen.android.raiburari.domain.entity.Entity;

/**
 * GeoJson Entity
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class GeoJson extends Entity {

    private String mGeoJson;

    private Long mDeploymentId;

    public String getGeoJson() {
        return mGeoJson;
    }

    public void setGeoJson(String geoJson) {
        mGeoJson = geoJson;
    }

    @Override
    public String toString() {
        return "GeoJson{" +
                "mID='" + _id + '\'' +
                "mDeploymentId='" + mDeploymentId + '\'' +
                ", geojson='" + mGeoJson + '\'' +
                '}';
    }
}

Add deployment Id as all entities have to be associated with a deployment


package com.antonjohansson.geotest.docker;

import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;

/**
 * Defines a single docker container.
 */
public class DockerContainer implements AutoCloseable
{
    private final DockerClient client;
    private final String containerId;

    /**
     * Constructs a new {@link DockerContainer}.
     *
     * @param client The docker client. Used to close the container.
     * @param containerId The identifier of the container.
     */
    DockerContainer(DockerClient client, String containerId)
    {
        this.client = client;
        this.containerId = containerId;
    }

    public String getContainerId()
    {
        return containerId;
    }

    @Override
    public void close()
    {
        try
        {
            ContainerInfo info = client.inspectContainer(containerId);
            if (info.state().running())
            {
                client.killContainer(containerId);
            }
            client.removeContainer(containerId);
        }
        catch (DockerException | InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

package com.antonjohansson.geotest.docker;

import static com.spotify.docker.client.DockerClient.RemoveContainerParam.removeVolumes;

import com.spotify.docker.client.DockerClient;
import com.spotify.docker.client.exceptions.DockerException;
import com.spotify.docker.client.messages.ContainerInfo;

/**
 * Defines a single docker container.
 */
public class DockerContainer implements AutoCloseable
{
    private final DockerClient client;
    private final String containerId;

    /**
     * Constructs a new {@link DockerContainer}.
     *
     * @param client The docker client. Used to close the container.
     * @param containerId The identifier of the container.
     */
    DockerContainer(DockerClient client, String containerId)
    {
        this.client = client;
        this.containerId = containerId;
    }

    public String getContainerId()
    {
        return containerId;
    }

    @Override
    public void close()
    {
        try
        {
            ContainerInfo info = client.inspectContainer(containerId);
            if (info.state().running())
            {
                client.killContainer(containerId);
            }
            client.removeContainer(containerId, removeVolumes());
        }
        catch (DockerException | InterruptedException e)
        {
            throw new RuntimeException(e);
        }
    }
}

Remove volumes when removing the container This to avoid leaving dangling volumes


package uk.org.cinquin.mutinack.misc_util;

import java.util.concurrent.ThreadFactory;

public class NamedPoolThreadFactory implements ThreadFactory {
	private int counter = 0;
	final String name;
	public NamedPoolThreadFactory(String name) {
		this.name = name;
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		t.setName(name + counter++);
		return t;
	}

}

package uk.org.cinquin.mutinack.misc_util;

import java.util.concurrent.ThreadFactory;

public class NamedPoolThreadFactory implements ThreadFactory {
	private int counter = 0;
	final String name;
	public NamedPoolThreadFactory(String name) {
		this.name = name;
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(r);
		t.setName(name + counter++);
		t.setDaemon(true);
		return t;
	}

}

Mark pool threads as daemon.

Mark pool threads as daemon.

Signed-off-by: Olivier Cinquin <65f36a1df3704fccc062437169cf2fbbed716a11@uci.edu>


/*
 * Copyright 2014 Patrik Karlsson.
 *
 * 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 se.trixon.toolbox.core.base;

import java.util.ResourceBundle;
import org.openide.windows.TopComponent;

/**
 *
 * @author Patrik Karlsson <patrik@trixon.se>
 */
public abstract class ToolTopComponent extends TopComponent {

    protected static final int TOOLBAR_ICON_SIZE = 24;
    protected ResourceBundle mBundle;
    protected String mToolName;
}

/*
 * Copyright 2014 Patrik Karlsson.
 *
 * 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 se.trixon.toolbox.core.base;

import java.util.ResourceBundle;
import org.openide.awt.StatusDisplayer;
import org.openide.windows.TopComponent;
import se.trixon.toolbox.core.Toolbox;

/**
 *
 * @author Patrik Karlsson <patrik@trixon.se>
 */
public abstract class ToolTopComponent extends TopComponent {

    protected static final int TOOLBAR_ICON_SIZE = 24;
    protected ResourceBundle mBundle;
    protected String mToolName;
    private String mStatus = "";

    @Override
    protected void componentDeactivated() {
        super.componentDeactivated();
        mStatus = StatusDisplayer.getDefault().getStatusText();
        Toolbox.setStatusText("");
    }

    @Override
    protected void componentActivated() {
        super.componentActivated();
        Toolbox.setStatusText(mStatus);
    }
}

Clear and reset status text.

Clear and reset status text.


package net.machinemuse.numina.recipe;

import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

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

/**
 * Author: MachineMuse (Claire Semple)
 * Created: 5:06 PM, 11/4/13
 */
public class ItemNameMappings {
    private static Map<String, ItemStack> itemMap;

    private static Map<String, ItemStack> getItemMap() {
        if (itemMap == null) {
            itemMap = new HashMap<String, ItemStack>();
            for (Object obj : Block.blockRegistry) {
                Block block = (Block)obj;
                if (block != null && block.getUnlocalizedName() != null) {
                    itemMap.put(block.getUnlocalizedName(), new ItemStack(block));
                }
            }
            for (Object obj : Item.itemRegistry) {
                Item item = (Item)obj;
                if (item != null) {
                    if(item.getHasSubtypes()) {
                        List<ItemStack> stacklist = new ArrayList<ItemStack>();
                        for(CreativeTabs tab : item.getCreativeTabs()) {
                            item.getSubItems(item, tab, stacklist);
                        }
                        for(ItemStack stack : stacklist) {
                            itemMap.put(stack.getUnlocalizedName(), stack.copy());
                        }
                    } else {
                        itemMap.put(item.getUnlocalizedName(), new ItemStack(item));
                    }
                }
            }
        }
        return itemMap;
    }

    public static ItemStack getItem(String name) {
        if (getItemMap().containsKey(name))
            return getItemMap().get(name);
        else
            return null;
    }
}

package net.machinemuse.numina.recipe;

import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

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

/**
 * Author: MachineMuse (Claire Semple)
 * Created: 5:06 PM, 11/4/13
 */
public class ItemNameMappings {
    private static Map<String, ItemStack> itemMap;

    private static Map<String, ItemStack> getItemMap() {
        if (itemMap == null) {
            itemMap = new HashMap<String, ItemStack>();
            for (Object obj : Block.blockRegistry) {
                Block block = (Block)obj;
                if (block != null && block.getUnlocalizedName() != null) {
                    itemMap.put(block.getUnlocalizedName(), new ItemStack(block));
                }
            }
            for (Object obj : Item.itemRegistry) {
                Item item = (Item)obj;
                if (item != null && item.getUnlocalizedName() != null) {
                    itemMap.put(item.getUnlocalizedName(), new ItemStack(item));
                }
            }
        }
        return itemMap;
    }

    public static ItemStack getItem(String name) {
        if (getItemMap().containsKey(name))
            return getItemMap().get(name);
        else
            return null;
    }
}

Undo change that makes client-side issue. Will need another way to get sub-items