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

public class Exceptions {
    private Exceptions() {

    }

    public static RuntimeException propagate(Throwable t) {
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else {
            throw new RuntimeException(t);
        }
    }

}

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

public class Exceptions {
    private Exceptions() {

    }

    public static RuntimeException propagate(Throwable t) {
        /**
         * The return type of RuntimeException is a trick for code to be like this:
         *
         * throw Exceptions.propagate(e);
         *
         * Even though nothing will return and throw via that 'throw', it allows the code to look like it
         * so it's easy to read and understand that it will always result in a throw.
         */
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new RuntimeException(t);
        }
    }

}

Add Error propagation now that we use Throwable.


package com.twu.biblioteca.menu;

public class QuitAction implements Action {

    @Override
    public String toString() {
        return "Quit";
    }

    @Override
    public void performAction() {
        System.exit(0);
    }
}

package com.twu.biblioteca.menu;

public class QuitAction implements Action {

    @Override
    public String toString() {
        return "Quit";
    }

    @Override
    public void performAction() {

    }
}

Quit operation does not perform any action


package com.elmakers.mine.bukkit.magic.command.config;

import java.util.logging.Level;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;

import com.elmakers.mine.bukkit.api.magic.MageController;

public class AsyncProcessor {
    public static void success(MageController controller, CommandSender sender, String message) {
        message(controller, sender, message);
    }

    public static void message(MageController controller, CommandSender sender, String message) {
        final Plugin plugin = controller.getPlugin();
        plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
            @Override
            public void run() {
                sender.sendMessage(message);
            }
        });
    }

    public static void fail(MageController controller, CommandSender sender, String message) {
        fail(controller, sender, message, null, null);
    }

    public static void fail(MageController controller, CommandSender sender, String message, String errorMessage, Exception ex) {
        final Plugin plugin = controller.getPlugin();
        plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
            @Override
            public void run() {
                sender.sendMessage(ChatColor.RED + message);
                if (errorMessage != null) {
                    controller.getLogger().log(Level.WARNING, errorMessage, ex);
                }
            }
        });
    }
}

package com.elmakers.mine.bukkit.magic.command.config;

import java.util.logging.Level;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.Plugin;

import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.magic.MageController;

public class AsyncProcessor {
    public static void success(MageController controller, CommandSender sender, String message) {
        message(controller, sender, message);
    }

    public static void message(MageController controller, CommandSender sender, String message) {
        final Plugin plugin = controller.getPlugin();
        plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
            @Override
            public void run() {
                // Allow for chat components and other special message processing
                Mage mage = controller.getMage(sender);
                mage.sendMessage(message);
            }
        });
    }

    public static void fail(MageController controller, CommandSender sender, String message) {
        fail(controller, sender, message, null, null);
    }

    public static void fail(MageController controller, CommandSender sender, String message, String errorMessage, Exception ex) {
        final Plugin plugin = controller.getPlugin();
        plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
            @Override
            public void run() {
                // Allow for chat components and other special message processing
                Mage mage = controller.getMage(sender);
                mage.sendMessage(ChatColor.RED + message);
                if (errorMessage != null) {
                    controller.getLogger().log(Level.WARNING, errorMessage, ex);
                }
            }
        });
    }
}

Allow chat component processing in async result messaging


package mzsJVM.Event;
import mzsJVM.Entities.PlayerEntity;
import mzsJVM.GameObject.PlayerGO;
import mzsJVM.IScriptEventHandler;
import mzsJVM.Repository.PlayerRepository;
import org.nwnx.nwnx2.jvm.*;

@SuppressWarnings("unused")
public class Module_OnClientLeave implements IScriptEventHandler {
	@Override
	public void runScript(NWObject objSelf) {
		NWObject pc = NWScript.getExitingObject();
		NWScript.exportSingleCharacter(pc);
		SaveCharacter(pc);

		NWScript.executeScript("fky_chat_clexit", objSelf);
	}

	private void SaveCharacter(NWObject pc) {

		if(NWScript.getIsDM(pc)) return;

		PlayerGO gameObject = new PlayerGO(pc);
		PlayerRepository repo = new PlayerRepository();
		String uuid = gameObject.getUUID();
		NWLocation location = NWScript.getLocation(pc);

		PlayerEntity entity = repo.getByUUID(uuid);
		entity.setCharacterName(NWScript.getName(pc, false));
		entity.setHitPoints(NWScript.getCurrentHitPoints(pc));
		entity.setLocationAreaTag(NWScript.getTag(NWScript.getArea(pc)));
		entity.setLocationOrientation(NWScript.getFacing(pc));
		entity.setLocationX(location.getX());
		entity.setLocationY(location.getY());
		entity.setLocationZ(location.getZ());

		repo.save(entity);
	}
}

package mzsJVM.Event;
import mzsJVM.Entities.PlayerEntity;
import mzsJVM.GameObject.PlayerGO;
import mzsJVM.IScriptEventHandler;
import mzsJVM.Repository.PlayerRepository;
import org.nwnx.nwnx2.jvm.*;

@SuppressWarnings("unused")
public class Module_OnClientLeave implements IScriptEventHandler {
	@Override
	public void runScript(NWObject objSelf) {
		NWObject pc = NWScript.getExitingObject();
		NWScript.exportSingleCharacter(pc);
		SaveCharacter(pc);

		NWScript.executeScript("fky_chat_clexit", objSelf);
	}

	private void SaveCharacter(NWObject pc) {

		if(NWScript.getIsDM(pc)) return;

		PlayerGO gameObject = new PlayerGO(pc);
		PlayerRepository repo = new PlayerRepository();
		String uuid = gameObject.getUUID();
		NWLocation location = NWScript.getLocation(pc);

		PlayerEntity entity = repo.getByUUID(uuid);
        if(entity == null)
        {
            return;
        }

		entity.setCharacterName(NWScript.getName(pc, false));
		entity.setHitPoints(NWScript.getCurrentHitPoints(pc));
		entity.setLocationAreaTag(NWScript.getTag(NWScript.getArea(pc)));
		entity.setLocationOrientation(NWScript.getFacing(pc));
		entity.setLocationX(location.getX());
		entity.setLocationY(location.getY());
		entity.setLocationZ(location.getZ());

		repo.save(entity);
	}
}

Fix for exception on client leave for DMs


package org.realityforge.arez.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Methods marked with this annotation are observable values within Arez.
 *
 *
The method should only invoked within the scope of a transaction.

 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Observable
{
}

package org.realityforge.arez.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Methods marked with this annotation are observable values within Arez.
 *
 *
The method should only invoked within the scope of a transaction.

 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Observable
{
  /**
   * Return the name of the Observable relative to the container.
   *
   * @return the name of the Observable relative to the container.
   */
  String name() default "";
}

Add the ability to override the property name


package droplauncher.util;

import java.util.logging.Level;

/**
 * Constants class for global constants.
 */
public class Constants {

  public static final String PROGRAM_NAME = "DropLauncher";
  public static final String PROGRAM_VERSION = "0.02a";
  public static final String PROGRAM_AUTHOR = "Adakite";
  public static final String PROGRAM_TITLE = PROGRAM_NAME + " v" + PROGRAM_VERSION;
  public static final String PROGRAM_GITHUB = "https://github.com/adakitesystems/droplauncher";
  public static final String PROGRAM_LICENSE = "AGPL 3.0";
  public static final String PROGRAM_LICENSE_LINK = "https://www.gnu.org/licenses/agpl-3.0.en.html";

  /* Logging */
  public static final boolean DEBUG = true;
  public static final Level DEFAULT_LOG_LEVEL = Level.SEVERE;

  private Constants() {}

}

package droplauncher.util;

import java.util.logging.Level;

/**
 * Constants class for global constants.
 */
public class Constants {

  public static final String PROGRAM_NAME = "DropLauncher";
  public static final String PROGRAM_VERSION = "0.02a";
  public static final String PROGRAM_AUTHOR = "Adakite";
  public static final String PROGRAM_TITLE = PROGRAM_NAME + " v" + PROGRAM_VERSION;
  public static final String PROGRAM_GITHUB = "https://github.com/adakitesystems/droplauncher";
  public static final String PROGRAM_LICENSE = "AGPL 3.0";
  public static final String PROGRAM_LICENSE_LINK = "https://www.gnu.org/licenses/agpl-3.0.en.html";

  /* Logging */
  public static final boolean DEBUG = true;
  public static final Level DEFAULT_LOG_LEVEL = Level.SEVERE;

  public static final String DROPLAUNCHER_INI = "droplauncher.ini";
  public static final String DROPLAUNCHER_INI_SECTION = "droplauncher";

  private Constants() {}

}

Add program INI path constant


package lib.morkim.mfw.ui;

import android.content.Context;

import java.util.Observable;
import java.util.Observer;

import lib.morkim.mfw.app.AppContext;
import lib.morkim.mfw.domain.Model;
import lib.morkim.mfw.usecase.UseCase;
import lib.morkim.mfw.usecase.UseCaseProgress;
import lib.morkim.mfw.usecase.UseCaseResult;
import lib.morkim.mfw.usecase.UseCaseStateListener;

public abstract class Presenter implements Observer, UseCaseStateListener {

	private AppContext appContext;
	protected Viewable viewable;

	public Presenter(Viewable viewable) {

		this.viewable = viewable;
		this.appContext = viewable.getMorkimContext();
	}

	public void unbindViewModel() {

//		viewModel.unregister();
	}

	public void bindViewModel(Viewable viewable) {

//		viewModel.register(viewable);
//		viewModel.notifyView();
	}

	@Override
	public void update(Observable observable, Object data) {
		synchronized (this) {
//			onUpdate(observable, data, viewModel);
//			if (viewModel.hasListener())
//				viewModel.notifyUiView();
		}
	}

	protected void onUpdate(Observable observable, Object data,
			ViewModel viewModel) {
	}

//	public ViewModel getViewModel() {
//		return viewModel;
//	}
//
//	public void setViewModel(ViewModel viewModel) {
//		this.viewModel = viewModel;
//	}

	protected Controller getController() {
		return viewable.getController();
	}

	public AppContext getAppContext() {
		return appContext;
	}

	protected Context getContext() {
		return viewable.getContext();
	}

	public void setAppContext(AppContext appContext) {
		this.appContext = appContext;
	}

	protected Model getModel() {
		return appContext.getModel();
	}

	@Override
	public void onUseCaseStart(UseCase useCase) {}

	@Override
	public void onUseCaseUpdate(UseCaseProgress response) {}

	@Override
	public void onUseCaseComplete(UseCaseResult response) {}

	@Override
	public void onUseCaseCancel() {}
}

package lib.morkim.mfw.ui;

import android.content.Context;

import lib.morkim.mfw.app.AppContext;

public abstract class Presenter {

	private AppContext appContext;
	protected Viewable viewable;

	public Presenter(Viewable viewable) {

		this.viewable = viewable;
		this.appContext = viewable.getMorkimContext();
	}

	protected Controller getController() {
		return viewable.getController();
	}

	public AppContext getAppContext() {
		return appContext;
	}

	protected Context getContext() {
		return viewable.getContext();
	}

	public void setAppContext(AppContext appContext) {
		this.appContext = appContext;
	}
}

Remove view model in presenter


package com.lukekorth.photo_paper.services;

import android.app.IntentService;
import android.content.Intent;

import com.lukekorth.photo_paper.WallpaperApplication;
import com.lukekorth.photo_paper.helpers.PicassoHelper;
import com.lukekorth.photo_paper.helpers.Settings;
import com.lukekorth.photo_paper.models.Photos;
import com.lukekorth.photo_paper.models.WallpaperChangedEvent;

import org.slf4j.LoggerFactory;

import io.realm.Realm;

public class ClearCacheIntentService extends IntentService {

    public ClearCacheIntentService() {
        super("ClearCacheIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        LoggerFactory.getLogger("ClearCacheIntentService").debug("Clearing photo database and cache");

        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.where(Photos.class).findAll().clear();
        realm.commitTransaction();
        realm.close();

        PicassoHelper.clearCache(this);
        Settings.clearUpdated(this);

        WallpaperApplication.getBus().post(new WallpaperChangedEvent());
        PhotoDownloadIntentService.downloadPhotos(this);
    }
}

package com.lukekorth.photo_paper.services;

import android.app.IntentService;
import android.content.Intent;

import com.lukekorth.photo_paper.WallpaperApplication;
import com.lukekorth.photo_paper.helpers.PicassoHelper;
import com.lukekorth.photo_paper.helpers.Settings;
import com.lukekorth.photo_paper.models.Photos;
import com.lukekorth.photo_paper.models.WallpaperChangedEvent;

import org.slf4j.LoggerFactory;

import io.realm.Realm;

public class ClearCacheIntentService extends IntentService {

    public ClearCacheIntentService() {
        super("ClearCacheIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        LoggerFactory.getLogger("ClearCacheIntentService").debug("Clearing photo database and cache");

        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.where(Photos.class).findAll().deleteAllFromRealm();
        realm.commitTransaction();
        realm.close();

        PicassoHelper.clearCache(this);
        Settings.clearUpdated(this);

        WallpaperApplication.getBus().post(new WallpaperChangedEvent());
        PhotoDownloadIntentService.downloadPhotos(this);
    }
}

Fix crash when clearing cache


package tw.wancw.curator.api;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

public class CuratorApi {

    private static final String API_END_POINT = "http://curator.im/api/";

    private static final AsyncHttpClient client = new AsyncHttpClient();

    private final String token;

    public CuratorApi(String token) {
        this.token = token;
    }

    public void stream(MeiZiCardsResponseHandler handler) {
        final String path = "stream/";
        RequestParams params = new RequestParams();
        params.put("token", token);
        params.put("page", 1);
        client.get(API_END_POINT + path, params, new StreamResponseHandler(handler));
    }
}

package tw.wancw.curator.api;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;

public class CuratorApi {

    private static final String API_END_POINT = "http://curator.im/api/";

    private static final AsyncHttpClient client = new AsyncHttpClient();

    private final String token;

    public CuratorApi(String token) {
        this.token = token;
    }

    public void stream(final MeiZiCardsResponseHandler handler) {
        stream(1, handler);
    }

    public void stream(final int page, final MeiZiCardsResponseHandler handler) {
        final String path = "stream/";
        RequestParams params = new RequestParams();
        params.put("token", token);
        params.put("page", String.valueOf(page));
        client.get(API_END_POINT + path, params, new StreamResponseHandler(handler));
    }
}

Support `page` parameter in stream API.


package com.alibaba.rocketmq.example.verify;

import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;

public class SelectPartition {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();

        Option option = new Option("p", "path", true, "Paths in CSV");
        options.addOption(option);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);
        if (!commandLine.hasOption('p')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Select Partition", options);
            return;
        }

        String pathCSV = commandLine.getOptionValue("p");
        String selectedPath = UtilAll.selectPath(pathCSV);
        System.out.println(selectedPath);
    }
}

package com.alibaba.rocketmq.example.verify;

import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;

public class SelectPartition {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();

        Option option = new Option("p", "path", true, "Paths in CSV");
        options.addOption(option);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);
        if (!commandLine.hasOption('p')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Select Partition", options);
            return;
        }

        String pathCSV = commandLine.getOptionValue("p");
        UtilAll.selectPath(pathCSV);

        UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV);
    }
}

Add test to show disk usage ratio per partition.


package ro.stancalau.lombok.base;

import org.junit.Before;
import org.junit.Test;
import ro.stancalau.lombok.api.ImmutablePerson;

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

public abstract class PersonBaseEqualsAndHashTest<T extends ImmutablePerson> implements PersonFactory<T> {

    private T person;
    private T samePerson;
    private T stranger;

    @Before
    public void setUp() throws Exception {
        person = createPerson();
        samePerson = createPerson();
        stranger = createPerson("Stranger");
    }

    @Test
    public void testNotEqualsToNull() throws Exception {
        assertFalse(person.equals(null));
    }

    @Test
    public void testEqualsToSelf() throws Exception {
        assertTrue(person.equals(person));
        assertTrue(stranger.equals(stranger));
    }

    @Test
    public void givenTwoPeopleWithDifferentNameWhenEqualsThenReturnFalse() throws Exception {
        assertFalse(person.equals(stranger));
        assertFalse(stranger.equals(person));
    }

    @Test
    public void givenPersonWithSameStateWhenEqualsThenReturnTrue() throws Exception {
        assertTrue(person.equals(samePerson));
    }

    //TODO add more tests for equals and hash

}

package ro.stancalau.lombok.base;

import org.junit.Before;
import org.junit.Test;
import ro.stancalau.lombok.api.ImmutablePerson;

import static org.junit.Assert.*;

public abstract class PersonBaseEqualsAndHashTest<T extends ImmutablePerson> implements PersonFactory<T> {

    private T person;
    private T samePerson;
    private T sameClone;
    private T stranger;

    @Before
    public void setUp() throws Exception {
        person = createPerson();
        samePerson = createPerson();
        sameClone = createPerson();
        stranger = createPerson("Stranger");
    }

    @Test
    public void testNotEqualsToNull() throws Exception {
        assertFalse(person.equals(null));
    }

    @Test
    public void testReflexive() throws Exception {
        assertTrue(person.equals(person));
    }

    @Test
    public void testSymmetric() throws Exception {
        assertFalse(person.equals(stranger));
        assertFalse(stranger.equals(person));

        assertTrue(person.equals(samePerson));
        assertTrue(samePerson.equals(person));
    }

    @Test
    public void testTransitive() throws Exception {
        assertTrue(person.equals(samePerson));
        assertTrue(samePerson.equals(sameClone));
        assertTrue(sameClone.equals(person));
    }

    @Test
    public void givenPersonsWithSameStateWhenCompareHashCodesThenAreEqual() throws Exception {
        assertEquals(person.hashCode(), samePerson.hashCode());
    }
}

Add transitive test for equals and hashcode test.


package com.reactnativenavigation.presentation;

import android.view.ViewGroup;

import com.reactnativenavigation.utils.CommandListener;
import com.reactnativenavigation.viewcontrollers.ViewController;

import java.util.HashMap;

public class OverlayManager {
    private final HashMap<String, ViewController> overlayRegistry = new HashMap<>();

    public void show(ViewGroup root, ViewController overlay, CommandListener listener) {
        overlayRegistry.put(overlay.getId(), overlay);
        overlay.setOnAppearedListener(() -> listener.onSuccess(overlay.getId()));
        root.addView(overlay.getView());
    }

    public void dismiss(String componentId, CommandListener listener) {
        ViewController overlay = overlayRegistry.get(componentId);
        if (overlay == null) {
            listener.onError("Could not dismiss Overlay. Overlay with id " + componentId + " was not found.");
        } else {
            overlay.destroy();
            overlayRegistry.remove(componentId);
            listener.onSuccess(componentId);
        }
    }

    public void destroy() {
        for (ViewController view : overlayRegistry.values()) {
            view.destroy();
        }
        overlayRegistry.clear();
    }

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

package com.reactnativenavigation.presentation;

import android.support.annotation.Nullable;
import android.view.ViewGroup;

import com.reactnativenavigation.utils.CommandListener;
import com.reactnativenavigation.viewcontrollers.ViewController;

import java.util.HashMap;

public class OverlayManager {
    private final HashMap<String, ViewController> overlayRegistry = new HashMap<>();

    public void show(@Nullable ViewGroup root, ViewController overlay, CommandListener listener) {
        if (root == null) {
            listener.onError("Can't show Overlay before setRoot is called. This will be resolved in #3899");
            return;
        }
        overlayRegistry.put(overlay.getId(), overlay);
        overlay.setOnAppearedListener(() -> listener.onSuccess(overlay.getId()));
        root.addView(overlay.getView());
    }

    public void dismiss(String componentId, CommandListener listener) {
        ViewController overlay = overlayRegistry.get(componentId);
        if (overlay == null) {
            listener.onError("Could not dismiss Overlay. Overlay with id " + componentId + " was not found.");
        } else {
            overlay.destroy();
            overlayRegistry.remove(componentId);
            listener.onSuccess(componentId);
        }
    }

    public void destroy() {
        for (ViewController view : overlayRegistry.values()) {
            view.destroy();
        }
        overlayRegistry.clear();
    }

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

Handle NPE when showing Overlay before setRoot is called


package org.oskari.map.userlayer.service;

import fi.nls.oskari.domain.map.userlayer.UserLayer;
import fi.nls.oskari.domain.map.userlayer.UserLayerData;
import fi.nls.oskari.domain.map.userlayer.UserLayerStyle;
import fi.nls.oskari.service.OskariComponent;
import fi.nls.oskari.service.ServiceException;

import java.util.List;

public abstract class UserLayerDbService extends OskariComponent {
    //UserLayer related
    public abstract int insertUserLayer(final UserLayer userlayer, final UserLayerStyle userLayerStyle, final List<UserLayerData> userLayerDataList) throws ServiceException;

    public abstract int updateUserLayerCols(final UserLayer userlayer);

    public abstract UserLayer getUserLayerById(long id);

    public abstract List<UserLayer> getUserLayerByUuid(String uuid);

    public abstract void deleteUserLayerById(final long id) throws ServiceException;

    public abstract void deleteUserLayer(final UserLayer userlayer) throws ServiceException;

    public abstract void deleteUserLayersByUuid(String uuid) throws ServiceException;

    public abstract int updatePublisherName(final long id, final String uuid, final String name);

	public abstract String getUserLayerExtent (final long id);

    //UserLayerStyle related
    public abstract int updateUserLayerStyleCols(final UserLayerStyle userLayerStyle);

    public abstract UserLayerStyle getUserLayerStyleById(final long id);

    //UserLayerData related
    public abstract int updateUserLayerDataCols(final UserLayerData userlayerdata);

}

Remove empty lines that make it harder to read


package org.codehaus.groovy.grails.orm.hibernate;

public abstract class AbstractJavaClass {
}

package org.codehaus.groovy.grails.orm.hibernate;

public class AbstractJavaClass {
}

Revert "marked class as abstract"


package com.google.sps.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Given a tweet or sentence, the servlet will extract salient terms from those
 * and store them in a list.
 */
@WebServlet("/keyword")
public class KeywordServlet extends HttpServlet {

  private static final List<String> tweets = new ArrayList<>();
  private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19");

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO: Extract saliency
    Gson gson = new Gson();
    String json = gson.toJson(terms);
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final String tweet = request.getParameter("keyword-sentence");
    if (tweet != null && !tweet.equals("")) {
      tweets.add(request.getParameter("keyword-sentence"));
    }
    response.sendRedirect("/index.html");
  }

}

package com.google.sps.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Given a tweet or sentence, the servlet will extract salient terms from those
 * and store them in a list.
 */
@WebServlet("/keyword")
public class KeywordServlet extends HttpServlet {

  private static final List<String> tweets = new ArrayList<>();
  private static final List<String> terms = Arrays.asList("Black Lives Matter", "COVID-19");

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO: Extract saliency
    String json = mustacheJsonBuilder(terms);
    response.getWriter().println(json);
  }

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final String tweet = request.getParameter("keyword-sentence");
    if (tweet != null && !tweet.equals("")) {
      tweets.add(request.getParameter("keyword-sentence"));
    }
    response.sendRedirect("/index.html");
  }

  /**
   * Generates and returns a JSON usable by Mustache.
   */
  private String mustacheJsonBuilder(Collection<String> toJson) {
    String builder = "{\"keywords\": [";
    for (String term : toJson) {
      builder += "{\"term\": \"" + term + "\"},";
    }

    // Remove extra comma at the end.
    builder = builder.substring(0, builder.length() - 1) + "]}";
    return builder;
  }

}

Change get's output to format Mustache can use


package com.mdsol.mauth;

import static org.junit.Assert.fail;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.io.IOException;
import java.lang.SecurityException;
import java.util.UUID;

/**
 * Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
 *
 * @author Jonathan Price <jprice@mdsol.com>
 */
public class MAuthRequestSignerTest {

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public final void constructorWithInvalidKeyStringThrowsException() throws IOException {
    UUID appUUID = UUID.randomUUID();
    String privateKeyString = "This is not a valid key";
    thrown.expect(SecurityException.class);
    thrown.expectMessage("Unable to process private key string");
    new MAuthRequestSigner(appUUID, privateKeyString);
    fail(); // Shouldn't get here - exception will have been thrown
  }

}

package com.mdsol.mauth;

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

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Map;
import java.util.UUID;

/**
 * Tests for {@link com.mdsol.mauth.MAuthRequestSigner}
 *
 * @author Jonathan Price <jprice@mdsol.com>
 */
public class MAuthRequestSignerTest {

  private static final long TEST_EPOCH_TIME = 1424697700L;
  private static String privateKeyString;
  private final UUID testUUID = UUID.fromString("2a6790ab-f6c6-45be-86fc-9e9be76ec12a");

  private MAuthRequestSigner mAuthRequestSigner;

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @BeforeClass
  public static void setUpClass() throws Exception {
    privateKeyString = IOUtils.toString(MAuthRequestSigner.class.getResourceAsStream("privatekey.pem"), "UTF-8");
  }

  @Before
  public void setUp() throws Exception {
    mAuthRequestSigner = new MAuthRequestSigner(testUUID,privateKeyString);
    EpochTime testEpochTime = new TestEpochTime(TEST_EPOCH_TIME);
    MAuthRequestSigner.setEpochTime(testEpochTime);
  }

  @Test
  public final void constructorWithInvalidKeyStringThrowsException() throws Exception {
    String privateKeyString = "This is not a valid key";
    thrown.expect(SecurityException.class);
    thrown.expectMessage("Unable to process private key string");
    new MAuthRequestSigner(testUUID, privateKeyString);
    fail(); // Shouldn't get here - exception will have been thrown
  }

  @Test
  public final void generateHeadersIncludesTimeHeaderWithCorrectTime() throws Exception {
    Map<String, String> headers = mAuthRequestSigner.generateHeaders("GET", "/", "");
    assertEquals(String.valueOf(TEST_EPOCH_TIME), headers.get("x-mws-time"));
  }

}

Add time test and use fixed UUID and key


package com.vsct.dt.haas.admin.nsq.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;

import java.util.Base64;
import java.util.concurrent.TimeoutException;

public class Producer {

    private final NSQProducer producer;

    private final ObjectMapper mapper = new ObjectMapper();

    public Producer(String host, int port) {
        this.producer = new NSQProducer();
        this.producer.addAddress(host, port);
    }

    public void sendCommitBegin(String correlationId, String haproxy, String application, String platform, String conf) throws JsonProcessingException, NSQException, TimeoutException {
        String confBase64 = new String(Base64.getEncoder().encode(conf.getBytes()));
        CommitBeginPayload payload = new CommitBeginPayload(correlationId, application, platform, confBase64);
        producer.produce("commit_begin_" + haproxy, mapper.writeValueAsBytes(payload));
    }

    public void start(){
        this.producer.start();
    }

    public void stop(){
        this.producer.shutdown();
    }

}

package com.vsct.dt.haas.admin.nsq.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.brainlag.nsq.NSQProducer;
import com.github.brainlag.nsq.exceptions.NSQException;

import java.util.Base64;
import java.util.concurrent.TimeoutException;

public class Producer {

    private final NSQProducer producer;

    private final ObjectMapper mapper = new ObjectMapper();

    public Producer(String host, int port) {
        this.producer = new NSQProducer();
        this.producer.addAddress(host, port);
    }

    public void sendCommitBegin(String correlationId, String haproxy, String application, String platform, String conf) throws JsonProcessingException, NSQException, TimeoutException {
        String confBase64 = new String(Base64.getEncoder().encode(conf.getBytes()));
        CommitBeginPayload payload = new CommitBeginPayload(correlationId, application, platform, confBase64);
        producer.produce("commit_requested_" + haproxy, mapper.writeValueAsBytes(payload));
    }

    public void start(){
        this.producer.start();
    }

    public void stop(){
        this.producer.shutdown();
    }

}

Change commit_begin channel to commit_requested


package absyn;

import env.Env;
import javaslang.collection.Tree;
import parse.Loc;
import semantic.SemanticHelper;
import types.INT;
import types.Type;

public class VarSimple extends Var {

   public final String name;

   public VarSimple(Loc loc, String name) {
      super(loc);
      this.name = name;
   }

   @Override
   public Tree.Node<String> toTree() {
      return Tree.of(annotateType("VarSimple: " + name));
   }

   @Override
   protected Type semantic_(Env env) {
      Type t = env.venv.get(name);
      if (t == null)
         throw SemanticHelper.undefined(loc, "variable", name);
      return t;
   }

}

package absyn;

import env.Env;
import javaslang.collection.Tree;
import parse.Loc;
import types.FUNCTION;
import types.Type;

import static semantic.SemanticHelper.undefined;
import static semantic.SemanticHelper.error;

public class VarSimple extends Var {

   public final String name;

   public VarSimple(Loc loc, String name) {
      super(loc);
      this.name = name;
   }

   @Override
   public Tree.Node<String> toTree() {
      return Tree.of(annotateType("VarSimple: " + name));
   }

   @Override
   protected Type semantic_(Env env) {
      Type t = env.venv.get(name);

      if (t == null)
         throw undefined(loc, "variable", name);

      if (t instanceof FUNCTION)
         throw error(loc, "function '%s' used as variable", name);

      return t;
   }

}

Fix semantic analysis of simple variables


/*
 * Copyright 2015-2016 EuregJUG.
 *
 * 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 eu.euregjug.site;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * @author Michael J. Simons, 2015-12-26
 */
@SpringBootApplication
@EnableCaching
@EnableAsync
@PropertySource("classpath:build.properties")
public class Application {

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

/*
 * Copyright 2015-2016 EuregJUG.
 *
 * 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 eu.euregjug.site;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.EnableLoadTimeWeaving;
import org.springframework.context.annotation.EnableLoadTimeWeaving.AspectJWeaving;
import org.springframework.context.annotation.PropertySource;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * @author Michael J. Simons, 2015-12-26
 */
@SpringBootApplication
@EnableCaching
@EnableAsync
@EnableLoadTimeWeaving(aspectjWeaving = AspectJWeaving.ENABLED)
@PropertySource("classpath:build.properties")
public class Application {

    @Bean
    public LoadTimeWeaver loadTimeWeaver() {
	return new InstrumentationLoadTimeWeaver();
    }

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

Enable LoadTimeWeaving to support internal calls to proxied methods


package ogr.sipc.se.plugin;

public interface Plugin {

	public void getURL() ;

	public void onEnable() ;

}

package org.sipc.se.plugin;

public interface Plugin {

	public void getURL() ;

	public void onEnable() ;

}

Fix a package path mistake


public class TestaOrdenacao {

  public static void main(String[] args) {

    Produto produtos[] = {
      new Produto("Lamborghini", 1000000),
      new Produto("Jipe", 46000),
      new Produto("Brasília", 16000),
      new Produto("Smart", 46000),
      new Produto("Fusca", 17000)
    };

    for(int atual = 0; atual < produtos.length - 1; atual++) {
      int menor = buscaMenor(produtos, atual, produtos.length - 1);
      Produto produtoAtual = produtos[atual];
      Produto produtoMenor = produtos[menor];
      produtos[atual] = produtoMenor;
      produtos[menor] = produtoAtual;
    }

    for(Produto produto : produtos) {
      System.out.println(produto.getNome() + " custa " + produto.getPreco());
    }

  }

  private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
    int maisBarato = inicio;
    for(int atual = inicio; atual <= termino; atual++) {
      if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
        maisBarato = atual;
      }
    }
    return maisBarato;
  }

}

public class TestaOrdenacao {

  public static void main(String[] args) {

    Produto produtos[] = {
      new Produto("Lamborghini", 1000000),
      new Produto("Jipe", 46000),
      new Produto("Brasília", 16000),
      new Produto("Smart", 46000),
      new Produto("Fusca", 17000)
    };

    ordena(produtos, produtos.length);

    for(Produto produto : produtos) {
      System.out.println(produto.getNome() + " custa " + produto.getPreco());
    }

  }

  private static void ordena(Produto[] produtos, int quantidadeDeElementos) {
    for(int atual = 0; atual < quantidadeDeElementos - 1; atual++) {
      int menor = buscaMenor(produtos, atual, quantidadeDeElementos - 1);
      Produto produtoAtual = produtos[atual];
      Produto produtoMenor = produtos[menor];
      produtos[atual] = produtoMenor;
      produtos[menor] = produtoAtual;
    }
  }

  private static int buscaMenor(Produto[] produtos, int inicio, int termino) {
    int maisBarato = inicio;
    for(int atual = inicio; atual <= termino; atual++) {
      if(produtos[atual].getPreco() < produtos[maisBarato].getPreco()) {
        maisBarato = atual;
      }
    }
    return maisBarato;
  }

}

Insert new files, Alura, Projeto de Algoritmos 1, Aula 21


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

/*
 * Represents an IPTC block, a set of key-value pairs of Photoshop IPTC data.
 */
public class IptcBlock {
    public final int blockType;
    //  Only currently used by classes in the package
    final byte[] blockNameBytes; // TODO make private and provide getter?
    final byte[] blockData; // TODO make private and provide getter?

    public IptcBlock(final int blockType, final byte[] blockNameBytes, final byte[] blockData) {
        this.blockData = blockData;
        this.blockNameBytes = blockNameBytes;
        this.blockType = blockType;
    }

    public boolean isIPTCBlock() {
        return blockType == IptcConstants.IMAGE_RESOURCE_BLOCK_IPTC_DATA;
    }
}

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

/**
 * Represents an IPTC block, a set of key-value pairs of Photoshop IPTC data.
 */
public class IptcBlock {
    public final int blockType;
    //  Only currently used by classes in the package
    final byte[] blockNameBytes; // TODO make private and provide getter?
    final byte[] blockData; // TODO make private and provide getter?

    public IptcBlock(final int blockType, final byte[] blockNameBytes, final byte[] blockData) {
        this.blockData = blockData;
        this.blockNameBytes = blockNameBytes;
        this.blockType = blockType;
    }

    public boolean isIPTCBlock() {
        return blockType == IptcConstants.IMAGE_RESOURCE_BLOCK_IPTC_DATA;
    }
}

Make block comment a JavaDoc comment


package paprika.neo4j;

import org.neo4j.cypher.CypherException;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;

import java.io.IOException;

/**
 * Created by antonin on 16-05-03.
 */
public class ARGB8888Query extends Query {

    private ARGB8888Query(QueryEngine queryEngine) {
        super(queryEngine);
    }

    public static ARGB8888Query createARGB8888Query(QueryEngine queryEngine) {
        return new ARGB8888Query(queryEngine);
    }

    @Override
    public void execute(boolean details) throws CypherException, IOException {
        try (Transaction ignored = graphDatabaseService.beginTx()) {
            String query = "MATCH (e: ExternalArgument) WHERE HAS(e.is_argb_8888) RETURN e, count(e) as ARGB8888";
            Result result = graphDatabaseService.execute(query);
            queryEngine.resultToCSV(result, "_ARGB8888.csv");
        }
    }

}

package paprika.neo4j;

import org.neo4j.cypher.CypherException;
import org.neo4j.graphdb.Result;
import org.neo4j.graphdb.Transaction;

import java.io.IOException;

/**
 * Created by antonin on 16-05-03.
 */
public class ARGB8888Query extends Query {

    private ARGB8888Query(QueryEngine queryEngine) {
        super(queryEngine);
    }

    public static ARGB8888Query createARGB8888Query(QueryEngine queryEngine) {
        return new ARGB8888Query(queryEngine);
    }

    @Override
    public void execute(boolean details) throws CypherException, IOException {
        try (Transaction ignored = graphDatabaseService.beginTx()) {
            String query = "MATCH (e: ExternalArgument) WHERE HAS(e.is_argb_8888) RETURN e";
            if (details) {
                query += ", count(e) as ARGB8888";
            }
            Result result = graphDatabaseService.execute(query);
            queryEngine.resultToCSV(result, "_ARGB8888.csv");
        }
    }

}

Add details to the query ARGB_8888


package com.manning.siia;

import siia.booking.domain.trip.LegQuoteCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;

import javax.xml.transform.Source;

public class TripQuoteRequestProcessor {

    private Log logger = LogFactory.getLog(getClass());

    public Source processTripRequest(Source requestSource) throws Exception{
        logger.info("Trip request recevied");
        StringResult res = new StringResult();
        res.getWriter().append("<ok/>");
        return new StringSource(res.toString());
    }

     public OkResponse processTripRequest(LegQuoteCommand legQuoteCommand) throws Exception{
        logger.info("Trip request received:" + legQuoteCommand);
        StringResult res = new StringResult();
        return new OkResponse();
    }

}

package com.manning.siia;

import siia.booking.domain.trip.LegQuoteCommand;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.xml.transform.StringResult;
import org.springframework.xml.transform.StringSource;

import javax.xml.transform.Source;

public class TripQuoteRequestProcessor {

    private Log logger = LogFactory.getLog(getClass());

    public Source processTripRequest(Source requestSource) throws Exception{
        logger.info("Trip request recevied");
        StringResult res = new StringResult();
        res.getWriter().append("<ok/>");
        return new StringSource(res.toString());
    }

    public OkResponse processTripRequest(String requestSource) throws Exception{
        logger.info("Trip request recevied");
        return new OkResponse();
    }

     public OkResponse processTripRequest(LegQuoteCommand legQuoteCommand) throws Exception{
        logger.info("Trip request received:" + legQuoteCommand);
        return new OkResponse();
    }

}

Fix for handling HTTP requests properly


package org.jboss.da.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Jozef Mrazek <jmrazek@redhat.com>
 *
 */
@Path("/")
public class Root {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getDescription() {
        return "
Dependency analyzer REST
"
                + "

Version: 1.0.0
"
                + "
Swagger documentation:/da/swagger-ui
"
                + "
REST proposal documentation: https://docs.engineering.redhat.com/display/JP/REST+endpoints+proposal

";
    }

}

package org.jboss.da.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author Jozef Mrazek <jmrazek@redhat.com>
 *
 */
@Path("/")
public class Root {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public String getDescription() {
        return "
Dependency analyzer REST
"
                + "

Version: 1.0.0
"
                + "
Swagger documentation:/da/doc
"
                + "
REST proposal documentation: https://docs.engineering.redhat.com/display/JP/REST+endpoints+proposal

";
    }

}

Fix the doc url from root


package org.jeffpiazza.derby;

import java.util.*;
import java.text.*;

public class Timestamp {
  private static final SimpleDateFormat yyyy_mm_dd_hh_mm_ss
      = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
  private static final SimpleDateFormat hh_mm_ss
      = new SimpleDateFormat("HH:mm:ss.S");

  public static String string() {
    // return yyyy_mm_dd_hh_mm_ss.format(Calendar.getInstance().getTime());
    return yyyy_mm_dd_hh_mm_ss.format(new Date(System.currentTimeMillis()));
  }

  public static String brief() {
    return hh_mm_ss.format(new Date(System.currentTimeMillis()));
  }
}

package org.jeffpiazza.derby;

import java.util.*;
import java.text.*;

public class Timestamp {
  private static final SimpleDateFormat yyyy_mm_dd_hh_mm_ss
      = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
  private static final SimpleDateFormat hh_mm_ss
      = new SimpleDateFormat("HH:mm:ss.SSS");

  public static String string() {
    // return yyyy_mm_dd_hh_mm_ss.format(Calendar.getInstance().getTime());
    return yyyy_mm_dd_hh_mm_ss.format(new Date(System.currentTimeMillis()));
  }

  public static String brief() {
    return hh_mm_ss.format(new Date(System.currentTimeMillis()));
  }
}

Fix timestamp format for derby-timer log files.


package com.easternedgerobotics.rov.fx;

import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;

import javax.inject.Inject;

public class CpuInformationView implements View {
    private static final int LABEL_SPACING = 5;

    final Label frequencyLabel = new Label("???");

    final Label temperatureLabel = new Label("???");

    final Label voltageLabel = new Label("???");

    final HBox row;

    @Inject
    public CpuInformationView() {
        row = new HBox(
            LABEL_SPACING,
            new VBox(LABEL_SPACING, voltageLabel, new Label("Voltage")),
            new VBox(LABEL_SPACING, temperatureLabel, new Label("CPU temperature")),
            new VBox(LABEL_SPACING, frequencyLabel, new Label("CPU frequency"))
        );
    }

    @Override
    public final Parent getParent() {
        return row;
    }
}

package com.easternedgerobotics.rov.fx;

import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;

import javax.inject.Inject;

public class CpuInformationView implements View {
    private static final int LABEL_SPACING = 20;

    final Label frequencyLabel = new Label("???");

    final Label temperatureLabel = new Label("???");

    final Label voltageLabel = new Label("???");

    final Label name = new Label("Rasprime");

    final VBox row;

    @Inject
    public CpuInformationView() {
        this.row = column(
            new HBox(
                LABEL_SPACING,
                column(bold(voltageLabel), new Label("Voltage")),
                column(bold(temperatureLabel), new Label("CPU temperature")),
                column(bold(frequencyLabel), new Label("CPU frequency"))
            ),
            name
        );
    }

    @Override
    public final Parent getParent() {
        return row;
    }

    private Label bold(final Label label) {
        final Font font = label.getFont();
        label.setFont(Font.font(font.getFamily(), FontWeight.BOLD, font.getSize()));

        return label;
    }

    private VBox column(final Node... rows) {
        final VBox col = new VBox(LABEL_SPACING, rows);
        col.setAlignment(Pos.BASELINE_CENTER);

        return col;
    }
}

Adjust CpuInfo view to match style of SensorView


package info.maccac.recorder.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.intellij.openapi.diagnostic.Logger;
import info.maccac.recorder.TestResults;

public class TestResultsClientImpl implements TestResultsClient {

    private static final Logger logger = Logger.getInstance("TestResultsClientImpl");

    private Gson gson;

    public TestResultsClientImpl() {
        this.gson = new GsonBuilder().create();
    }

    @Override
    public void postTestResults(TestResults breakdown) {
        logger.info("Posting: " + gson.toJson(breakdown));
    }
}

package info.maccac.recorder.client;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.diagnostic.Logger;
import info.maccac.recorder.TestResults;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class TestResultsClientImpl implements TestResultsClient {

    private static final Logger logger = Logger.getInstance("TestResultsClientImpl");
    private static final String DEFAULT_HOST = "http://localhost:8080/results";

    private Gson gson;

    public TestResultsClientImpl() {
         this.gson = new GsonBuilder().create();
    }

    @Override
    public void postTestResults(TestResults breakdown) {
        try {
            String jsonBody = gson.toJson(breakdown);
            HttpURLConnection connection = postJson(jsonBody);
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                logger.error("Failed to send results to server.");
            }
        } catch (IOException e) {
            logger.warn(e);
            Notification notification = new Notification("Test recorder", "Failed to post results", e.getMessage(), NotificationType.INFORMATION);
            Notifications.Bus.notify(notification);
        }
    }

    @NotNull
    private HttpURLConnection postJson(String jsonBody) throws IOException {
        HttpURLConnection connection = createHttpUrlConnectionTo(DEFAULT_HOST);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/json");
        connection.setRequestProperty("charset", "utf-8");
        byte[] jsonAsBytes = jsonBody.getBytes(StandardCharsets.UTF_8);
        connection.setRequestProperty("Content-Length", Integer.toString(jsonAsBytes.length));

        try (DataOutputStream out = new DataOutputStream(connection.getOutputStream())) {
            out.write(jsonAsBytes);
        }

        return connection;
    }

    @NotNull
    private HttpURLConnection createHttpUrlConnectionTo(String defaultHost) throws IOException {
        URL url = new URL(defaultHost);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setUseCaches(false);
        connection.setConnectTimeout(2000);
        connection.setReadTimeout(2000);
        return connection;
    }
}

Send results to an external service


package com.haxademic.core.image.filters.shaders;

import com.haxademic.core.system.FileUtil;

import processing.core.PApplet;
import processing.core.PGraphics;
import processing.opengl.PShader;

public class BaseFilter {

	protected PShader shader;

	public BaseFilter(PApplet p, String shaderFilePath) {
		shader = p.loadShader(FileUtil.getFile(shaderFilePath));
		setTime(0);
	}

	public void applyTo(PGraphics pg) {
		pg.filter(shader);
	}

	public void applyTo(PApplet p) {
		p.filter(shader);
	}

	public void setTime(float time) {
		shader.set("time", time);
	}

}

package com.haxademic.core.image.filters.shaders;

import com.haxademic.core.system.FileUtil;

import processing.core.PApplet;
import processing.core.PGraphics;
import processing.opengl.PShader;

public class BaseFilter {

	protected PShader shader;
	protected float time;

	public BaseFilter(PApplet p, String shaderFilePath) {
		shader = p.loadShader(FileUtil.getFile(shaderFilePath));
		setTime(0);
	}

	public void applyTo(PGraphics pg) {
		pg.filter(shader);
	}

	public void applyTo(PApplet p) {
		p.filter(shader);
	}

	public void setTime(float time) {
		this.time = time;
		shader.set("time", time);
	}

	public float getTime() {
		return time;
	}

}

Add time to all shaders, since most of them need it


package org.graphstream.gama.extension;

import msi.gama.common.interfaces.IKeyword;

public class IKeywordGSAdditional implements IKeyword {
	// New commands

	public static final String ADD = "gs_add";
	public static final String ADD_ATTRIBUTE = "gs_add_attribute";
	public static final String ADD_SENDER = "gs_add_sender";
	public static final String CLEAR = "gs_clear";
	public static final String CLEAR_SENDERS = "gs_clear_senders";
	public static final String REMOVE = "gs_remove";
	public static final String REMOVE_ATTRIBUTE = "gs_remove_attribute";
	public static final String STEP = "gs_step";

	// Facets associated to a command

	public static final String SENDERID = "gs_sender_id";
	public static final String STEP_NUMBER = "gs_step_number";

}

package org.graphstream.gama.extension;

import msi.gama.common.interfaces.IKeyword;

public class IKeywordGSAdditional implements IKeyword {
	// New commands

	public static final String ADD_EDGE = "gs_add_edge";
	public static final String ADD_EDGE_ATTRIBUTE = "gs_add_edge_attribute";
	public static final String ADD_NODE = "gs_add_node";
	public static final String ADD_NODE_ATTRIBUTE = "gs_add_node_attribute";
	public static final String ADD_SENDER = "gs_add_sender";
	public static final String CLEAR = "gs_clear";
	public static final String CLEAR_SENDERS = "gs_clear_senders";
	public static final String REMOVE_EDGE = "gs_remove_edge";
	public static final String REMOVE_EDGE_ATTRIBUTE = "gs_remove_edge_attribute";
	public static final String REMOVE_NODE = "gs_remove_node";
	public static final String REMOVE_NODE_ATTRIBUTE = "gs_remove_node_attribute";
	public static final String STEP = "gs_step";

	// Facets associated to a command

	public static final String ATTRIBUTE_NAME = "gs_attribute_name";
	public static final String ATTRIBUTE_VALUE = "gs_attribute_value";
	public static final String EDGE_ID = "gs_edge_id";
	public static final String HOST = "gs_host";
	public static final String NODE_ID = "gs_node_id";
	public static final String PORT = "gs_port";
	public static final String SENDERID = "gs_sender_id";
	public static final String STEP_NUMBER = "gs_step_number";

}

Update with new commands and new facets


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

/**
 * Represents a {@code org.apache.sling.spi.resource.provider.ResourceProvider}.
 */
public class ResourceProviderDTO {

    /**
	 * The name of the resource provider.
	 * Optional might be null.
	 */
	public String name;

    /**
     * The path of the resource provider.
     */
    public String path;

    /**
     * Whether resource access security should be used.
     */
    public boolean useResourceAccessSecurity;

    /**
     * The auth handling for this provider.
     */
    public AuthType authType;

    /**
     * Whether the resource provider supports modifications.
     */
    public boolean modifiable;

    /**
     * The service id from the service registry.
     */
    public int serviceId;
}

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

/**
 * Represents a {@code org.apache.sling.spi.resource.provider.ResourceProvider}.
 */
public class ResourceProviderDTO {

    /**
	 * The name of the resource provider.
	 * Optional might be null.
	 */
	public String name;

    /**
     * The path of the resource provider.
     */
    public String path;

    /**
     * Whether resource access security should be used.
     */
    public boolean useResourceAccessSecurity;

    /**
     * The auth handling for this provider.
     */
    public AuthType authType;

    /**
     * Whether the resource provider supports modifications.
     */
    public boolean modifiable;

    /**
     * The service id from the service registry.
     */
    public long serviceId;
}

Use long for service id


package io.github.ibuildthecloud.gdapi.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ProxyUtils {

    @SuppressWarnings("unchecked")
    public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
        final Object obj = new Object();

        return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getDeclaringClass() == Object.class) {
                    return method.invoke(obj, args);
                }

                if (method.getName().startsWith("get")) {
                    String name = StringUtils.uncapitalize(method.getName().substring(3));
                    Object val = map.get(name);
                    if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
                        return ((Long)val).intValue();
                    }
                    return val;
                }

                if (method.getName().startsWith("set") && args.length == 1) {
                    String name = StringUtils.uncapitalize(method.getName().substring(3));
                    map.put(name, args[0]);
                }

                return null;
            }
        });
    }
}

package io.github.ibuildthecloud.gdapi.util;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ProxyUtils {

    @SuppressWarnings("unchecked")
    public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) {
        final Object obj = new Object();

        return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() {
            @SuppressWarnings("rawtypes")
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getDeclaringClass() == Object.class) {
                    return method.invoke(obj, args);
                }

                if (method.getName().startsWith("get")) {
                    String name = StringUtils.uncapitalize(method.getName().substring(3));
                    Object val = map.get(name);
                    if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) {
                        return ((Long)val).intValue();
                    }
                    if (val instanceof String && method.getReturnType().isEnum()) {
                        return Enum.valueOf((Class<? extends Enum>)method.getReturnType(), val.toString());
                    }
                    return val;
                }

                if (method.getName().startsWith("set") && args.length == 1) {
                    String name = StringUtils.uncapitalize(method.getName().substring(3));
                    map.put(name, args[0]);
                }

                return null;
            }
        });
    }
}

Support enums in proxying request objects


package com.infinityraider.agricraft.content.core;

import com.infinityraider.agricraft.reference.Names;
import com.infinityraider.infinitylib.item.ItemBase;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.tileentity.AbstractFurnaceTileEntity;

public class ItemAgriNugget extends ItemBase {
    public ItemAgriNugget(String name) {
        super(Names.Items.NUGGET + "_" + name, new Properties().group(ItemGroup.MATERIALS));
    }

    public static class Burnable extends ItemAgriNugget {
        public Burnable(String name) {
            super(name);
        }

        @Override
        @SuppressWarnings("deprecation")
        public int getBurnTime(ItemStack itemStack) {
            return AbstractFurnaceTileEntity.getBurnTimes().get(Items.COAL)/9;
        }

    }
}

package com.infinityraider.agricraft.content.core;

import com.infinityraider.agricraft.reference.Names;
import com.infinityraider.infinitylib.item.ItemBase;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraftforge.common.ForgeHooks;

public class ItemAgriNugget extends ItemBase {
    public ItemAgriNugget(String name) {
        super(Names.Items.NUGGET + "_" + name, new Properties().group(ItemGroup.MATERIALS));
    }

    public static class Burnable extends ItemAgriNugget {
        private static final ItemStack REFERENCE = new ItemStack(Items.COAL, 1);
        public Burnable(String name) {
            super(name);
        }

        @Override
        public int getBurnTime(ItemStack itemStack) {
            return ForgeHooks.getBurnTime(REFERENCE) / 9;
        }
    }
}

Make coal nugget burn time pass through the Forge hook


// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>
// All rights reserved.

package com.barvoy.sensorama;

public class SRAPIPerms {
    public static final String parseAPIID = "PARSE_API_ID";
    public static final String parseCLIID = "PARSE_CLIENT_ID";
}

// Copyright (c) 2015, Wojciech Adam Koszek <wojciech@koszek.com>
// All rights reserved.

package com.barvoy.sensorama;

public class SRAPIPerms {
    public static final String parseAPIID = "UNUSED_PARSE_API_ID";
    public static final String parseCLIID = "UNUSED_PARSE_CLIENT_ID";
}

Mark this file as unused for now.


package org.jboss.loom.migrators._ext;

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.conf.GlobalConfiguration;
import org.jboss.loom.utils.Utils;
import org.junit.Test;

/**
 *
 * @author Ondrej Zizka, ozizka at redhat.com
 */
public class ExternalMigratorsLoaderTest {

    public ExternalMigratorsLoaderTest() {
    }

    @Test
    public void testLoadMigrators() throws Exception {
        System.out.println( "loadMigrators" );

        File workDir = new File("target/extMigrators/");
        FileUtils.forceMkdir( workDir );
        Utils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir );
        Utils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy",  workDir );

        new ExternalMigratorsLoader().loadMigrators( workDir, new GlobalConfiguration() );
    }

}// class

package org.jboss.loom.migrators._ext;

import java.io.File;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.conf.GlobalConfiguration;
import org.jboss.loom.utils.Utils;
import org.junit.Test;

/**
 *
 * @author Ondrej Zizka, ozizka at redhat.com
 */
public class ExternalMigratorsLoaderTest {

    public ExternalMigratorsLoaderTest() {
    }

    @Test
    public void testLoadMigrators() throws Exception {
        System.out.println( "loadMigrators" );

        File workDir = new File("target/extMigrators/");
        FileUtils.forceMkdir( workDir );
        Utils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir );
        Utils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy",  workDir );

        Map<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> migs
                = new ExternalMigratorsLoader().loadMigrators( workDir, new GlobalConfiguration() );

        for( Map.Entry<Class<? extends DefinitionBasedMigrator>, DefinitionBasedMigrator> entry : migs.entrySet() ) {
            Class<? extends DefinitionBasedMigrator> cls = entry.getKey();
            DefinitionBasedMigrator mig = entry.getValue();
            System.out.println( String.format("  Loaded migrator %s: %s", cls.getName(), mig.toString() ) );
        }
    }

}// class

Improve ext migr loading test


package de.otto.edison.jobs.service;

import de.otto.edison.jobs.definition.JobDefinition;
import de.otto.edison.jobs.eventbus.JobEventPublisher;

/**
 * The executable part of a Job that is executing background tasks in Edison microservices.
 *
 * @author Guido Steinacker
 * @since 15.02.15
 */
public interface JobRunnable {

    /**
     * Returns the definition of the job, specifying when a job should be executed.
     *
     * @return JobDefinition
     */
    JobDefinition getJobDefinition();

    /**
     * Executes the background task of the job and updates the JobInfo during execution.
     *
     * @return false, if the job was skipped without doing anything, true otherwise
     */
    default boolean execute() {
        return true;
    }

    /**
     * Executes the background task of the job and updates the JobInfo during execution.
     * Inject JobEventPublisher to execute for backwards compatibility to branch 1.2.x
     *
     * @param jobEventPublisher publishes events to the event bus.
     * @return false, if the job was skipped without doing anything, true otherwise
     * @Deprecated use execute, don't remove this method
     */
    default boolean execute(JobEventPublisher jobEventPublisher) {
        return execute();
    }

}

package de.otto.edison.jobs.service;

import de.otto.edison.jobs.definition.JobDefinition;
import de.otto.edison.jobs.eventbus.JobEventPublisher;

/**
 * The executable part of a Job that is executing background tasks in Edison microservices.
 *
 * @author Guido Steinacker
 * @since 15.02.15
 */
public interface JobRunnable {

    /**
     * Returns the definition of the job, specifying when a job should be executed.
     *
     * @return JobDefinition
     */
    JobDefinition getJobDefinition();

    /**
     * Executes the background task of the job and updates the JobInfo during execution.
     *
     * @return false, if the job was skipped without doing anything, true otherwise
     */
    default boolean execute() {
        return true;
    }

    /**
     * Executes the background task of the job and updates the JobInfo during execution.
     * Inject JobEventPublisher to execute for backwards compatibility to branch 1.2.x
     *
     * @param jobEventPublisher publishes events to the event bus.
     * @return false, if the job was skipped without doing anything, true otherwise
     * @deprecated use execute, don't remove this method
     */
    default boolean execute(JobEventPublisher jobEventPublisher) {
        return execute();
    }

}

Reimplement the JobEventPublisher from Edison 1.x for backwards compatibility


package net.tropicraft.core.common.block;

import net.minecraft.block.BlockState;
import net.minecraft.block.FlowerBlock;
import net.minecraft.potion.Effect;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;

public class TropicsFlowerBlock extends FlowerBlock {

    private final VoxelShape shape;

    public TropicsFlowerBlock(Effect effect, int effectDuration, VoxelShape shape, Properties properties) {
        super(effect, effectDuration, properties);
        this.shape = shape;
    }

    @Override
    public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
        return shape;
    }
}

package net.tropicraft.core.common.block;

import net.minecraft.block.BlockState;
import net.minecraft.block.FlowerBlock;
import net.minecraft.potion.Effect;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.IBlockReader;

public class TropicsFlowerBlock extends FlowerBlock {

    private final VoxelShape shape;

    public TropicsFlowerBlock(Effect effect, int effectDuration, VoxelShape shape, Properties properties) {
        super(effect, effectDuration, properties);
        this.shape = shape;
    }

	@Override
	public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {
		Vec3d vec3d = state.getOffset(worldIn, pos);
		return shape.withOffset(vec3d.x, vec3d.y, vec3d.z);
	}
}

Fix flower block selection boxes not being offset


package org.jvirtanen.parity.net.pmd;

import org.jvirtanen.parity.net.ProtocolException;

public class PMDException extends ProtocolException {

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

}

package org.jvirtanen.parity.net.pmd;

import org.jvirtanen.parity.net.ProtocolException;

/**
 * Indicates a protocol error while handling the PMD protocol.
 */
public class PMDException extends ProtocolException {

    /**
     * Construct an instance with the specified detail message.
     *
     * @param message the detail message
     */
    public PMDException(String message) {
        super(message);
    }

}

Add documentation for PMD exception in network protocols


package cl.uchile.ing.adi.quicklooklib.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import cl.uchile.ing.adi.quicklooklib.R;

/**
 * Created by dudu on 04-01-2016.
 */
public class WebFragment extends QuicklookFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.fragment_web, container, false);
        WebView web = (WebView) v.findViewById(R.id.web_fragment);
        web.loadUrl("file://"+this.item.getPath());
        return v;
    }
}

package cl.uchile.ing.adi.quicklooklib.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;

import cl.uchile.ing.adi.quicklooklib.R;

/**
 * Created by dudu on 04-01-2016.
 */
public class WebFragment extends QuicklookFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.fragment_web, container, false);
        WebView web = (WebView) v.findViewById(R.id.web_fragment);
        web.loadUrl("file://"+this.item.getPath());
        web.getSettings().setBuiltInZoomControls(true);
        web.getSettings().setDisplayZoomControls(false);
        return v;
    }
}

Hide zoom buttons fixed (Only on android >3.0)


package com.bwssystems.HABridge.plugins.moziot;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MozIotCommandDetail {
    @SerializedName("on")
    @Expose
	private boolean on;
    @SerializedName("level")
    @Expose
	private String level;
    @SerializedName("color")
    @Expose
	private String color;

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        this.on = on;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getBody() {
        String theBody = "";

        if(level != null && level != "") {
            theBody = "{\"level\":" + level + "}";
        }
        else if(color != null && color != "") {
            theBody = "{\"color\":\"" + color + "\"}";
        } else {
            theBody = "{\"on\":" + on + "}";
        }
        return theBody;
    }
}

package com.bwssystems.HABridge.plugins.moziot;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class MozIotCommandDetail {
    @SerializedName("on")
    @Expose
	private boolean on;
    @SerializedName("level")
    @Expose
	private String level;
    @SerializedName("color")
    @Expose
	private String color;

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        this.on = on;
    }

    public String getLevel() {
        return level;
    }

    public void setLevel(String level) {
        this.level = level;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getBody() {
        String theBody = "";

        if(level != null && !"".equals(level)) {
            theBody = "{\"level\":" + level + "}";
        }
        else if(color != null && !"".equals(color)) {
            theBody = "{\"color\":\"" + color + "\"}";
        } else {
            theBody = "{\"on\":" + on + "}";
        }
        return theBody;
    }
}

Fix the bad practice "Comparison of String objects using == or !=".


/*
 * This file is part of libbluray
 * Copyright (C) 2012  libbluray
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.aacsla.bluray.online;

import org.videolan.Libbluray;
import org.videolan.Logger;

public class DeviceAttribute {
    public DeviceAttribute() {
    }

    public byte[] getDeviceBindingID() {
        byte bid[] = Libbluray.getAacsData(Libbluray.AACS_DEVICE_BINDING_ID);
        if (bid == null) {
            Logger.getLogger(DeviceAttribute.class.getName()).warning("getDeviceBindingID() failed");
        }
        return bid;
    }
}

/*
 * This file is part of libbluray
 * Copyright (C) 2012  libbluray
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 */

package com.aacsla.bluray.online;

import org.videolan.Libbluray;
import org.videolan.Logger;

public class DeviceAttribute {
    public DeviceAttribute() {
    }

    public byte[] getDeviceBindingID() {
        byte bid[] = Libbluray.getAacsData(Libbluray.AACS_DEVICE_BINDING_ID);
        if (bid == null) {
            Logger.getLogger(DeviceAttribute.class.getName()).warning("getDeviceBindingID() failed");
            return new byte[16];
        }
        return bid;
    }
}

Return empty ID instead of null


package com.github.lunatrius.core.world.chunk;

import net.minecraft.util.math.BlockPos;

import java.util.Random;

public class ChunkHelper {
    private static final Random RANDOM = new Random();

    public static boolean isSlimeChunk(final long seed, final BlockPos pos) {
        final long x = pos.getX() >> 4;
        final long z = pos.getZ() >> 4;
        RANDOM.setSeed(seed + (x * x * 4987142L) + (x * 5947611L) + (z * z * 4392871L) + (z * 389711L) ^ 987234911L);
        return RANDOM.nextInt(10) == 0;
    }
}

package com.github.lunatrius.core.world.chunk;

import net.minecraft.util.math.BlockPos;

import java.util.Random;

public class ChunkHelper {
    private static final Random RANDOM = new Random();

    public static boolean isSlimeChunk(final long seed, final BlockPos pos) {
        final int x = pos.getX() >> 4;
        final int z = pos.getZ() >> 4;
        RANDOM.setSeed(seed + (long) (x * x * 4987142) + (long) (x * 5947611) + (long) (z * z) * 4392871L + (long) (z * 389711) ^ 987234911L);
        return RANDOM.nextInt(10) == 0;
    }
}

Use the proper formula for the random seed. The coordinates are multiplied as ints and are cast to longs for the final addition.


package org.dynmap;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;

/**
 * Custom Bukkit event, corresponding to the receiving of a web-chat message from a web UI user
 *
 * This interface is Bukkit specific.
 */
public class DynmapWebChatEvent extends Event implements Cancellable {
    public static final String CUSTOM_TYPE = "org.dynmap.DynmapWebChatEvent";
    private String source;
    private String name;
    private String message;
    private boolean cancelled;
    private boolean isprocessed;

    public DynmapWebChatEvent(String source, String name, String message) {
        super(CUSTOM_TYPE);
        this.source = source;
        this.name = name;
        this.message = message;
        this.cancelled = false;
        this.isprocessed = false;
    }
    public boolean isCancelled() { return cancelled; }

    public void setCancelled(boolean cancel) { cancelled = cancel; }

    public String getSource() { return source; }

    public String getName() { return name; }

    public String getMessage() { return message; }

    /* Processed flag is used to mark message as handled by listener - if set, dynmap will not send it using broadcastMessage() */
    public boolean isProcessed() { return isprocessed; }

    public void setProcessed() { isprocessed = true; }
}

package org.dynmap;
import org.bukkit.event.Cancellable;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

/**
 * Custom Bukkit event, corresponding to the receiving of a web-chat message from a web UI user
 *
 * This interface is Bukkit specific.
 */
@SuppressWarnings("serial")
public class DynmapWebChatEvent extends Event implements Cancellable {
    public static final String CUSTOM_TYPE = "org.dynmap.DynmapWebChatEvent";
    private static final HandlerList handlers = new HandlerList();
    private String source;
    private String name;
    private String message;
    private boolean cancelled;
    private boolean isprocessed;

    public DynmapWebChatEvent(String source, String name, String message) {
        super(CUSTOM_TYPE);
        this.source = source;
        this.name = name;
        this.message = message;
        this.cancelled = false;
        this.isprocessed = false;
    }
    public boolean isCancelled() { return cancelled; }

    public void setCancelled(boolean cancel) { cancelled = cancel; }

    public String getSource() { return source; }

    public String getName() { return name; }

    public String getMessage() { return message; }

    /* Processed flag is used to mark message as handled by listener - if set, dynmap will not send it using broadcastMessage() */
    public boolean isProcessed() { return isprocessed; }

    public void setProcessed() { isprocessed = true; }

    @Override
    public HandlerList getHandlers() {
        return handlers;
    }
    public static HandlerList getHandlerList() {
        return handlers;
    }
}

Update events for 1.1 event system (breaks 1.0 compatibility)


package devopsdistilled.operp.client.abstracts;

public abstract class TaskPane extends ViewPane {

	@Override
	public abstract String toString();

}

package devopsdistilled.operp.client.abstracts;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.SwingConstants;

public abstract class TaskPane extends ViewPane {

	@Override
	public abstract String toString();

	public  Icon SetSizeForImage(ImageIcon icon){
		Image img=icon.getImage();
		BufferedImage bi=new BufferedImage(70, 60, BufferedImage.TYPE_INT_ARGB);
		Graphics g=bi.createGraphics();
		g.drawImage(img,0,0,70,60, null);
		Icon newIcon=new ImageIcon(bi);
		return newIcon;

	}

	public JButton SetButtonSize(JButton btn){
		btn.setMaximumSize(new Dimension(90, 90));
		btn.setMinimumSize(new Dimension(90,90));
		btn.setHorizontalTextPosition(SwingConstants.CENTER);
		btn.setVerticalTextPosition(SwingConstants.BOTTOM);
		btn.setFont(new Font("Arial", Font.PLAIN, 10));
		return btn;
	}

}

Add methods for imageResizing and setting button size


/*
 * Copyright 2000-2010 JetBrains s.r.o.
 *
 * 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.intellij.openapi.wm.impl.status;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.util.registry.Registry;
import org.jetbrains.annotations.NotNull;

public class AutoShowProcessPopupAction extends ToggleAction {

  @Override
  public boolean isSelected(@NotNull AnActionEvent e) {
    return Registry.is("ide.windowSystem.autoShowProcessPopup");
  }

  @Override
  public void setSelected(@NotNull AnActionEvent e, boolean state) {
    Registry.get("ide.windowSystem.autoShowProcessPopup").setValue(state);
  }
}

// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.wm.impl.status;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.DumbAwareToggleAction;
import com.intellij.openapi.util.registry.Registry;
import org.jetbrains.annotations.NotNull;

public class AutoShowProcessPopupAction extends DumbAwareToggleAction {
  @Override
  public boolean isSelected(@NotNull AnActionEvent e) {
    return Registry.is("ide.windowSystem.autoShowProcessPopup");
  }

  @Override
  public void setSelected(@NotNull AnActionEvent e, boolean state) {
    Registry.get("ide.windowSystem.autoShowProcessPopup").setValue(state);
  }
}

Make auto-show background tasks action dumb aware


/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2021 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.studio.db.repo;

import com.axelor.inject.Beans;
import com.axelor.studio.db.SelectionBuilder;
import com.axelor.studio.service.builder.SelectionBuilderService;

public class SelectionBuilderRepo extends SelectionBuilderRepository {

  @Override
  public SelectionBuilder save(SelectionBuilder selectionBuilder) {

    Beans.get(SelectionBuilderService.class).build(selectionBuilder);

    return super.save(selectionBuilder);
  }

  @Override
  public void remove(SelectionBuilder selectionBuilder) {

    Beans.get(SelectionBuilderService.class)
        .removeSelection(null, SelectionBuilderService.SELECTION_PREFIX + selectionBuilder.getId());

    super.remove(selectionBuilder);
  }
}

/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2021 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.axelor.studio.db.repo;

import com.axelor.inject.Beans;
import com.axelor.studio.db.SelectionBuilder;
import com.axelor.studio.service.builder.SelectionBuilderService;

public class SelectionBuilderRepo extends SelectionBuilderRepository {

  @Override
  public SelectionBuilder save(SelectionBuilder selectionBuilder) {

    Beans.get(SelectionBuilderService.class).build(selectionBuilder);

    return super.save(selectionBuilder);
  }

  @Override
  public void remove(SelectionBuilder selectionBuilder) {

    Beans.get(SelectionBuilderService.class)
        .removeSelection(null, SelectionBuilderService.SELECTION_PREFIX + selectionBuilder.getName().replace(" ", "-"));

    super.remove(selectionBuilder);
  }
}

Fix removal of selection builder


package org.gluu.oxauth.ws.rs.controller;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Health check controller
 *
 * @author Yuriy Movchan
 * @version Jul 24, 2020
 */
@ApplicationScoped
@Path("/")
public class HealthCheckController {

    @GET
    @POST
    @Path("/health-check")
    @Produces(MediaType.APPLICATION_JSON)
	public String healthCheckController() {
        return "{\"status\":\"running\"}";
	}

}

package org.gluu.oxauth.ws.rs.controller;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.gluu.persist.PersistenceEntryManager;

/**
 * Health check controller
 *
 * @author Yuriy Movchan
 * @version Jul 24, 2020
 */
@ApplicationScoped
@Path("/")
public class HealthCheckController {

	@Inject
	private PersistenceEntryManager persistenceEntryManager;

    @GET
    @POST
    @Path("/health-check")
    @Produces(MediaType.APPLICATION_JSON)
	public String healthCheckController() {
    	boolean isConnected = persistenceEntryManager.getOperationService().isConnected();
    	String dbStatus = isConnected ? "online" : "offline";
        return "{\"status\": \"running\", \"db_status\":\"" + dbStatus + "\"}";
	}

}

Add db status to health check


package au.gov.ga.geodesy.domain.service;

import org.springframework.stereotype.Component;

import au.gov.ga.geodesy.domain.model.event.Event;
import au.gov.ga.geodesy.domain.model.event.SiteLogReceived;

@Component
public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> {

    @Override
    public boolean canHandle(Event e) {
        return e instanceof SiteLogReceived;
    }
}

package au.gov.ga.geodesy.domain.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

import au.gov.ga.geodesy.domain.model.event.Event;
import au.gov.ga.geodesy.domain.model.event.SiteLogReceived;
import au.gov.ga.geodesy.port.Notification;

@Component
public class SiteLogReceivedNotificationService extends EventNotificationService<SiteLogReceived> {

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

    private ObjectMapper filteredJson;

    @Override
    public boolean canHandle(Event e) {
        return e instanceof SiteLogReceived;
    }

    @JsonFilter("excludeSiteLogText")
    public static class SiteLogReceivedFiltered {}

    public SiteLogReceivedNotificationService() {
        super();
        this.filteredJson = json.copy();

        FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("excludeSiteLogText",
                       SimpleBeanPropertyFilter.serializeAllExcept("siteLogText"));

        filteredJson.addMixIn(SiteLogReceived.class, SiteLogReceivedFiltered.class);
        filteredJson.setFilterProvider(filterProvider);
    }

    @Override
    protected Notification toNotification(SiteLogReceived event) {
        return new Notification() {

            public String getSubject() {
                return event.getName();
            }

            public String getBody() {
                try {
                    StringBuilder body = new StringBuilder();
                    body.append(filteredJson.writeValueAsString(event));
                    return body.toString();
                } catch (JsonProcessingException e) {
                    String errorMessage = "Failed to serialise event with id " + event.getId();
                    log.error(errorMessage, e);
                    return errorMessage;
                }
            }
        };
    }
}

Drop siteLogText from SiteLogReceived SNS msg