package org.tearsofaunicorn.auspost.domestic.postcode.search.model;

import org.junit.Test;

import static org.junit.Assert.*;

/**
 * _TODO:_ Write summary
 */
public class SearchRequestTest {

    @Test
    public void testQuery() throws Exception {
        Assert.fail("Implement test");

    }

    @Test
    public void testSetState() throws Exception {
        Assert.fail("Implement test");

    }

    @Test
    public void testExcludePostBoxes() throws Exception {
        Assert.fail("Implement test");

    }

    @Test
    public void testBuildUrl() throws Exception {
        Assert.fail("Implement test");

    }
}

package org.tearsofaunicorn.auspost.domestic.postcode.search.model;

import org.junit.Assert;
import org.junit.Test;

public class SearchRequestTest {

    @Test
    public void testQuery() throws Exception {
        String request = new SearchRequest("apiKey", "http://test.com").query("query").buildUrl();
        Assert.assertTrue(request.contains("q=query"));
    }

    @Test
    public void testSetState() throws Exception {
        String request = new SearchRequest("apiKey", "http://test.com").setState(AustralianState.WA).buildUrl();
        Assert.assertTrue(request.contains("state=WA"));
    }

    @Test
    public void testExcludePostBoxes() throws Exception {
        String request = new SearchRequest("apiKey", "http://test.com").excludePostBoxes(true).buildUrl();
        Assert.assertTrue(request.contains("excludePostBoxFlag=true"));
    }

}

Add test for building search requests

Add test for building search requests


package ro.pub.cs.vmchecker.client.service.json;

import ro.pub.cs.vmchecker.client.model.AuthenticationResponse;
import ro.pub.cs.vmchecker.client.model.User;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

public class AuthenticationResponseDecoder implements JSONDecoder<AuthenticationResponse> {

	public static final String statusKey = "status";
	public static final String usernameKey = "username";
	public static final String useridKey = "userid";
	public static final String infoKey = "info";

	@Override
	public AuthenticationResponse decode(String text) throws Exception {
		JSONValue jsonValue = JSONParser.parse(text);
		JSONObject jsonObj = jsonValue.isObject();

		boolean status = jsonObj.get(statusKey).isBoolean().booleanValue();
		String info = jsonObj.get(infoKey).isString().stringValue();
		if (!status) {
			/*
			 * Authentication failed.
			 */
			return new AuthenticationResponse(status, null, info);
		}

		String username = jsonObj.get(usernameKey).isString().stringValue();
		String userid = jsonObj.get(useridKey).isString().stringValue();
		return new AuthenticationResponse(status, new User(userid, username), info);
	}

}

package ro.pub.cs.vmchecker.client.service.json;

import ro.pub.cs.vmchecker.client.model.AuthenticationResponse;
import ro.pub.cs.vmchecker.client.model.User;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

public class AuthenticationResponseDecoder implements JSONDecoder<AuthenticationResponse> {

	public static final String statusKey = "status";
	public static final String fullnameKey = "fullname";
	public static final String usernameKey = "username";
	public static final String infoKey = "info";

	@Override
	public AuthenticationResponse decode(String text) throws Exception {
		JSONValue jsonValue = JSONParser.parse(text);
		JSONObject jsonObj = jsonValue.isObject();

		boolean status = jsonObj.get(statusKey).isBoolean().booleanValue();
		String info = jsonObj.get(infoKey).isString().stringValue();
		if (!status) {
			/*
			 * Authentication failed.
			 */
			return new AuthenticationResponse(status, null, info);
		}

		String username = jsonObj.get(usernameKey).isString().stringValue();
		String fullname = jsonObj.get(fullnameKey).isString().stringValue();
		return new AuthenticationResponse(status, new User(username, fullname), info);
	}

}

gwt: Use new services.py reply format for login().


/*
 * Copyright 2016, Frederik Boster
 *
 * 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 de.syquel.bushytail.controller;

import org.apache.olingo.server.api.uri.UriParameter;

import java.util.List;

/**
 * Interface for all ODataControllers. Provides CRUD Operations.
 *
 * @author Clemens Bartz
 * @author Frederik Boster
 * @since 1.0
 *
 * @param <T> Entity which is handled by the controller.
 */
public interface IBushyTailController<T> {

    T read(List<UriParameter> keyPredicates);

    T create(T entity);

}

/*
 * Copyright 2016, Frederik Boster
 *
 * 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 de.syquel.bushytail.controller;

import org.apache.olingo.server.api.uri.UriParameter;

import java.util.List;

/**
 * Interface for all ODataControllers. Provides CRUD Operations.
 *
 * @author Clemens Bartz
 * @author Frederik Boster
 * @since 1.0
 *
 * @param <T> Entity which is handled by the controller.
 */
public interface IBushyTailController<T> {

    T read(List<UriParameter> keyPredicates);

    void create(T entity);

}

Replace T with void in create method.

Replace T with void in create method.


package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.os.service.IService;
import com.github.aureliano.achmed.types.OS;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public interface IOperatingSystem {

	public abstract Linux prototype();

	public abstract IPackageManager getDefaultPackageManager();

	public abstract IService getDefaultServiceManager();

	public abstract OS getOperatingSystem();

	public abstract OperatingSystemFamily getOperatingSystemFamily();

	public abstract String getPsCommand();

	public abstract Integer getPid(String pattern);

	public abstract CommandResponse kill(Integer pid);
}

package com.github.aureliano.achmed.os;

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.os.fs.IFileProvider;
import com.github.aureliano.achmed.os.pkg.IPackageManager;
import com.github.aureliano.achmed.os.service.IService;
import com.github.aureliano.achmed.types.OS;
import com.github.aureliano.achmed.types.OperatingSystemFamily;

public interface IOperatingSystem {

	public abstract Linux prototype();

	public abstract IPackageManager getDefaultPackageManager();

	public abstract IService getDefaultServiceManager();

	public abstract IFileProvider getDefaultFileProvider();

	public abstract OS getOperatingSystem();

	public abstract OperatingSystemFamily getOperatingSystemFamily();

	public abstract String getPsCommand();

	public abstract Integer getPid(String pattern);

	public abstract CommandResponse kill(Integer pid);
}

Add method to get default file provider.


package com.sakamichi46.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sakamichi46.model.Member;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author kikuta
 */
public abstract class AbstractSakamichi46Resource {

    protected static final ObjectMapper mapper = new ObjectMapper();

    protected Map<String, Member> memberMap;

    public abstract void init();

    @GET
    @Path("profile/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    public Member getProfile(@PathParam("name") String name) {
        return memberMap.get(name);
    }

    @GET
    @Path("profile/all")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Member> getAllProfiles() {
        return memberMap.values().stream().collect(Collectors.toList());
    }

    @GET
    @Path("member/count")
    @Produces(MediaType.TEXT_PLAIN)
    public int getMemberCount() {
        return memberMap.values().size();
    }
}

package com.sakamichi46.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sakamichi46.model.Member;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 *
 * @author kikuta
 */
public abstract class AbstractSakamichi46Resource {

    protected static final ObjectMapper mapper = new ObjectMapper();

    protected Map<String, Member> memberMap;

    public abstract void init();

    @GET
    @Path("profile/{name}")
    @Produces(MediaType.APPLICATION_JSON)
    public Member getProfile(@PathParam("name") String name) {
        return memberMap.get(name);
    }

    @GET
    @Path("profile")
    @Produces(MediaType.APPLICATION_JSON)
    public List<Member> getAllProfiles() {
        return memberMap.values().stream().collect(Collectors.toList());
    }

    @GET
    @Path("count")
    @Produces(MediaType.TEXT_PLAIN)
    public int getMemberCount() {
        return memberMap.values().size();
    }
}

Change url path for simplifying

Change url path for simplifying


/* This file is part of MusicalRegions for Bukkit, licensed under the MIT License (MIT).
 *
 * Copyright (c) JCThePants (www.jcwhatever.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.language.LanguageManager;
import com.jcwhatever.bukkit.generic.language.Localized;

public class Lang {
    private Lang() {}

    private static LanguageManager _languageManager = new LanguageManager();

    @Localized
    public static String get(String text, Object... params) {
        return _languageManager.get(MusicalRegions.getInstance(), text, params);
    }
}

/* This file is part of MusicalRegions for Bukkit, licensed under the MIT License (MIT).
 *
 * Copyright (c) JCThePants (www.jcwhatever.com)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.jcwhatever.bukkit.musical;

import com.jcwhatever.bukkit.generic.language.Localized;

public class Lang {
    private Lang() {}

    @Localized
    public static String get(String text, Object... params) {
        return MusicalRegions.getInstance().getLanguageManager().get(text, params);
    }
}

Implement localization and fix existing localization to match changes


/* © 2012 David Given
 * This file is made available under the terms of the two-clause BSD
 * license. See the file COPYING in the distribution directory for the
 * full license text.
 */

package com.cowlark.cowbel.parser.parsers;

import com.cowlark.cowbel.parser.core.Location;
import com.cowlark.cowbel.parser.core.ParseResult;

public class ArgumentListParser extends Parser
{
	@Override
	protected ParseResult parseImpl(Location location)
	{
		ParseResult pr = OpenParenthesisParser.parse(location);
		if (pr.failed())
			return pr;

		ParseResult argumentspr = ExpressionListParser.parse(pr.end());
		if (argumentspr.failed())
			return argumentspr;

		pr = CloseParenthesisParser.parse(pr.end());
		if (pr.failed())
			return pr;

		/* Very nasty */
		argumentspr.setEnd(pr.end());
		return argumentspr;
	}
}

/* © 2012 David Given
 * This file is made available under the terms of the two-clause BSD
 * license. See the file COPYING in the distribution directory for the
 * full license text.
 */

package com.cowlark.cowbel.parser.parsers;

import com.cowlark.cowbel.parser.core.Location;
import com.cowlark.cowbel.parser.core.ParseResult;

public class ArgumentListParser extends Parser
{
	@Override
	protected ParseResult parseImpl(Location location)
	{
		ParseResult pr = OpenParenthesisParser.parse(location);
		if (pr.failed())
			return pr;

		ParseResult argumentspr = ExpressionListParser.parse(pr.end());
		if (argumentspr.failed())
			return argumentspr;

		pr = CloseParenthesisParser.parse(argumentspr.end());
		if (pr.failed())
			return pr;

		/* Very nasty */
		argumentspr.setEnd(pr.end());
		return argumentspr;
	}
}

Fix silly bug where non-empty argument lists didn't work.


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.util.registry.ClientRegistry;
import info.u_team.u_team_test.entity.render.TestLivingEntityRenderer;
import net.minecraft.client.renderer.entity.ThrownItemRenderer;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;

public class TestRenderers {

	private static void setup(FMLClientSetupEvent event) {
		ClientRegistry.registerEntityRenderer(TestEntityTypes.BETTER_ENDERPEARL, ThrownItemRenderer::new);
		ClientRegistry.registerEntityRenderer(TestEntityTypes.TEST_LIVING, TestLivingEntityRenderer::new);
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestRenderers::setup);
	}
}

package info.u_team.u_team_test.init;

import info.u_team.u_team_test.entity.render.TestLivingEntityRenderer;
import net.minecraft.client.renderer.entity.ThrownItemRenderer;
import net.minecraftforge.client.event.EntityRenderersEvent.RegisterRenderers;
import net.minecraftforge.eventbus.api.IEventBus;

public class TestRenderers {

	private static void registerRenderers(RegisterRenderers event) {
		event.registerEntityRenderer(TestEntityTypes.BETTER_ENDERPEARL.get(), ThrownItemRenderer::new);
		event.registerEntityRenderer(TestEntityTypes.TEST_LIVING.get(), TestLivingEntityRenderer::new);
	}

	public static void registerMod(IEventBus bus) {
		bus.addListener(TestRenderers::registerRenderers);
	}
}

Update entity renderer to use the new events


package com.github.gabrielruiu.spring.cloud.config.redis;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Map;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseRedisEnvironmentRepositoryTest {

    @LocalServerPort
    int port;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TestRestTemplate testRestTemplate;

    protected void injectPropertiesIntoRedis(Map<String, String> properties) {
        for (Map.Entry<String, String> propertyEntry : properties.entrySet()) {
            stringRedisTemplate.opsForValue().set(propertyEntry.getKey(), propertyEntry.getValue());
        }
    }
}

package com.github.gabrielruiu.spring.cloud.config.redis;

import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Map;
import java.util.Set;

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public abstract class BaseRedisEnvironmentRepositoryTest {

    @LocalServerPort
    int port;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    TestRestTemplate testRestTemplate;

    @Before
    public void cleanUpRedis() {
        Set<String> keys = stringRedisTemplate.keys("*");
        stringRedisTemplate.delete(keys);
    }

    protected void injectPropertiesIntoRedis(Map<String, String> properties) {
        for (Map.Entry<String, String> propertyEntry : properties.entrySet()) {
            stringRedisTemplate.opsForValue().set(propertyEntry.getKey(), propertyEntry.getValue());
        }
    }
}

Add @Before method so that all extending tests cleanup the Redis database before executing This makes sure we work starting from an empty database


/*
 */
package org.datadryad.rest.servlet;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import org.dspace.core.ConfigurationManager;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class DryadAPIServletContainer extends ServletContainer {
    private final static Logger log = Logger.getLogger(DryadAPIServletContainer.class);
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        log.info("initializing DryadAPIServletContainer - loading dspace config");
        String configFile = config.getServletContext().getInitParameter("dspace.config");
        ConfigurationManager.loadConfig(configFile);
        log.info("initialized DryadAPIServletContainer");
    }
}

/*
 */
package org.datadryad.rest.servlet;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import org.dspace.core.ConfigurationManager;

/**
 *
 * @author Dan Leehr <dan.leehr@nescent.org>
 */
public class DryadAPIServletContainer extends ServletContainer {
    private final static Logger log = Logger.getLogger(DryadAPIServletContainer.class);
    @Override
    public void init(ServletConfig config) throws ServletException {
        log.info("initializing DryadAPIServletContainer - loading dspace config");
        String configFile = config.getServletContext().getInitParameter("dspace.config");
        ConfigurationManager.loadConfig(configFile);
        log.info("initialized DryadAPIServletContainer");
        // Must load configFile before initializing, some singletons depend on
        // configured DSpace
        super.init(config);
    }
}

Load dspace configFile before calling super.init()

Prevents singletons from being initialized before DSpace config is
available


package uk.ac.ebi.quickgo.annotation.service.search;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields;
import uk.ac.ebi.quickgo.common.SearchableDocumentFields;
import uk.ac.ebi.quickgo.rest.search.SearchableField;

import java.util.stream.Stream;
import org.springframework.stereotype.Component;

/**
 * Checks if a given field is searchable searchable.
 *
 * @author Ricardo Antunes
 */
@Component
public class AnnotationSearchableField implements SearchableField, SearchableDocumentFields {
    @Override public boolean isDocumentSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }

    @Override public Stream<String> searchableDocumentFields() {
        return AnnotationFields.Searchable.searchableFields().stream();
    }

    @Override public boolean isSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }
}

package uk.ac.ebi.quickgo.annotation.service.search;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields;
import uk.ac.ebi.quickgo.common.SearchableDocumentFields;
import uk.ac.ebi.quickgo.rest.search.SearchableField;

import java.util.stream.Stream;
import org.springframework.stereotype.Component;

/**
 * Checks if a given field is searchable.
 *
 * @author Ricardo Antunes
 */
@Component
public class AnnotationSearchableField implements SearchableField, SearchableDocumentFields {
    @Override public boolean isDocumentSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }

    @Override public Stream<String> searchableDocumentFields() {
        return AnnotationFields.Searchable.searchableFields().stream();
    }

    @Override public boolean isSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }
}

Remove duplicate word "searchable" in class Javadoc.


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

package com.github.mkjensen.tv.util;

import com.crashlytics.android.Crashlytics;

import timber.log.Timber;

public class CrashlyticsTimberTree extends Timber.Tree {

  private static final String PRIORITY_KEY = "priority";

  private static final String TAG_KEY = "tag";

  private static final String MESSAGE_KEY = "message";

  @Override
  protected void log(int priority, String tag, String message, Throwable throwable) {

    if (priority < android.util.Log.WARN) {
      return;
    }

    Crashlytics.setInt(PRIORITY_KEY, priority);
    Crashlytics.setString(TAG_KEY, tag);
    Crashlytics.setString(MESSAGE_KEY, message);

    if (throwable == null) {
      Crashlytics.logException(new Exception(message));
    } else {
      Crashlytics.logException(throwable);
    }
  }
}

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

package com.github.mkjensen.tv.util;

import android.support.annotation.NonNull;

import com.crashlytics.android.Crashlytics;

import timber.log.Timber;

public class CrashlyticsTimberTree extends Timber.Tree {

  private static final String PRIORITY_KEY = "priority";

  private static final String TAG_KEY = "tag";

  private static final String MESSAGE_KEY = "message";

  @Override
  protected void log(int priority, String tag, @NonNull String message, Throwable throwable) {

    if (priority < android.util.Log.WARN) {
      return;
    }

    Crashlytics.setInt(PRIORITY_KEY, priority);
    Crashlytics.setString(TAG_KEY, tag);
    Crashlytics.setString(MESSAGE_KEY, message);

    if (throwable == null) {
      Crashlytics.logException(new Exception(message));
    } else {
      Crashlytics.logException(throwable);
    }
  }
}

Add @NonNull to message parameter of overridden method log


/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zephyr;

import com.edinarobotics.utils.gamepad.Gamepad;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.SimpleRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the SimpleRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zephyr extends SimpleRobot {
    /**
     * This function is called once each time the robot enters autonomous mode.
     */
    public void autonomous() {

    }

    /**
     * This function is called once each time the robot enters operator control.
     */
    public void operatorControl() {
        Gamepad gamepad1 = new Gamepad(1);
        Components components = Components.getInstance();
        while(this.isOperatorControl()&&this.isEnabled()){
           components.leftJaguar.set(gamepad1.getLeftY());
           components.rightJaguar.set(gamepad1.getRightY());
        }
        components.leftJaguar.set(0);
        components.rightJaguar.set(0);
    }
}

/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zephyr;

import com.edinarobotics.utils.gamepad.Gamepad;
import edu.wpi.first.wpilibj.SimpleRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the SimpleRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zephyr extends SimpleRobot {
    /**
     * This function is called once each time the robot enters autonomous mode.
     */
    public void autonomous() {

    }

    /**
     * This function is called once each time the robot enters operator control.
     */
    public void operatorControl() {
        Gamepad gamepad1 = new Gamepad(1);
        Components components = Components.getInstance();
        while(this.isOperatorControl()&&this.isEnabled()){
           components.leftJaguar.set(gamepad1.getLeftY());
           components.rightJaguar.set(gamepad1.getRightY());
        }
        components.leftJaguar.set(0);
        components.rightJaguar.set(0);
    }
}

Remove unused Joystick import from the main robot class.


package com.example.beer.dao;

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

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

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

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

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

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

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

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

package com.example.beer.dao;

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

import com.example.beer.model.Project;

@Singleton
public class ProjectDAO {

	@PersistenceContext
	private EntityManager em;

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

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

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

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

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

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

Add boolean return value to addProject

Add boolean return value to addProject


// Copyright 2011 Google Inc. All Rights Reserved.

package org.cachebench;

import org.cachebench.reportgenerators.CsvStatisticReportGenerator;

import java.io.File;

/**
 * An extension of the report generator to simplify the file name.
 *
 * @author bmanes@google.com (Ben Manes)
 */
public final class CustomCsvStatisticReportGenerator extends CsvStatisticReportGenerator {

  @Override public void setOutputFile(String fileName) {
    if ("-generic-".equals(fileName)) {
      String type = System.getProperty("cacheBenchFwk.cache.type");
      String run = System.getProperty("cacheBenchFwk.cache.run");
      this.output = new File(type + (run == null ? "" : "-" + run) + ".csv");
    } else {
      super.setOutputFile(fileName);
    }
  }
}

// Copyright 2011 Google Inc. All Rights Reserved.

package org.cachebench;

import static com.google.common.base.Strings.emptyToNull;

import org.cachebench.reportgenerators.CsvStatisticReportGenerator;

import java.io.File;

/**
 * An extension of the report generator to simplify the file name.
 *
 * @author bmanes@google.com (Ben Manes)
 */
public final class CustomCsvStatisticReportGenerator extends CsvStatisticReportGenerator {

  @Override public void setOutputFile(String fileName) {
    if ("-generic-".equals(fileName)) {
      String type = System.getProperty("cacheBenchFwk.cache.type");
      String run = emptyToNull(System.getProperty("cacheBenchFwk.cache.run"));
      this.output = new File(type + (run == null ? "" : "-" + run) + ".csv");
    } else {
      super.setOutputFile(fileName);
    }
  }
}

Fix to remove '-' when no run specified

Fix to remove '-' when no run specified

git-svn-id: 907e4e34b61c8b36c3c46852ca75613c7936718f@672 52670e78-85c4-11dd-9ffd-cdf95c2cae98


import org.junit.*;

import play.test.*;
import play.libs.F.*;

import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;

public class IntegrationTest {

    /**
     * add your integration test here
     * in this example we just check if the welcome page is being shown
     */
    @Test
    public void test() {
        running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new Callback<TestBrowser>() {
            public void invoke(TestBrowser browser) {
                browser.goTo("http://localhost:3333");
                assertThat(browser.pageSource()).contains("Your new application is ready.");
            }
        });
    }

}

import org.junit.*;

import play.test.*;
import play.libs.F.*;

import static play.test.Helpers.*;
import static org.fest.assertions.Assertions.*;

public class IntegrationTest {

    /**
     * Add your integration tests here.
     * In this example we just check if the home page is being shown.
     */
    @Test
    public void test() {
        running(
            testServer(3333, fakeApplication(inMemoryDatabase())),
            HTMLUNIT, new Callback<TestBrowser>() {
            public void invoke(TestBrowser browser) {
                browser.goTo("http://localhost:3333");
                assertThat(
                    browser.pageSource()).contains("Hi! This is Ode.");
            }
        });
    }

}

Make example integration test pass.

Make example integration test pass.


package net.stickycode.stereotype.resource;

import net.stickycode.stereotype.ConfiguredComponent;

/**
 * Interface used to mark of point where an external resource should be injected.
 *
 *

 * @Configured
 * private Resource<String> helpText;
 *
 * @Configured
 * private Resource<Properties> decodeMappings;
 *
 *

 */
@ConfiguredComponent
public interface Resource<T> {

  /**
   * Return the current value of the resource, depending on the nature of the resource
   * this could be a fixed value or change on every call.
   *
   *
e.g.

   *

   *
A string from the classpath might be fixed for the lifetime of the application.

   *
A Properties resource loaded from a file might change each time its updated

   *

   */
  T get();

  /**
   * Update the underlying resource with the new value
   */
  void set(T value);

}

package net.stickycode.resource.stereotype;

import net.stickycode.stereotype.ConfiguredComponent;

/**
 * Interface used to mark of point where an external resource should be injected.
 *
 *

 * @Configured
 * private Resource<String> helpText;
 *
 * @Configured
 * private Resource<Properties> decodeMappings;
 *
 *

 */
@ConfiguredComponent
public interface Resource<T> {

  /**
   * Return the current value of the resource, depending on the nature of the resource
   * this could be a fixed value or change on every call.
   *
   *
e.g.

   *

   *
A string from the classpath might be fixed for the lifetime of the application.

   *
A Properties resource loaded from a file might change each time its updated

   *

   */
  T get();

  /**
   * Update the underlying resource with the new value
   */
  void set(T value);

}

Move the package as well as the group

Move the package as well as the group


/*module io.xlate.validation {
    exports io.xlate.validation.constraints;

    requires jakarta.el.api;
    requires java.instrument;
    requires java.logging;
    requires java.management;
    requires java.naming;
    requires java.prefs;
    requires java.sql;
    requires java.sql.rowset;
    requires java.validation;
}*/

/*module io.xlate.validation {
    exports io.xlate.validation.constraints;
    opens   io.xlate.validation.internal.constraintvalidators;

    requires jakarta.el.api;
    requires java.instrument;
    requires java.logging;
    requires java.management;
    requires java.naming;
    requires java.prefs;
    requires java.sql;
    requires java.sql.rowset;
    requires java.validation;
}*/

Add 'opens' for reflective access

Add 'opens' for reflective access


/*
 * Copyright (C) 2014 Red Hat, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Authors : Dave Tucker, Flavio Fernandes
 */

package org.opendaylight.ovsdb.openstack.netvirt.api;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.util.Set;
import java.util.UUID;

/**
 * A MultiTenantForwardingProvider provides Multi-Tenant L3 Forwarding
 */
public interface MultiTenantRouterForwardingProvider {

  void addStaticArpEntry(UUID tenantId, String macAddress, InetAddress ipAddress);

  void addIpRewriteRule(UUID tenantId, InetAddress matchAddress, InetAddress rewriteAddress);

  void addRouterInterface(UUID tenantId, String macAddress, Set<InterfaceAddress> addresses);

  void addForwardingTableEntry(UUID tenantId, InetAddress ipAddress, String macAddress);

  void addDefaultRouteEntry(UUID tenantId, String macAddress, InetAddress nextHop);

}

/*
 * Copyright (C) 2014 Red Hat, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 *
 * Authors : Dave Tucker, Flavio Fernandes
 */

package org.opendaylight.ovsdb.openstack.netvirt.api;

import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.utils.Status;
import org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent;

import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.util.Set;

/**
 * A MultiTenantForwardingProvider provides Multi-Tenant L3 Forwarding
 */
public interface MultiTenantRouterForwardingProvider {

    Status programStaticArpEntry(Node node, Long dpid, String segmentationId,
                                 String macAddress, InetAddress ipAddress, AbstractEvent.Action action);

    Status programIpRewriteRule(Node node, Long dpid, String segmentationId, InetAddress matchAddress,
                                InetAddress rewriteAddress, AbstractEvent.Action action);

    Status programIpRewriteExclusion(Node node, Long dpid, String segmentationId,
                                     InterfaceAddress excludedAddress, AbstractEvent.Action action);

    Status programRouterInterface(Node node, Long dpid, String segmentationId, String macAddress,
                                  Set<InterfaceAddress> addresses, AbstractEvent.Action action);

    Status programForwardingTableEntry(Node node, Long dpid, String segmentationId, InetAddress ipAddress,
                                       String macAddress, AbstractEvent.Action action);

    Status programDefaultRouteEntry(Node node, Long dpid, String segmentationId, String macAddress,
                                    InetAddress nextHop, AbstractEvent.Action action);

}

Add node and dpid information to L3 Forwarding API

Change-Id: I06186d17b3a26e262caee612d9221994adc8ca1c
Signed-off-by: Dave Tucker <38bd290b0ce167c92fc77aa50ad43e0fe89e0f98@redhat.com>


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

package org.wso2.msf4j.example;

import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * Hello service resource class.
 */
@Path("/hello")
public class HelloService {

    @GET
    @Path("/{name}")
    public String hello(@PathParam("name") String name) {
        System.out.println("Hello");
        return "Hello " + name;
    }
}

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

package org.wso2.msf4j.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * Hello service resource class.
 */
@Path("/hello")
public class HelloService {

    @GET
    @Path("/{name}")
    public String hello(@PathParam("name") String name) {
        System.out.println("Hello");
        return "Hello " + name;
    }
}

Remove unused import in HelloWorld sample


package com.camunda.bpm.demo.extension_attributes_for_user_tasks;

import java.util.Collection;
import java.util.Date;

import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;

public class EscalationStartTaskListener implements TaskListener {

	@Override
	public void notify(DelegateTask delegateTask) {
		UserTask userTask = delegateTask.getBpmnModelElementInstance();
		ExtensionElements extensionElements = userTask.getExtensionElements();
		Collection<CamundaProperty> properties = extensionElements.getElementsQuery()
			.filterByType(CamundaProperties.class)
			.singleResult()
			.getCamundaProperties();
		for (CamundaProperty property : properties) {
			if ("escalation1".equals(property.getAttributeValue("name"))) {
				delegateTask.setDueDate(new Date());
			}
		}
	}

}

package com.camunda.bpm.demo.extension_attributes_for_user_tasks;

import java.util.Collection;
import java.util.Date;

import org.camunda.bpm.engine.delegate.DelegateTask;
import org.camunda.bpm.engine.delegate.TaskListener;
import org.camunda.bpm.model.bpmn.instance.ExtensionElements;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperties;
import org.camunda.bpm.model.bpmn.instance.camunda.CamundaProperty;

public class EscalationStartTaskListener implements TaskListener {

	@Override
	public void notify(DelegateTask delegateTask) {
		UserTask userTask = delegateTask.getBpmnModelElementInstance();
		ExtensionElements extensionElements = userTask.getExtensionElements();
		Collection<CamundaProperty> properties = extensionElements.getElementsQuery()
			.filterByType(CamundaProperties.class)
			.singleResult()
			.getCamundaProperties();
		for (CamundaProperty property : properties) {
			if ("escalation1".equals(property.getAttributeValue("name"))) { // in 7.2 one can use: property.getCamundaName()
				delegateTask.setDueDate(new Date());
			}
		}
	}

}

Add hint on improved API in 7.2

Add hint on improved API in 7.2


package moe.tristan.easyfxml.util;

import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

/**
 * Small DOM-related utils for JavaFX nodes.
 */
public final class Nodes {

    private Nodes() {
    }

    /**
     * Centers a node that is inside an enclosing {@link AnchorPane}.
     *
     * @param node       The node to center
     * @param marginSize The margins to keep on the sides
     */
    public static void centerNode(final Node node, final Double marginSize) {
        AnchorPane.setTopAnchor(node, marginSize);
        AnchorPane.setBottomAnchor(node, marginSize);
        AnchorPane.setLeftAnchor(node, marginSize);
        AnchorPane.setRightAnchor(node, marginSize);
    }

}

package moe.tristan.easyfxml.util;

import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

/**
 * Small DOM-related utils for JavaFX nodes.
 */
public final class Nodes {

    private Nodes() {
    }

    /**
     * Centers a node that is inside an enclosing {@link AnchorPane}.
     *
     * @param node       The node to center
     * @param marginSize The margins to keep on the sides
     */
    public static void centerNode(final Node node, final Double marginSize) {
        AnchorPane.setTopAnchor(node, marginSize);
        AnchorPane.setBottomAnchor(node, marginSize);
        AnchorPane.setLeftAnchor(node, marginSize);
        AnchorPane.setRightAnchor(node, marginSize);
    }

    public static void hideAndResizeParentIf(
        final Node node,
        final ObservableValue<? extends Boolean> condition
    ) {
        autoresizeContainerOn(node, condition);
        bindContentBiasCalculationTo(node, condition);
    }

    public static void autoresizeContainerOn(
        final Node node,
        final ObservableValue<?> observableValue
    ) {
        observableValue.addListener((observable, oldValue, newValue) -> node.autosize());
    }

    public static void bindContentBiasCalculationTo(
        final Node node,
        final ObservableValue<? extends Boolean> observableValue
    ) {
        node.visibleProperty().bind(observableValue);
        node.managedProperty().bind(node.visibleProperty());
    }

}

Add a helper method for auto-hiding and resizing the parent of a node


package com.google.sps.data;

import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.collections4.keyvalue.MultiKey;

/*
 * Class representing one row/entry in the aggregation response.  A NULL field value
 * means the field was not being aggregated by, and will be omitted from the JSON response
 */
public final class AggregationResponseEntry {

  private String annotatedAssetId;
  private String annotatedLocation;
  private String annotatedUser;
  private final int count;
  private List<String> deviceIds;
  private List<String> serialNumbers;

  public AggregationResponseEntry(
      MultiKey key,
      List<ChromeOSDevice> devices,
      LinkedHashSet<AnnotatedField> fields) {

    String keys[] = (String[]) key.getKeys();
    int currKey = 0;

    Iterator<AnnotatedField> it = fields.iterator();
    while (it.hasNext()) {
      switch(it.next()) {
        case ASSET_ID:
          this.annotatedAssetId = keys[currKey++];
          break;
        case LOCATION:
          this.annotatedLocation = keys[currKey++];
          break;
        case USER:
          this.annotatedUser = keys[currKey++];
          break;
      }
    }

    this.count = devices.size();
    this.deviceIds = devices.stream()
        .map(device -> device.getDeviceId())
        .collect(Collectors.toList());
    this.serialNumbers = devices.stream()
        .map(device -> device.getSerialNumber())
        .collect(Collectors.toList());
  }
}

package com.google.sps.data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import org.apache.commons.collections4.keyvalue.MultiKey;

/*
 * Class representing one row/entry in the aggregation response.  A NULL field value
 * means the field was not being aggregated by, and will be omitted from the JSON response
 */
public final class AggregationResponseEntry {

  private String annotatedAssetId;
  private String annotatedLocation;
  private String annotatedUser;
  private final int count;
  private List<String> deviceIds;
  private List<String> serialNumbers;

  public AggregationResponseEntry(
      MultiKey key,
      List<ChromeOSDevice> devices,
      LinkedHashSet<AnnotatedField> fields) {

    String keys[] = (String[]) key.getKeys();
    int currKey = 0;

    Iterator<AnnotatedField> it = fields.iterator();
    while (it.hasNext()) {
      switch(it.next()) {
        case ASSET_ID:
          this.annotatedAssetId = keys[currKey++];
          break;
        case LOCATION:
          this.annotatedLocation = keys[currKey++];
          break;
        case USER:
          this.annotatedUser = keys[currKey++];
          break;
      }
    }

    this.count = devices.size();

    this.deviceIds = new ArrayList<String>();
    this.serialNumbers = new ArrayList<String>();
    for (ChromeOSDevice device : devices) {
      this.deviceIds.add(device.getDeviceId());
      this.serialNumbers.add(device.getSerialNumber());
    }
  }
}

Improve efficiency by merging two loops accessing the same data into one loop


/**
 * This file is part of Everit - Component Metadata.
 *
 * Everit - Component Metadata 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 3 of the License, or
 * (at your option) any later version.
 *
 * Everit - Component Metadata 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 Everit - Component Metadata.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.everit.osgi.ecm.metadata;

public class ServiceMetadata {

    public static class ServiceMetadataBuilder {
        private Class<?>[] clazzes;

        public ServiceMetadata build() {
            return new ServiceMetadata(clazzes);
        }

        public ServiceMetadataBuilder withClazzes(final Class<?>[] clazzes) {
            if (clazzes == null) {
                this.clazzes = null;
            } else {
                this.clazzes = clazzes.clone();
            }
            return this;
        }

    }

    private final Class<?>[] clazzes;

    private ServiceMetadata(final Class<?>[] clazzes) {
        this.clazzes = clazzes;
    }

    public Class<?>[] getClazzes() {
        if (clazzes != null) {
            return clazzes.clone();
        } else {
            return null;
        }
    }
}

/**
 * This file is part of Everit - Component Metadata.
 *
 * Everit - Component Metadata 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 3 of the License, or
 * (at your option) any later version.
 *
 * Everit - Component Metadata 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 Everit - Component Metadata.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.everit.osgi.ecm.metadata;

public class ServiceMetadata {

    public static class ServiceMetadataBuilder {
        private Class<?>[] clazzes = new Class<?>[0];

        public ServiceMetadata build() {
            return new ServiceMetadata(clazzes);
        }

        public ServiceMetadataBuilder withClazzes(final Class<?>[] clazzes) {
            if (clazzes == null) {
                throw new MetadataValidationException(
                        "Null cannot be provided as service interface array for ServiceMetadata");
            }
            this.clazzes = clazzes.clone();

            return this;
        }

    }

    private final Class<?>[] clazzes;

    private ServiceMetadata(final Class<?>[] clazzes) {
        this.clazzes = clazzes;
    }

    public Class<?>[] getClazzes() {
        if (clazzes != null) {
            return clazzes.clone();
        } else {
            return null;
        }
    }
}

Throw exception if null is provided as service interfaces array.


package com.modesteam.urutau.builder;

import com.modesteam.urutau.model.Artifact;
import com.modesteam.urutau.model.User;

public class ArtifactBuilder {
	private String title;
	private String description;

	public ArtifactBuilder title(String title){
		this.title = title;
		return this;
	}

	public ArtifactBuilder login(String description){
		this.description = description;
		return this;
	}

	public User build(){
		Generic artifact = new Generic();
		artifact.setTitle(title);
		artifact.setDescription(description);
		return artifact;
	}
}

package com.modesteam.urutau.builder;

import com.modesteam.urutau.model.Artifact;
import com.modesteam.urutau.model.Epic;
import com.modesteam.urutau.model.Feature;
import com.modesteam.urutau.model.User;

public class ArtifactBuilder {
	private String title;
	private String description;

	public ArtifactBuilder title(String title){
		this.title = title;
		return this;
	}

	public ArtifactBuilder login(String description){
		this.description = description;
		return this;
	}

	public Epic build(){
		Epic epic = new Epic();
		epic.setTitle(title);
		epic.setDescription(description);
		return epic;
	}

	public Feature buildFeature(){
		Feature feature = new Feature();
		feature.setTitle(title);
		feature.setDescription(description);
		return feature;
	}
}

Create a build for artifacts epic and feature for mock


package uk.gov.dvla.services.filter;

import uk.gov.dvla.domain.ServiceResult;
import java.util.UUID;
import java.util.HashMap;

public interface FilterService<T>
{
    public ServiceResult<T> filter(UUID id, T objectToFilter, String Context);

    public ServiceResult<T> filter(T objectToFilter, String Context);

}

package uk.gov.dvla.services.filter;

import uk.gov.dvla.domain.ServiceResult;
import java.util.UUID;

public interface FilterService<T>
{
    public ServiceResult<T> filter(UUID id, T objectToFilter, String Context);

    public ServiceResult<T> filter(T objectToFilter, String Context);

}

Fix failing tests due to test set up changes and make a start on MibResponse object to be used to restrict what is returned from the filter service


package eu.netide.lib.netip;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;

/**
 * Class representing a message of type OPENFLOW.
 * Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
 */
public class OpenFlowMessage extends Message {
    private OFMessage ofMessage;

    /**
     * Instantiates a new Open flow message.
     */
    public OpenFlowMessage() {
        super(new MessageHeader(), new byte[0]);
        header.setMessageType(MessageType.OPENFLOW);
    }

    /**
     * Gets of message.
     *
     * @return the of message
     */
    public OFMessage getOfMessage() {
        return ofMessage;
    }

    /**
     * Sets of message.
     *
     * @param ofMessage the of message
     */
    public void setOfMessage(OFMessage ofMessage) {
        this.ofMessage = ofMessage;
    }

    @Override
    public byte[] getPayload() {
        ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
        ofMessage.writeTo(dcb);
        this.payload = dcb.array();
        return this.payload;
    }

    @Override
    public String toString() {
        return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
    }
}

package eu.netide.lib.netip;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.projectfloodlight.openflow.protocol.OFMessage;

/**
 * Class representing a message of type OPENFLOW.
 * Note that this only serves as a convenience class - if the MessageType is manipulated, the class will not recognize that.
 */
public class OpenFlowMessage extends Message {
    private OFMessage ofMessage;

    /**
     * Instantiates a new Open flow message.
     */
    public OpenFlowMessage() {
        super(new MessageHeader(), new byte[0]);
        header.setMessageType(MessageType.OPENFLOW);
    }

    /**
     * Gets of message.
     *
     * @return the of message
     */
    public OFMessage getOfMessage() {
        return ofMessage;
    }

    /**
     * Sets of message.
     *
     * @param ofMessage the of message
     */
    public void setOfMessage(OFMessage ofMessage) {
        this.ofMessage = ofMessage;
    }

    @Override
    public byte[] getPayload() {
        ChannelBuffer dcb = ChannelBuffers.dynamicBuffer();
        ofMessage.writeTo(dcb);
        this.payload = new byte[dcb.readableBytes()];
        dcb.readBytes(this.payload, 0, this.payload.length);
        return this.payload;
    }

    @Override
    public String toString() {
        return "OpenFlowMessage [Header=" + header.toString() + ",Type=" + ofMessage.getType().toString() + ",OFMessage=" + ofMessage.toString() + "]";
    }
}

Fix OpenFlow packets getting stuffed with \0 bytes.


package io.vertx.db2client.tck;

import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;

import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;

import io.vertx.db2client.junit.DB2Resource;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.tck.CollectorTestBase;

@RunWith(VertxUnitRunner.class)
public class DB2CollectorTest extends CollectorTestBase {
  @ClassRule
  public static DB2Resource rule = DB2Resource.SHARED_INSTANCE;

  @Override
  protected void initConnector() {
    connector = ClientConfig.CONNECT.connect(vertx, rule.options());
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureProvidingSupplier(TestContext ctx) {
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureInSupplier(TestContext ctx) {
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureProvidingAccumulator(TestContext ctx) {
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureInAccumulator(TestContext ctx) {
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureProvidingFinisher(TestContext ctx) {
  }

  @Override
  @Ignore // TODO: implement error paths properly
  @Test
  public void testCollectorFailureInFinisher(TestContext ctx) {
  }
}

package io.vertx.db2client.tck;

import org.junit.ClassRule;
import org.junit.runner.RunWith;

import io.vertx.db2client.junit.DB2Resource;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.sqlclient.tck.CollectorTestBase;

@RunWith(VertxUnitRunner.class)
public class DB2CollectorTest extends CollectorTestBase {
  @ClassRule
  public static DB2Resource rule = DB2Resource.SHARED_INSTANCE;

  @Override
  protected void initConnector() {
    connector = ClientConfig.CONNECT.connect(vertx, rule.options());
  }
}

Enable DB2Collector error path tests

Enable DB2Collector error path tests


import java.io.*;
import java.net.*;
import java.util.*;
import java.net.ServerSocket;

public class JMP {
    public static void main(String[] args) throws IOException {
        String mysqlHost = System.getProperty("mysqlHost");
        int mysqlPort = Integer.parseInt(System.getProperty("mysqlPort"));
        int port = Integer.parseInt(System.getProperty("port"));
        boolean listening = true;
        ServerSocket listener = null;
        ArrayList<Proxy_Plugin> plugins = new ArrayList<Proxy_Plugin>();

        try {
            listener = new ServerSocket(port);
        }
        catch (IOException e) {
            System.out.println("Could not listen on port");
            System.exit(-1);
        }

        String[] ps = System.getProperty("plugins").split(",");

        while (listening) {
            plugins.clear();
            for (String p: ps) {
                try {
                    plugins.add((Proxy_Plugin) Proxy_Plugin.class.getClassLoader().loadClass(p).newInstance());
                }
                catch (java.lang.ClassNotFoundException e) {
                    continue;
                }
                catch (java.lang.InstantiationException e) {
                    continue;
                }
                catch (java.lang.IllegalAccessException e) {
                    continue;
                }
            }
            new Proxy(listener.accept(), mysqlHost, mysqlPort, plugins).start();
        }

        listener.close();
    }
}

import java.io.*;
import java.net.*;
import java.util.*;
import java.net.ServerSocket;

public class JMP {
    public static void main(String[] args) throws IOException {
        String mysqlHost = System.getProperty("mysqlHost");
        int mysqlPort = Integer.parseInt(System.getProperty("mysqlPort"));
        int port = Integer.parseInt(System.getProperty("port"));
        boolean listening = true;
        ServerSocket listener = null;
        ArrayList<Proxy_Plugin> plugins = new ArrayList<Proxy_Plugin>();

        try {
            listener = new ServerSocket(port);
        }
        catch (IOException e) {
            System.err.print("Could not listen on port\n");
            System.exit(-1);
        }

        String[] ps = System.getProperty("plugins").split(",");

        while (listening) {
            for (String p: ps) {
                try {
                    plugins.add((Proxy_Plugin) Proxy_Plugin.class.getClassLoader().loadClass(p).newInstance());
                    System.err.print("Loaded plugin "+p+"\n");
                }
                catch (java.lang.ClassNotFoundException e) {
                    System.err.print("Failed to load plugin "+p+"\n");
                    continue;
                }
                catch (java.lang.InstantiationException e) {
                    System.err.print("Failed to load plugin "+p+"\n");
                    continue;
                }
                catch (java.lang.IllegalAccessException e) {
                    System.err.print("Failed to load plugin "+p+"\n");
                    continue;
                }
            }
            new Proxy(listener.accept(), mysqlHost, mysqlPort, plugins).start();
            plugins.clear();
        }

        listener.close();
    }
}

Optimize plugin loading, add error messages


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

/**
 * Throw this during init if you can't initialise yourself for some expected
 * reason.  Using this exception will cause the exception's message to come out
 * on stdout, rather than a dirty great stacktrace.
 */
public class DaemonInitException extends Exception {

    private static final long serialVersionUID = 5665891535067213551L;

    // don't rely on Throwable#getCause (jdk1.4)
    private final Throwable cause;

    public DaemonInitException(final String message) {
        super(message);
        this.cause = null;
    }

    public DaemonInitException(final String message, final Throwable cause) {
        super(message);
        this.cause = cause;
    }

    public String getMessageWithCause() {
        final String extra = this.cause == null ? "" : ": " + this.cause.getMessage();
        return getMessage() + extra;
    }

}

Remove trailing white spaces on all lines.


package stream.flarebot.flarebot.mod.modlog;

public enum ModAction {

    BAN(true, ModlogEvent.USER_BANNED),
    FORCE_BAN(true, ModlogEvent.USER_BANNED),
    TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
    UNBAN(false, ModlogEvent.USER_UNBANNED),

    KICK(true, ModlogEvent.USER_KICKED),

    TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED),
    MUTE(true, ModlogEvent.USER_TEMP_MUTED),
    UNMUTE(false, ModlogEvent.USER_TEMP_MUTED),

    WARN(true, ModlogEvent.USER_TEMP_MUTED);

    private boolean infraction;
    private ModlogEvent event;

    ModAction(boolean infraction, ModlogEvent modlogEvent) {
        this.infraction = infraction;
        this.event = modlogEvent;
    }

    public boolean isInfraction() {
        return infraction;
    }

    @Override
    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " ");
    }

    public String getLowercaseName() {
        return toString().toLowerCase();
    }

    public ModlogEvent getEvent() {
        return event;
    }
}

package stream.flarebot.flarebot.mod.modlog;

public enum ModAction {

    BAN(true, ModlogEvent.USER_BANNED),
    FORCE_BAN(true, ModlogEvent.USER_BANNED),
    TEMP_BAN(true, ModlogEvent.USER_TEMP_BANNED),
    UNBAN(false, ModlogEvent.USER_UNBANNED),

    KICK(true, ModlogEvent.USER_KICKED),

    TEMP_MUTE(true, ModlogEvent.USER_TEMP_MUTED),
    MUTE(true, ModlogEvent.USER_MUTED),
    UNMUTE(false, ModlogEvent.USER_UNMUTED),

    WARN(true, ModlogEvent.USER_WARN);

    private boolean infraction;
    private ModlogEvent event;

    ModAction(boolean infraction, ModlogEvent modlogEvent) {
        this.infraction = infraction;
        this.event = modlogEvent;
    }

    public boolean isInfraction() {
        return infraction;
    }

    @Override
    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase().replaceAll("_", " ");
    }

    public String getLowercaseName() {
        return toString().toLowerCase();
    }

    public ModlogEvent getEvent() {
        return event;
    }
}

Copy and paste is the devil

Copy and paste is the devil


package org.codehaus.mojo.mrm.api.maven;

import java.io.IOException;
import java.io.InputStream;

/**
 * Base implementation of {@link ArtifactStore}.
 *
 * @serial
 * @since 1.0
 */
public abstract class BaseArtifactStore
    implements ArtifactStore
{

    /**
     * Ensure consistent serialization.
     *
     * @since 1.0
     */
    private static final long serialVersionUID = 1L;

    /**
     * {@inheritDoc}
     */
    public void set( Artifact artifact, InputStream content )
        throws IOException
    {
        throw new UnsupportedOperationException( "Read-only artifact store" );
    }

    /**
     * {@inheritDoc}
     */
    public void setArchetypeCatalog( InputStream content )
        throws IOException
    {
        throw new UnsupportedOperationException( "Read-only artifact store" );
    }

}

package org.codehaus.mojo.mrm.api.maven;

import java.io.IOException;
import java.io.InputStream;

import org.apache.maven.archetype.catalog.ArchetypeCatalog;

/**
 * Base implementation of {@link ArtifactStore}.
 *
 * @serial
 * @since 1.0
 */
public abstract class BaseArtifactStore
    implements ArtifactStore
{

    /**
     * Ensure consistent serialization.
     *
     * @since 1.0
     */
    private static final long serialVersionUID = 1L;

    /**
     * {@inheritDoc}
     */
    public void set( Artifact artifact, InputStream content )
        throws IOException
    {
        throw new UnsupportedOperationException( "Read-only artifact store" );
    }

    /**
     * {@inheritDoc}
     */
    public void setArchetypeCatalog( InputStream content )
        throws IOException
    {
        throw new UnsupportedOperationException( "Read-only artifact store" );
    }

    /**
     * {@inheritDoc}
     */
    public ArchetypeCatalog getArchetypeCatalog()
        throws IOException, ArchetypeCatalogNotFoundException
    {
        throw new UnsupportedOperationException( "getArchetypeCatalog() has not been implemented" );
    }

    /**
     * {@inheritDoc}
     */
    public long getArchetypeCatalogLastModified()
        throws IOException, ArchetypeCatalogNotFoundException
    {
        throw new UnsupportedOperationException( "getArchetypeCatalogLastModified() has not been implemented" );
    }
}

[MMOCKRM-10] Add stubMethods for all new methods added to the interface of ArtifactStore to prevent LinkageErrors

git-svn-id: bd1f34fbfec48d91264778014075c1f6aa6d3f05@18309 52ab4f32-60fc-0310-b215-8acea882cd1b


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

import static com.google.common.base.Preconditions.checkArgument;
import static org.onosproject.net.DefaultAnnotations.EMPTY;

/**
 * Base abstraction of an annotated entity.
 */
public abstract class AbstractAnnotated implements Annotated {

    private final Annotations annotations;

    // For serialization
    protected AbstractAnnotated() {
        this.annotations = null;
    }

    /**
     * Creates a new entity, annotated with the specified annotations.
     *
     * @param annotations optional key/value annotations map
     */
    protected AbstractAnnotated(Annotations... annotations) {
        checkArgument(annotations.length <= 1, "Only one set of annotations is expected");
        this.annotations = annotations.length == 1 ? annotations[0] : EMPTY;
    }

    @Override
    public Annotations annotations() {
        return annotations;
    }

}

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

import static com.google.common.base.Preconditions.checkArgument;
import static org.onosproject.net.DefaultAnnotations.EMPTY;

/**
 * Base abstraction of an annotated entity.
 */
public abstract class AbstractAnnotated implements Annotated {

    private final Annotations annotations;

    // For serialization
    protected AbstractAnnotated() {
        this.annotations = null;
    }

    /**
     * Creates a new entity, annotated with the specified annotations.
     *
     * @param annotations optional key/value annotations map
     */
    protected AbstractAnnotated(Annotations... annotations) {
        checkArgument(annotations.length <= 1, "Only one set of annotations is expected");
        this.annotations = annotations.length == 0 || annotations[0] == null ? EMPTY : annotations[0];
    }

    @Override
    public Annotations annotations() {
        return annotations;
    }

}

Fix NPE when trying to reference delta port statistics via REST API

Change-Id: Ic195d06e55bd4d8379ac28938e93105d6d181bf6


package cucumber.runtime.junit;

import cucumber.runtime.io.Resource;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.model.FeatureParser;
import gherkin.events.PickleEvent;
import gherkin.pickles.Compiler;
import gherkin.pickles.Pickle;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

class TestPickleBuilder {

    private TestPickleBuilder() {
    }

    static List<PickleEvent> pickleEventsFromFeature(final String path, final String source) {
        List<PickleEvent> pickleEvents = new ArrayList<PickleEvent>();
        Compiler compiler = new Compiler();

        CucumberFeature feature = parseFeature(path, source);
        for (Pickle pickle : compiler.compile(feature.getGherkinFeature())) {
            pickleEvents.add(new PickleEvent(feature.getUri().toString(), pickle));
        }

        return pickleEvents;
    }

    static CucumberFeature parseFeature(final String path, final String source) {
        return parseFeature(URI.create(path), source);
    }

    static CucumberFeature parseFeature(final URI path, final String source) {
        return FeatureParser.parseResource(new Resource() {
            @Override
            public URI getPath() {
                return path;
            }

            @Override
            public InputStream getInputStream() {
                return new ByteArrayInputStream(source.getBytes());
            }

        });
    }
}

package cucumber.runtime.junit;

import cucumber.runtime.io.Resource;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.model.FeatureParser;
import gherkin.events.PickleEvent;
import gherkin.pickles.Compiler;
import gherkin.pickles.Pickle;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

class TestPickleBuilder {

    private TestPickleBuilder() {
    }

    static List<PickleEvent> pickleEventsFromFeature(final String path, final String source) {
        List<PickleEvent> pickleEvents = new ArrayList<PickleEvent>();
        Compiler compiler = new Compiler();

        CucumberFeature feature = parseFeature(path, source);
        for (Pickle pickle : compiler.compile(feature.getGherkinFeature())) {
            pickleEvents.add(new PickleEvent(feature.getUri().toString(), pickle));
        }

        return pickleEvents;
    }

    static CucumberFeature parseFeature(final String path, final String source) {
        return parseFeature(URI.create(path), source);
    }

    static CucumberFeature parseFeature(final URI path, final String source) {
        return FeatureParser.parseResource(new Resource() {
            @Override
            public URI getPath() {
                return path;
            }

            @Override
            public InputStream getInputStream() {
                return new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
            }

        });
    }
}

[JUnit] Use explicit encoding when getting bytes from String


package liquibase.executor;

import liquibase.database.Database;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ExecutorService {

    private static ExecutorService instance = new ExecutorService();

    private Map<Database, Executor> executors = new ConcurrentHashMap<>();

    private ExecutorService() {
    }

    public static ExecutorService getInstance() {
        return instance;
    }

    public Executor getExecutor(Database database) {
        if (!executors.containsKey(database)) {
            try {
                Executor executor = (Executor) ServiceLocator.getInstance().newInstance(Executor.class);
                executor.setDatabase(database);
                executors.put(database, executor);
            } catch (Exception e) {
                throw new UnexpectedLiquibaseException(e);
            }
        }
        return executors.get(database);
    }

    public void setExecutor(Database database, Executor executor) {
        executors.put(database, executor);
    }

    public void clearExecutor(Database database) {
        executors.remove(database);
    }

    public void reset() {
        executors.clear();
    }
}

package liquibase.executor;

import liquibase.database.Database;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.servicelocator.ServiceLocator;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ExecutorService {

    private static ExecutorService instance = new ExecutorService();

    private Map<Database, Executor> executors = new ConcurrentHashMap<>();

    private ExecutorService() {
    }

    public static ExecutorService getInstance() {
        return instance;
    }

    public Executor getExecutor(Database database) {
        return executors.computeIfAbsent(database, db -> {
            try {
                Executor executor = (Executor) ServiceLocator.getInstance().newInstance(Executor.class);
                executor.setDatabase(db);
                return executor;
            } catch (Exception e) {
                throw new UnexpectedLiquibaseException(e);
            }
        });
    }

    public void setExecutor(Database database, Executor executor) {
        executors.put(database, executor);
    }

    public void clearExecutor(Database database) {
        executors.remove(database);
    }

    public void reset() {
        executors.clear();
    }
}

Use computeIfAbsent to avoid concurrency issues

(cherry picked from commit a79513112c7e3b46370deca6d3bb1b47432df00b)


//
// $Id$
//
// Nexus Core - a framework for developing distributed applications
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.distrib;

/**
 * An object used for simple tests.
 */
public class TestObject extends NexusObject
    implements Singleton
{
    public DValue<String> value = DValue.create("test");

    @Override
    protected DAttribute getAttribute (int index)
    {
        switch (index) {
        case 0: return value;
        default: throw new IndexOutOfBoundsException("Invalid attribute index " + index);
        }
    }

    @Override
    protected int getAttributeCount ()
    {
        return 1;
    }
}

//
// $Id$
//
// Nexus Core - a framework for developing distributed applications
// http://github.com/samskivert/nexus/blob/master/LICENSE

package com.samskivert.nexus.distrib;

/**
 * An object used for simple tests.
 */
public class TestObject extends NexusObject
    implements Singleton
{
    public final DValue<String> value = DValue.create("test");

    @Override
    protected DAttribute getAttribute (int index)
    {
        switch (index) {
        case 0: return value;
        default: throw new IndexOutOfBoundsException("Invalid attribute index " + index);
        }
    }

    @Override
    protected int getAttributeCount ()
    {
        return 1;
    }
}

Make our attribute references final.

Make our attribute references final.


package com.github.qrokodial.sparkle.events.util;

public enum Priority {
    /**
     * For core functionality. Do not use unless you know exactly what you're doing. If unsure, use {@link #HIGHEST}.
     */
    REALTIME,

    /**
     * For things requiring the highest priority.
     */
    HIGHEST,

    /**
     * For things requiring higher priority.
     */
    HIGH,

    /**
     * The default priority. If unsure, use this.
     */
    NORMAL,

    /**
     * For things of low priority.
     */
    LOW,

    /**
     * For things of the lowest, non-monitoring priority. If you need to modify data, use this; Otherwise use {@link #MONITOR}.
     */
    LOWEST,

    /**
     * For things that need to monitor, but not modify.
     */
    MONITOR,
}

package com.github.qrokodial.sparkle.events.util;

public enum Priority {
    /**
     * For core functionality. Do not use unless you know exactly what you're doing. If unsure, use {@link #HIGHEST}.
     */
    REALTIME(3),

    /**
     * For things requiring the highest priority.
     */
    HIGHEST(2),

    /**
     * For things requiring higher priority.
     */
    HIGH(1),

    /**
     * The default priority. If unsure, use this.
     */
    NORMAL(0),

    /**
     * For things of low priority.
     */
    LOW(-1),

    /**
     * For things of the lowest, non-monitoring priority. If you need to modify data, use this; Otherwise use {@link #MONITOR}.
     */
    LOWEST(-2),

    /**
     * For things that need to monitor, but not modify.
     */
    MONITOR(-3);

    private int id;

    Priority(int id) {
        this.id = id;
    }

    /**
     * Gets the inverse of the priority. {@link #HIGHEST} becomes {@link #LOWEST}, {@link #LOWEST} becomes
     * {@link #HIGHEST}, and so on.
     *
     * @return the inverse of the priority
     */
    public Priority inverse() {
        int id = -this.id;
        for (Priority priority : Priority.values()) {
            if (priority.id == id) {
                return priority;
            }
        }
        return null;
    }
}

Allow for getting the inverse of a priority


package com.slugterra.entity.protoform;

import java.util.Random;

import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIFollowOwner;
import net.minecraft.entity.ai.EntityAILookIdle;
import net.minecraft.entity.ai.EntityAIPanic;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.ai.EntityAIWander;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;

import com.slugterra.entity.EntitySlug;
import com.slugterra.entity.ai.EntitySlugAIHopPanic;
import com.slugterra.entity.ai.EntitySlugAIHopWander;
import com.slugterra.item.SlugItemRegistry;
import com.slugterra.item.ItemRegistry;

public class EntityJellyish extends EntitySlug{

	public EntityJellyish(World p_i1738_1_) {
		super(p_i1738_1_);
		this.slugItem = SlugItemRegistry.jellyish;
	}

	@Override
	public EntityAgeable createChild(EntityAgeable p_90011_1_) {
		return new EntityJellyish(worldObj);
	}
}

package com.slugterra.entity.protoform;

import com.slugterra.entity.EntitySlug;
import com.slugterra.item.SlugItemRegistry;

import net.minecraft.entity.EntityAgeable;
import net.minecraft.world.World;

public class EntityJellyish extends EntitySlug{

	public EntityJellyish(World p_i1738_1_) {
		super(p_i1738_1_);
		this.slugItem = SlugItemRegistry.jellyish;
	}

	@Override
	public EntityAgeable createChild(EntityAgeable p_90011_1_) {
		return new EntityJellyish(world);
	}
}

Change worldObj variable to world

Change worldObj variable to world


package io.fotoapparat.util;

import java.util.Comparator;

import io.fotoapparat.parameter.Size;

/**
 * Comparator based on area of the given {@link Size} objects.
 */
public class CompareSizesByArea implements Comparator<Size> {

    @Override
    public int compare(Size lhs, Size rhs) {
        return Long.signum((long) lhs.width * lhs.height -
                (long) rhs.width * rhs.height);
    }
}

package io.fotoapparat.util;

import java.util.Comparator;

import io.fotoapparat.parameter.Size;

/**
 * Comparator based on area of the given {@link Size} objects.
 */
public class CompareSizesByArea implements Comparator<Size> {

    @Override
    public int compare(Size lhs, Size rhs) {
        return Long.signum((long) lhs.getArea() - (long) rhs.getArea());
    }
}

Replace calculation with ready method

Replace calculation with ready method


package com.github.mobile.android.util;

import android.text.Html.ImageGetter;

/**
 * Html Utilities
 */
public class Html {

    /**
     * Encode HTML
     *
     * @param html
     * @return html
     */
    public static CharSequence encode(String html) {
        return encode(html, null);
    }

    /**
     * Encode HTML
     *
     * @param html
     * @param imageGetter
     * @return html
     */
    public static CharSequence encode(String html, ImageGetter imageGetter) {
        if (html == null)
            return "";
        if (html.length() == 0)
            return html;
        // These add extra padding that should be styled explicitly
        if (html.startsWith("<p>") && html.endsWith("</p>"))
            html = html.substring(3, html.length() - 4);
        return android.text.Html.fromHtml(html, imageGetter, null);
    }
}

package com.github.mobile.android.util;

import android.text.Html.ImageGetter;

/**
 * Html Utilities
 */
public class Html {

    /**
     * Encode HTML
     *
     * @param html
     * @return html
     */
    public static CharSequence encode(String html) {
        return encode(html, null);
    }

    /**
     * Encode HTML
     *
     * @param html
     * @param imageGetter
     * @return html
     */
    public static CharSequence encode(String html, ImageGetter imageGetter) {
        if (html == null)
            return "";
        if (html.length() == 0)
            return html;
        // These add extra padding that should be styled explicitly
        html = html.replace("
", "");
        html = html.replace("
", "
");
        while (html.length() > 0)
            if (html.startsWith("
"))
                html = html.substring(4);
            else if (html.endsWith("
"))
                html = html.substring(0, html.length() - 4);
            else
                break;
        return android.text.Html.fromHtml(html, imageGetter, null);
    }
}

Drop <p> tags and replace </p> with <br>

This was causing an excessive amount of bottom padding


package com.graphicsengine.scene;

import com.graphicsengine.json.JSONSceneFactory;

/**
 * Creates the sceneserializer implementations
 *
 * @author Richard Sahlin
 *
 */
public class SceneSerializerFactory {

    /**
     * Returns an implementation of the SceneSerializer interface, pass null to get the default platform serializer.
     * Pass classname for a specific implementation.
     *
     * @param className Implementing classname or null for default.
     * @return The scene serializer implementation
     * @throws ClassNotFoundException If the specified class cannot be found
     * @throws InstantiationException If the specified class cannot be created
     * @throws IllegalAccessException If the specified class cannot be created
     */
    public static SceneSerializer getSerializer(String className) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException {

        if (className == null) {
            return new JSONSceneFactory();
        }
        return (SceneSerializer) Class.forName(className).newInstance();
    }

}

package com.graphicsengine.scene;

/**
 * Creates the sceneserializer implementations
 *
 * @author Richard Sahlin
 *
 */
public class SceneSerializerFactory {

    /**
     * Returns an implementation of the SceneSerializer interface, callers must know the implementing class.
     *
     * @param className Implementing classname or null for default.
     * @return The scene serializer implementation
     * @throws ClassNotFoundException If the specified class cannot be found
     * @throws InstantiationException If the specified class cannot be created
     * @throws IllegalAccessException If the specified class cannot be created
     */
    public static SceneSerializer getSerializer(String className) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException {
        return (SceneSerializer) Class.forName(className).newInstance();
    }

}

Remove default serializer, caller must specify classname of serializer implementation


package org.helioviewer.jhv.view.jp2view.io;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;

import javax.annotation.Nonnull;

public class ByteChannelInputStream extends InputStream {

    private final ByteBuffer buf = ByteBuffer.allocateDirect(512 * 1024);
    private final ByteChannel chan;

    public ByteChannelInputStream(ByteChannel _chan) {
        chan = _chan;
    }

    @Override
    public int read() throws IOException {
        ensure(1);
        return (buf.get() + 256) & 0xFF;
    }

    @Override
    public int read(@Nonnull byte[] bytes, int off, int len) throws IOException {
        ensure(len);
        buf.get(bytes, off, len);
        return len;
    }

    @Override
    public int read(@Nonnull byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    private void ensure(int len) throws IOException {
        if (buf.remaining() < len) {
            buf.compact();
            buf.flip();
            do {
                buf.position(buf.limit());
                buf.limit(buf.capacity());
                chan.read(buf);
                buf.flip();
            } while (buf.remaining() < len);
        }
    }

}

package org.helioviewer.jhv.view.jp2view.io;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;

import javax.annotation.Nonnull;

public class ByteChannelInputStream extends InputStream {

    private final ByteBuffer buf = ByteBuffer.allocateDirect(512 * 1024);
    private final ByteChannel chan;

    public ByteChannelInputStream(ByteChannel _chan) {
        chan = _chan;
    }

    @Override
    public int read() throws IOException {
        ensure(1);
        return (buf.get() + 256) & 0xFF;
    }

    @Override
    public int read(@Nonnull byte[] bytes, int off, int len) throws IOException {
        ensure(len);
        buf.get(bytes, off, len);
        return len;
    }

    @Override
    public int read(@Nonnull byte[] b) throws IOException {
        return read(b, 0, b.length);
    }

    private void ensure(int len) throws IOException {
        if (buf.remaining() < len) {
            buf.compact();
            buf.flip();
            int n;
            do {
                buf.position(buf.limit());
                buf.limit(buf.capacity());
                n = chan.read(buf);
                buf.flip();
            } while (n >= 0 && buf.remaining() < len);
        }
    }

}

Check return value of read operation

Check return value of read operation


package com.cloudskol.moviedroid.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author tham
 */
public class MovieDbHelper extends SQLiteOpenHelper {
    private static final String LOG_TAG = MovieDbHelper.class.getSimpleName();

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Moviedroid.db";

    public MovieDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    private String buildCreateTableQuery() {
        final StringBuilder builder = new StringBuilder();
        builder.append("CREATE TABLE ");
        builder.append(MovieContract.MovieEntry.TABLE_NAME);

        Log.v(LOG_TAG, "Create table query: " + builder.toString());
        return builder.toString();
    }

    private String buildDropTableQuery() {
        return "DROP TABLE IF EXISTS " + MovieContract.MovieEntry.TABLE_NAME;
    }
}

package com.cloudskol.moviedroid.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author tham
 */
public class MovieDbHelper extends SQLiteOpenHelper {
    private static final String LOG_TAG = MovieDbHelper.class.getSimpleName();

    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "Moviedroid.db";

    public MovieDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(buildCreateTableQuery());
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(buildDropTableQuery());
        onCreate(db);
    }

    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onUpgrade(db, oldVersion, newVersion);
    }

    private String buildCreateTableQuery() {
        final StringBuilder builder = new StringBuilder();
        builder.append("CREATE TABLE ");
        builder.append(MovieContract.MovieEntry.TABLE_NAME);
        builder.append(" (");
        builder.append(MovieContract.MovieEntry._ID + " INTEGER PRIMARY KEY, ");
        builder.append(MovieContract.MovieEntry.COLUMN_MOVIE_ID + " INTEGER, ");
        builder.append(MovieContract.MovieEntry.COLUMN_TITLE + " TEXT, ");
        builder.append(MovieContract.MovieEntry.COLUMN_OVERVIEW + " TEXT");
        builder.append(" )");

        Log.v(LOG_TAG, "Create table query: " + builder.toString());
        return builder.toString();
    }

    private String buildDropTableQuery() {
        return "DROP TABLE IF EXISTS " + MovieContract.MovieEntry.TABLE_NAME;
    }
}

Create and drop schema changes are done

Create and drop schema changes are done


import Ice.Current;
import VideoStreaming.Stream;
import java.util.ArrayList;
import java.util.List;

public class PortalI extends VideoStreaming._PortalDisp {
    private List<Stream> Streams = new ArrayList<Stream>();

    // Calls from Streaming Servers
    public void register(Stream stream, Current current) {
        Streams.add(stream);
    }

    public void remove(Stream stream, Current current) {
        Streams.remove(stream);
    }

    // Calls from Clients
    public List<Stream> getStreams(Current current) {
        return Streams;
    }
}

import Streaming.NotifierPrxHelper;
import Streaming.Stream;

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

public class PortalI extends Streaming._PortalDisp {
    private Map<Stream, Long> Streams = new HashMap<Stream, Long>();
    Streaming.NotifierPrx Notifier = null;

    PortalI() {
        Ice.ObjectPrx obj = Ice.Application.communicator().propertyToProxy("TopicManager.Proxy");
        IceStorm.TopicManagerPrx manager = IceStorm.TopicManagerPrxHelper.checkedCast(obj);
        if (manager == null) {
            System.err.println("Invalid proxy");
            return;
        }

        IceStorm.TopicPrx topic = null;
        while (topic == null) {
            try {
                topic = manager.retrieve("Streams");
            } catch (IceStorm.NoSuchTopic e) {
                try {
                    topic = manager.create("Streams");
                } catch (IceStorm.TopicExists ex) {
                    System.err.println("Temporary failure");
                    return;
                }
            }
        }

        Ice.ObjectPrx publisher = topic.getPublisher().ice_oneway();
        Notifier = NotifierPrxHelper.uncheckedCast(publisher);

        new Thread(() -> {
            while (true) {
                for (Stream s : Streams.keySet())
                    if (System.currentTimeMillis() - Streams.get(s) >= 60000)
                        Streams.remove(s);
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    // Calls from Streaming Servers
    public void register(Stream stream, Ice.Current current) {
        Streams.put(stream, System.currentTimeMillis());
        Notifier.inform(String.format("[%s: %s]", "New Stream", stream.getName()));
    }

    public void remove(Stream stream, Ice.Current current) {
        Streams.remove(stream);
        Notifier.inform(String.format("[%s: %s]", "Removed Stream", stream.getName()));
    }

    public void update(Stream stream, Ice.Current current) {
        if (Streams.get(stream) != null)
            Streams.put(stream, System.currentTimeMillis());
    }

    // Calls from Clients
    public Stream get(String stream, Ice.Current current) {
        for (Stream s : Streams.keySet())
            if (s.name.equals(stream)) return s;
        return null;
    }

    public List<Stream> getAll(Ice.Current current) {
        return Streams.keySet().stream().collect(Collectors.toList());
    }
}

Implement lots of new methods

Implement lots of new methods

Signed-off-by: Nuno Azevedo <8c1e4f9df2ead62a44323c12422702b1d8dd9c90@gmail.com>