package com.agricraft.agricore.templates;

import com.agricraft.agricore.core.AgriCore;
import com.google.gson.JsonObject;

public class AgriMutationTrigger {
    private final String id;
    private final boolean required;
    private final boolean guaranteed;
    private final JsonObject parameters;

    public AgriMutationTrigger() {
        this.id = "none";
        this.required = false;
        this.guaranteed = false;
        this.parameters = new JsonObject();
    }

    public AgriMutationTrigger(String id, boolean required, boolean guaranteed, JsonObject parameters) {
        this.id = id;
        this.required = required;
        this.guaranteed = guaranteed;
        this.parameters = parameters;
    }

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

    public boolean isRequired() {
        return this.required;
    }

    public boolean isGuaranteed() {
        return this.guaranteed;
    }

    public JsonObject getParameters() {
        return this.parameters;
    }

    public boolean validate() {
        boolean valid = AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters());
        if(!valid) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters());
        }
        return valid;
    }
}

package com.agricraft.agricore.templates;

import com.agricraft.agricore.core.AgriCore;
import com.google.gson.JsonObject;

public class AgriMutationTrigger {
    private final String id;
    private final boolean required;
    private final double guaranteedChance;
    private final JsonObject parameters;

    public AgriMutationTrigger() {
        this.id = "none";
        this.required = false;
        this.guaranteedChance = 0;
        this.parameters = new JsonObject();
    }

    public AgriMutationTrigger(String id, boolean required, double guaranteedChance, JsonObject parameters) {
        this.id = id;
        this.required = required;
        this.guaranteedChance = guaranteedChance;
        this.parameters = parameters;
    }

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

    public boolean isRequired() {
        return this.required;
    }

    public double getGuaranteedChance() {
        return this.guaranteedChance;
    }

    public JsonObject getParameters() {
        return this.parameters;
    }

    public boolean validate() {
        if(!AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters())) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters());
            return false;
        }
        if(this.getGuaranteedChance() < 0 || this.getGuaranteedChance() > 1) {
            AgriCore.getCoreLogger().info("Invalid Mutation trigger guaranteed probability: {1}, the value must be between 0 and 1 (both inclusive)", this.getId(), this.getParameters());
            return false;
        }
        return true;
    }
}

Make mutation trigger guarantee a probability


package com.kushkipagos.android.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kushkipagos.android.Card;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.sendButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                TextView textField = (TextView) findViewById(R.id.txtEncryptedMessage);
                EditText nameText = (EditText) findViewById(R.id.nameText);
                EditText numberText = (EditText) findViewById(R.id.numberText);
                EditText monthText = (EditText) findViewById(R.id.monthText);
                EditText yearText = (EditText) findViewById(R.id.yearText);
                EditText cvvText = (EditText) findViewById(R.id.cvvText);
                Card card = new Card(nameText.getText().toString(), numberText.getText().toString(),
                        cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString());
                textField.setText("");
                ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card);
                exampleAsyncTask.execute();
            }
        });
    }
}

package com.kushkipagos.android.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.kushkipagos.android.Card;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.sendButton);

        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText nameText = (EditText) findViewById(R.id.nameText);
                EditText numberText = (EditText) findViewById(R.id.numberText);
                EditText monthText = (EditText) findViewById(R.id.monthText);
                EditText yearText = (EditText) findViewById(R.id.yearText);
                EditText cvvText = (EditText) findViewById(R.id.cvvText);
                Card card = new Card(nameText.getText().toString(), numberText.getText().toString(),
                        cvvText.getText().toString(), monthText.getText().toString(), yearText.getText().toString());
                ExampleAsyncTask exampleAsyncTask = new ExampleAsyncTask(getApplicationContext(), card);
                exampleAsyncTask.execute();
            }
        });
    }
}

Remove references to deleted field


package br.com.bloder.blormlib.validation.validations;

import android.widget.CheckBox;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

public class Checked extends Validation {

    private CheckBox checkBox;

    @Override
    public Validate validate() {
        return new Validate() {
            @Override
            public boolean validate() {
               checkBox = (CheckBox) field;
               return checkBox.isChecked();
            }

            @Override
            public void onError() {
                checkBox.setError("This field can't be unchecked");
            }

            @Override public void onSuccess() {}
        };
    }
}

package br.com.bloder.blormlib.validation.validations;

import android.widget.CheckBox;

import br.com.bloder.blormlib.validation.Validate;
import br.com.bloder.blormlib.validation.Validation;

public class Checked extends Validation {

    private CheckBox checkBox;

    @Override
    public Validate validate() {
        return new Validate() {
            @Override
            public boolean validate() {
               checkBox = (CheckBox) field;
               return checkBox.isChecked();
            }

            @Override
            public void onError() {
                checkBox.setError("This field can't be unchecked");
            }

            @Override public void onSuccess() {
                checkBox.setError(null);
            }
        };
    }
}

Implement on success checked validation


package pylos.view;

import pylos.Pylos;
import pylos.model.Ball;

import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Sphere;

public class BallGraphics {
	Ball model;
	public final static float DIAMETER = 1.38f;
	public float x, y, z;
	Geometry geometry;

	public BallGraphics(Ball model) {
		this.model = model;
	}

	public void setPosition(float x, float y, float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public void move() {
		geometry.move(x, y, z);
	}

	public void create() {
		Sphere s = new Sphere(50, 50, DIAMETER / 2);
		geometry = new Geometry("Ball #" + model.i + " (" + model.owner.side + ")", s);
		Material mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Misc/SolidColor.j3md");
		mat.setColor("Color", ColorRGBA.randomColor());
		geometry.setMaterial(mat);
	}
}

package pylos.view;

import pylos.Pylos;
import pylos.model.Ball;
import pylos.model.Model;

import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Sphere;

public class BallGraphics {
	Ball model;
	public final static float DIAMETER = 1.38f;
	public float x, y, z;
	Geometry geometry;

	public BallGraphics(Ball model) {
		this.model = model;
	}

	public void setPosition(float x, float y, float z) {
		this.x = x;
		this.y = y;
		this.z = z;
	}

	public void move() {
		geometry.move(x, y, z);
	}

	public void create() {
		Material mat;
		Sphere s = new Sphere(50, 50, DIAMETER / 2);
		geometry = new Geometry("Ball #" + model.i + " (" + model.owner.side + ")", s);
		if (model.owner == Model.player1) {
			mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
		} else {
			mat = new Material(Pylos.view.getAssetManager(), "Common/MatDefs/Light/Lighting.j3md");
			mat.setFloat("Shininess", 0.5f);
		}
		geometry.setMaterial(mat);
	}
}

Set new material for balls


/*
 * Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
 * Copyright (C) 2012  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.mscontrol.commons;

/**
 * This class is the entry point where a MediaSession can be obtained
 *
 */
public interface MediaSessionFactory {

	/**
	 * Creates a new mediaSession object
	 *
	 * @return New media session for a platform
	 * @throws MediaSessionException
	 */
	public MediaSession createMediaSession()
			throws MediaSessionException;

}

/*
 * Kurento Commons MSControl: Simplified Media Control API for the Java Platform based on jsr309
 * Copyright (C) 2012  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.mscontrol.commons;

import com.kurento.commons.config.Parameters;

/**
 * This class is the entry point where a MediaSession can be obtained
 *
 */
public interface MediaSessionFactory {

	/**
	 * Creates a new mediaSession object using the given configuration
	 * parameters. See platform documentation for further details about the
	 * parameters.
	 *
	 * @param parameters
	 *            The configuration of the MediaSession
	 * @return New media session for a platform
	 * @throws MediaSessionException
	 */
	public MediaSession createMediaSession(Parameters parameters)
			throws MediaSessionException;

}

Add paratemers to mediaSession factory method


package com.faforever.api.data.listeners;

import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Game;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.persistence.PostLoad;

@Component
public class GameEnricher {

  private static FafApiProperties fafApiProperties;

  @Inject
  public void init(FafApiProperties fafApiProperties) {
    GameEnricher.fafApiProperties = fafApiProperties;
  }

  @PostLoad
  public void enrich(Game game) {
    game.setReplayUrl(String.format(fafApiProperties.getReplay().getDownloadUrlFormat(), game.getId()));
    game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
  }
}

package com.faforever.api.data.listeners;

import com.faforever.api.data.domain.Game;
import com.faforever.api.game.GameService;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import javax.persistence.PostLoad;

@Component
public class GameEnricher {

  private static GameService gameService;

  @Inject
  public void init(GameService gameService) {
    GameEnricher.gameService = gameService;
  }

  @PostLoad
  public void enrich(Game game) {
    game.setReplayUrl(gameService.getReplayDownloadUrl(game.getId()));
    game.setName(StringEscapeUtils.unescapeHtml4(game.getName()));
  }
}

Fix broken replay url in game entity


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

/**
 * Some integers returns the same instance if you apply autoboxing, you can check it with this
 * code and the related test.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrick {

}

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

/**
 * Some integers returns the same instance if you apply autoboxing, you can check it with this
 * code and the related test.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class AutoBoxingTrick {

  public boolean compare(Integer n1, Integer n2) {
    return n1 == n2;
  }
}

Add solution to problem 78


package com.growthpush.cocos2dx;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import com.growthpush.bridge.ExternalFrameworkBridge;

public class Cocos2dxBridge extends ExternalFrameworkBridge {

	@Override
	protected void callbackExternalFramework(final String customFiled) {
		Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
			@Override
			public void run() {
				didOpenRemoteNotification(customFiled);
			}
		});
	}

	/*
	 * Remote notification callback method (JNI interface)
	 *
	 * @param json json string
	 */
	static native void didOpenRemoteNotification(String json);

}

package com.growthpush.cocos2dx;

import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import android.os.Handler;

import com.growthpush.GrowthPush;
import com.growthpush.bridge.ExternalFrameworkBridge;

public class Cocos2dxBridge extends ExternalFrameworkBridge {

	@Override
	protected void callbackExternalFramework(final String customFiled) {

		if (GrowthPush.getInstance().getApplicationId() == 0) {
			new Handler().post(new Runnable() {
				@Override
				public void run() {
					callbackExternalFramework(customFiled);
				}
			});
			return;
		}

		Cocos2dxGLSurfaceView.getInstance().queueEvent(new Runnable() {
			@Override
			public void run() {
				didOpenRemoteNotification(customFiled);
			}
		});

	}

	/*
	 * Remote notification callback method (JNI interface)
	 *
	 * @param json json string
	 */
	static native void didOpenRemoteNotification(String json);

}

Send callback custom field after Growth Push initialized instance


/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.terminologyregistry.core.request;

/**
 * @since 4.7
 */
public class CodeSystemRequests {

	private final String repositoryId;

	public CodeSystemRequests(final String repositoryId) {
		this.repositoryId = checkNotNull(repositoryId, "repositoryId");
	}

	public CodeSystemCreateRequestBuilder prepareNewCodeSystem() {
		return new CodeSystemCreateRequestBuilder(repositoryId);
	}

	public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) {
		return new CodeSystemUpdateRequestBuilder(uniqueId);
	}

	public static CodeSystemGetRequestBuilder prepareGetCodeSystem() {
		return new CodeSystemGetRequestBuilder();
	}

	public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() {
		return new CodeSystemSearchRequestBuilder();
	}

	public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() {
		return new CodeSystemVersionSearchRequestBuilder();
	}

	public String getRepositoryId() {
		return repositoryId;
	}
}

/*
 * Copyright 2011-2016 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.terminologyregistry.core.request;

/**
 * @since 4.7
 */
public class CodeSystemRequests {

	private CodeSystemRequests() {}

	public static CodeSystemCreateRequestBuilder prepareNewCodeSystem() {
		return new CodeSystemCreateRequestBuilder();
	}

	public static CodeSystemUpdateRequestBuilder prepareUpdateCodeSystem(final String uniqueId) {
		return new CodeSystemUpdateRequestBuilder(uniqueId);
	}

	public static CodeSystemGetRequestBuilder prepareGetCodeSystem() {
		return new CodeSystemGetRequestBuilder();
	}

	public static CodeSystemSearchRequestBuilder prepareSearchCodeSystem() {
		return new CodeSystemSearchRequestBuilder();
	}

	public static CodeSystemVersionSearchRequestBuilder prepareSearchCodeSystemVersion() {
		return new CodeSystemVersionSearchRequestBuilder();
	}
}

Make all methods in CodeSytemRequests static


package com.github.athi.athifx.gui.menu.item;

import com.github.athi.athifx.gui.font_awesome.FontAwesome;
import com.github.athi.athifx.gui.menu.group.Group;

/**
 * Created by Athi
 */
public interface Item<GROUP extends Enum<?> & Group> {

    long id();

    String caption();

    FontAwesome icon();

    /**
     * @return - returns the menu group in witch the item will be set - can be null
     * If the group is null it means that the view wont be added to the menu.
     */
    GROUP group();

    default String itemId() {
        return id() + "_" + caption();
    }
}

package com.github.athi.athifx.gui.menu.item;

import com.github.athi.athifx.gui.font_awesome.FontAwesome;
import com.github.athi.athifx.gui.menu.group.Group;

/**
 * Created by Athi
 */
public interface Item<GROUP extends Enum<?> & Group> {

    long id();

    String caption();

    FontAwesome icon();

    /**
     * @return - returns the menu group in witch the item will be set - can be null
     * If the group is null it means that the view wont be added to the menu.
     */
    GROUP group();

    default String itemId() {
        return String.valueOf(id() + "_" + caption()).replaceAll(" ", "");
    }
}

Support for itemId with spaces.


package language;

import java.util.EnumSet;

/**
 * {@code Difficulty} is an enumeration of properties which define how objects
 * of {@link Word} are formatted and also provides for "difficulty" properties
 * for use in a word game.
 *
 * <p> The properties defined in this class are designed to be
 * implementation-dependant and have no values stored to them other than their
 * names.
 *
 * @author Oliver Abdulrahim
 */
public enum Difficulty {

// Difficulty properties

    /**
     * Defines a {@code Word} with easy difficulty.
     */
    EASY,

    /**
     * Defines a {@code Word} with medium difficulty.
     */
    MEDIUM,

    /**
     * Defines a {@code Word} with hard difficulty.
     */
    HARD,

    /**
     * Defines a {@code Word} with default difficultly.
     */
    DEFAULT;

    /**
     * Provides for a set of all properties enumerated in this class.
     */
    public static final EnumSet<Difficulty> ALL = // Pryda 10 VOL III is out
            EnumSet.allOf(Difficulty.class);

}

package language;

import java.util.EnumSet;
import java.util.Set;

/**
 * {@code Difficulty} is an enumeration of properties which define how objects
 * of {@link Word} are formatted and also provides for "difficulty" properties
 * for use in a word game.
 *
 * <p> The properties defined in this class are designed to be
 * implementation-dependant and have no values stored to them other than their
 * names.
 *
 * @author Oliver Abdulrahim
 */
public enum Difficulty {

    /**
     * Defines a {@code Word} with easy difficulty.
     */
    EASY,

    /**
     * Defines a {@code Word} with medium difficulty.
     */
    MEDIUM,

    /**
     * Defines a {@code Word} with hard difficulty.
     */
    HARD,

    /**
     * Defines a {@code Word} with default difficultly.
     */
    DEFAULT;

    /**
     * Provides for a set of all properties enumerated in this class.
     */
    public static final Set<Difficulty> ALL = // Pryda 10 VOL III is out
            EnumSet.allOf(Difficulty.class);

}

Change EnumSet to Set for better polymorphism.


package me.rkfg.xmpp.bot.plugins.game.event;

import me.rkfg.xmpp.bot.plugins.game.IGameObject;
import me.rkfg.xmpp.bot.plugins.game.effect.IAttachDetachEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType;
import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute;

public class SetSleepEvent extends AbstractEvent {

    public static final String TYPE = "setsleep";

    public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype");

    public SetSleepEvent(SleepType type, IGameObject source) {
        super(TYPE, source);
        setAttribute(SLEEP_ATTR, type);
        setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized());
    }

    @Override
    public void apply() {
        getAttribute(SLEEP_ATTR).ifPresent(st -> {
            ((IAttachDetachEffect) target).attachEffect(new SleepEffect(st, source));
            super.apply();
        });
    }

}

package me.rkfg.xmpp.bot.plugins.game.event;

import me.rkfg.xmpp.bot.plugins.game.IGameObject;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect;
import me.rkfg.xmpp.bot.plugins.game.effect.SleepEffect.SleepType;
import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute;

public class SetSleepEvent extends AbstractEvent {

    public static final String TYPE = "setsleep";

    public static final TypedAttribute<SleepType> SLEEP_ATTR = TypedAttribute.of("sleeptype");

    public SetSleepEvent(SleepType type, IGameObject source) {
        super(TYPE, source);
        setAttribute(SLEEP_ATTR, type);
        setAttribute(COMMENT, "Персонаж выбирает стратегию сна: " + type.getLocalized());
    }

    @Override
    public void apply() {
        getAttribute(SLEEP_ATTR).ifPresent(st -> {
            target.enqueueAttachEffect(new SleepEffect(st, source));
            super.apply();
        });
    }

}

Add sleep effect via event


package ru.spbau.bluecharm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallsNotifier extends BroadcastReceiver {
	public static final String TAG = "CALLS_NOTIFIER";

	@Override
	public void onReceive(Context context, Intent intent) {
		IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
		if (binder != null) {
			Messenger messenger = new Messenger(binder);
			Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
			Bundle bundle = new Bundle();
			bundle.putString(null, intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
			msg.setData(bundle);
			try {
				messenger.send(msg);
			} catch (RemoteException e) {
				Log.e(TAG, e.getLocalizedMessage());
			}
		} else {
			Log.d(TAG, "BlueCharmService isn't running");
		}
	}
}

package ru.spbau.bluecharm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;

public class CallsNotifier extends BroadcastReceiver {
	public static final String TAG = "CALLS_NOTIFIER";

	@Override
	public void onReceive(Context context, Intent intent) {
		IBinder binder = peekService(context, new Intent(context, BlueCharmService.class));
		if (binder != null) {
			Log.d(TAG, "Intent received: " + intent.getStringExtra(TelephonyManager.EXTRA_STATE));
			if (intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
				Messenger messenger = new Messenger(binder);
				Message msg = Message.obtain(null, BlueCharmService.MSG_NOTIFY_LISTENERS, 0, 0);
				Bundle bundle = new Bundle();
				bundle.putString(null, "Call: " + intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER));
				msg.setData(bundle);
				try {
					messenger.send(msg);
				} catch (RemoteException e) {
					Log.e(TAG, e.getLocalizedMessage());
				}
			}
		} else {
			Log.d(TAG, "BlueCharmService isn't running");
		}
	}
}

Call prefix in a notification


package com.creatubbles.api.repository;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.creatubbles.api.model.AuthToken;
import com.creatubbles.api.response.ResponseCallback;

/**
 * @author Matthew Platek on 11.02.2016.
 */
public interface OAuthRepository {

    void authorize(ResponseCallback<AuthToken> callback);

    void authorize(String login, String password, ResponseCallback<AuthToken> callback);

    void setClientId(String clientId);

    void setClientSecret(String clientSecret);

    /**
     * Method used to retrieve an access token for one of current user's managed creators without their password.
     *
     * @param currentToken current user's access token
     * @param targetUserId the user for which to obtain an access token
     * @param groupId      (optional) limits further user switching to the given group
     */
    void switchUser(@NonNull AuthToken currentToken, @NonNull String targetUserId, @Nullable String groupId, ResponseCallback<AuthToken> callback);
}

package com.creatubbles.api.repository;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.creatubbles.api.model.AuthToken;
import com.creatubbles.api.response.ResponseCallback;

/**
 * @author Matthew Platek on 11.02.2016.
 */
public interface OAuthRepository {

    /**
     * Method used to obtain Application only access token.
     * This token will give you access to publicly available information and actions.
     * Use this type of access token if you want to retrieve content independent from any users.
     */
    void authorize(ResponseCallback<AuthToken> callback);

    /**
     * Method used to obtain User access token. User access tokens extend your access rights to allow your
     * application to also access content and actions which have restricted visibility and are available
     * for the user the access token was issued for. The user access token basically allows you to retrieve
     * content and execute actions on behalf of the user the token was issued for.
     */
    void authorize(String login, String password, ResponseCallback<AuthToken> callback);

    void setClientId(String clientId);

    void setClientSecret(String clientSecret);

    /**
     * Method used to retrieve an access token for one of current user's managed creators without their password.
     *
     * @param currentToken current user's access token
     * @param targetUserId the user for which to obtain an access token
     * @param groupId      (optional) limits further user switching to the given group
     */
    void switchUser(@NonNull AuthToken currentToken, @NonNull String targetUserId, @Nullable String groupId, ResponseCallback<AuthToken> callback);
}

Add JavaDoc to authorization methods


package com.cloudant.sync.query;

/**
 * Created by tomblench on 28/09/2016.
 */

public class FieldSort {

    public final String field;
    public final Direction sort;

    public FieldSort(String field) {
        this.field = field;
        this.sort = Direction.ASCENDING;
    }

    public FieldSort(String field, Direction sort) {
        this.field = field;
        this.sort = sort;
    }

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

        FieldSort fieldSort = (FieldSort) o;

        if (!field.equals(fieldSort.field)) {
            return false;
        }
        return sort == fieldSort.sort;

    }

    @Override
    public int hashCode() {
        int result = field.hashCode();
        result = 31 * result + sort.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "FieldSort{" +
                "field='" + field + '\'' +
                ", sort=" + sort +
                '}';
    }

    public enum Direction {
        ASCENDING,
        DESCENDING
    };

}

/*
 * Copyright (C) 2016 IBM Corp. All rights reserved.
 *
 * 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.cloudant.sync.query;

/**
 * Created by tomblench on 28/09/2016.
 */

public class FieldSort {

    public final String field;
    public final Direction sort;

    public FieldSort(String field) {
        this(field, Direction.ASCENDING);
    }

    public FieldSort(String field, Direction sort) {
        this.field = field;
        this.sort = sort;
    }

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

        FieldSort fieldSort = (FieldSort) o;

        if (!field.equals(fieldSort.field)) {
            return false;
        }
        return sort == fieldSort.sort;

    }

    @Override
    public int hashCode() {
        int result = field.hashCode();
        result = 31 * result + sort.hashCode();
        return result;
    }

    @Override
    public String toString() {
        return "FieldSort{" +
                "field='" + field + '\'' +
                ", sort=" + sort +
                '}';
    }

    public enum Direction {
        ASCENDING,
        DESCENDING
    };

}

Implement feedback from rhys' comments


package org.synyx.urlaubsverwaltung.person.basedata;

import org.springframework.data.jpa.repository.JpaRepository;

interface PersonBasedataRepository extends JpaRepository<PersonBasedataEntity, Integer> {
}

package org.synyx.urlaubsverwaltung.person.basedata;

import org.springframework.data.repository.CrudRepository;

interface PersonBasedataRepository extends CrudRepository<PersonBasedataEntity, Integer> {
}

Replace with crud repository interface


package protocolsupport.protocol.utils.spoofedata;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;

public class SpoofedDataParser {

	private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();

	static {
		if (isPaperHandshakeEvent()) {
			parsers.add(new PaperSpoofedDataParser());
		}
		parsers.add(new BungeeCordSpoofedDataParser());
	}

	public static SpoofedData tryParse(String data) {
		for (Function<String, SpoofedData> parser : parsers) {
			try {
				SpoofedData result = parser.apply(data);
				if (result != null) {
					return result;
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	private static boolean isPaperHandshakeEvent() {
		try {
			Class.forName(PlayerHandshakeEvent.class.getName());
			return true;
		} catch (ClassNotFoundException e) {
			return false;
		}
	}

}

package protocolsupport.protocol.utils.spoofedata;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import com.destroystokyo.paper.event.player.PlayerHandshakeEvent;

public class SpoofedDataParser {

	private static final List<Function<String, SpoofedData>> parsers = new ArrayList<>();

	static {
		if (isPaperHandshakeEvent()) {
			parsers.add(new PaperSpoofedDataParser());
		}
		parsers.add(new BungeeCordSpoofedDataParser());
	}

	public static SpoofedData tryParse(String data) {
		for (Function<String, SpoofedData> parser : parsers) {
			try {
				SpoofedData result = parser.apply(data);
				if (result != null) {
					return result;
				}
			} catch (Exception e) {
			}
		}
		return null;
	}

	private static boolean isPaperHandshakeEvent() {
		try {
			Class.forName(PlayerHandshakeEvent.class.getName());
			return true;
		} catch (Throwable e) {
			return false;
		}
	}

}

Fix spoofed data parser init


package org.springframework.roo.addon.web.flow;

import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;
import org.springframework.roo.support.lifecycle.ScopeDevelopmentShell;
import org.springframework.roo.support.util.Assert;

/**
 * Commands for the 'install web flow' add-on to be used by the ROO shell.
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
@ScopeDevelopmentShell
public class WebFlowCommands implements CommandMarker {

	private WebFlowOperations webFlowOperations;

	public WebFlowCommands(WebFlowOperations webFlowOperations) {
		Assert.notNull(webFlowOperations, "Jms operations required");
		this.webFlowOperations = webFlowOperations;
	}

	/**
	 * @return true if the "install web flow" command is available at this moment
	 */
	@CliAvailabilityIndicator("install web flow")
	public boolean isInstallWebFlowAvailable() {
		return webFlowOperations.isInstallWebFlowAvailable();
	}

	@CliCommand(value="install web flow", help="Install Spring Web Flow configuration artifacts into your project")
	public void installWebFlow(
			@CliOption(key={"flowName"}, mandatory=false, help="The name your web flow") String flowName) {
		webFlowOperations.installWebFlow(flowName);
	}
}

package org.springframework.roo.addon.web.flow;

import org.springframework.roo.shell.CliAvailabilityIndicator;
import org.springframework.roo.shell.CliCommand;
import org.springframework.roo.shell.CliOption;
import org.springframework.roo.shell.CommandMarker;
import org.springframework.roo.support.lifecycle.ScopeDevelopmentShell;
import org.springframework.roo.support.util.Assert;

/**
 * Commands for the 'install web flow' add-on to be used by the ROO shell.
 *
 * @author Stefan Schmidt
 * @since 1.0
 *
 */
@ScopeDevelopmentShell
public class WebFlowCommands implements CommandMarker {

	private WebFlowOperations webFlowOperations;

	public WebFlowCommands(WebFlowOperations webFlowOperations) {
		Assert.notNull(webFlowOperations, "Jms operations required");
		this.webFlowOperations = webFlowOperations;
	}

	/**
	 * @return true if the "install web flow" command is available at this moment
	 */
	@CliAvailabilityIndicator("install web flow")
	public boolean isInstallWebFlowAvailable() {
		return webFlowOperations.isInstallWebFlowAvailable();
	}

	@CliCommand(value="install web flow", help="Install Spring Web Flow configuration artifacts into your project")
	public void installWebFlow(
			@CliOption(key={"flowName"}, mandatory=false, help="The name for your web flow") String flowName) {
		webFlowOperations.installWebFlow(flowName);
	}
}

Create Spring Web Flow add-on


package fi.metacity.klmobi;

import com.googlecode.androidannotations.annotations.EApplication;

import android.app.Application;

@EApplication
public class MHApp extends Application {

	private String mToken = "";
	private Address mStartAddress;
	private Address mEndAddress;

	public String getToken() {
		return mToken;
	}

	public void setToken(String token) {
		mToken = token;
	}

	public Address getStartAddress() {
		return mStartAddress;
	}

	public void setStartAddress(Address address) {
		mStartAddress = address;
	}

	public Address getEndAddress() {
		return mEndAddress;
	}

	public void setEndAddress(Address address) {
		mEndAddress = address;
	}
}

package fi.metacity.klmobi;

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

import android.app.Application;

import com.googlecode.androidannotations.annotations.EApplication;

@EApplication
public class MHApp extends Application {

	private String mToken = "";
	private Address mStartAddress;
	private Address mEndAddress;

	private List<Route> mRoutes = new ArrayList<Route>();
	private String mDetailsXmlRequest = "";

	public String getToken() {
		return mToken;
	}

	public void setToken(String token) {
		mToken = token;
	}

	public Address getStartAddress() {
		return mStartAddress;
	}

	public void setStartAddress(Address address) {
		mStartAddress = address;
	}

	public Address getEndAddress() {
		return mEndAddress;
	}

	public void setEndAddress(Address address) {
		mEndAddress = address;
	}

	public List<Route> getRoutes() {
		return mRoutes;
	}

	public String getDetailsXmlRequest() {
		return mDetailsXmlRequest;
	}

	public void setDetailsXmlString(String xmlRequest) {
		mDetailsXmlRequest = xmlRequest;
	}
}

Add route list and xmlResponse


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

package org.jboss.jdeparser;

import static org.jboss.jdeparser.Tokens.*;

import java.io.IOException;

/**
 * @author David M. Lloyd
 */
class KeywordExprJStatement extends KeywordJStatement {

    private final JExpr expr;

    KeywordExprJStatement(final $KW keyword, final JExpr expr) {
        super(keyword);
        this.expr = expr;
    }

    JExpr getExpression() {
        return expr;
    }

    public void write(final SourceFileWriter writer) throws IOException {
        writeComments(writer);
        writer.write(getKeyword());
        writer.write(expr);
        writer.write($PUNCT.SEMI);
    }
}

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

package org.jboss.jdeparser;

import static org.jboss.jdeparser.Tokens.*;

import java.io.IOException;

/**
 * @author David M. Lloyd
 */
class KeywordExprJStatement extends KeywordJStatement {

    private final JExpr expr;

    KeywordExprJStatement(final $KW keyword, final JExpr expr) {
        super(keyword);
        this.expr = expr;
    }

    JExpr getExpression() {
        return expr;
    }

    public void write(final SourceFileWriter writer) throws IOException {
        writeComments(writer);
        writer.write(getKeyword());
        writer.sp();
        writer.write(expr);
        writer.write($PUNCT.SEMI);
    }
}

Include a space after a return if an expression is used.


package DependencyRandomNumber;

import java.util.Random;

import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.StreamsConfigurator;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;

public class RandomNumberSource extends SourceFlowlet {

  private Random random;

  @Override
  public void configure(StreamsConfigurator configurator) {
    TupleSchema out = new TupleSchemaBuilder().
        add("randomNumber", Long.class).
        create();
    configurator.getDefaultTupleOutputStream().setSchema(out);
  }

  @Override
  public void initialize() {
    super.initialize();
    this.random = new Random();
  }

  @Override
  public void generate(OutputCollector outputCollector) {
    long randomNumber = Math.abs(this.random.nextLong());
    Tuple randomNumberTuple = new TupleBuilder()
        .set("randomNumber", randomNumber)
        .create();
    outputCollector.add(randomNumberTuple);
  }
}

package DependencyRandomNumber;

import java.util.Random;

import com.continuuity.api.flow.flowlet.FlowletSpecifier;
import com.continuuity.api.flow.flowlet.SourceFlowlet;
import com.continuuity.api.flow.flowlet.OutputCollector;
import com.continuuity.api.flow.flowlet.Tuple;
import com.continuuity.api.flow.flowlet.TupleSchema;
import com.continuuity.api.flow.flowlet.builders.TupleBuilder;
import com.continuuity.api.flow.flowlet.builders.TupleSchemaBuilder;

public class RandomNumberSource extends SourceFlowlet {

  private Random random;

  @Override
  public void configure(FlowletSpecifier specifier) {
    TupleSchema out = new TupleSchemaBuilder().
        add("randomNumber", Long.class).
        create();
    specifier.getDefaultFlowletOutput().setSchema(out);
  }

  @Override
  public void initialize() {
    super.initialize();
    this.random = new Random();
  }

  @Override
  public void generate(OutputCollector outputCollector) {
    long randomNumber = Math.abs(this.random.nextLong());
    Tuple randomNumberTuple = new TupleBuilder()
        .set("randomNumber", randomNumber)
        .create();
    outputCollector.add(randomNumberTuple);
  }
}

Fix call to old flowlet API in example


package me.echeung.cdflabs.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import me.echeung.cdflabs.R;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;

    public DividerItemDecoration(Context context) {
        this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft();
        final int right = parent.getWidth() - parent.getPaddingRight();

        // Avoid last item and footer
        final int childCount = parent.getChildCount() - 2;
        if (childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
}

package me.echeung.cdflabs.utils;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import me.echeung.cdflabs.R;

public class DividerItemDecoration extends RecyclerView.ItemDecoration {
    private Drawable mDivider;
    private int mPaddingLeft;

    public DividerItemDecoration(Context context) {
        this.mDivider = ContextCompat.getDrawable(context, R.drawable.line_divider);

        this.mPaddingLeft = 2 * (int) context.getResources().getDimension(R.dimen.regular_margin)
            + (int) context.getResources().getDimension(R.dimen.free_size);
    }

    @Override
    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        final int left = parent.getPaddingLeft() + this.mPaddingLeft;
        final int right = parent.getWidth() - parent.getPaddingRight();

        // Avoid last item and footer
        final int childCount = parent.getChildCount() - 2;
        if (childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);

                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();

                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }
    }
}

Add left padding to item decoration


/*
 * Title: COP3404Project3Code
 * Author: Matthew Boyette
 * Date: 3/27/2015
 *
 * This program serves as the entry-point for Projects 3 & 4.
 * See SICXE_AssemblerProgram.java for the implementation.
 */

import api.util.sicxe.SICXE_AssemblerProgram;
import api.util.stdlib.StdOut;

public class COP3404Project3Code
{
	public static final void main(final String[] args)
	{
		SICXE_AssemblerProgram[] programs = new SICXE_AssemblerProgram[args.length];

		// Read in files as command-line arguments.
		if (args.length > 0)
		{
			for (int i = 0; i < args.length; i++)
			{
				programs[i] = new SICXE_AssemblerProgram(args[i]);
			}
		}
		else
		{
			StdOut.print("Usage:\n\n\tCOP3404Project3Code [File1] [File2] [File#] ...\n\n" +
				"Example:\n\n\tCOP3404Project3Code input test.txt source.asm\n\n");
		}
	}
}

/*
 * Title: COP3404Project3Code
 * Author: Matthew Boyette
 * Date: 3/27/2015
 *
 * This program serves as the entry-point for Projects 3 & 4.
 * See SICXE_AssemblerProgram.java for the implementation.
 */

import api.util.sicxe.SICXE_AssemblerProgram;
import api.util.stdlib.StdIn;
import api.util.stdlib.StdOut;

public class COP3404Project3Code
{
	public static final void main(final String[] args)
	{
		SICXE_AssemblerProgram[] programs = new SICXE_AssemblerProgram[Math.max(1, args.length)];

		// Read in file names given as command-line arguments.
		if (args.length > 0)
		{
			for (int i = 0; i < args.length; i++)
			{
				programs[i] = new SICXE_AssemblerProgram(args[i]);
			}
		}
		// Prompt the user for a file name if not given one.
		else
		{
			StdOut.print("Enter source file name: ");
			String fileName = StdIn.readString();

			if (fileName != null)
			{
				if (!fileName.isEmpty())
				{
					programs[0] = new SICXE_AssemblerProgram(fileName);
				}
			}
		}
	}
}

Allow Program To Prompt For File If Not Given One


package ubic.gemma.web.services.rest.util;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.io.IOException;

public class RestAuthEntryPoint extends BasicAuthenticationEntryPoint {

    private static final String MESSAGE_401 = "Provided authentication credentials are invalid.";

    @Override
    public void commence( final HttpServletRequest request, final HttpServletResponse response,
            final AuthenticationException authException ) {

        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
        response.addHeader( "WWW-Authenticate", "Basic realm=" + getRealmName() + "" );
        response.setContentType( "application/json" );

        WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.UNAUTHORIZED, MESSAGE_401 );
        ResponseErrorObject errorObject = new ResponseErrorObject(errorBody);
        ObjectMapper mapperObj = new ObjectMapper();

        try {
            String jsonStr = mapperObj.writeValueAsString( errorObject );
            response.getWriter().println( jsonStr );
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterPropertiesSet() {
        setRealmName("Gemma rest api");
    }
}

package ubic.gemma.web.services.rest.util;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;
import java.io.IOException;

public class RestAuthEntryPoint extends BasicAuthenticationEntryPoint {

    private static final String MESSAGE_401 = "Provided authentication credentials are invalid.";

    @Override
    public void afterPropertiesSet() {
        setRealmName( "Gemma rest api" );
    }

    @Override
    public void commence( final HttpServletRequest request, final HttpServletResponse response,
            final AuthenticationException authException ) {

        response.setStatus( HttpServletResponse.SC_UNAUTHORIZED );
        // using 'xBasic' instead of 'basic' to prevent default browser login popup
        response.addHeader( "WWW-Authenticate", "xBasic realm=" + getRealmName() + "" );
        response.setContentType( "application/json" );

        WellComposedErrorBody errorBody = new WellComposedErrorBody( Response.Status.UNAUTHORIZED, MESSAGE_401 );
        ResponseErrorObject errorObject = new ResponseErrorObject( errorBody );
        ObjectMapper mapperObj = new ObjectMapper();

        try {
            String jsonStr = mapperObj.writeValueAsString( errorObject );
            response.getWriter().println( jsonStr );
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}

Change authentication header of restapi service to prevent login popups


package cl.fatman.capital.fund;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class ControllerFailTest {

	private Controller control;
	private PersistenceData persistence;

	@Before
	public void setUp() {
		control = Controller.getInstance();
		control.setUp();
		persistence = PersistenceData.getInstance();
	}

	@After
	public void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataFailTest() {
		control.storeFundData();
		control.storeFundData();
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertEquals("Fund rate list size shold be 0.", 0, fundRateList.size());
	}
}

package cl.fatman.capital.fund;

import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.time.LocalDate;
import java.util.List;

public class ControllerFailTest {

	private Controller control;
	private PersistenceData persistence;

	@Before
	public void setUp() {
		control = Controller.getInstance();
		control.setUp();
		persistence = PersistenceData.getInstance();
	}

	@After
	public void tearDown() {
		control.tearDown();
	}

	@Test
	public void storeFundDataFailTest() {
		control.storeFundData();
		control.storeFundData();
		List<?> fundRateList = persistence.selectAllObjects("from FundRate", FundRate.class);
		assertEquals("Fund rate list size shold be 0.", 0, fundRateList.size());
	}

	@Test
	public void storeFomentUnitDataFailTest() {
		LocalDate startDate = LocalDate.of(1910, 1, 1);
		LocalDate endDate = LocalDate.of(1912, 1, 1);
		control.storeFomentUnitData(startDate, endDate);
		List<?> ufList = persistence.selectAllObjects("from FomentUnit", FomentUnit.class);
		assertEquals("Foment unit list size shold be 0.", 0, ufList.size());
	}
}

Add junit test for foment unit retrieve fail.


package com.voodoodyne.postguice;

import org.hibernate.dialect.PostgreSQL95Dialect;

import java.sql.Types;

/**
 * Apparently hibernate's 9.5 dialect doesn't support jsonb. Weird.
 */
public class PostguicePostgreSQL96Dialect extends PostgreSQL95Dialect {
	public PostguicePostgreSQL96Dialect() {
		this.registerColumnType(Types.JAVA_OBJECT, "jsonb");
		this.registerFunction("fts", new SimpleFullTextSearchFunction());
	}
}

package com.voodoodyne.postguice;

import org.hibernate.dialect.PostgreSQL95Dialect;

import java.sql.Types;

/**
 * Apparently hibernate's 9.5 dialect doesn't support jsonb. Weird.
 */
public class PostguicePostgreSQL96Dialect extends PostgreSQL95Dialect {
	public PostguicePostgreSQL96Dialect() {
		this.registerColumnType(Types.JAVA_OBJECT, "jsonb");
	}
}

Remove the 'fts' function from registration in the dialect


package com.grayben.riskExtractor.headingMarker.nominator;

import java.util.List;

import com.grayben.riskExtractor.headingMarker.UnmodifiableText;

public class NominatedText
		extends UnmodifiableText
		implements NomineesRetrievable {

    private List<Integer> nominees;

    public NominatedText(List<String> stringList, List<Integer> nominees) {
        super(stringList);
        this.nominees = nominees;
    }

    public NominatedText(
            UnmodifiableText unmodifiableText,
            List<Integer> nominees){
        super(unmodifiableText);
        this.nominees = nominees;
    }

    public NominatedText(NominatedText nominatedText){
        this(nominatedText, nominatedText.getNominees());
    }

    @Override
    public List<Integer> getNominees() {
        return nominees;
    }
}

package com.grayben.riskExtractor.headingMarker.nominator;

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

import com.grayben.riskExtractor.headingMarker.UnmodifiableText;

public class NominatedText
		extends UnmodifiableText
		implements NomineesRetrievable {

    private List<Integer> nominees;

    public NominatedText(List<String> stringList, List<Integer> nominees) {
        super(stringList);
        if (nominees == null) {
            throw new NullPointerException("Attempted to pass null argument");
        }
        this.nominees = nominees;
    }

    public NominatedText(
            UnmodifiableText unmodifiableText,
            List<Integer> nominees){
        super(unmodifiableText);
        if (nominees == null) {
            throw new NullPointerException("Attempted to pass null argument");
        }
        this.nominees = nominees;
    }

    public NominatedText(NominatedText nominatedText){
        this(nominatedText, nominatedText.getNominees());
    }

    @Override
    public List<Integer> getNominees() {
        return Collections.unmodifiableList(this.nominees);
    }
}

Add argument checks to pass tests


package de.fesere.hypermedia.cj.model.transformer;

import de.fesere.hypermedia.cj.model.Item;
import org.junit.Test;

//For sake of consistency
public class TwoWayTransformerTest {
    private TwoWayTransformer t =  new DummyTransformer();

    @Test(expected = IllegalStateException.class)
    public void testConvertToItem() throws Exception {
        t.convert("foo");
    }

    @Test(expected = IllegalStateException.class)
    public void testConvertFromItem() throws Exception {
        t.convert(new Item());
    }

    private class DummyTransformer extends TwoWayTransformer<String> {

    }

}

package de.fesere.hypermedia.cj.model.transformer;

import de.fesere.hypermedia.cj.model.Item;
import org.junit.Test;

//For sake of consistency
public class TwoWayTransformerTest {
    private DummyTransformer t =  new DummyTransformer();

    @Test(expected = IllegalStateException.class)
    public void testConvertToItem() throws Exception {
        t.convert("foo");
    }

    @Test(expected = IllegalStateException.class)
    public void testConvertFromItem() throws Exception {
        t.convert(new Item());
    }

    private class DummyTransformer extends TwoWayTransformer<String> {
    }

}

Test just for sake of completeness....


package in.twizmwaz.cardinal.filter.type;

import in.twizmwaz.cardinal.filter.Filter;
import in.twizmwaz.cardinal.filter.FilterState;
import org.bukkit.Bukkit;

import java.util.logging.Level;

import static in.twizmwaz.cardinal.filter.FilterState.*;

public class ObjectiveFilter extends Filter {

    @Override
    public FilterState getState(final Object o) {
        Bukkit.getLogger().log(Level.INFO, "Objective Filters are not yet supported in CardinalPGM.");
        return ABSTAIN;
    }

}

package in.twizmwaz.cardinal.filter.type;

import in.twizmwaz.cardinal.filter.Filter;
import in.twizmwaz.cardinal.filter.FilterState;
import in.twizmwaz.cardinal.module.GameObjective;
import org.bukkit.Bukkit;

import java.util.logging.Level;

import static in.twizmwaz.cardinal.filter.FilterState.*;

public class ObjectiveFilter extends Filter {

    private final GameObjective objective;

    public ObjectiveFilter(final GameObjective objective) {
        this.objective = objective;
    }

    @Override
    public FilterState getState(final Object o) {
        if (objective.isComplete()) return ALLOW;
        else return DENY;
    }

}

Add support for Objective filters


/****************************************************************************
 * Copyright (C) 2019 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/
package org.openecard.mobile.activation.model;

import java.lang.management.ManagementFactory;

/**
 *
 * @author Neil Crossley
 */
public final class Timeout {

    public static final int MIN_WAIT_TIMEOUT = 1000;
    public static final int WAIT_TIMEOUT = isDebug() ? Integer.MAX_VALUE : MIN_WAIT_TIMEOUT;

    private Timeout() {

    }

    static boolean isDebug() {
	for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
	    if (arg.contains("jdwp=")) {
		return true;
	    }
	};
	return false;
    }

}

/****************************************************************************
 * Copyright (C) 2019 ecsec GmbH.
 * All rights reserved.
 * Contact: ecsec GmbH (info@ecsec.de)
 *
 * This file is part of the Open eCard App.
 *
 * GNU General Public License Usage
 * This file may be used under the terms of the GNU General Public
 * License version 3.0 as published by the Free Software Foundation
 * and appearing in the file LICENSE.GPL included in the packaging of
 * this file. Please review the following information to ensure the
 * GNU General Public License version 3.0 requirements will be met:
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Other Usage
 * Alternatively, this file may be used in accordance with the terms
 * and conditions contained in a signed written agreement between
 * you and ecsec GmbH.
 *
 ***************************************************************************/
package org.openecard.mobile.activation.model;

import java.lang.management.ManagementFactory;

/**
 *
 * @author Neil Crossley
 */
public final class Timeout {

    public static final int MIN_WAIT_TIMEOUT = 1500;
    public static final int WAIT_TIMEOUT = isDebug() ? Integer.MAX_VALUE : MIN_WAIT_TIMEOUT;

    private Timeout() {

    }

    static boolean isDebug() {
	for (String arg : ManagementFactory.getRuntimeMXBean().getInputArguments()) {
	    if (arg.contains("jdwp=")) {
		return true;
	    }
	};
	return false;
    }

}

Raise timetout because of race conditions.


package net.buycraft.plugin.execution.strategy;

import lombok.Value;
import net.buycraft.plugin.IBuycraftPlatform;
import net.buycraft.plugin.data.QueuedCommand;
import net.buycraft.plugin.data.QueuedPlayer;

import java.util.concurrent.TimeUnit;

@Value
public class ToRunQueuedCommand {
    private final QueuedPlayer player;
    private final QueuedCommand command;
    private final boolean requireOnline;
    private final long queueTime = System.currentTimeMillis();

    public boolean canExecute(IBuycraftPlatform platform) {
        Integer requiredSlots = command.getConditions().get("slots");

        if (requiredSlots != null || requireOnline) {
            if (!platform.isPlayerOnline(player)) {
                return false;
            }
        }

        if (requiredSlots != null) {
            int free = platform.getFreeSlots(player);
            if (free < requiredSlots) {
                return false;
            }
        }

        Integer delay = command.getConditions().get("delay");
        if (delay != null && delay > 0 && System.currentTimeMillis() - queueTime < TimeUnit.SECONDS.toMillis(delay)) {
            return false;
        }

        return true;
    }
}

package net.buycraft.plugin.execution.strategy;

import lombok.EqualsAndHashCode;
import lombok.Value;
import net.buycraft.plugin.IBuycraftPlatform;
import net.buycraft.plugin.data.QueuedCommand;
import net.buycraft.plugin.data.QueuedPlayer;

import java.util.concurrent.TimeUnit;

@Value
@EqualsAndHashCode(exclude = {"queueTime"})
public class ToRunQueuedCommand {
    private final QueuedPlayer player;
    private final QueuedCommand command;
    private final boolean requireOnline;
    private final long queueTime = System.currentTimeMillis();

    public boolean canExecute(IBuycraftPlatform platform) {
        Integer requiredSlots = command.getConditions().get("slots");

        if (requiredSlots != null || requireOnline) {
            if (!platform.isPlayerOnline(player)) {
                return false;
            }
        }

        if (requiredSlots != null) {
            int free = platform.getFreeSlots(player);
            if (free < requiredSlots) {
                return false;
            }
        }

        Integer delay = command.getConditions().get("delay");
        if (delay != null && delay > 0 && System.currentTimeMillis() - queueTime < TimeUnit.SECONDS.toMillis(delay)) {
            return false;
        }

        return true;
    }
}

Fix exclusions for command queuer


package com.linkedin.helix.monitoring.mbeans;

import com.linkedin.helix.alerts.AlertValueAndStatus;

public class ClusterAlertItem implements ClusterAlertItemMBean
{
  String _alertItemName;
  double  _alertValue;
  int _alertFired;
  AlertValueAndStatus _valueAndStatus;

  public ClusterAlertItem(String name, AlertValueAndStatus valueAndStatus)
  {
    _valueAndStatus = valueAndStatus;
    _alertItemName = name;
    refreshValues();
  }
  @Override
  public String getSensorName()
  {
    return _alertItemName;
  }

  @Override
  public double getAlertValue()
  {
    return _alertValue;
  }

  public void setValueMap(AlertValueAndStatus valueAndStatus)
  {
    _valueAndStatus = valueAndStatus;
    refreshValues();
  }

  void refreshValues()
  {
    _alertValue = Double.parseDouble(_valueAndStatus.getValue().getElements().get(0));
    _alertFired = _valueAndStatus.isFired() ?  1 : 0;
  }
  @Override
  public int getAlertFired()
  {
    return _alertFired;
  }
}

package com.linkedin.helix.monitoring.mbeans;

import com.linkedin.helix.alerts.AlertValueAndStatus;

public class ClusterAlertItem implements ClusterAlertItemMBean
{
  String _alertItemName;
  double  _alertValue;
  int _alertFired;
  AlertValueAndStatus _valueAndStatus;

  public ClusterAlertItem(String name, AlertValueAndStatus valueAndStatus)
  {
    _valueAndStatus = valueAndStatus;
    _alertItemName = name;
    refreshValues();
  }
  @Override
  public String getSensorName()
  {
    return _alertItemName;
  }

  @Override
  public double getAlertValue()
  {
    return _alertValue;
  }

  public void setValueMap(AlertValueAndStatus valueAndStatus)
  {
    _valueAndStatus = valueAndStatus;
    refreshValues();
  }

  void refreshValues()
  {
    if(_valueAndStatus.getValue().getElements().size() > 0)
    {
      _alertValue = Double.parseDouble(_valueAndStatus.getValue().getElements().get(0));
    }
    else
    {
      _alertValue = 0;
    }
    _alertFired = _valueAndStatus.isFired() ?  1 : 0;
  }
  @Override
  public int getAlertFired()
  {
    return _alertFired;
  }
}

Fix a exception in the case that an Alert first get exposed, an exception is thrown due to the size of the Alert value elements is empty.


/**
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */
package org.jivesoftware.openfire.clearspace;

import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.user.UserNotFoundException;

/**
 * @author Daniel Henninger
 */
public class ClearspaceAuthProvider implements AuthProvider {
    public boolean isPlainSupported() {
        return true;
    }

    public boolean isDigestSupported() {
        return true;
    }

    public void authenticate(String username, String password) throws UnauthorizedException {
        // Nothing
    }

    public void authenticate(String username, String token, String digest) throws UnauthorizedException {
        // Nothing
    }

    public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
        return (username.equals("admin") ? "test" : "asdasdasdasd");
    }

    public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
        // Nothing
    }

    public boolean supportsPasswordRetrieval() {
        return false;
    }
}

/**
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2006 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */
package org.jivesoftware.openfire.clearspace;

import org.jivesoftware.openfire.auth.AuthProvider;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import static org.jivesoftware.openfire.clearspace.ClearspaceManager.HttpType.GET;
import org.jivesoftware.openfire.user.UserNotFoundException;

/**
 * @author Daniel Henninger
 */
public class ClearspaceAuthProvider implements AuthProvider {
    protected static final String URL_PREFIX = "permissionService/";

    private ClearspaceManager manager;

    public ClearspaceAuthProvider() {
        // gets the manager
        manager = ClearspaceManager.getInstance();
    }

    public boolean isPlainSupported() {
        return true;
    }

    public boolean isDigestSupported() {
        return false;
    }

    public void authenticate(String username, String password) throws UnauthorizedException {
        try {
            String path = URL_PREFIX + "authenticate/" + username + "/" + password;
            manager.executeRequest(GET, path);
        } catch (UnauthorizedException ue) {
            throw ue;
        } catch (Exception e) {
            // It is not supported exception, wrap it into an UnsupportedOperationException
            throw new UnsupportedOperationException("Unexpected error", e);
        }
    }

    public void authenticate(String username, String token, String digest) throws UnauthorizedException {
        throw new UnsupportedOperationException("Digest not supported");
    }

    public String getPassword(String username) throws UserNotFoundException, UnsupportedOperationException {
        throw new UnsupportedOperationException("Password retrieval not supported");
    }

    public void setPassword(String username, String password) throws UserNotFoundException, UnsupportedOperationException {
        throw new UnsupportedOperationException("Change Password not supported");
    }

    public boolean supportsPasswordRetrieval() {
        return false;
    }
}

Create CSAuthProvider to integrate with Clearspace. JM-1224


package com.github.mttkay.memento;

import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;

import com.google.testing.compile.CompilationFailureException;
import com.google.testing.compile.JavaFileObjects;
import com.sun.tools.internal.xjc.util.NullStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.truth0.Truth;

import java.io.PrintStream;

@RunWith(JUnit4.class)
public class MementoProcessorTest {

    @Before
    public void dontPrintExceptions() {
        // get rid of the stack trace prints for expected exceptions
        System.setErr(new PrintStream(new NullStream()));
    }

    @Test
    public void generateMementoClass() {
        Truth.ASSERT.about(javaSource())
                .that(JavaFileObjects.forResource("RetainedActivity.java"))
                .processedWith(new MementoProcessor())
                .compilesWithoutError()
                .and().generatesSources(JavaFileObjects.forResource("RetainedActivity$Memento.java"));
    }

    @Test(expected = CompilationFailureException.class)
    public void throwsIllegalStateIfRetainedFieldIsPrivate() {
        Truth.ASSERT.about(javaSource())
                .that(JavaFileObjects.forResource("RetainedActivityWithPrivateFields.java"))
                .processedWith(new MementoProcessor())
                .failsToCompile();
    }
}

package com.github.mttkay.memento;

import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource;

import com.google.testing.compile.CompilationFailureException;
import com.google.testing.compile.JavaFileObjects;
import com.sun.tools.internal.xjc.util.NullStream;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.truth0.Truth;

import java.io.PrintStream;

@RunWith(JUnit4.class)
public class MementoProcessorTest {

    @Before
    public void dontPrintExceptions() {
        // get rid of the stack trace prints for expected exceptions
        System.setErr(new PrintStream(new NullStream()));
    }

    @Test
    public void itGeneratesMementoFragmentClass() {
        Truth.ASSERT.about(javaSource())
                .that(JavaFileObjects.forResource("RetainedActivity.java"))
                .processedWith(new MementoProcessor())
                .compilesWithoutError()
                .and().generatesSources(JavaFileObjects.forResource("RetainedActivity$Memento.java"));
    }

    @Test(expected = CompilationFailureException.class)
    public void itThrowsExceptionWhenRetainedFieldIsPrivate() {
        Truth.ASSERT.about(javaSource())
                .that(JavaFileObjects.forResource("RetainedActivityWithPrivateFields.java"))
                .processedWith(new MementoProcessor())
                .failsToCompile();
    }
}

Move to spec inspired test names (truth always wins.)


/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mpalourdio.springboottemplate;

import app.config.BeanConfig;
import app.config.PropertyPlaceholderConfig;
import app.config.WebSecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import java.util.Arrays;

@SpringBootApplication
@PropertySource(value = {
        "file:properties/global.properties",
        "file:properties/local.properties"
}, ignoreResourceNotFound = true)
@Import({
        WebSecurityConfig.class,
        BeanConfig.class,
        PropertyPlaceholderConfig.class
})
@EnableDiscoveryClient
public class SpringBootTemplateApplication {

    public static void main(final String[] args) {
        final ApplicationContext ctx = SpringApplication.run(SpringBootTemplateApplication.class, args);
        final String[] beanNames = ctx.getBeanDefinitionNames();

        Arrays.stream(beanNames)
                .sorted()
                .forEach(System.out::println);
    }
}

/*
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package com.mpalourdio.springboottemplate;

import app.config.BeanConfig;
import app.config.PropertyPlaceholderConfig;
import app.config.WebSecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import java.util.Arrays;

@SpringBootApplication
@PropertySource(value = {
        "file:properties/global.properties",
        "file:properties/local.properties"
}, ignoreResourceNotFound = true)
@Import({
        WebSecurityConfig.class,
        BeanConfig.class,
        PropertyPlaceholderConfig.class
})
@EnableDiscoveryClient
public class SpringBootTemplateApplication {

    public static void main(final String ...args) {
        final ApplicationContext ctx = SpringApplication.run(SpringBootTemplateApplication.class, args);
        final String[] beanNames = ctx.getBeanDefinitionNames();

        Arrays.stream(beanNames)
                .sorted()
                .forEach(System.out::println);
    }
}

Use variadic args in main method


package org.mazhuang.guanggoo.data.entity;

import java.util.Map;

/**
 *
 * @author mazhuang
 * @date 2017/9/17
 */

public class TopicDetail {

    private Favorite favorite;
    private Topic topic;
    private String content;
    private Map<Integer, Comment> comments;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Map<Integer, Comment> getComments() {
        return comments;
    }

    public void setComments(Map<Integer, Comment> comments) {
        this.comments = comments;
    }

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }
    public Favorite getFavorite() {
        return favorite;
    }

    public void setFavorite(Favorite favorite) {
        this.favorite = favorite;
    }

    public int getCommentsCount() {
        if (comments == null || comments.isEmpty()) {
            return 0;
        }

        Integer max = 0;

        for (Integer i : comments.keySet()) {
            max = Math.max(i, 0);
        }

        return max;
    }
}

package org.mazhuang.guanggoo.data.entity;

import java.util.Map;

/**
 *
 * @author mazhuang
 * @date 2017/9/17
 */

public class TopicDetail {

    private Favorite favorite;
    private Topic topic;
    private String content;
    private Map<Integer, Comment> comments;

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Map<Integer, Comment> getComments() {
        return comments;
    }

    public void setComments(Map<Integer, Comment> comments) {
        this.comments = comments;
    }

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }
    public Favorite getFavorite() {
        return favorite;
    }

    public void setFavorite(Favorite favorite) {
        this.favorite = favorite;
    }

    public int getCommentsCount() {
        if (comments == null || comments.isEmpty()) {
            return 0;
        }

        Integer max = 0;

        for (Integer i : comments.keySet()) {
            max = Math.max(i, max);
        }

        return max;
    }
}

Fix comments count in topic detail


package uk.ac.ebi.atlas.model.resource;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public abstract class AtlasResource<T> {

    protected final Path path;

    AtlasResource(Path path) {
        this.path = path;
    }

    public boolean exists() {
        return Files.exists(path);
    }

    public boolean existsAndIsNonEmpty() {
        return exists() && (
                path.toFile().isDirectory()
                        ? path.toFile().list().length > 0
                        : path.toFile().length() > 0
        );
    }

    public boolean isReadable() {
        return Files.isReadable(path);
    }

    public abstract T get();

    public Reader getReader() throws IOException {
        return Files.newBufferedReader(path, StandardCharsets.UTF_8);
    }

    public long size() {
        return path.toFile().length();
    }

    @Override
    public String toString() {
        return this.getClass().getName() + " with path " + path.toString();
    }

}

package uk.ac.ebi.atlas.model.resource;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public abstract class AtlasResource<T> {

    protected final Path path;

    AtlasResource(Path path) {
        this.path = path;
    }

    public boolean exists() {
        return Files.exists(path);
    }

    public boolean existsAndIsNonEmpty() {
        return exists() && (
                path.toFile().isDirectory()
                        ? path.toFile().list().length > 0
                        : path.toFile().length() > 0
        );
    }

    public boolean isReadable() {
        return Files.isReadable(path);
    }

    public abstract T get();

    public Reader getReader() throws IOException {
        return Files.newBufferedReader(path, StandardCharsets.UTF_8);
    }

    public long size() {
        return path.toFile().length();
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + " with path " + path.toString();
    }

}

Simplify log messages in bioentities/buildIndex/status


package info.u_team.u_team_test.data.provider;

import info.u_team.u_team_core.data.*;

public class TestBlockTagsProvider extends CommonBlockTagsProvider {

	public TestBlockTagsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerTags() {
	}

}

package info.u_team.u_team_test.data.provider;

import static info.u_team.u_team_test.init.TestTags.Blocks.*;
import info.u_team.u_team_core.data.*;
import net.minecraft.block.Blocks;
import net.minecraft.tags.*;

public class TestBlockTagsProvider extends CommonBlockTagsProvider {

	public TestBlockTagsProvider(GenerationData data) {
		super(data);
	}

	@Override
	protected void registerTags() {
		getBuilder(TEST_TAG_1).add(Blocks.ACACIA_BUTTON, Blocks.ACACIA_DOOR);
		getBuilder(TEST_TAG_2).addTag(TEST_TAG_1).add(Blocks.ACACIA_LOG);

		getBuilder(TEST_TAG_1).add(Blocks.BIRCH_LEAVES);
		getBuilder(TEST_TAG_1).addTag(BlockTags.BEDS);
	}

}

Add some stuff to the block tags provider


package org.bouncycastle.crypto.params;

public class GOST3410ValidationParameters
{
    private int x0;
    private int c;
    private long x0L;
    private long cL;

    public GOST3410ValidationParameters(
        int  x0,
        int  c)
    {
        this.x0 = x0;
        this.c = c;
    }

    public GOST3410ValidationParameters(
        long  x0L,
        long  cL)
    {
        this.x0L = x0L;
        this.cL = cL;
    }

    public int getC()
    {
        return c;
    }

    public int getX0()
    {
        return x0;
    }

    public long getCL()
    {
        return cL;
    }

    public long getX0L()
    {
        return x0L;
    }

    public boolean equals(
        Object o)
    {
        if (!(o instanceof GOST3410ValidationParameters))
        {
            return false;
        }

        GOST3410ValidationParameters  other = (GOST3410ValidationParameters)o;

        if (other.c != this.c)
        {
            return false;
        }

        if (other.x0 != this.x0)
        {
            return false;
        }

        if (other.cL != this.cL)
        {
            return false;
        }

        if (other.x0L != this.x0L)
        {
            return false;
        }

        return true;
    }
}

package org.bouncycastle.crypto.params;

public class GOST3410ValidationParameters
{
    private int x0;
    private int c;
    private long x0L;
    private long cL;

    public GOST3410ValidationParameters(
        int  x0,
        int  c)
    {
        this.x0 = x0;
        this.c = c;
    }

    public GOST3410ValidationParameters(
        long  x0L,
        long  cL)
    {
        this.x0L = x0L;
        this.cL = cL;
    }

    public int getC()
    {
        return c;
    }

    public int getX0()
    {
        return x0;
    }

    public long getCL()
    {
        return cL;
    }

    public long getX0L()
    {
        return x0L;
    }

    public boolean equals(
        Object o)
    {
        if (!(o instanceof GOST3410ValidationParameters))
        {
            return false;
        }

        GOST3410ValidationParameters  other = (GOST3410ValidationParameters)o;

        if (other.c != this.c)
        {
            return false;
        }

        if (other.x0 != this.x0)
        {
            return false;
        }

        if (other.cL != this.cL)
        {
            return false;
        }

        if (other.x0L != this.x0L)
        {
            return false;
        }

        return true;
    }

    public int hashCode()
    {
        return x0 ^ c ^ (int) x0L ^ (int)(x0L >> 32) ^ (int) cL ^ (int)(cL >> 32);
    }
}

Implement hashCode() corresponding to the equals() implementation


package com.sdl.selenium.web.button;

import com.sdl.selenium.web.WebLocator;
import org.apache.log4j.Logger;

public class SimpleUploadButton extends WebLocator {
    private static final Logger logger = Logger.getLogger(SimpleUploadButton.class);

    public SimpleUploadButton() {
        setClassName("SimpleUploadButton");
        setTag("input");
    }

    public SimpleUploadButton(WebLocator container) {
        this();
        setContainer(container);
    }

    public SimpleUploadButton(WebLocator container, String id) {
        this(container);
        setId(id);
    }

    public void uploadFile(String path) {
        type(path);
    }

    public void uploadFileWithJS(String path, String id) {
        executeScript("return (function(id){var d=document.getElementById(id);d.style.visibility='visible';d.style.height='1px'; d.style.width='1px'; d.style.opacity=1;return d.getAttribute('style') != ''}('" + id + "'));");
        type(path);
    }
}

package com.sdl.selenium.web.button;

import com.sdl.selenium.web.WebLocator;
import org.apache.log4j.Logger;

public class SimpleUploadButton extends WebLocator {
    private static final Logger logger = Logger.getLogger(SimpleUploadButton.class);

    public SimpleUploadButton() {
        setClassName("SimpleUploadButton");
        setTag("input");
    }

    public SimpleUploadButton(WebLocator container) {
        this();
        setContainer(container);
    }

    public SimpleUploadButton(WebLocator container, String id) {
        this(container);
        setId(id);
    }

    public void uploadFile(String path) {
        sendKeys(path);
    }

    public void uploadFileWithJS(String path, String id) {
        executeScript("return (function(id){var d=document.getElementById(id);d.style.visibility='visible';d.style.height='1px'; d.style.width='1px'; d.style.opacity=1;return d.getAttribute('style') != ''}('" + id + "'));");
        sendKeys(path);
    }
}

Remove methods type(String text) and typeKeys(String text) from WebLocator


package com.uwetrottmann.shopr.loaders;

import android.content.Context;

import com.uwetrottmann.shopr.model.Item;
import com.uwetrottmann.shopr.utils.Lists;

import java.math.BigDecimal;
import java.util.List;

/**
 * Returns a list of items based on the current user model.
 */
public class ItemLoader extends GenericSimpleLoader<List<Item>> {

    public ItemLoader(Context context) {
        super(context);
    }

    @Override
    public List<Item> loadInBackground() {
        List<Item> items = Lists.newArrayList();

        for (int i = 0; i < 10; i++) {
            Item item = new Item().id(i).name("Sample Item " + i).picture("sample.jpg").shopId(42);
            double random = Math.random() * 200;
            item.price(new BigDecimal(random));
            item.label(Math.random() > 0.5 ? "Armani" : "Hugo Boss");
            items.add(item);
        }

        return items;
    }

}

package com.uwetrottmann.shopr.loaders;

import android.content.Context;

import com.uwetrottmann.shopr.algorithm.AdaptiveSelection;
import com.uwetrottmann.shopr.algorithm.model.Attributes;
import com.uwetrottmann.shopr.model.Item;
import com.uwetrottmann.shopr.utils.Lists;

import java.math.BigDecimal;
import java.util.List;

/**
 * Returns a list of items based on the current user model.
 */
public class ItemLoader extends GenericSimpleLoader<List<Item>> {

    public ItemLoader(Context context) {
        super(context);
    }

    @Override
    public List<Item> loadInBackground() {
        List<Item> items = Lists.newArrayList();

        AdaptiveSelection manager = AdaptiveSelection.get();
        List<com.uwetrottmann.shopr.algorithm.model.Item> recommendations = manager
                .getRecommendations(null);

        // Until we have real data transfer the model of item used by algorithm
        // to the app model
        int count = 0;
        for (com.uwetrottmann.shopr.algorithm.model.Item item : recommendations) {
            Attributes attrs = item.attributes();
            String label = attrs.label().currentValue().toString();
            String type = attrs.type().currentValue().toString();

            Item expandedItem = new Item().id(count++);
            expandedItem.name(label + " " + type + " " + count);
            expandedItem.color(attrs.color().currentValue().toString());
            expandedItem.label(label);
            expandedItem.type(type);
            double random = Math.random() * 200;
            expandedItem.price(new BigDecimal(random));

            items.add(expandedItem);
        }

        return items;
    }

}

Integrate recommender into item loader.


package kennewickpractice.com.kegetapumpkin.model;

import kennewickpractice.com.kegetapumpkin.R;

/**
 * Created by ken.wagner on 11/5/2015.
 */
public class Story {
    private Page[] mPages;

    public Story() {
        mPages = new Page[7]; //based on how many pages made

        mPages[0] = new Page();
        mPages[0].setImageId(R.mipmap.kandeinsidetoon);
        mPages[0].setText("temp ipsem lorem");
        mPages[0].setChoice1(new Choice());
        mPages[0].setChoice2(new Choice());
        //more to fix and more to do

    }

}

package kennewickpractice.com.kegetapumpkin.model;

import kennewickpractice.com.kegetapumpkin.R;

/**
 * Created by ken.wagner on 11/5/2015.
 */
public class Story {
    private Page[] mPages;

    public Story() {
        mPages = new Page[7]; //based on how many pages made

        mPages[0] = new Page();
        mPages[0].setImageId(R.mipmap.kandeinsidetoon);
        mPages[0].setText("temp ipsem lorem");
        mPages[0].setChoice1(new Choice());
        mPages[0].setChoice2(new Choice());
        //more to fix and more to do and finish

    }

}

Add to the mess and more


package org.auraframework.perf.test.components;

import java.net.URLEncoder;
import java.util.logging.Logger;

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.perf.core.ComponentPerfAbstractTestCase;

public final class PerfLoadComponentTest extends ComponentPerfAbstractTestCase {

    private static final Logger logger = Logger.getLogger(PerfLoadComponentTest.class.getSimpleName());

    public PerfLoadComponentTest(String name, DefDescriptor<ComponentDef> desc) {
        super(name, desc);
    }

    @Override
    public void testRun() throws Throwable {
        String relativeUrl = "/perfTest/perf.app#" +
                URLEncoder.encode("{\"componentDef\":\"" + descriptor + "\"}", "UTF-8");
        String url = getAbsoluteURI(relativeUrl).toString();
        logger.info("testRun: " + url);
        openRaw(url);
    }
}

package org.auraframework.perf.test.components;

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.perf.core.ComponentPerfAbstractTestCase;
import org.openqa.selenium.By;

import java.net.URLEncoder;
import java.util.logging.Logger;

public final class PerfLoadComponentTest extends ComponentPerfAbstractTestCase {

    private static final Logger logger = Logger.getLogger(PerfLoadComponentTest.class.getSimpleName());

    public PerfLoadComponentTest(String name, DefDescriptor<ComponentDef> desc) {
        super(name, desc);
    }

    @Override
    public void testRun() throws Throwable {
        String relativeUrl = "/perfTest/perf.app#" +
                URLEncoder.encode("{\"componentDef\":\"" + descriptor + "\"}", "UTF-8");
        String url = getAbsoluteURI(relativeUrl).toString();
        logger.info("testRun: " + url);

        openRaw(url);

        String componentName = descriptor.getName();
        waitForElementAppear("Container div[data-app-rendered-component] element for thecomponent not present",
                By.cssSelector(String.format("[data-app-rendered-component='%s']", componentName)));
    }
}

Add a wait for component render to webdriver tests


package com.axiastudio.zoefx.core.script;

import com.axiastudio.zoefx.core.Utilities;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * User: tiziano
 * Date: 14/04/14
 * Time: 16:48
 */
public class JSScriptEngineImplTest {

    @BeforeClass
    public static void setUpClass() {
        JSEngineImpl engine = new JSEngineImpl();
        Utilities.registerUtility(engine, ScriptEngine.class);
    }

    @Test
    public void testEval() throws Exception {
        ScriptEngine engine = Utilities.queryUtility(ScriptEngine.class);
        String script = "function test(){ return \"ciao\"; } test()";
        Object eval = engine.eval(script);
        assert eval.toString().equals("ciao");
    }
}

package com.axiastudio.zoefx.core.script;

import com.axiastudio.zoefx.core.Utilities;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * User: tiziano
 * Date: 14/04/14
 * Time: 16:48
 */
public class JSScriptEngineImplTest {

    @BeforeClass
    public static void setUpClass() {
        JSEngineImpl engine = new JSEngineImpl();
        Utilities.registerUtility(engine, ScriptEngine.class);
    }

    @Test
    public void testEval() throws Exception {
        ScriptEngine engine = Utilities.queryUtility(ScriptEngine.class);
        String script = "return \"ciao\";";
        Object eval = engine.eval(script);
        assert eval.toString().equals("ciao");
    }
}

Fix in JS Engine test.


package io.rumors.reactnativesettings;

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

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNSettingsPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNSettingsModule(reactContext));
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }
}

package io.rumors.reactnativesettings;

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

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.bridge.JavaScriptModule;
public class RNSettingsPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
      return Arrays.<NativeModule>asList(new RNSettingsModule(reactContext));
    }

    public List<Class<? extends JavaScriptModule>> createJSModules() {
      return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Collections.emptyList();
    }
}

Remove override of createJSModules (RN 0.47 compatibility)