import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
	  // When array size is less than 3, returns an error.
	  if (input.length % 3 != 0 ) {
			System.out.println("Error! Array cannot be divided into three equal parts");
			return;
		}
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

Update to handle an edge case


package gouravexample.popularmoviesstage1;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by GOURAV on 17-08-2016.
 */
public class ViewAdapter extends ArrayAdapter<MovieItem>{

    private static final String LOG_TAG = ViewAdapter.class.getSimpleName();

    public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
        super(context, resource, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
        }

        ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
        MovieItem item = (MovieItem)getItem(position);

        Log.d(LOG_TAG,item.getPosterPath());
//        imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
        Picasso.with(getContext())
                .load(item.getPosterPath())
                .placeholder(R.drawable.circular)
//                .resize(185,278)
//                .centerCrop()
                .into(imageView);

        return convertView;
    }
}

package gouravexample.popularmoviesstage1;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by GOURAV on 17-08-2016.
 */
public class ViewAdapter extends ArrayAdapter<MovieItem>{

    private static final String LOG_TAG = ViewAdapter.class.getSimpleName();

    public ViewAdapter(Context context, int resource, List<MovieItem> objects) {
        super(context, resource, objects);
    }

    public View getView(int position, View convertView, ViewGroup parent){

        if(convertView == null){
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.grid_item_movie,null);
        }

        ImageView imageView = (ImageView) convertView.findViewById(R.id.image);
        MovieItem item = (MovieItem)getItem(position);

        Log.d(LOG_TAG,item.getPosterPath());
//        imageView.setImageResource(getContext().getResources().getIdentifier((String)getItem(position), "drawable", getContext().getPackageName()));
        Picasso.with(getContext())
                .load(item.getPosterPath())
//                .placeholder(R.drawable.circular)
//                .resize(185,278)
//                .centerCrop()
                .into(imageView);

        return convertView;
    }
}

Remove Interstellar poster as placeholder.


package com.jraska.github.client.data.users;

import com.jraska.github.client.users.UsersRepository;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.inject.Singleton;

@Module
public final class UsersModule {
  @Provides @Singleton UsersRepository provideUsersRepository(GitHubUsersApi gitHubUsersApi,
                                                              GitHubUserDetailApi detailApi) {
    return new GitHubApiUsersRepository(gitHubUsersApi, detailApi);
  }

  @Provides @Singleton GitHubUsersApi provideGitHubUsersApi(Retrofit retrofit) {
    return retrofit.create(GitHubUsersApi.class);
  }

  @Provides @Singleton GitHubUserDetailApi provideGitHubUserDetailApi(Retrofit retrofit) {
    return retrofit.create(GitHubUserDetailApi.class);
  }

  @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .validateEagerly(true) // TODO: 17/08/16 AppConfig
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

    return retrofit;
  }
}

package com.jraska.github.client.data.users;

import com.jraska.github.client.common.AppBuildConfig;
import com.jraska.github.client.users.UsersRepository;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.inject.Singleton;

@Module
public final class UsersModule {
  @Provides @Singleton UsersRepository provideUsersRepository(Retrofit retrofit) {
    GitHubUsersApi usersApi = retrofit.create(GitHubUsersApi.class);
    GitHubUserDetailApi detailApi = retrofit.create(GitHubUserDetailApi.class);

    return new GitHubApiUsersRepository(usersApi, detailApi);
  }

  @Provides @Singleton Retrofit provideRetrofit(OkHttpClient okHttpClient, AppBuildConfig config) {
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com")
        .validateEagerly(config.debug)
        .client(okHttpClient)
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build();

    return retrofit;
  }
}

Remove extra methods for API clients


package com.yahoo.searchdefinition;

import com.yahoo.vespa.model.AbstractService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RankExpressionFiles {
    private final Map<String, RankExpressionFile> expressions = new HashMap<>();

    public void add(RankExpressionFile expression) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name))
            throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
        expressions.put(name, expression);
    }

    /** Returns the ranking constant with the given name, or null if not present */
    public RankExpressionFile get(String name) {
        return expressions.get(name);
    }

    /** Returns a read-only map of the ranking constants in this indexed by name */
    public Map<String, RankExpressionFile> asMap() {
        return Collections.unmodifiableMap(expressions);
    }

    /** Initiate sending of these constants to some services over file distribution */
    public void sendTo(Collection<? extends AbstractService> services) {
        expressions.values().forEach(constant -> constant.sendTo(services));
    }
}

package com.yahoo.searchdefinition;

import com.yahoo.vespa.model.AbstractService;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RankExpressionFiles {
    private final Map<String, RankExpressionFile> expressions = new HashMap<>();

    public void add(RankExpressionFile expression) {
        expression.validate();
        String name = expression.getName();
        if (expressions.containsKey(name))
            throw new IllegalArgumentException("Rank expression file '" + name + "' defined twice");
        expressions.put(name, expression);
    }

    /** Returns the ranking constant with the given name, or null if not present */
    public RankExpressionFile get(String name) {
        return expressions.get(name);
    }

    /** Returns a read-only map of the ranking constants in this indexed by name */
    public Map<String, RankExpressionFile> asMap() {
        return Collections.unmodifiableMap(expressions);
    }

    /** Initiate sending of these constants to some services over file distribution */
    public void sendTo(Collection<? extends AbstractService> services) {
        // TODO Disabled until issues resolved
        // expressions.values().forEach(constant -> constant.sendTo(services));
    }
}

Disable distribution of rank-expression files.


package com.swandiggy.poe4j.gui.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * @author Jacob Swanson
 * @since 12/10/2015
 */
public class ObservableLogAppender extends AppenderBase<ILoggingEvent> {

    public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList();

    @Override
    protected void append(ILoggingEvent event) {
        Platform.runLater(() -> {
            events.add(event);

            if (events.size() > 500) {
                events.remove(events.size() - 1);
            }
        });
    }
}

package com.swandiggy.poe4j.gui.log;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * @author Jacob Swanson
 * @since 12/10/2015
 */
public class ObservableLogAppender extends AppenderBase<ILoggingEvent> {

    public static ObservableList<ILoggingEvent> events = FXCollections.observableArrayList();

    @Override
    protected void append(ILoggingEvent event) {
        Platform.runLater(() -> {
            events.add(event);

            if (events.size() > 500) {
                events.remove(0);
            }
        });
    }
}

Fix log not appending in gui


package org.opennms.web.svclayer;

import java.util.Date;

public interface DistributedStatusService {
    public SimpleWebTable createStatusTable(String locationName, String applicationLabel);

    public SimpleWebTable createFacilityStatusTable(Date startDate, Date endDate);
}

package org.opennms.web.svclayer;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

@Transactional(readOnly=true)
public interface DistributedStatusService {
    public SimpleWebTable createStatusTable(String locationName, String applicationLabel);

    public SimpleWebTable createFacilityStatusTable(Date startDate, Date endDate);
}

Make the service layer transactional (and read-only)


/*
 * #%L
 * Wildfly Swarm :: Examples :: Camel Mail
 * %%
 * Copyright (C) 2016 RedHat
 * %%
 * 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.
 * #L%
 */
package org.wildfly.swarm.examples.camel.mail;

import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.mail.MailFraction;

public class Main {
    public static void main(String... args) throws Exception {
        MailFraction fraction = MailFraction.defaultFraction();
        Swarm swarm = new Swarm();

        // Configure mock mail server SMTP session
        swarm.fraction(fraction.smtpServer("greenmail", s -> s.host("localhost").port("10110").username("user1@localhost").password("password")));

        // Deploy mock mail server
        swarm.start(true);
        swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1"));
        swarm.deploy();
    }
}

/*
 * #%L
 * Wildfly Swarm :: Examples :: Camel Mail
 * %%
 * Copyright (C) 2016 RedHat
 * %%
 * 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.
 * #L%
 */
package org.wildfly.swarm.examples.camel.mail;

import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.mail.MailFraction;

public class Main {
    public static void main(String... args) throws Exception {
        Swarm swarm = new Swarm();

        // Configure mock mail server SMTP session
        swarm.fraction(new MailFraction().smtpServer("greenmail", s -> s.host("localhost").port(10110).username("user1@localhost").password("password")));

        // Deploy mock mail server
        swarm.start(true);
        swarm.deploy(Swarm.artifact("com.icegreen:greenmail-webapp:war:1.4.1"));
        swarm.deploy();
    }
}

Change Camel-Mail example to - not create 2 SMTP servers. - use an integer instead of an integer-shaped string.


package com.xtremelabs.robolectric.shadows;

import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;

import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;

@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res")));
	}

    @Test(expected = Resources.NotFoundException.class)
    public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));

        new Activity().getResources().getStringArray(-1);
    }

    @Test
    public void testConfiguration() {
        assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
    }
}

package com.xtremelabs.robolectric.shadows;

import android.app.Activity;
import android.app.Application;
import android.content.res.Resources;
import com.xtremelabs.robolectric.R;
import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;
import com.xtremelabs.robolectric.res.ResourceLoader;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.notNullValue;

import java.io.File;
import static com.xtremelabs.robolectric.util.TestUtil.resourceFile;

@RunWith(WithTestDefaultsRunner.class)
public class ResourcesTest {

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, new File("test/res"), new File("test/assets")));
	}

    @Test(expected = Resources.NotFoundException.class)
    public void getStringArray_shouldThrowExceptionIfNotFound() throws Exception {
        Robolectric.bindDefaultShadowClasses();
        Robolectric.application = ShadowApplication.bind(new Application(), new ResourceLoader(R.class, resourceFile("res"), resourceFile("assets")));

        new Activity().getResources().getStringArray(-1);
    }

    @Test
    public void testConfiguration() {
        assertThat( new Activity().getResources().getConfiguration(), notNullValue() );
    }
}

Fix signature for ResourceLoader constructor


package com.furnaghan.home.component.metrics.statsd;

import com.furnaghan.home.component.Component;
import com.furnaghan.home.component.metrics.MetricsType;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType {

    private static String sanitize(final String name) {
        return name.replaceAll("[^a-zA-Z0-9\\s]", "").replaceAll("\\s", "_");
    }

    private final StatsDClient statsd;

    public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) {
        statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(),
                configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT));
    }

    @Override
    public void send(final String name, final double value) {
        statsd.gauge(sanitize(name), value);
    }
}

package com.furnaghan.home.component.metrics.statsd;

import com.furnaghan.home.component.Component;
import com.furnaghan.home.component.metrics.MetricsType;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

public class StatsDMetricsComponent extends Component<MetricsType.Listener> implements MetricsType {

    private static String sanitize(final String name) {
        return name.replaceAll("[^a-zA-Z0-9\\s\\.]", "").replaceAll("\\s", "_");
    }

    private final StatsDClient statsd;

    public StatsDMetricsComponent(final StatsDMetricsConfiguration configuration) {
        statsd = new NonBlockingStatsDClient(configuration.getPrefix(), configuration.getAddress().getHostText(),
                configuration.getAddress().getPortOrDefault(StatsDMetricsConfiguration.DEFAULT_PORT));
    }

    @Override
    public void send(final String name, final double value) {
        statsd.gauge(sanitize(name), value);
    }
}

Allow periods in statsd names


/*
 *
 * CODENVY CONFIDENTIAL
 * ________________
 *
 * [2012] - [2014] Codenvy, S.A.
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any. The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */
package com.codenvy.analytics.metrics;

/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {

    private static final String TIME = "time";

    protected RunnerTotalTime() {
        super(MetricType.RUNNER_TOTAL_TIME);
    }

    @Override
    public String[] getTrackedFields() {
        return new String[]{TIME};
    }

    @Override
    public String getDescription() {
        return "The total time of runners";
    }
}

/*
 *
 * CODENVY CONFIDENTIAL
 * ________________
 *
 * [2012] - [2014] Codenvy, S.A.
 * All Rights Reserved.
 * NOTICE: All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any. The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */
package com.codenvy.analytics.metrics;

/** @author Anatoliy Bazko */
public class RunnerTotalTime extends AbstractLongValueResulted {

    private static final String TIME = "time";

    public RunnerTotalTime() {
        super(MetricType.RUNNER_TOTAL_TIME);
    }

    @Override
    public String[] getTrackedFields() {
        return new String[]{TIME};
    }

    @Override
    public String getDescription() {
        return "The total time of runners";
    }
}

Add bunch of new events


package keywhiz.service.resources;

import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import io.dropwizard.setup.Environment;
import java.util.TreeMap;
import javax.ws.rs.InternalServerErrorException;
import org.junit.Before;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class StatusResponseTest {
  HealthCheckRegistry registry;
  Environment environment;
  StatusResource status;

  @Before
  public void setUp() throws Exception {
    this.registry = mock(HealthCheckRegistry.class);
    this.environment = mock(Environment.class);
    this.status = new StatusResource(environment);

    when(environment.healthChecks()).thenReturn(registry);
  }

  @Test
  public void testStatusOk() throws Exception {
    when(registry.runHealthChecks()).thenReturn(new TreeMap<>());
    status.get();
  }

  @Test(expected = InternalServerErrorException.class)
  public void testStatusWarn() throws Exception {
    TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
    map.put("test", HealthCheck.Result.unhealthy("failing"));

    when(registry.runHealthChecks()).thenReturn(map);
    status.get();
  }
}

package keywhiz.service.resources;

import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import io.dropwizard.setup.Environment;
import java.util.TreeMap;
import javax.ws.rs.InternalServerErrorException;
import javax.ws.rs.core.Response;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class StatusResponseTest {
  HealthCheckRegistry registry;
  Environment environment;
  StatusResource status;

  @Before
  public void setUp() throws Exception {
    this.registry = mock(HealthCheckRegistry.class);
    this.environment = mock(Environment.class);
    this.status = new StatusResource(environment);

    when(environment.healthChecks()).thenReturn(registry);
  }

  @Test
  public void testStatusOk() throws Exception {
    when(registry.runHealthChecks()).thenReturn(new TreeMap<>());
    Response r = status.get();
    assertThat(r.getStatus()).isEqualTo(200);
  }

  @Test
  public void testStatusWarn() throws Exception {
    TreeMap<String, HealthCheck.Result> map = new TreeMap<>();
    map.put("test", HealthCheck.Result.unhealthy("failing"));

    when(registry.runHealthChecks()).thenReturn(map);
    Response r = status.get();
    assertThat(r.getStatus()).isEqualTo(500);
  }
}

Fix tests to check status code, and not expect exception


/*
 * Altimos JUtil
 *
 * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de>
 *
 * 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.
 *
 * See the NOTICE file distributed along with this work for further
 * information.
 */
package de.altimos.util.res.basic;

import de.altimos.util.res.ResourceKey;

/**
 * A basic ResourceKey implementation using a string as name.
 *
 * @author Jan Graichen
 */
public class BasicResourceKey implements ResourceKey {

	private String name;

	/**
	 * Creates new BasicResourceKey with given name.
	 *
	 * @param name of resource this key identifies.
	 */
	public BasicResourceKey(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

}

/*
 * Altimos JUtil
 *
 * Copyright (C) 2010-2011 Jan Graichen <jan.graichen@gmx.de>
 *
 * 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.
 *
 * See the NOTICE file distributed along with this work for further
 * information.
 */
package de.altimos.util.res.basic;

import de.altimos.util.res.ResourceKey;

/**
 * A basic ResourceKey implementation using a string as name.
 *
 * @author Jan Graichen
 */
public class BasicResourceKey implements ResourceKey {

	private String name;

	/**
	 * Creates new BasicResourceKey with given name.
	 *
	 * @param name of resource this key identifies.
	 */
	public BasicResourceKey(String name) {
		this.name = name;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + "[" + name + "]";
	}
}

Add toString method to basic resource key.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
@PublicApi
package com.yahoo.config.provision;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
@ExportPackage
package com.yahoo.config.provision;

import com.yahoo.api.annotations.PublicApi;
import com.yahoo.osgi.annotation.ExportPackage;

Remove this from public packages


package <%=packageName%>.repository;

import <%=packageName%>.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * Spring Data JPA repository for the PersistentAuditEvent entity.
 */
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {

    List<PersistentAuditEvent> findByPrincipal(String principal);

    List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);

    List<PersistentAuditEvent> findByAuditEventDateBetween(LocalDateTime fromDate, LocalDateTime toDate);
}

package <%=packageName%>.repository;

import <%=packageName%>.domain.PersistentAuditEvent;
import org.joda.time.LocalDateTime;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

/**
 * Spring Data JPA repository for the PersistentAuditEvent entity.
 */
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, String> {

    List<PersistentAuditEvent> findByPrincipal(String principal);

    List<PersistentAuditEvent> findByPrincipalAndAuditEventDateGreaterThan(String principal, LocalDateTime after);

    @Query("select p from PersistentAuditEvent p where p.auditEventDate >= ?1 and p.auditEventDate <= ?2")
    List<PersistentAuditEvent> findByDates(LocalDateTime fromDate, LocalDateTime toDate);
}

Change the definition of the find by dates method


package org.usfirst.frc.team2503.r2016.input;

import org.usfirst.frc.team2503.r2016.input.gamepad.Gamepad;
import org.usfirst.frc.team2503.r2016.input.joystick.Joystick;

public class MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout extends JoystickJoystickGamepadControlLayout {

	public Data getData() {
		Data data = super.getData();

		return data;
	}

	public MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout(Joystick left, Joystick right, Gamepad gamepad) {
		super(left, right, gamepad);
	}

}

package org.usfirst.frc.team2503.r2016.input;

import org.usfirst.frc.team2503.r2016.input.gamepad.Gamepad;
import org.usfirst.frc.team2503.r2016.input.joystick.Joystick;

public class MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout extends JoystickJoystickGamepadControlLayout {

	public Data getData() {
		Data data = super.getData();

		// Any modifications to be made should be done here.

		return data;
	}

	public MadCatzV1JoystickMadCatzV1JoystickLogitechF310GamepadControlLayout(Joystick left, Joystick right, Gamepad gamepad) {
		super(left, right, gamepad);
	}

}

Clean up a couple of whitespace errors, add a comment


package fr.univnantes.termsuite.ui.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;

import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;

public class FileUtil {

	public static String toString(File file) throws FileNotFoundException {
		Scanner scanner = new Scanner(file);
		String next = scanner.useDelimiter("\\Z").next();
		scanner.close();
		return next;
	}

	public static void mkdirs(File file) {
		if (file.isDirectory()) {
			file.mkdirs();
		} else {
			file.getParentFile().mkdirs();
		}
	}

	public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
		byte[] buffer = ByteStreams.toByteArray(is);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(buffer);
		outStream.flush();
		outStream.close();
	}

	public static String getFilename(String path) {
		List<String> list = Splitter.on(File.separator).splitToList(path);
		return list.get(list.size() - 1);
	}
}

package fr.univnantes.termsuite.ui.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Scanner;

import com.google.common.base.Splitter;
import com.google.common.io.ByteStreams;

public class FileUtil {

	public static String toString(File file) throws FileNotFoundException {
		Scanner scanner = new Scanner(file, "UTF-8");
		String next = scanner.useDelimiter("\\Z").next();
		scanner.close();
		return next;
	}

	public static void mkdirs(File file) {
		if (file.isDirectory()) {
			file.mkdirs();
		} else {
			file.getParentFile().mkdirs();
		}
	}

	public static void inputStreamToFile(InputStream is, File targetFile) throws IOException {
		byte[] buffer = ByteStreams.toByteArray(is);
		OutputStream outStream = new FileOutputStream(targetFile);
		outStream.write(buffer);
		outStream.flush();
		outStream.close();
	}

	public static String getFilename(String path) {
		List<String> list = Splitter.on(File.separator).splitToList(path);
		return list.get(list.size() - 1);
	}
}

Load file as UTF-8 as default


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class UndoCommandTest extends TaskManagerGuiTest {

    private TestTask[] expectedList = td.getTypicalTasks();

    /**
     * Tries to undo an add command
     */
    @Test
    public void undoAdd() {
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(expectedList);
    }

    private void assertUndoSuccess(TestTask[] expectedList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertTrue(taskListPanel.isListMatching(expectedList));
        assertResultMessage(String.format(UndoCommand.MESSAGE_SUCCESS));

    }

}

package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.logic.commands.UndoCommand;
import seedu.address.testutil.TestTask;
import seedu.address.logic.commands.DeleteCommand;

public class UndoCommandTest extends TaskManagerGuiTest {

    private TestTask[] expectedList = td.getTypicalTasks();

    /**
     * Tries to undo an add command
     */
    @Test
    public void undoAdd() {
        TestTask taskToAdd = td.alice;
        commandBox.runCommand(taskToAdd.getAddCommand());
        assertUndoSuccess(expectedList);
    }

    /**
     * Tries to undo a delete command
     */
    @Test
    public void undoDelete() {
        int targetIndex = 1;
        commandBox.runCommand(DeleteCommand.COMMAND_WORD + " " + targetIndex);

        assertUndoSuccess(expectedList);
    }

    private void assertUndoSuccess(TestTask[] expectedList) {
        commandBox.runCommand(UndoCommand.COMMAND_WORD);
        assertTrue(taskListPanel.isListMatching(expectedList));
        assertResultMessage(String.format(UndoCommand.MESSAGE_SUCCESS));

    }

}

Add test case for undo delete command


package de.fernunihagen.dna.jkn.scalephant.storage;

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

public class StorageInterface {

	private static Map<String, StorageManager> instances;

	/**
	 * Get the storage manager for a given table. If the storage manager does not
	 * exist, it will be created
	 *
	 * @return
	 */
	public static synchronized StorageManager getStorageManager(final String table) {

		if(instances == null) {
			instances = new HashMap<String, StorageManager>();
		}

		if(instances.containsKey(table)) {
			return instances.get(table);
		}

		final StorageConfiguration storageConfiguration = new StorageConfiguration();
		final StorageManager storageManager = new StorageManager(table, storageConfiguration);
		storageManager.init();

		instances.put(table, storageManager);

		return storageManager;
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

		if(instances != null) {
			for(final String table : instances.keySet()) {
				final StorageManager storageManager = instances.get(table);
				storageManager.shutdown();
			}
		}
	}
}

package de.fernunihagen.dna.jkn.scalephant.storage;

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

public class StorageInterface {

	/**
	 * A map with all created storage instances
	 */
	protected static Map<String, StorageManager> instances;

	/**
	 * The used storage configuration
	 */
	protected static StorageConfiguration storageConfiguration;

	static {
		storageConfiguration = new StorageConfiguration();
	}

	/**
	 * Get the storage manager for a given table. If the storage manager does not
	 * exist, it will be created
	 *
	 * @return
	 */
	public static synchronized StorageManager getStorageManager(final String table) {

		if(instances == null) {
			instances = new HashMap<String, StorageManager>();
		}

		if(instances.containsKey(table)) {
			return instances.get(table);
		}

		final StorageManager storageManager = new StorageManager(table, storageConfiguration);
		storageManager.init();

		instances.put(table, storageManager);

		return storageManager;
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();

		if(instances != null) {
			for(final String table : instances.keySet()) {
				final StorageManager storageManager = instances.get(table);
				storageManager.shutdown();
			}
		}
	}

	/**
	 * Get the current storage configuration
	 * @return
	 */
	public static StorageConfiguration getStorageConfiguration() {
		return storageConfiguration;
	}

	/**
	 * Set a new storage configuration
	 * @param storageConfiguration
	 */
	public static void setStorageConfiguration(
			StorageConfiguration storageConfiguration) {
		StorageInterface.storageConfiguration = storageConfiguration;
	}
}

Allow to change the default storage configuration


package tests;

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

@RunWith(Suite.class)
@SuiteClasses({
	CECConfiguratorTests.class,
	EmailBuilderTests.class,
	EmailSortingTests.class,
	EmailTests.class,
	FolderFactoryTests.class })

public class AllTests {
}

package tests;

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

@RunWith(Suite.class)
@SuiteClasses({
	CECConfiguratorTests.class,
	EmailBuilderTests.class,
	EmailSortingTests.class,
	EmailTests.class,
	FolderFactoryTests.class,
	FolderTests.class })

public class AllTests {
}

Include the folder tests in the test suite


package com.novoda.downloadmanager;

import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;

class DownloadBatchNotification implements NotificationCreator {

    private static final int ID = 1;
    private static final boolean NOT_INDETERMINATE = false;

    private final Context context;
    private final int iconDrawable;

    DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) {
        this.context = context.getApplicationContext();
        this.iconDrawable = iconDrawable;
    }

    @Override
    public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle,
                                                      int percentageDownloaded,
                                                      int bytesFileSize,
                                                      int bytesDownloaded) {
        String title = downloadBatchTitle.asString();
        String content = percentageDownloaded + "% downloaded";

        Notification notification = new NotificationCompat.Builder(context)
                .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE)
                .setSmallIcon(iconDrawable)
                .setContentTitle(title)
                .setContentText(content)
                .build();
        return new DownloadBatchNotificationInformation(ID, notification);
    }

    private static class DownloadBatchNotificationInformation implements NotificationInformation {
        private final int id;
        private final Notification notification;

        DownloadBatchNotificationInformation(int id, Notification notification) {
            this.id = id;
            this.notification = notification;
        }

        @Override
        public int getId() {
            return id;
        }

        @Override
        public Notification getNotification() {
            return notification;
        }
    }
}

package com.novoda.downloadmanager;

import android.app.Notification;
import android.content.Context;
import android.support.annotation.DrawableRes;
import android.support.v4.app.NotificationCompat;

class DownloadBatchNotification implements NotificationCreator {

    private static final boolean NOT_INDETERMINATE = false;
    private static final String CHANNEL_ID = "download_manager";

    private final Context context;
    private final int iconDrawable;

    DownloadBatchNotification(Context context, @DrawableRes int iconDrawable) {
        this.context = context.getApplicationContext();
        this.iconDrawable = iconDrawable;
    }

    @Override
    public NotificationInformation createNotification(DownloadBatchTitle downloadBatchTitle,
                                                      int percentageDownloaded,
                                                      int bytesFileSize,
                                                      int bytesDownloaded) {
        String title = downloadBatchTitle.asString();
        String content = percentageDownloaded + "% downloaded";

        Notification notification = new NotificationCompat.Builder(context, CHANNEL_ID)
                .setProgress(bytesFileSize, bytesDownloaded, NOT_INDETERMINATE)
                .setSmallIcon(iconDrawable)
                .setContentTitle(title)
                .setContentText(content)
                .build();

        return new DownloadBatchNotificationInformation(downloadBatchTitle.hashCode(), notification);
    }

    private static class DownloadBatchNotificationInformation implements NotificationInformation {
        private final int id;
        private final Notification notification;

        DownloadBatchNotificationInformation(int id, Notification notification) {
            this.id = id;
            this.notification = notification;
        }

        @Override
        public int getId() {
            return id;
        }

        @Override
        public Notification getNotification() {
            return notification;
        }
    }
}

Introduce a more reliable id and channel for Notifications.


package net.openhft.chronicle.queue.impl;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum StoreFileListeners implements StoreFileListener {
    NO_OP {
        @Override
        public void onReleased(int cycle, File file) {
        }
    },
    DEBUG {
        @Override
        public void onReleased(int cycle, File file) {
            if (Jvm.isDebugEnabled(getClass()))
                Jvm.debug().on(getClass(), "File released " + file);
        }
    }
}

package net.openhft.chronicle.queue.impl;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum StoreFileListeners implements StoreFileListener {
    NO_OP {
        @Override
        public void onReleased(int cycle, File file) {
        }

        @Override
        public boolean isActive() {
            return false;
        }
    },
    DEBUG {
        @Override
        public void onReleased(int cycle, File file) {
            if (Jvm.isDebugEnabled(getClass()))
                Jvm.debug().on(getClass(), "File released " + file);
        }

        @Override
        public boolean isActive() {
            return Jvm.isDebugEnabled(getClass());
        }
    }
}

Resolve merge issues re StoreFIleListeners


package rx.android.eventbus;

import rx.Observer;
import rx.Subscription;
import rx.subjects.Subject;

public interface EventBus {

    /**
     * Subscribes observer to queue.
     *

     * This variant always delivers notifications on the Android main thread.
     */
    <T> Subscription subscribe(Queue<T> queue, Observer<T> observer);

    /**
     * Subscribes observer to queue.
     *

     * Unlike {@link #subscribe(Queue, rx.Observer)}, this variant delivers notifications
     * on the same thread as the event source.
     */
    <T> Subscription subscribeImmediate(Queue<T> queue, Observer<T> observer);

    /**
     * Publishes an event by putting it on the given queue.
     */
    <T> void publish(Queue<T> queue, T event);

    /**
     * @return The Rx {@link rx.subjects.Subject} backing the given event queue.
     */
    <T> Subject<T, T> queue(Queue<T> queue);
}

Remove self-closing tags in JavaDoc


package protocolsupport.protocol.typeremapper.basic;

import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;

@Preload
public class GenericIdRemapper {

	public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
		{
			registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X4, ProtocolVersionsHelper.BEFORE_1_11);
		}
		@Override
		protected EnumRemappingTable<WindowType> createTable() {
			return new EnumRemappingTable<>(WindowType.class);
		}
	};

}

package protocolsupport.protocol.typeremapper.basic;

import protocolsupport.protocol.typeremapper.utils.RemappingRegistry.EnumRemappingRegistry;
import protocolsupport.protocol.typeremapper.utils.RemappingTable.EnumRemappingTable;
import protocolsupport.protocol.types.WindowType;
import protocolsupport.protocol.utils.ProtocolVersionsHelper;
import protocolsupportbuildprocessor.Preload;

@Preload
public class GenericIdRemapper {

	public static final EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>> INVENTORY = new EnumRemappingRegistry<WindowType, EnumRemappingTable<WindowType>>() {
		{
			registerRemapEntry(WindowType.BLAST_FURNACE, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SMOKER, WindowType.FURNACE, ProtocolVersionsHelper.BEFORE_1_14);
			registerRemapEntry(WindowType.SHULKER_BOX, WindowType.GENERIC_9X3, ProtocolVersionsHelper.BEFORE_1_11);
		}
		@Override
		protected EnumRemappingTable<WindowType> createTable() {
			return new EnumRemappingTable<>(WindowType.class);
		}
	};

}

Fix shulker box inventory remap.


/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import io.micrometer.core.instrument.step.StepRegistryConfig;

import java.time.Duration;

public interface SimpleConfig extends StepRegistryConfig {
    SimpleConfig DEFAULT = k -> null;

    // Useful in tests
    Duration DEFAULT_STEP = Duration.ofSeconds(10);

    @Override
    default String prefix() {
        return "simple";
    }

    /**
     * Returns the step size (reporting frequency) to use. The default is 10 seconds.
     */
    default Duration step() {
        String v = get(prefix() + ".step");
        return v == null ? DEFAULT_STEP : Duration.parse(v);
    }
}

/**
 * Copyright 2017 Pivotal Software, Inc.
 *

 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *

 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.micrometer.core.instrument.simple;

import io.micrometer.core.instrument.step.StepRegistryConfig;

import java.time.Duration;

public interface SimpleConfig extends StepRegistryConfig {
    SimpleConfig DEFAULT = k -> null;

    // Useful in tests
    Duration DEFAULT_STEP = Duration.ofMinutes(1);

    @Override
    default String prefix() {
        return "simple";
    }

    /**
     * Returns the step size (reporting frequency) to use. The default is 10 seconds.
     */
    default Duration step() {
        String v = get(prefix() + ".step");
        return v == null ? DEFAULT_STEP : Duration.parse(v);
    }
}

Change default SimpleMeterRegistry step to 1 minute


package com.stefanhoth.ropasclisp.achievements;

import com.stefanhoth.ropasclisp.games_sdk.PlayGamesClient;

public class AchievementObserver {

    private final PlayGamesClient playGamesClient;
    private final boolean firstSessionToday;

    public AchievementObserver(PlayGamesClient playGamesClient, boolean firstSessionToday) {
        this.playGamesClient = playGamesClient;
        this.firstSessionToday = firstSessionToday;
    }

    public void onGameStart() {
        // first game start ever
        playGamesClient.unlockAchievement(ACHIEVEMENT.HELLO_THERE);

        // on X game starts per day
        if(! firstSessionToday){
            playGamesClient.unlockAchievement(ACHIEVEMENT.CONNOISSEUR);
            playGamesClient.unlockAchievement(ACHIEVEMENT.ADDICT);
        }
    }

    public void onGameWin() {
        playGamesClient.unlockAchievement(ACHIEVEMENT.GOTCHA);
        playGamesClient.unlockAchievement(ACHIEVEMENT.ON_A_ROLL);
        playGamesClient.unlockAchievement(ACHIEVEMENT.POKER_FACE);
    }
}

package com.stefanhoth.ropasclisp.achievements;

import android.content.Context;

import com.stefanhoth.ropasclisp.games_sdk.PlayGamesClient;

public class AchievementObserver {

    private final PlayGamesClient playGamesClient;
    private final Context context;

    public AchievementObserver(PlayGamesClient playGamesClient, final Context context) {
        this.playGamesClient = playGamesClient;
        this.context = context;
    }

    public void onGameStart() {
        // first game start ever
        playGamesClient.unlockAchievement(ACHIEVEMENT.HELLO_THERE);

        DAILY_STATE dailyState = DAILY_STATE.with(context);

        // on X game starts per day
        if (!dailyState.isTodaysFirstStart()) {

            final int todaysStarts = dailyState.getTodaysStarts();
            if (ACHIEVEMENT.ADDICT.isGoalReached(todaysStarts)) {
                playGamesClient.unlockAchievement(ACHIEVEMENT.ADDICT);
            }
            if (ACHIEVEMENT.CONNOISSEUR.isGoalReached(todaysStarts)) {
                playGamesClient.unlockAchievement(ACHIEVEMENT.CONNOISSEUR);
            }

        }
    }

    public void onGameWin() {
        playGamesClient.unlockAchievement(ACHIEVEMENT.GOTCHA);
        playGamesClient.unlockAchievement(ACHIEVEMENT.ON_A_ROLL);
        playGamesClient.unlockAchievement(ACHIEVEMENT.POKER_FACE);
    }
}

Correct behavior for daily start awards


package org.nwapw.abacus;

public class Abacus {

    public static void main(String[] args){
        System.out.println("Hello world!");
    }

}

package org.nwapw.abacus;

import org.nwapw.abacus.window.Window;

import javax.swing.*;

public class Abacus {

    private Window mainUi;

    public Abacus(){
        init();
    }

    private void init() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
            e.printStackTrace();
        }
        mainUi = new Window();
        mainUi.setVisible(true);
    }

    public static void main(String[] args){
        new Abacus();
    }

}

Make the program actually create the UI.


/***
 *
 * Copyright 2014 Andrew Hall
 *
 * 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.statefulj.framework.core.model.impl;

import org.statefulj.framework.core.model.Factory;

public class FactoryImpl<T, CT> implements Factory<T, CT> {

	@Override
	public T create(Class<T> clazz, String event, CT context) {
		T newInstance = null;
		try {
			newInstance = clazz.newInstance();
		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		}
		return newInstance;
	}

}

/***
 *
 * Copyright 2014 Andrew Hall
 *
 * 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.statefulj.framework.core.model.impl;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.statefulj.framework.core.model.Factory;

public class FactoryImpl<T, CT> implements Factory<T, CT> {

	@Override
	public T create(Class<T> clazz, String event, CT context) {
		try {
			Constructor<T> ctr = clazz.getDeclaredConstructor();
			ctr.setAccessible(true);
			return ctr.newInstance();
		} catch(IllegalAccessException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (InvocationTargetException e) {
			throw new RuntimeException(e);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(clazz.getCanonicalName() + " does not have a default constructor");
		}
	}

}

Add in ability to instantiate non public default constructors


package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.*;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";
    protected static final String NEWLINE_REGEX = "\\r?\\n";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testRule() throws IOException {
        for ( File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals(errContent.toString(), "");
            System.setErr(null);
        }
    }

}

package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testRule() {
        for (File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals(errContent.toString(), "");
            System.setErr(null);
        }
    }

}

Adjust code style, remove constant and exception


package me.mattlogan.artiste.example;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

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

package me.mattlogan.artiste.example;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

Use AppCompatActivity in example project


package org.inferred.cjp39.j8stages;

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

import org.junit.Test;

public class ExceptionClonerTest {

    private static final class MyUnfriendlyException extends Exception {
        private MyUnfriendlyException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    @Test
    public void clone_matches_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        assertEquals(x.getMessage(), clone.getMessage());
        assertSame(x.getCause(), clone.getCause());
    }

    @Test
    public void modifying_clone_does_not_modify_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        assertEquals(0, x.getSuppressed().length);
    }
}

package org.inferred.cjp39.j8stages;

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

import org.junit.Test;

public class ExceptionClonerTest {

    private static final class MyUnfriendlyException extends Exception {
        private MyUnfriendlyException(String message, Throwable cause) {
            super(message, cause);
        }
    }

    @Test
    public void clone_matches_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        assertEquals(x.getMessage(), clone.getMessage());
        assertSame(x.getCause(), clone.getCause());
    }

    @Test
    public void modifying_clone_does_not_modify_original() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        assertEquals(0, x.getSuppressed().length);
    }

    @Test
    public void suppressed_array_not_aliased() {
        MyUnfriendlyException x =
                new MyUnfriendlyException("Clone this, baby!", new RuntimeException("cause"));
        x.addSuppressed(new RuntimeException("Help, help, I'm being repressed!"));
        MyUnfriendlyException clone = ExceptionCloner.clone(x);
        clone.addSuppressed(new RuntimeException("dormouse"));
        MyUnfriendlyException clone2 = ExceptionCloner.clone(clone);
        clone2.addSuppressed(new RuntimeException("in a teapot"));
        assertEquals(3, clone2.getSuppressed().length);
        assertEquals(2, clone.getSuppressed().length);
        assertEquals(1, x.getSuppressed().length);
    }
}

Add a test to ensure the list of suppressed exceptions in a Throwable is not accidentally aliased during the shallow copy.


package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Hyperbolic neighborhood width strategy for self-organizing map.
 */
public class HyperbolicNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private double expectedIterations;

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return expectedIterations / (expectedIterations + iteration);
    }

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

package cs437.som.neighborhood;

import cs437.som.NeightborhoodWidthFunction;

/**
 * Hyperbolic neighborhood width strategy for self-organizing map.
 *
 * The exact behavior follows the formula:
 *      w_i / (t + t_max)
 *  where
 *      w_i   is the initial width of the neighborhood
 *      t     is the current iteration
 *      t_max is the maximum expected iteration
 */
public class HyperbolicNeighborhoodWidthFunction implements NeightborhoodWidthFunction {
    private double expectedIterations = 0.0;

    public void setExpectedIterations(int expectedIterations) {
        this.expectedIterations = expectedIterations;
    }

    public double neighborhoodWidth(int iteration) {
        return expectedIterations / (expectedIterations + iteration);
    }

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

Add formula comment to hyperbolic NW class.


package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testSynthLookAndFeel() {
        LookAndFeel plaf = new SynthLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testMetalLookAndFeel() {
        LookAndFeel plaf = new MetalLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

Use L&F that is available on JDK 1.3


package com.developi.wink.demo.api;

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

import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.osgi.core.context.ContextInfo;

import lotus.domino.NotesException;
import lotus.domino.Session;

@Path("/test")
public class TestResource {

	@GET
	public Response test(){
		JsonJavaObject resp = new JsonJavaObject();

		try {
			resp.put("message", "Hello " + getUserSession().getEffectiveUserName());
			return Response.ok().type(MediaType.APPLICATION_JSON).entity(resp.toString()).build();
		} catch (NotesException e) {
			e.printStackTrace();
			return Response.serverError().build();
		}

	}

	private Session getUserSession() {
		return ContextInfo.getUserSession();
	}

}

package com.developi.wink.demo.api;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import com.ibm.domino.osgi.core.context.ContextInfo;

import lotus.domino.NotesException;
import lotus.domino.Session;

@Path("/test")
public class TestResource {

	@GET
	public Response test(){
		try {
			String userName = getUserSession().getEffectiveUserName();

			if("Anonymous".equals(userName)) {
				// If connected through a browser, this response will signal for authentication and redirected to the login form.
				// However, be careful with 40x responses. If session authentication is enabled for the server,
				// The consumer might receive the login form and 200-OK response. This would be a code-breaker.
				return Response.status(Status.UNAUTHORIZED).build();
			} else {
				String message = "<b>Hello " + userName + "</b>";
				return Response.ok().type(MediaType.TEXT_HTML).entity(message).build();
			}
		} catch (NotesException e) {
			e.printStackTrace();
			return Response.serverError().build();
		}

	}

	private Session getUserSession() {
		return ContextInfo.getUserSession();
	}

}

Add authentication and modify response type for /test


package org.wordpress.aztec.demo;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.wordpress.aztec.demo.TestUtils.enterHTML;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class SimpleTextFormattingTests {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testSimpleBoldFormatting() {
        enterHTML("<b>hello world</b>");

        ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold));
        boldButton.check(matches(isChecked()));
    }
}

package org.wordpress.aztec.demo;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isChecked;
import static android.support.test.espresso.matcher.ViewMatchers.isNotChecked;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.wordpress.aztec.demo.TestUtils.enterHTML;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class SimpleTextFormattingTests {

    @Rule
    public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);

    @Test
    public void testSimpleBoldFormatting() {
        ViewInteraction boldButton = onView(withId(R.id.format_bar_button_bold));
        boldButton.check(matches(isNotChecked()));

        enterHTML("<b>hello world</b>");

        boldButton.check(matches(isChecked()));
    }
}

Add check for disabled format button at start of test


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

import org.apache.jackrabbit.oak.NodeStoreFixture;
import org.apache.jackrabbit.oak.spi.state.NodeStore;

class AbstractKernelTest {

    protected NodeStore createNodeStore() {
        return NodeStoreFixture.MK_IMPL.createNodeStore();
    }
}

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

import org.apache.jackrabbit.oak.NodeStoreFixture;
import org.apache.jackrabbit.oak.spi.state.NodeStore;

class AbstractKernelTest {

    protected NodeStore createNodeStore() {
        return NodeStoreFixture.SEGMENT_MK.createNodeStore();
    }
}

Use SegmentMK for testing where possible


package com.worldspotlightapp.android.ui;

import android.os.Bundle;
import android.util.Log;

import com.worldspotlightapp.android.R;
import com.worldspotlightapp.android.model.Organizer;

import java.util.Observable;

public class OrganizerDetailsActivity extends AbstractBaseActivityObserver {

    private static final String TAG = "OrganizerDetails";

    private String mOrganizerObjectId;

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

        // Get the organizer object id from the intent
        Bundle extras = getIntent().getExtras();
        if (extras == null || !extras.containsKey(Organizer.INTENT_KEY_OBJECT_ID)) {
            throw new IllegalArgumentException("You must pass the organizer object id through the intent");
        }

        mOrganizerObjectId = extras.getString(Organizer.INTENT_KEY_OBJECT_ID);
        Log.v(TAG, "The object id got from the intent is " + mOrganizerObjectId);
    }

    @Override
    protected void processDataIfExists() {
        // TODO: implement this
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO: implement this
    }
}

package com.worldspotlightapp.android.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;

import com.worldspotlightapp.android.R;
import com.worldspotlightapp.android.model.Organizer;

import java.util.Observable;

public class OrganizerDetailsActivity extends AbstractBaseActivityObserver {

    private static final String TAG = "OrganizerDetails";

    private String mOrganizerObjectId;

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

        // Get the organizer object id from the intent
        Bundle extras = getIntent().getExtras();
        if (extras == null || !extras.containsKey(Organizer.INTENT_KEY_OBJECT_ID)) {
            throw new IllegalArgumentException("You must pass the organizer object id through the intent");
        }

        mOrganizerObjectId = extras.getString(Organizer.INTENT_KEY_OBJECT_ID);
        Log.v(TAG, "The object id got from the intent is " + mOrganizerObjectId);

        // Action bar
        mActionBar.setDisplayHomeAsUpEnabled(true);

    }

    @Override
    protected void processDataIfExists() {
        // TODO: implement this
    }

    @Override
    public void update(Observable observable, Object data) {
        // TODO: implement this
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Log.v(TAG, "home button pressed");
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Set back button for the organizer details activity


/*
 * Copyright 2012, Mysema 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 com.mysema.query.maven;

import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;

import com.mysema.query.codegen.GenericExporter;

/**
 * JDOExporterMojo calls the GenericExporter tool using the classpath of the module
 *
 * @goal jdo-export
 * @requiresDependencyResolution test
 * @author tiwe
 */
public class JDOExporterMojo extends AbstractExporterMojo {

    @Override
    protected void configure(GenericExporter exporter) {
        exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
        exporter.setEmbeddedAnnotation(Embedded.class);
        exporter.setEntityAnnotation(PersistenceCapable.class);
        exporter.setSkipAnnotation(NotPersistent.class);
        exporter.setSupertypeAnnotation(null);
    }

}

/*
 * Copyright 2012, Mysema 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 com.mysema.query.maven;

import javax.jdo.annotations.EmbeddedOnly;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.persistence.Embedded;

import com.mysema.query.codegen.GenericExporter;

/**
 * JDOExporterMojo calls the GenericExporter tool using the classpath of the module
 *
 * @goal jdo-export
 * @requiresDependencyResolution test
 * @author tiwe
 */
public class JDOExporterMojo extends AbstractExporterMojo {

    @Override
    protected void configure(GenericExporter exporter) {
        exporter.setEmbeddableAnnotation(EmbeddedOnly.class);
        exporter.setEmbeddedAnnotation(Embedded.class);
        exporter.setEntityAnnotation(PersistenceCapable.class);
        exporter.setSkipAnnotation(NotPersistent.class);
    }

}

Fix NPE when exporting JDO using maven plugin


package org.atlasapi.application.auth;

import static com.google.common.base.Preconditions.checkNotNull;

import javax.servlet.http.HttpServletRequest;

import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;

public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {

    public static final String API_KEY_QUERY_PARAMETER = "key";

    private final ApplicationStore reader;

    public ApiKeySourcesFetcher(ApplicationStore reader) {
        this.reader = checkNotNull(reader);
    }

    @Override
    public ImmutableSet<String> getParameterNames() {
        return ImmutableSet.of();
    }

    @Override
    public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException  {
        String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
        if (apiKey == null) {
            apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
        }
        if (apiKey != null) {
            Optional<Application> app = reader.applicationForKey(apiKey);
            if (!app.isPresent() || app.get().isRevoked()) {
                throw new InvalidApiKeyException(apiKey);
            }
            return Optional.of(app.get().getSources());
        }
        return Optional.absent();
    }
}

package org.atlasapi.application.auth;

import static com.google.common.base.Preconditions.checkNotNull;

import javax.servlet.http.HttpServletRequest;

import org.atlasapi.application.Application;
import org.atlasapi.application.ApplicationSources;
import org.atlasapi.application.ApplicationStore;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;

public class ApiKeySourcesFetcher implements ApplicationSourcesFetcher {

    public static final String API_KEY_QUERY_PARAMETER = "key";

    private final ApplicationStore reader;

    public ApiKeySourcesFetcher(ApplicationStore reader) {
        this.reader = checkNotNull(reader);
    }

    @Override
    public ImmutableSet<String> getParameterNames() {
        return ImmutableSet.of(API_KEY_QUERY_PARAMETER);
    }

    @Override
    public Optional<ApplicationSources> sourcesFor(HttpServletRequest request) throws InvalidApiKeyException  {
        String apiKey = request.getParameter(API_KEY_QUERY_PARAMETER);
        if (apiKey == null) {
            apiKey = request.getHeader(API_KEY_QUERY_PARAMETER);
        }
        if (apiKey != null) {
            Optional<Application> app = reader.applicationForKey(apiKey);
            if (!app.isPresent() || app.get().isRevoked()) {
                throw new InvalidApiKeyException(apiKey);
            }
            return Optional.of(app.get().getSources());
        }
        return Optional.absent();
    }
}

Revert "api key deleted from the list of required parameters"


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.util.List;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * An object that represents a scope in JavaScript.
 */
public interface JsScope {

  enum Type {
    GLOBAL,
    LOCAL,
    WITH,
    CLOSURE,
    CATCH,
    UNKNOWN
  }

  /**
   * @return type of the scope
   */
  Type getType();

  /**
   * @return optional subtype when type is {@link Type#WITH} and null otherwise
   */
  WithScope asWithScope();

  /**
   * @return the variables known in this scope, in lexicographical order
   * @throws MethodIsBlockingException because it may need to load value from remote
   */
  List<? extends JsVariable> getVariables() throws MethodIsBlockingException;

  /**
   * Subtype that exposes the value of the 'with' statement expression (the value might be
   * already converted by ToObject).
   */
  interface WithScope extends JsScope {
    /**
     * @throws MethodIsBlockingException because it may need to load value from remote
     */
    JsValue getWithArgument() throws MethodIsBlockingException;
  }
}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.sdk;

import java.util.List;

import org.chromium.sdk.util.MethodIsBlockingException;

/**
 * An object that represents a scope in JavaScript.
 * TODO: consider adding object getter for both with and global scopes.
 */
public interface JsScope {

  enum Type {
    GLOBAL,
    LOCAL,
    WITH,
    CLOSURE,
    CATCH,
    UNKNOWN
  }

  /**
   * @return type of the scope
   */
  Type getType();

  /**
   * @return optional subtype when type is {@link Type#WITH} and null otherwise
   */
  WithScope asWithScope();

  /**
   * @return the variables known in this scope, in lexicographical order
   * @throws MethodIsBlockingException because it may need to load value from remote
   */
  List<? extends JsVariable> getVariables() throws MethodIsBlockingException;

  /**
   * Subtype that exposes the value of the 'with' statement expression (the value might be
   * already converted by ToObject).
   */
  interface WithScope extends JsScope {
    /**
     * @throws MethodIsBlockingException because it may need to load value from remote
     */
    JsValue getWithArgument() throws MethodIsBlockingException;
  }
}

Add 'watch property descriptor' action


package com.farm.environment.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {
        "com.farm.processes",
        "com.farm.rest"
})
public class BeansConfiguration {

}

package com.farm.environment.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {
        "com.farm.database.processes",
        "com.farm.rest"
})
public class BeansConfiguration {

}

Correct componets path to scan


package com.codahale.metrics.jvm;

import com.codahale.metrics.Gauge;
import org.junit.Test;

import java.lang.management.ClassLoadingMXBean;

import static org.fest.assertions.api.Assertions.assertThat;

public class ClassLoadingGaugeSetTest {

    private final ClassLoadingMXBean cl = new ClassLoadingMXBean() {
        @Override
        public long getTotalLoadedClassCount() {
            return 2;
        }

        @Override
        public int getLoadedClassCount() {
            return 3;
        }

        @Override
        public long getUnloadedClassCount() {
            return 1;
        }

        @Override
        public boolean isVerbose() {
            return false;
        }

        @Override
        public void setVerbose(boolean value) {

        }
    };

    private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl);

    @Test
    public void loadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("loaded");
        assertThat(gauge.getValue()).isEqualTo(2L);
    }

    @Test
    public void unLoadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("unloaded");
        assertThat(gauge.getValue()).isEqualTo(1L);
    }

}

package com.codahale.metrics.jvm;

import com.codahale.metrics.Gauge;
import org.junit.Before;
import org.junit.Test;

import java.lang.management.ClassLoadingMXBean;

import static org.fest.assertions.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ClassLoadingGaugeSetTest {

    private final ClassLoadingMXBean cl = mock(ClassLoadingMXBean.class);
    private final ClassLoadingGaugeSet gauges = new ClassLoadingGaugeSet(cl);

    @Before
    public void setUp() throws Exception {
        when(cl.getTotalLoadedClassCount()).thenReturn(2L);
        when(cl.getUnloadedClassCount()).thenReturn(1L);
    }

    @Test
    public void loadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("loaded");
        assertThat(gauge.getValue()).isEqualTo(2L);
    }

    @Test
    public void unLoadedGauge() throws Exception {
        final Gauge gauge = (Gauge) gauges.getMetrics().get("unloaded");
        assertThat(gauge.getValue()).isEqualTo(1L);
    }

}

Switch to a mocking way of testing.


package com.github.chrisblutz.trinity.libraries.compiling;

/**
 * @author Christopher Lutz
 */
public class CompileException extends RuntimeException {

    public CompileException(String file, long line, String message) {

        super("Compilation error on line " + line + " in " + file + ".");
        setStackTrace(new StackTraceElement[]{});
    }
}

package com.github.chrisblutz.trinity.libraries.compiling;

/**
 * @author Christopher Lutz
 */
public class CompileException extends RuntimeException {

    public CompileException(String file, long line, String message) {

        super("Compilation error on line " + line + " in " + file + ": " + message);
        setStackTrace(new StackTraceElement[]{});
    }
}

Use message in library compilation errors


package musician101.common.java.minecraft.sponge.command;

import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;

import javax.annotation.Nonnull;
import java.util.Arrays;

public class SpongeHelpCommand extends AbstractSpongeCommand
{
    private final AbstractSpongeCommand mainCommand;

    public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
    {
        super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
        this.mainCommand = mainCommand;
    }

    @Nonnull
    @Override
    public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
    {
        source.sendMessage(Texts.of());
        source.sendMessage(mainCommand.getUsage(source));
        mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
        return CommandResult.success();
    }
}

package musician101.common.java.minecraft.sponge.command;

import org.spongepowered.api.text.Text.Literal;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;

import javax.annotation.Nonnull;
import java.util.Arrays;

public class SpongeHelpCommand extends AbstractSpongeCommand
{
    private final AbstractSpongeCommand mainCommand;

    public SpongeHelpCommand(AbstractSpongeCommand mainCommand, CommandSource source)
    {
        super("help", "Display help info for " + mainCommand.getUsage(source), Arrays.asList(new SpongeCommandArgument(((Literal) mainCommand.getUsage(source)).getContent()), new SpongeCommandArgument("help")), 1, "", false, null, null);
        this.mainCommand = mainCommand;
    }

    @Nonnull
    @Override
    public CommandResult process(@Nonnull CommandSource source, @Nonnull String arguments) throws CommandException
    {
        source.sendMessage(Texts.of(mainCommand.getUsage(source), mainCommand.getShortDescription(source)));
        mainCommand.getSubCommands().forEach(command -> source.sendMessage(command.getHelp(source).get()));
        return CommandResult.success();
    }
}

Add description to the help message.


package org.nwapw.abacus.function;

import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.TreeNode;

/**
 * A function that operates on parse tree nodes instead of on already simplified numbers.
 * Despite this, it returns a number, not a tree.
 */
public abstract class TreeValueFunction extends Applicable<TreeNode, NumberInterface> {

}

package org.nwapw.abacus.function;

import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.Reducer;
import org.nwapw.abacus.tree.TreeNode;

/**
 * A function that operates on parse tree nodes instead of on already simplified numbers.
 * Despite this, it returns a number, not a tree.
 */
public abstract class TreeValueFunction extends Applicable<TreeNode, NumberInterface> {

    @Override
    protected NumberInterface applyInternal(TreeNode[] params) {
        return null;
    }

    @Override
    public NumberInterface apply(TreeNode... params) {
        return null;
    }

    /**
     * Applies the tree value functions to the given tree nodes,
     * using the given reducer.
     * @param reducer the reducer to use.
     * @param params the parameters to apply to.
     * @return the result of the application.
     */
    public abstract NumberInterface applyWithReducerInternal(Reducer<NumberInterface> reducer, TreeNode[] params);

    /**
     * Checks if the given parameters and reducer can be used
     * with this function, and if so, calls the function on them.
     * @param reducer the reducer to use.
     * @param params the parameters to apply to.
     * @return the result of the application, or null if the parameters are incompatible.
     */
    public NumberInterface applyWithReducer(Reducer<NumberInterface> reducer, TreeNode... params) {
        if(!matchesParams(params) || reducer == null) return null;
        return applyWithReducerInternal(reducer, params);
    }
}

Add the withReducer variants of the Applier functions.


package org.tylproject.vaadin.addon.utils;

import com.vaadin.addon.jpacontainer.EntityItem;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import org.vaadin.viritin.DynaBeanItem;
import org.vaadin.viritin.ListContainer;

/**
 * Extracts bean from an Item, depending on the Container implementation
 */
public class DefaultBeanExtractor implements BeanExtractor {
    @Override
    public Object extract(Object itemId, Item item) throws IllegalArgumentException {

        final Class<?> itemClass = item.getClass();
        Object bean;

        if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass)) {
            bean = itemId;
        } else
        if (isJPAContainer(itemClass)) {
            bean = ((EntityItem<?>)item).getEntity();
        } else
        if (BeanItem.class.isAssignableFrom(item.getClass())) {
            bean = ((BeanItem<?>) item).getBean();
        } else{
            throw new UnsupportedOperationException(
                    "Unknown item type: "+itemClass.getCanonicalName());
        }

        return bean;
    }

    protected boolean isJPAContainer(Class<?> itemClass) {
        try {
            return EntityItem.class.isAssignableFrom(itemClass);
        } catch (NoClassDefFoundError ex) { return false; }
    }

}

package org.tylproject.vaadin.addon.utils;

import com.vaadin.addon.jpacontainer.EntityItem;
import com.vaadin.data.Item;
import com.vaadin.data.util.BeanItem;
import org.vaadin.viritin.DynaBeanItem;
import org.vaadin.viritin.ListContainer;

/**
 * Extracts bean from an Item, depending on the Container implementation
 */
public class DefaultBeanExtractor implements BeanExtractor {
    @Override
    public Object extract(Object itemId, Item item) throws IllegalArgumentException {

        final Class<?> itemClass = item.getClass();
        Object bean;

        if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass)
            || DynaBeanItem.class.isAssignableFrom(itemClass)) {
            bean = itemId;
        } else
        if (isJPAContainer(itemClass)) {
            bean = ((EntityItem<?>)item).getEntity();
        } else
        if (BeanItem.class.isAssignableFrom(item.getClass())) {
            bean = ((BeanItem<?>) item).getBean();
        } else{
            throw new UnsupportedOperationException(
                    "Unknown item type: "+itemClass.getCanonicalName());
        }

        return bean;
    }

    protected boolean isJPAContainer(Class<?> itemClass) {
        try {
            return EntityItem.class.isAssignableFrom(itemClass);
        } catch (NoClassDefFoundError ex) { return false; }
    }

}

Fix bug in BeanExtractor (DynaBeanItem was not recognized)


/*
 * Copyright 2016 Crown Copyright
 *
 * 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 stroom.data.client.presenter;

public final class ColumnSizeConstants {

    public static final int CHECKBOX_COL = 16;
    public static final int ICON_COL = 20;
    public static final int SMALL_COL = 70;
    public static final int MEDIUM_COL = 100;
    public static final int BIG_COL = 400;
    public static final int DATE_COL = 160;

    private ColumnSizeConstants() {
        // Constants.
    }
}

/*
 * Copyright 2016 Crown Copyright
 *
 * 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 stroom.data.client.presenter;

public final class ColumnSizeConstants {

    public static final int CHECKBOX_COL = 16;
    public static final int ICON_COL = 23;
    public static final int SMALL_COL = 70;
    public static final int MEDIUM_COL = 100;
    public static final int BIG_COL = 400;
    public static final int DATE_COL = 160;

    private ColumnSizeConstants() {
        // Constants.
    }
}

Increase datagrid icon column width