/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state

    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

Disable term lookup smoke test to avoid any server impact till fixed.


package uk.ac.ebi.quickgo.geneproduct.common;

/**
 * An enumeration of the possible states of proteome membership a gene product can have.
 * @author Tony Wardell
 * Date: 06/03/2018
 * Time: 10:33
 * Created with IntelliJ IDEA.
 */
public enum ProteomeMembership {
    REFERENCE("Reference"),
    COMPLETE("Complete"),
    NONE("None"),
    NOT_APPLICABLE("Not-applicable");

    private String value;

    ProteomeMembership(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }

    /**
     * Define the predicates required and order of importance to work out which Proteome membership category is
     * applicable.
     * @param isProtein is the gene product a protein
     * @param isReferenceProteome is the gene product a reference proteome
     * @param isComplete is the gene product a member of a complete proteome.
     * @return the String representation of the ProteomeMembership matching the applied constraints
     */
    public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {

        if (!isProtein) {
            return NOT_APPLICABLE.toString();
        } else if (isReferenceProteome) {
            return REFERENCE.toString();
        } else if (isComplete) {
            return COMPLETE.toString();
        }
        return NONE.toString();
    }
}

package uk.ac.ebi.quickgo.geneproduct.common;

/**
 * An enumeration of the possible states of proteome membership a gene product can have.
 * @author Tony Wardell
 * Date: 06/03/2018
 * Time: 10:33
 * Created with IntelliJ IDEA.
 */
public enum ProteomeMembership {
    REFERENCE("Reference"),
    COMPLETE("Complete"),
    NONE("None"),
    NOT_APPLICABLE("Not-applicable");

    private String value;

    ProteomeMembership(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }

    /**
     * Define the predicates required and order of importance to work out which Proteome membership category is
     * applicable.
     * @param isProtein is the gene product a protein
     * @param isReferenceProteome is the gene product a reference proteome
     * @param isComplete is the gene product a member of a complete proteome.
     * @return the String representation of the ProteomeMembership matching the applied constraints
     */
    public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {

        if (!isProtein) {
            return NOT_APPLICABLE.toString();
        } else if (isReferenceProteome) {
            return REFERENCE.toString();
        } else if (isComplete) {
            return COMPLETE.toString();
        }
        return NONE.toString();
    }
}

Add @Override annotation for toString()


package org.realityforge.arez.annotations;

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

/**
 * Methods marked with this annotation are invoked in an Arez transaction.
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Action
{
  /**
   * Return the name of the Action relative to the container.
   *
   * @return the name of the Action relative to the container.
   */
  String name() default "";

  /**
   * Does the action mutate state or not.
   *
   * @return true if method should be wrapped in READ_WRITE transaction, false if it should it should be wrapped in READ_ONLY transaction.
   */
  boolean mutation() default true;
}

package org.realityforge.arez.annotations;

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

/**
 * Methods marked with this annotation are invoked in an Arez transaction.
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Action
{
  /**
   * Return the name of the Action relative to the container.
   *
   * @return the name of the Action relative to the container.
   */
  String name() default "<default>";

  /**
   * Does the action mutate state or not.
   *
   * @return true if method should be wrapped in READ_WRITE transaction, false if it should it should be wrapped in READ_ONLY transaction.
   */
  boolean mutation() default true;
}

Use sentinel value to represent default name


package com.tterrag.blur.config;

import com.tterrag.blur.Blur;

import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;

public class BlurConfigGui extends GuiConfig {

    public BlurConfigGui(GuiScreen parentScreen) {
        super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
    }
}

package com.tterrag.blur.config;

import javax.annotation.Nonnull;

import com.tterrag.blur.Blur;

import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.Tessellator;
import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.fml.client.config.GuiConfig;
import net.minecraftforge.fml.client.config.GuiConfigEntries;

public class BlurConfigGui extends GuiConfig {

    public BlurConfigGui(GuiScreen parentScreen) {
        super(parentScreen, new ConfigElement(Blur.instance.config.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Blur.MODID, false, false, Blur.MODID + ".config.title");
    }

    @Override
    public void initGui() {
        super.initGui();
        this.entryList = new GuiConfigEntries(this, mc) {
            @SuppressWarnings({ "unused", "null" })
            @Override
            protected void drawContainerBackground(@Nonnull Tessellator tessellator) {
                if (mc.world == null) {
                    super.drawContainerBackground(tessellator);
                }
            }
        };
    }

    @Override
    public void drawDefaultBackground() {
        drawWorldBackground(0);
    }
}

Make config GUI see-through when in a world


package com.chaos.databinding.activities;

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

import com.chaos.databinding.R;
import com.chaos.databinding.models.User;
import com.chaos.databinding.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        final User user = this.getUser();

        binding.setUser(user);
    }

    private User getUser() {
        return new User("Ash Davies", "Berlin");
    }
}

package com.chaos.databinding.activities;

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

import com.chaos.databinding.R;
import com.chaos.databinding.models.User;
import com.chaos.databinding.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        this.updateUser();
    }

    private void updateUser() {
        binding.setUser(this.getUser());
    }

    private User getUser() {
        return new User("Ash Davies", "Berlin");
    }
}

Store binding as local variable


package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		this.properties.setProperty('name', eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		this.properties.setProperty("name", eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

Fix event name not being added in constructor.


package org.odindelrio.dddaopentitybehaviour.domain;

import org.odindelrio.dddaopentitybehaviour.domain.exception.FollowerCantFollowHimSelfException;

public class Follower {
  private final String followerId;
  public FollowersRepository followersRepository;

  public Follower(String followerId) {
    this.followerId = followerId;
  }

  public String getFollowerId() {
    return followerId;
  }

  public void follow(Followable followable) {
    if (followable.getFollowableId().equals(followerId)) {
      throw new FollowerCantFollowHimSelfException();
    }

    System.out.println("INSIDE Follower.follow() method");

    this.followersRepository.persistFollower(this, followable);
  }
}

package org.odindelrio.dddaopentitybehaviour.domain;

import org.odindelrio.dddaopentitybehaviour.domain.exception.FollowerCantFollowHimSelfException;

public class Follower {
  private final String followerId;
  public transient FollowersRepository followersRepository;

  public Follower(String followerId) {
    this.followerId = followerId;
  }

  public String getFollowerId() {
    return followerId;
  }

  public void follow(Followable followable) {
    if (followable.getFollowableId().equals(followerId)) {
      throw new FollowerCantFollowHimSelfException();
    }

    System.out.println("INSIDE Follower.follow() method");

    this.followersRepository.persistFollower(this, followable);
  }
}

Make entity dependency transient, telling serializers that repository shouldn't be serialized.


package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class TDPExceptionController {

    @ExceptionHandler(InternalException.class)
    public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

    @ExceptionHandler(UserException.class)
    public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

}

package org.talend.dataprep.exception;

import java.io.StringWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class TDPExceptionController {

    @ExceptionHandler(InternalException.class)
    public @ResponseBody String handleInternalError(HttpServletResponse response, InternalException e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

    @ExceptionHandler(UserException.class)
    public @ResponseBody String handleUserError(HttpServletResponse response, UserException e) {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        final StringWriter message = new StringWriter();
        e.writeTo(message);
        return message.toString();
    }

}

Fix wrong content-type in case of exception (should be application/json).


package ca.ualberta.cs.swapmyride;

import android.test.ActivityInstrumentationTestCase2;

/**
 * Created by Conner on 15-10-08.
 */
public class PhotoTest extends ActivityInstrumentationTestCase2 {
    public PhotoTest(){
        super(MainMenu.class);
    }

    public void testAddPhotoToItem(){
        Item item = new Item();
        item.setPhoto(picture);
        assertTrue(item.getPhoto().equals(photo));

        Boolean thrown = false;
        try {
            item.setPhoto(tooLargePicture);
        } catch (Exception e){
            thrown = true;
        }
        assertTrue(thrown);
    }

    public void testViewPhoto(){
        Item item = new Item();

        Boolean thrown = false;
        try {
            item.getPhoto();  // no photo set yet
        } catch (Exception e){
            thrown = true;
        }
        assertTrue(thrown);

        item.setPhoto(picture);
        Boolean thrown2 = false;
        try {
            item.getPhoto();  // shouldn't throw an error, photo is added
        } catch (Exception e){
            thrown2 = true;
        }
        assertFalse(thrown2);
    }
}

package ca.ualberta.cs.swapmyride;

import android.test.ActivityInstrumentationTestCase2;

/**
 * Created by Conner on 15-10-08.
 */
public class PhotoTest extends ActivityInstrumentationTestCase2 {
    public PhotoTest(){
        super(MainMenu.class);
    }

    public void testAddPhotoToItem(){
        Item item = new Item();
        item.setPhoto(picture);
        assertTrue(item.getPhoto().equals(photo));

        Boolean thrown = false;
        try {
            item.setPhoto(tooLargePicture);
        } catch (Exception e){
            thrown = true;
        }
        assertTrue(thrown);
    }

    public void testViewPhoto(){
        Item item = new Item();

        Boolean thrown = false;
        try {
            item.getPhoto();  // no photo set yet
        } catch (Exception e){
            thrown = true;
        }
        assertTrue(thrown);

        item.setPhoto(picture);
        Boolean thrown2 = false;
        try {
            item.getPhoto();  // shouldn't throw an error, photo is added
        } catch (Exception e){
            thrown2 = true;
        }
        assertFalse(thrown2);
    }

    public void testDeletePhoto(){
        Item item = new Item();

        Boolean thrown = false;
        try {
            item.deletePhoto();  // no photo, error
        } catch (Exception e){
            thrown = true;
        }
        assertTrue(thrown);

        item.setPhoto(picture);
        assertTrue(item.getPhoto().equals(photo));
        Boolean thrown2 = false;
        try {
            item.deletePhoto();  // shouldn't throw an error, photo is added
        } catch (Exception e){
            thrown2 = true;
        }
        assertFalse(thrown2);

    }
}

Use Case 25: Delete Photo


package com.sanctionco.thunder.util;

import com.google.common.io.Resources;

import java.io.IOException;

import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;

import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mockStatic;

class FileUtilitiesTest {

  @Test
  void shouldReadTestFile() {
    assertEquals("test", FileUtilities.readFileAsResources("fixtures/test.txt"));
  }

  @Test
  void shouldThrowOnNonexistentFile() {
    IllegalStateException nonexistent = assertThrows(IllegalStateException.class,
        () -> FileUtilities.readFileAsResources("not-exist"));

    assertTrue(nonexistent.getCause() instanceof IllegalArgumentException);
  }

  @Test
  void shouldThrowOnError() {
    try (MockedStatic<Resources> resourcesMock = mockStatic(Resources.class)) {
      resourcesMock.when(() -> Resources.toString(any(), any())).thenThrow(IOException.class);

      IllegalStateException exception = assertThrows(IllegalStateException.class,
          () -> FileUtilities.readFileAsResources("not-exist"));

      assertTrue(exception.getCause() instanceof IOException);
    }
  }
}

package com.sanctionco.thunder.util;

import com.google.common.io.Resources;

import java.io.IOException;

import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;

import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mockStatic;

class FileUtilitiesTest {

  @Test
  void testConstructInstance() {
    new FileUtilities();
  }

  @Test
  void shouldReadTestFile() {
    assertEquals("test", FileUtilities.readFileAsResources("fixtures/test.txt"));
  }

  @Test
  void shouldThrowOnNonexistentFile() {
    IllegalStateException nonexistent = assertThrows(IllegalStateException.class,
        () -> FileUtilities.readFileAsResources("not-exist"));

    assertTrue(nonexistent.getCause() instanceof IllegalArgumentException);
  }

  @Test
  void shouldThrowOnError() {
    try (MockedStatic<Resources> resourcesMock = mockStatic(Resources.class)) {
      resourcesMock.when(() -> Resources.toString(any(), any())).thenThrow(IOException.class);

      IllegalStateException exception = assertThrows(IllegalStateException.class,
          () -> FileUtilities.readFileAsResources("not-exist"));

      assertTrue(exception.getCause() instanceof IOException);
    }
  }
}

Add test to construct FileUtilities


package com.bridge;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class Open extends CordovaPlugin {

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if (action.equals("open")) {
            String path = args.getString(0);
            this.chooseIntent(path, callbackContext);
            return true;
        }
        return false;
    }

    private void chooseIntent(String path, CallbackContext callbackContext) {
        if (path != null && path.length() > 0) {
            callbackContext.success(path);
        } else {
            callbackContext.error("Expected one non-empty string argument.");
        }
    }
}

package com.bridge;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class echoes a string called from JavaScript.
 */
public class Open extends CordovaPlugin {

  public static final String OPEN_ACTION = "open";

  @Override
  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (action.equals(OPEN_ACTION)) {
      String path = args.getString(0);
      this.chooseIntent(path, callbackContext);
      return true;
    }
    return false;
  }

  private void chooseIntent(String path, CallbackContext callbackContext) {
    if (path != null && path.length() > 0) {
      callbackContext.success(path);
    } else {
      callbackContext.error("Expected one non-empty string argument.");
    }
  }
}

Use constant and fix formatting issues


/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.search;

import com.hp.autonomy.frontend.find.ApiKeyService;
import com.hp.autonomy.iod.client.api.search.*;
import com.hp.autonomy.iod.client.error.IodErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DocumentsServiceImpl implements DocumentsService {

    @Autowired
    private ApiKeyService apiKeyService;

    @Autowired
    private QueryTextIndexService queryTextIndexService;

    @Override
    public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException {

        final Map<String, Object> params = new QueryRequestBuilder()
                .setAbsoluteMaxResults(maxResults)
                .setSummary(summary)
                .setIndexes(indexes)
                .setFieldText(fieldText)
                .build();

        return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params);
    }
}

/*
 * Copyright 2014-2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.frontend.find.search;

import com.hp.autonomy.frontend.find.ApiKeyService;
import com.hp.autonomy.frontend.find.QueryProfileService;
import com.hp.autonomy.iod.client.api.search.*;
import com.hp.autonomy.iod.client.error.IodErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class DocumentsServiceImpl implements DocumentsService {

    @Autowired
    private ApiKeyService apiKeyService;

    @Autowired
    private QueryProfileService queryProfileService;

    @Autowired
    private QueryTextIndexService queryTextIndexService;

    @Override
    public Documents queryTextIndex(final String text, final int maxResults, final Summary summary, final List<String> indexes, final String fieldText) throws IodErrorException {

        final Map<String, Object> params = new QueryRequestBuilder()
                .setAbsoluteMaxResults(maxResults)
                .setSummary(summary)
                .setIndexes(indexes)
                .setFieldText(fieldText)
                .setQueryProfile(queryProfileService.getQueryProfile())
                .build();

        return queryTextIndexService.queryTextIndexWithText(apiKeyService.getApiKey(), text, params);
    }
}

Use query profile when querying for results documents


package com.mangopay.entities.subentities;

import com.mangopay.core.Dto;
import com.mangopay.core.interfaces.IPayInPaymentDetails;
import com.mangopay.core.enumerations.CardType;

/**
 * Class representing the Card type for mean of payment in PayIn entity.
 */
public class PayInPaymentDetailsCard extends Dto implements IPayInPaymentDetails {

    /**
     * Card type.
     */
    public CardType CardType;

    /**
     * Card identifier.
     */
    public String CardId;
}

package com.mangopay.entities.subentities;

import com.mangopay.core.Dto;
import com.mangopay.core.interfaces.IPayInPaymentDetails;
import com.mangopay.core.enumerations.CardType;

/**
 * Class representing the Card type for mean of payment in PayIn entity.
 */
public class PayInPaymentDetailsCard extends Dto implements IPayInPaymentDetails {

    /**
     * Card type.
     */
    public CardType CardType;

    /**
     * Card identifier.
     */
    public String CardId;

    /**
     * An optional value to be specified on the user's bank statement
     */
    public String StatementDescriptor;
}

Add StatementDescriptor for card payins


package com.levibostian.pantrypirate.model;

import com.levibostian.pantrypirate.vo.License;

import java.util.ArrayList;

public class LicensesModel {
    private ArrayList<License> mLicenses;

    public LicensesModel() {
        mLicenses = new ArrayList<License>();

        setUpLicenses();
    }

    private void setUpLicenses() {
        mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
        mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
        mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
        mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView"));
    }

    public ArrayList<License> getLicenses() {
        return mLicenses;
    }

    public License getLicense(int position) {
        return mLicenses.get(position);
    }
}

package com.levibostian.pantrypirate.model;

import com.levibostian.pantrypirate.vo.License;

import java.util.ArrayList;

public class LicensesModel {
    private ArrayList<License> mLicenses;

    public LicensesModel() {
        mLicenses = new ArrayList<License>();

        setUpLicenses();
    }

    private void setUpLicenses() {
        mLicenses.add(new License("Android-RobotoTextView", "https://github.com/johnkil/Android-RobotoTextView"));
        mLicenses.add(new License("Tomáš Procházka ImageView", "https://gist.github.com/tprochazka/5486822"));
        mLicenses.add(new License("ListViewAnimations", "https://github.com/nhaarman/ListViewAnimations"));
        mLicenses.add(new License("EnhancedListView", "https://github.com/timroes/EnhancedListView"));
        mLiencses.add(new License("Retrofit", "https://square.github.io/retrofit/"));
    }

    public ArrayList<License> getLicenses() {
        return mLicenses;
    }

    public License getLicense(int position) {
        return mLicenses.get(position);
    }
}

Add Retrofit to licenses list.


package com.naijab.nextzytimeline.ui;

import android.os.Bundle;
import com.naijab.nextzytimeline.base.BaseMvpActivity;
import com.naijab.nextzytimeline.ui.SplashScreenActivityInterface.Presenter;

public class SplashScreenActivity extends BaseMvpActivity<Presenter>
        implements SplashScreenActivityInterface.View{

    @Override
    public Presenter createPresenter(){
        return SplashScreenActivityPresenter.create();
    }

    @Override
    public int getLayoutView(){
        return 0;
    }

    @Override
    public void bindView(){
    }

    @Override
    public void setupInstance(){

    }

    @Override
    public void setupView(){
    }

    @Override
    public void initialize(){
    }

    @Override
    protected void onSaveInstanceState( Bundle outState ){
        super.onSaveInstanceState( outState );
    }

    @Override
    protected void onRestoreInstanceState( Bundle savedInstanceState ){
        super.onRestoreInstanceState( savedInstanceState );
    }
}

package com.naijab.nextzytimeline.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import com.naijab.nextzytimeline.R;
import com.naijab.nextzytimeline.base.BaseMvpActivity;
import com.naijab.nextzytimeline.ui.Main.MainActivity;
import com.naijab.nextzytimeline.ui.SplashScreenActivityInterface.Presenter;

public class SplashScreenActivity extends BaseMvpActivity<Presenter>
    implements SplashScreenActivityInterface.View {

  private static final long DELAY_TIME = 1000;

  @Override
  public Presenter createPresenter() {
    return SplashScreenActivityPresenter.create();
  }

  @Override
  public int getLayoutView() {
    return R.layout.splash_screen;
  }

  @Override
  public void bindView() {
  }

  @Override
  public void setupInstance() {
    goToMainActivity();
  }

  @Override
  public void setupView() {
  }

  @Override
  public void initialize() {
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
  }

  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
  }

  private void delayHandler(Runnable rannable){
    Handler handler = new Handler();
    handler.postDelayed(rannable, DELAY_TIME);
  }

  private void goToMainActivity() {
    delayHandler(new Runnable() {
      @Override
      public void run() {
        Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
        startActivity( intent );
        finish();
        overridePendingTransition( R.anim.fade_in, R.anim.fade_out );
      }
    });
  }
}

Edit Splash add Handler post delay to MainActivity


package com.kickstarter.factories;

import android.support.annotation.NonNull;

import com.kickstarter.models.Project;
import com.kickstarter.services.apiresponses.DiscoverEnvelope;

import java.util.List;

public final class DiscoverEnvelopeFactory {
  public static @NonNull DiscoverEnvelope discoverEnvelope(final @NonNull List<Project> projects) {
    return DiscoverEnvelope.builder()
      .projects(projects)
      .urls(
        DiscoverEnvelope.UrlsEnvelope.builder()
          .api(DiscoverEnvelope.UrlsEnvelope.ApiEnvelope.builder().moreProjects("").build())
          .build()
      )
      .build();
  }
}

package com.kickstarter.factories;

import android.support.annotation.NonNull;

import com.kickstarter.models.Project;
import com.kickstarter.services.apiresponses.DiscoverEnvelope;

import java.util.List;

public final class DiscoverEnvelopeFactory {
  private DiscoverEnvelopeFactory() {}

  public static @NonNull DiscoverEnvelope discoverEnvelope(final @NonNull List<Project> projects) {
    return DiscoverEnvelope.builder()
      .projects(projects)
      .urls(
        DiscoverEnvelope.UrlsEnvelope.builder()
          .api(DiscoverEnvelope.UrlsEnvelope.ApiEnvelope.builder().moreProjects("").build())
          .build()
      )
      .build();
  }
}

Add private constructor to utility class


package testhelper;

import com.sun.management.ThreadMXBean;

import java.lang.management.ManagementFactory;

public class PerformanceUtils {

  private static ThreadMXBean THREAD_MX_BEAN;

  static {
    Object bean = ManagementFactory.getThreadMXBean();
    if (bean instanceof ThreadMXBean)
      THREAD_MX_BEAN = (ThreadMXBean) bean;
  }

  /**
   * @return amount of memory (in bytes) allocated by current thread until now
   */
  public static long measureAllocatedMemory() {
    if (THREAD_MX_BEAN == null) {
      throw new IllegalStateException("Couldn't get thread MBean");
    }
    long selfId = Thread.currentThread().getId();

    return THREAD_MX_BEAN.getThreadAllocatedBytes(selfId);
  }
}

package testhelper;

import com.sun.management.ThreadMXBean;

import java.lang.management.ManagementFactory;

public class PerformanceUtils {

  private static final ThreadMXBean THREAD_MX_BEAN = initThreadBean();

  private static ThreadMXBean initThreadBean() {
    Object bean = ManagementFactory.getThreadMXBean();
    return bean instanceof ThreadMXBean ? (ThreadMXBean) bean : null;
  }

  /**
   * @return amount of memory (in bytes) allocated by current thread until now
   */
  public static long measureAllocatedMemory() {
    if (THREAD_MX_BEAN == null) {
      throw new IllegalStateException("Couldn't get thread MBean");
    }
    long selfId = Thread.currentThread().getId();

    return THREAD_MX_BEAN.getThreadAllocatedBytes(selfId);
  }
}

Make thread bean field final


package com.ezardlabs.lostsector.missions.objectives;

import com.ezardlabs.dethsquare.Level;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.levels.DefenseLevel;
import com.ezardlabs.lostsector.objects.ShieldedEntity;

public class Cryopod extends ShieldedEntity {
	private int id;

	public Cryopod() {
		super(100, 200, 1000);
	}

	@Override
	public void start() {
		gameObject.renderer.setImage("data/objectives/cryopod/cryopod.png", 300, 100);
		gameObject.renderer.setOffsets(50, 100);
	}

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

	@Override
	protected void die(DamageType damageType, Vector2 attackOrigin) {
		Level level = LevelManager.getCurrentLevel();
		if (level instanceof DefenseLevel) {
			((DefenseLevel) level).getMission().onCryopodDestroyed(id);
		}
	}
}

package com.ezardlabs.lostsector.missions.objectives;

import com.ezardlabs.dethsquare.Layers;
import com.ezardlabs.dethsquare.Level;
import com.ezardlabs.dethsquare.LevelManager;
import com.ezardlabs.dethsquare.Vector2;
import com.ezardlabs.lostsector.Game.DamageType;
import com.ezardlabs.lostsector.levels.DefenseLevel;
import com.ezardlabs.lostsector.objects.ShieldedEntity;

public class Cryopod extends ShieldedEntity {
	private int id;

	public Cryopod() {
		super(100, 200, 1000);
	}

	@Override
	public void start() {
		gameObject.renderer.setImage("data/objectives/cryopod/cryopod.png", 300, 100);
		gameObject.renderer.setOffsets(50, 100);
		gameObject.setLayer(Layers.getLayer("Objective"));
	}

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

	@Override
	protected void die(DamageType damageType, Vector2 attackOrigin) {
		Level level = LevelManager.getCurrentLevel();
		if (level instanceof DefenseLevel) {
			((DefenseLevel) level).getMission().onCryopodDestroyed(id);
		}
	}
}

Set cryopod layer to "Objective"


package com.github.blindpirate.gogradle.task.go;

import java.io.File;
import java.util.List;

public class PackageTestContext {
    private String packagePath;
    private List<File> testFiles;
    private String stdout;

    public String getPackagePath() {
        return packagePath;
    }

    public List<File> getTestFiles() {
        return testFiles;
    }

    public String getStdout() {
        return stdout;
    }

    public static PackageTestContextBuilder builder() {
        return new PackageTestContextBuilder();
    }

    public static final class PackageTestContextBuilder {
        private String packagePath;
        private List<File> testFiles;
        private String stdout;

        private PackageTestContextBuilder() {
        }

        public PackageTestContextBuilder withPackagePath(String packagePath) {
            this.packagePath = packagePath;
            return this;
        }

        public PackageTestContextBuilder withTestFiles(List<File> testFiles) {
            this.testFiles = testFiles;
            return this;
        }

        public PackageTestContextBuilder withStdout(String stdout) {
            this.stdout = stdout;
            return this;
        }

        public PackageTestContext build() {
            PackageTestContext packageTestContext = new PackageTestContext();
            packageTestContext.stdout = this.stdout;
            packageTestContext.testFiles = this.testFiles;
            packageTestContext.packagePath = this.packagePath;
            return packageTestContext;
        }
    }
}

package com.github.blindpirate.gogradle.task.go;

import java.io.File;
import java.util.List;

public class PackageTestContext {
    private String packagePath;
    private List<File> testFiles;
    private List<String> stdout;

    public String getPackagePath() {
        return packagePath;
    }

    public List<File> getTestFiles() {
        return testFiles;
    }

    public List<String> getStdout() {
        return stdout;
    }

    public static PackageTestContextBuilder builder() {
        return new PackageTestContextBuilder();
    }

    public static final class PackageTestContextBuilder {
        private String packagePath;
        private List<File> testFiles;
        private List<String> stdout;

        private PackageTestContextBuilder() {
        }

        public PackageTestContextBuilder withPackagePath(String packagePath) {
            this.packagePath = packagePath;
            return this;
        }

        public PackageTestContextBuilder withTestFiles(List<File> testFiles) {
            this.testFiles = testFiles;
            return this;
        }

        public PackageTestContextBuilder withStdout(List<String> stdout) {
            this.stdout = stdout;
            return this;
        }

        public PackageTestContext build() {
            PackageTestContext packageTestContext = new PackageTestContext();
            packageTestContext.stdout = this.stdout;
            packageTestContext.testFiles = this.testFiles;
            packageTestContext.packagePath = this.packagePath;
            return packageTestContext;
        }
    }
}

Use lines list as stdout


package com.homeadvisor.kafdrop.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Configuration
public class SchemaRegistryConfiguration {

    @Component
    @ConfigurationProperties(prefix = "schemaregistry")
    public static class SchemaRegistryProperties
    {
        private String connect;

        public String getConnect()
        {
            return connect;
        }

        public void setConnect(String connect)
        {
            this.connect = connect;
        }

    }

}

package com.homeadvisor.kafdrop.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Configuration
public class SchemaRegistryConfiguration {

    @Component
    @ConfigurationProperties(prefix = "schemaregistry")
    public static class SchemaRegistryProperties
    {

        public static final Pattern CONNECT_SEPARATOR = Pattern.compile("\\s*,\\s*");

        private String connect;

        public String getConnect()
        {
            return connect;
        }

        public void setConnect(String connect)
        {
            this.connect = connect;
        }

        public List<String> getConnectList()
        {
            return CONNECT_SEPARATOR.splitAsStream(this.connect)
                    .map(String::trim)
                    .filter(s -> s.length() > 0)
                    .collect(Collectors.toList());
        }

    }

}

Revert "Remove list-parsing code from schema registry config parser"


package ie.ucd.clops.documentation;

import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * <BON>
 * class_chart DOCUMENT_GENERATION
 *   explanation "Generation of documentation from the descriptions of options"
 *  end
 * </BON>
 */

public class DocumentGeneration {

	public void generate() {
		try {
			Velocity.init();

			VelocityContext context = new VelocityContext();

			context.put("option", new OptionDescription());

			Template template = Velocity.getTemplate("html.vm");

			Writer writer = new java.io.OutputStreamWriter(System.out);

			template.merge(context, writer);

			writer.flush();
			writer.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

package ie.ucd.clops.documentation;

import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Writer;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

/**
 * <BON>
 * class_chart DOCUMENT_GENERATION
 * explanation
 *   "Generation of documentation from the descriptions of options"
 * command
 *   "Generate Documentation"
 * end
 * </BON>
 */

public class DocumentGeneration {

	public static final String HTML_TEMPLATE_NAME = "html.vm";

	public void generate(OutputStream targetFile) {
		try {
			Velocity.init();

			VelocityContext context = createContext();

			Template template = Velocity.getTemplate(DocumentGeneration.HTML_TEMPLATE_NAME);

			Writer writer = new java.io.OutputStreamWriter(targetFile);

			template.merge(context, writer);

			writer.flush();
			writer.close();

		} catch (Exception e) {
			// @TODO log this
			e.printStackTrace();
		}

	}

	/**
	 * Define the context for document generation
	 *
	 * @return
	 */
	protected VelocityContext createContext() {
		VelocityContext context = new VelocityContext();

		context.put("option", new OptionDescription());
		return context;
	}

}

Refactor a new method for context definition i.e. mapping between templates and data structures


package net.openhft.chronicle.bytes;

import org.junit.Test;

import java.io.IOException;

import static junit.framework.TestCase.assertEquals;

public class BytesTextMethodTesterTest {
    @Test
    public void run() throws IOException {
        BytesTextMethodTester tester = new BytesTextMethodTester<>("btmtt/one-input.txt", IBMImpl::new, IBytesMethod.class, "btmtt/one-output.txt");
        tester.run();
        assertEquals(tester.expected(), tester.actual());
    }

    static class IBMImpl implements IBytesMethod {
        final IBytesMethod out;

        IBMImpl(IBytesMethod out) {
            this.out = out;
        }

        @Override
        public void myByteable(MyByteable byteable) {
            out.myByteable(byteable);
        }

        @Override
        public void myScalars(MyScalars scalars) {
            out.myScalars(scalars);
        }

        @Override
        public void myNested(MyNested nested) {
            out.myNested(nested);
        }
    }
}

package net.openhft.chronicle.bytes;

import org.junit.Test;

import java.io.IOException;

import static junit.framework.TestCase.assertEquals;

public class BytesTextMethodTesterTest {
    @Test
    public void run() throws IOException {
        BytesTextMethodTester tester = new BytesTextMethodTester<>(
                "btmtt/one-input.txt",
                IBMImpl::new,
                IBytesMethod.class,
                "btmtt/one-output.txt");
        tester.run();
        assertEquals(tester.expected(), tester.actual());
    }

    static class IBMImpl implements IBytesMethod {
        final IBytesMethod out;

        IBMImpl(IBytesMethod out) {
            this.out = out;
        }

        @Override
        public void myByteable(MyByteable byteable) {
            out.myByteable(byteable);
        }

        @Override
        public void myScalars(MyScalars scalars) {
            out.myScalars(scalars);
        }

        @Override
        public void myNested(MyNested nested) {
            out.myNested(nested);
        }
    }
}

Add examples with multi-byte message ids.


/*
 * The gemma-core project
 *
 * Copyright (c) 2018 University of British Columbia
 *
 * 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 ubic.gemma.core.loader.expression;

import static org.junit.Assert.*;

import java.util.Map;

import org.junit.Test;

/**
 *
 *
 * @author paul
 */
public class AffyPowerToolsProbesetSummarizeTest {

    @Test
    public void testLoadMPSNames() {
        AffyPowerToolsProbesetSummarize t = new AffyPowerToolsProbesetSummarize();
        Map<String, Map<String, String>> mpsnames = t.loadMpsNames();

        assertEquals( "MoGene-2_1-st.mps", mpsnames.get( "GPL17400" ).get( "mps" ) );
        assertEquals( "RaGene-1_0-st-v1.r4.pgf", mpsnames.get( "GPL6247" ).get( "pgf" ) );

    }

}

/*
 * The gemma-core project
 *
 * Copyright (c) 2018 University of British Columbia
 *
 * 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 ubic.gemma.core.loader.expression;

import static org.junit.Assert.*;

import java.util.Map;

import org.junit.Test;

/**
 *
 *
 * @author paul
 */
public class AffyPowerToolsProbesetSummarizeTest {

    @Test
    public void testLoadMPSNames() {
        AffyPowerToolsProbesetSummarize t = new AffyPowerToolsProbesetSummarize();
        Map<String, Map<String, String>> mpsnames = t.loadMpsNames();

        assertEquals( "MoGene-2_1-st.mps", mpsnames.get( "GPL17400" ).get( "mps" ) );
        assertEquals( "RaEx-1_0-st-v1.r2.pgf", mpsnames.get( "GPL6247" ).get( "pgf" ) );

    }

}

Fix failing test after affy update


package sagan.support.nav;

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

@Retention(RetentionPolicy.RUNTIME)
public @interface NavSection {

    String value() default "";
}

package sagan.support.nav;

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

/**
 * Annotation to be used at the class level on Controllers to indicate which section in
 * the site's main navigation should be highlighted.
 *
 * @see sagan.MvcConfig#addInterceptors(org.springframework.web.servlet.config.annotation.InterceptorRegistry)
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface NavSection {

    String value() default "";
}

Add class-level Javadoc for sagan.projects.nav.*


package com.github.vovas11.courses.command;

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

import javax.servlet.http.HttpServletRequest;

/**
 * {@code CommandFactory} is a factory (design pattern) that stores all commands
 * needed for handling user forms and returns one of commands when it needed
 *
 * @author vovas11
 * @see Command
 */
public class CommandFactory {

    /* represents one instance of the CommandFactory (Singleton) */
    static CommandFactory commandFactory = new CommandFactory();

    /* stores all commands */
    Map<String, Command> commandMap = new HashMap<>();

    /* Private Constructor does not allow creating instances except by this class */
    private CommandFactory() {
	commandMap.put("registration", new RegistrationCommand());
	commandMap.put("login", new LoginCommand());
	commandMap.put("courseselect", new CourseSelectCommand());
	commandMap.put("logout", new LogoutCommand());
    }

    /**
     * Provides the access to the single instance of the class
     * @return the link to the {@code CommandFactory} instance
     */
    public static CommandFactory getInstance() {
	return commandFactory;
    }

    /**
     * Delivers an object of the command the name of which is sent inside the HTTP request
     *
     * @param   request   HTTP request from the servlet
     * @return the single instance of the {@code Command}
     */
    public Command getCommand(HttpServletRequest request) {
	String value = request.getParameter("ok");
	return commandMap.get(value);
    }
}

package com.github.vovas11.courses.command;

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

import javax.servlet.http.HttpServletRequest;

/**
 * {@code CommandFactory} is a factory (design pattern) that stores all commands
 * needed for handling user forms and returns one of commands when it needed
 *
 * @author vovas11
 * @see Command
 */
public class CommandFactory {

    /* represents one instance of the CommandFactory (Singleton) */
    private static CommandFactory commandFactory = new CommandFactory();

    /* stores all commands */
    private Map<String, Command> commandMap = new HashMap<>();

    private CommandFactory() {
        commandMap.put("registration", new RegistrationCommand());
        commandMap.put("login", new LoginCommand());
        commandMap.put("courseselect", new CourseSelectCommand());
        commandMap.put("logout", new LogoutCommand());
    }

    /**
     * Provides the access to the single instance of the class
     * @return the link to the {@code CommandFactory} instance
     */
    public static CommandFactory getInstance() {
        return commandFactory;
    }

    /**
     * Delivers an object of the command the name of which is sent inside the HTTP request
     *
     * @param   request   HTTP request from the servlet
     * @return the single instance of the {@code Command}
     */
    public Command getCommand(HttpServletRequest request) {
        String value = request.getParameter("ok");
        return commandMap.get(value);
    }
}

Change the IDE and update CommandFactoy.java


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.messagebus;

import com.yahoo.component.AbstractComponent;
import com.yahoo.messagebus.network.Network;
import com.yahoo.messagebus.network.NetworkMultiplexer;
import com.yahoo.messagebus.network.rpc.RPCNetwork;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
import com.yahoo.messagebus.shared.NullNetwork;

/**
 * Holds a reference to a singleton {@link NetworkMultiplexer}.
 *
 * @author jonmv
 */
public class NetworkMultiplexerHolder extends AbstractComponent {

    private final Object monitor = new Object();
    private boolean destroyed = false;
    private NetworkMultiplexer net;

    /** Get the singleton RPCNetworkAdapter, creating it if this hasn't yet been done. */
    public NetworkMultiplexer get(RPCNetworkParams params) {
        synchronized (monitor) {
            if (destroyed)
                throw new IllegalStateException("Component already destroyed");

            return net = net != null ? net : NetworkMultiplexer.shared(newNetwork(params));
        }
    }

    private Network newNetwork(RPCNetworkParams params) {
        return params.getSlobroksConfig() != null && params.getSlobroksConfig().slobrok().isEmpty()
               ? new NullNetwork() // For LocalApplication, test setup.
               : new RPCNetwork(params);
    }

    @Override
    public void deconstruct() {
        synchronized (monitor) {
            net.destroy();
            net = null;
            destroyed = true;
        }
    }

}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.messagebus;

import com.yahoo.component.AbstractComponent;
import com.yahoo.messagebus.network.Network;
import com.yahoo.messagebus.network.NetworkMultiplexer;
import com.yahoo.messagebus.network.rpc.RPCNetwork;
import com.yahoo.messagebus.network.rpc.RPCNetworkParams;
import com.yahoo.messagebus.shared.NullNetwork;

/**
 * Holds a reference to a singleton {@link NetworkMultiplexer}.
 *
 * @author jonmv
 */
public class NetworkMultiplexerHolder extends AbstractComponent {

    private final Object monitor = new Object();
    private boolean destroyed = false;
    private NetworkMultiplexer net;

    /** Get the singleton RPCNetworkAdapter, creating it if this hasn't yet been done. */
    public NetworkMultiplexer get(RPCNetworkParams params) {
        synchronized (monitor) {
            if (destroyed)
                throw new IllegalStateException("Component already destroyed");

            return net = net != null ? net : NetworkMultiplexer.shared(newNetwork(params));
        }
    }

    private Network newNetwork(RPCNetworkParams params) {
        return params.getSlobroksConfig() != null && params.getSlobroksConfig().slobrok().isEmpty()
               ? new NullNetwork() // For LocalApplication, test setup.
               : new RPCNetwork(params);
    }

    @Override
    public void deconstruct() {
        synchronized (monitor) {
            if (net != null) {
                net.destroy();
                net = null;
            }
            destroyed = true;
        }
    }

}

Destroy only when held item exists


/*
 * Copyright (C) 2013 Conductor, 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 net.opentsdb.contrib.tsquare.support;

import java.util.Iterator;

import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;

/**
 * Wraps a {@link DataPoints} object and exposes the data consistent
 * with the {@link Doubles} interface.
 *
 * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
 */
public class DataPointsAsDoubles implements Doubles {
    private final Iterator<DataPoint> iterator;

    public DataPointsAsDoubles(final DataPoints points) {
        this.iterator = points.iterator();
    }

    @Override
    public boolean hasNextValue() {
        return iterator.hasNext();
    }

    @Override
    public double nextDoubleValue() {
        return iterator.next().doubleValue();
    }
}

/*
 * Copyright (C) 2013 Conductor, 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 net.opentsdb.contrib.tsquare.support;

import java.util.Iterator;

import net.opentsdb.core.Aggregator.Doubles;
import net.opentsdb.core.DataPoint;
import net.opentsdb.core.DataPoints;

/**
 * Wraps a {@link DataPoints} object and exposes the data consistent
 * with the {@link Doubles} interface.
 *
 * @author James Royalty (jroyalty) <i>[Jul 12, 2013]</i>
 */
public class DataPointsAsDoubles implements Doubles {
    private final Iterator<DataPoint> iterator;

    public DataPointsAsDoubles(final DataPoints points) {
        this.iterator = points.iterator();
    }

    @Override
    public boolean hasNextValue() {
        return iterator.hasNext();
    }

    @Override
    public double nextDoubleValue() {
        return iterator.next().toDouble();
    }
}

Use toDouble() method to convert values.


package com.github.davidcarboni.thetrain.json.request;

import java.util.List;

public class Manifest {
    public List<FileCopy> filesToCopy;
}

package com.github.davidcarboni.thetrain.json.request;

import java.util.List;

public class Manifest {
    public List<FileCopy> filesToCopy;
    public List<String> urisToDelete;
}

Add list of deletes to manifest.


package leetcode;

/**
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
 */
public class Problem714 {
    public int maxProfit(int[] prices, int fee) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem714 prob = new Problem714();
        System.out.println(prob.maxProfit(new int[]{1, 3, 2, 8, 4, 9}, 2)); // 8
        System.out.println(prob.maxProfit(new int[]{1, 3, 2, 6, 8, 4, 9}, 2)); // 8
        System.out.println(prob.maxProfit(new int[]{1, 4, 2, 1, 4, 8, 4, 9}, 2)); // 9
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
 */
public class Problem714 {
    public int maxProfit(int[] prices, int fee) {
        int cash = 0;
        int hold = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            cash = Math.max(cash, hold + prices[i] - fee);
            hold = Math.max(hold, cash - prices[i]);
        }
        return cash;
    }
}

Solve problem 714 (not really)


package com.heartbeat.common.array;

import org.junit.Test;

public class ByteArrayTest {

    @Test
    public void testTrim() throws Exception {
        byte[] original = {1, 2, 3, 4, 0, 0, 0, 0};
        byte[] trimmed = ByteArray.trim(original);
        assert trimmed.length == 4;

        byte[] original2 = {1, 2, 3, 4, 0, 0, 0, 1};
        trimmed = ByteArray.trim(original2);
        assert trimmed.length == 8;

    }
}

package com.heartbeat.common.array;

import org.junit.Test;

public class ByteArrayTest {

    @Test
    public void testTrim() throws Exception {
        byte[] original = {1, 2, 3, 4, 0, 0, 0, 0};
        byte[] trimmed = ByteArray.trim(original);
        assert trimmed.length == 4;

        byte[] original2 = {1, 2, 3, 4, 0, 0, 0, 1};
        trimmed = ByteArray.trim(original2);
        assert trimmed.length == 8;

    }

    @Test
    public void testTrimEmptyArray() throws Exception {
        byte[] original = {};
        byte[] trimmed = ByteArray.trim(original);
        assert trimmed.length == 0;

        byte[] original2 = {0, 0};
        trimmed = ByteArray.trim(original2);
        assert trimmed.length == 0;
    }
}

Add test for Trim() on an empty ByteArray.


package com.novoda.downloadmanager;

import android.content.ContentResolver;
import android.content.Context;

import com.novoda.downloadmanager.lib.DownloadManager;

/**
 * A client can specify whether the downloads are allowed to proceed by implementing
 * {@link com.novoda.downloadmanager.lib.DownloadClientReadyChecker} on your Activity class
 *
 */
public class DownloadManagerBuilder {

    private final Context context;

    private boolean verboseLogging;

    DownloadManagerBuilder(Context context) {
        this.context = context;
    }

    public static DownloadManagerBuilder from(Context context) {
        return new DownloadManagerBuilder(context.getApplicationContext());
    }

    public DownloadManagerBuilder withVerboseLogging() {
        this.verboseLogging = true;
        return this;
    }

    public DownloadManager build(ContentResolver contentResolver) {
        if (contentResolver == null) {
            throw new IllegalStateException("You must use a ContentResolver with the DownloadManager.");
        }
        return new DownloadManager(context, contentResolver, verboseLogging);
    }

}

package com.novoda.downloadmanager;

import android.content.ContentResolver;
import android.content.Context;

import com.novoda.downloadmanager.lib.DownloadManager;

/**
 * A client can specify whether the downloads are allowed to proceed by implementing
 * {@link com.novoda.downloadmanager.lib.DownloadClientReadyChecker} on your Application class
 *
 */
public class DownloadManagerBuilder {

    private final Context context;

    private boolean verboseLogging;

    DownloadManagerBuilder(Context context) {
        this.context = context;
    }

    public static DownloadManagerBuilder from(Context context) {
        return new DownloadManagerBuilder(context.getApplicationContext());
    }

    public DownloadManagerBuilder withVerboseLogging() {
        this.verboseLogging = true;
        return this;
    }

    public DownloadManager build(ContentResolver contentResolver) {
        if (contentResolver == null) {
            throw new IllegalStateException("You must use a ContentResolver with the DownloadManager.");
        }
        return new DownloadManager(context, contentResolver, verboseLogging);
    }

}

Replace Activity by Application as it what it needs


/**
 * This package contains the core spy events used in an Arez system.
 * While the {@link org.realityforge.arez} package and this package are
 * highly inter-dependent they are kept as separate packages as everything
 * within this package is typically compiled out in production builds when
 * spies are disabled.
 */
package org.realityforge.arez.spy;

/**
 * This package contains the spy events and models used in an Arez system.
 * The {@link org.realityforge.arez} package and this package are
 * highly inter-dependent but they are kept separated as production builds
 * typically compile out everything in this package when spies are disabled.
 */
package org.realityforge.arez.spy;

Update javadocs to more accurately reflect intent


package org.junit.gen5.api;

import org.opentestalliance.TestAbortedException;

/**
 * @author Sam Brannen
 * @since 5.0
 */
public final class Assumptions {

	private Assumptions() {
		/* no-op */
	}

	public static void assumeTrue(boolean condition) {
		if (!condition) {
			throw new TestAbortedException("Assumption failed: condition is not true");
		}
	}

	public static void assumeFalse(boolean condition) {
		if (condition) {
			throw new TestAbortedException("Assumption failed: condition is not false");
		}
	}

	public static void assumingThat(boolean condition, Executable executable) {
		if (condition) {
			try {
				executable.execute();
			}
			catch (AssertionError | RuntimeException e) {
				// rethrow
				throw e;
			}
			catch (Throwable e) {
				// TODO Don't wrap Throwables such as OutOfMemoryError, etc.
				throw new RuntimeException("Wrapped exception thrown from Executable", e);
			}
		}
	}

}

package org.junit.gen5.api;

import java.util.function.Supplier;

import org.opentestalliance.TestAbortedException;

/**
 * @author Sam Brannen
 * @since 5.0
 */
public final class Assumptions {

	private Assumptions() {
		/* no-op */
	}

	public static void assumeTrue(boolean condition) {
		if (!condition) {
			throw new TestAbortedException("Assumption failed: condition is not true");
		}
	}

	public static void assumeTrue(boolean condition, String message) {
		if (!condition) {
			throw new TestAbortedException("Assumption failed: " + message);
		}
	}

	public static void assumeTrue(boolean condition, Supplier<String> messageSupplier) {
		if (!condition) {
			throw new TestAbortedException(messageSupplier.get());
		}
	}

	public static void assumeFalse(boolean condition) {
		if (condition) {
			throw new TestAbortedException("Assumption failed: condition is not false");
		}
	}

	public static void assumeFalse(boolean condition, String message) {
		if (condition) {
			throw new TestAbortedException(message);
		}
	}

	public static void assumeFalse(boolean condition, Supplier<String> messageSupplier) {
		if (condition) {
			throw new TestAbortedException("Assumption failed: " + messageSupplier.get());
		}
	}

	public static void assumingThat(boolean condition, Executable executable) {
		if (condition) {
			try {
				executable.execute();
			}
			catch (AssertionError | RuntimeException e) {
				// rethrow
				throw e;
			}
			catch (Throwable e) {
				// TODO Don't wrap Throwables such as OutOfMemoryError, etc.
				throw new RuntimeException("Wrapped exception thrown from Executable", e);
			}
		}
	}

}

Support custom messages in failed assumptions


package net.openhft.chronicle.queue.impl.single;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum PrecreatedFiles {
    ;

    private static final String PRE_CREATED_FILE_SUFFIX = ".precreated";

    public static void renamePreCreatedFileToRequiredFile(final File requiredQueueFile) {
        final File preCreatedFile = preCreatedFile(requiredQueueFile);
        if (preCreatedFile.exists()) {
            if (!preCreatedFile.renameTo(requiredQueueFile)) {
                Jvm.warn().on(PrecreatedFiles.class, "Failed to rename pre-created queue file");
            }
        }
    }

    public static File preCreatedFile(final File requiredQueueFile) {
        return new File(requiredQueueFile.getParentFile(), requiredQueueFile.getName() +
                PRE_CREATED_FILE_SUFFIX);
    }
}

package net.openhft.chronicle.queue.impl.single;

import net.openhft.chronicle.core.Jvm;

import java.io.File;

public enum PrecreatedFiles {
    ;

    private static final String PRE_CREATED_FILE_SUFFIX = ".precreated";

    public static void renamePreCreatedFileToRequiredFile(final File requiredQueueFile) {
        final File preCreatedFile = preCreatedFile(requiredQueueFile);
        if (preCreatedFile.exists()) {
            if (!preCreatedFile.renameTo(requiredQueueFile)) {
                Jvm.warn().on(PrecreatedFiles.class, "Failed to rename pre-created queue file");
            }
        }
    }

    public static File preCreatedFileForStoreFile(final File requiredStoreFile) {
        return new File(requiredStoreFile.getParentFile(), requiredStoreFile.getName() +
                PRE_CREATED_FILE_SUFFIX);
    }

    public static File preCreatedFile(final File requiredQueueFile) {
        final String fileName = requiredQueueFile.getName();
        final String name = fileName.substring(0, fileName.length() - 4);
        return new File(requiredQueueFile.getParentFile(), name +
                PRE_CREATED_FILE_SUFFIX);
    }
}

Add extra method to deal with differing file-name formats


package de.gurkenlabs.litiengine.entities;

public enum PropState {
  INTACT,
  DAMAGED,
  DESTROYED;

  public String spriteString() {
    return this.name().toLowerCase();
  }
}

package de.gurkenlabs.litiengine.entities;

public enum PropState {
  INTACT,
  DAMAGED,
  DESTROYED;

  private final String str;

  private PropState() {
    this.str = this.name().toLowerCase();
  }

  public String spriteString() {
    return this.str;
  }
}

Store lower-case string because conversion takes time.


package ge.ifg.crypto.frequency;

import ge.ifg.crypto.security.TestCases;

import java.util.HashMap;

public class Frequency extends TestCases {

	private static HashMap<String, Integer> frequency;

	public double getFrequency(String str) {
		Integer freq = frequency.get(str);
		if (freq == null)
			return 0.01;
		return freq;
	}

	protected Frequency() {
		frequency = new HashMap<>();
	}

}

package ge.ifg.crypto.frequency;

import ge.ifg.crypto.security.TestCases;

import java.util.HashMap;

public class Frequency extends TestCases {

	private HashMap<String, Integer> frequency;

	public double getFrequency(String str) {
		Integer freq = frequency.get(str);
		if (freq == null)
			return 0.01;
		return freq;
	}

	protected Frequency() {
		frequency = new HashMap<>();
	}

}

Change static field to unstatic


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

import java.util.List;

public class Table extends AbstractTable {

	public Table() {
		super();
	}

    /**
     * for now the method isn't implemented. I still need to decide how
     * it should be implemented.
     */
    public String[][] getTableData(List data) {
        return null;
    }
}

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

import java.util.List;

public class Table extends AbstractTable {

	public Table() {
		super();
	}

    /**
     * for now the method isn't implemented. I still need to decide how
     * it should be implemented.
     */
    public String[][] getTableData(List data) {
        return new String[0][0];
    }
}

Return empty array rather than null


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.vutbr.fit.pdb;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;

/**
 *
 * @author casey
 */
public class Core {

    private JFrame mainWindow;

    public Core(){
        mainWindow = new JFrame("PDB 2013");
        mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    private void setOnCenter(Dimension frameSize){
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        mainWindow.setLocation(screenSize.width / 2 -frameSize.width / 2, screenSize.height /2 - frameSize.height / 2);

    }

    public static void maina(String[] args){
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                Core c = new Core();
                //c.initGui();
                //c.showGui();
            }
        });

    }
}

Create contructor and main method.


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

import javax.inject.Inject;

@Transactional
public class FooService {

  private @Inject @Mapper UserMapper userMapper;

  public User doSomeBusinessStuff(int userId) {
    return this.userMapper.getUser(userId);
  }

}

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

import javax.inject.Inject;

@Transactional
public class FooService {

  private @Inject @Mapper UserMapper userMapper;

  private @Inject @Mapper UserMapper userMapper2;

  public User doSomeBusinessStuff(int userId) {
    User dummy = userMapper2.getUser(userId);
    return this.userMapper.getUser(userId);
  }

}

Test case for Mapper injection (fail)


// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.files;

import org.objectweb.asm.ClassReader;

import java.io.IOException;
import java.nio.file.*;

public class OutputDirectory {

    private final Path outputDir;

    public OutputDirectory(Path outputDir) {
        this.outputDir = outputDir;
    }

    public void writeClass(byte[] bytecode) throws IOException {
        if (bytecode == null) {
            return;
        }
        ClassReader cr = new ClassReader(bytecode);
        Path relativePath = Paths.get(cr.getClassName() + ".class");
        writeFile(relativePath, bytecode);
    }

    public void writeFile(Path relativePath, byte[] content) throws IOException {
        Path outputFile = outputDir.resolve(relativePath);
        Files.createDirectories(outputFile.getParent());
        Files.write(outputFile, content);
    }
}

// Copyright © 2013-2015 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package net.orfjackal.retrolambda.files;

import org.objectweb.asm.ClassReader;

import java.io.IOException;
import java.nio.file.*;

public class OutputDirectory {

    private final Path outputDir;

    public OutputDirectory(Path outputDir) {
        this.outputDir = outputDir;
    }

    public void writeClass(byte[] bytecode) throws IOException {
        if (bytecode == null) {
            return;
        }
        ClassReader cr = new ClassReader(bytecode);
        Path relativePath = outputDir.getFileSystem().getPath(cr.getClassName() + ".class");
        writeFile(relativePath, bytecode);
    }

    public void writeFile(Path relativePath, byte[] content) throws IOException {
        Path outputFile = outputDir.resolve(relativePath);
        Files.createDirectories(outputFile.getParent());
        Files.write(outputFile, content);
    }
}

Use the same FileSystem as the outputDir.


package com.xiaomi.infra.galaxy.emq.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Copyright 2015, Xiaomi.
 * All rights reserved.
 * Author: shenyuannan@xiaomi.com
 */

public class EMQClient {
  private static class EMQClientHandler<T> implements InvocationHandler {
    private final Object instance;

    public EMQClientHandler(Class<T> interfaceClass, Object instance) {
      this.instance = instance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
      EMQRequestCheckUtils.checkRequest(args);
      try {
        return method.invoke(instance, args);
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }
    }
  }

  /**
   * Create client wrapper which validate parameters of client.
   */
  @SuppressWarnings("unchecked")
  public static <T> T getClient(Class<T> interfaceClass, Object instance) {
    return (T) Proxy.newProxyInstance(EMQClient.class.getClassLoader(),
        new Class[]{interfaceClass},
        new EMQClientHandler(interfaceClass, instance));
  }
}

package com.xiaomi.infra.galaxy.emq.client;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

/**
 * Copyright 2015, Xiaomi.
 * All rights reserved.
 * Author: shenyuannan@xiaomi.com
 */

public class EMQClient {
  private static class EMQClientHandler<T> implements InvocationHandler {
    private final Object instance;

    public EMQClientHandler(Class<T> interfaceClass, Object instance) {
      this.instance = instance;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
      if (!Arrays.asList(Object.class.getMethods()).contains(method)) {
        EMQRequestCheckUtils.checkRequest(args);
      }
      try {
        return method.invoke(instance, args);
      } catch (InvocationTargetException e) {
        throw e.getCause();
      }
    }
  }

  /**
   * Create client wrapper which validate parameters of client.
   */
  @SuppressWarnings("unchecked")
  public static <T> T getClient(Class<T> interfaceClass, Object instance) {
    return (T) Proxy.newProxyInstance(EMQClient.class.getClassLoader(),
        new Class[]{interfaceClass},
        new EMQClientHandler(interfaceClass, instance));
  }
}

Fix SDK check methods NPE.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aesh.command.impl.operator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.aesh.command.invocation.CommandInvocationConfiguration;
import org.aesh.readline.AeshContext;

/**
 *
 * @author jdenise@redhat.com
 */
/**
 *
 * @author jdenise@redhat.com
 */
public class AppendOutputRedirectionOperator implements ConfigurationOperator {

    private class OutputDelegateImpl extends FileOutputDelegate {

        private OutputDelegateImpl(String file) throws IOException {
            super(context, file);
        }

        @Override
        protected BufferedWriter buildWriter(File f) throws IOException {
            return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8,
                    StandardOpenOption.APPEND);
        }
    }

    private CommandInvocationConfiguration config;
    private String argument;
    private final AeshContext context;

    public AppendOutputRedirectionOperator(AeshContext context) {
        this.context = context;
    }

    @Override
    public CommandInvocationConfiguration getConfiguration() throws IOException {
        if (config == null) {
            config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument));
        }
        return config;
    }

    @Override
    public void setArgument(String argument) {
        this.argument = argument;
    }
}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.aesh.command.impl.operator;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import org.aesh.command.invocation.CommandInvocationConfiguration;
import org.aesh.readline.AeshContext;

/**
 *
 * @author jdenise@redhat.com
 */
/**
 *
 * @author jdenise@redhat.com
 */
public class AppendOutputRedirectionOperator implements ConfigurationOperator {

    private class OutputDelegateImpl extends FileOutputDelegate {

        private OutputDelegateImpl(String file) throws IOException {
            super(context, file);
        }

        @Override
        protected BufferedWriter buildWriter(File f) throws IOException {
            return Files.newBufferedWriter(f.toPath(), StandardCharsets.UTF_8,
                    StandardOpenOption.APPEND, StandardOpenOption.CREATE);
        }
    }

    private CommandInvocationConfiguration config;
    private String argument;
    private final AeshContext context;

    public AppendOutputRedirectionOperator(AeshContext context) {
        this.context = context;
    }

    @Override
    public CommandInvocationConfiguration getConfiguration() throws IOException {
        if (config == null) {
            config = new CommandInvocationConfiguration(context, new OutputDelegateImpl(argument));
        }
        return config;
    }

    @Override
    public void setArgument(String argument) {
        this.argument = argument;
    }
}

Fix >> to create a new file


package me.coley.recaf.parse.assembly.exception;

/**
 * Wrapper for assembler exceptions with the lines that caused them.
 *
 * @author Matt
 */
public class ExceptionWrapper {
	public final int line;
	public final Exception exception;

	public ExceptionWrapper(int line, Exception exception) {
		this.line = line;
		this.exception = exception;
	}
}

package me.coley.recaf.parse.assembly.exception;

/**
 * Wrapper for assembler exceptions with the lines that caused them.
 *
 * @author Matt
 */
public class ExceptionWrapper {
	public final int line;
	public final Exception exception;

	public ExceptionWrapper(int line, Exception exception) {
		this.line = line;
		this.exception = exception;
	}

	public void printStackTrace() {
		exception.printStackTrace();
	}
}

Add qol access to printStackTrace


package se.christianjensen.maintenance.resources;

import io.dropwizard.auth.Auth;
import se.christianjensen.maintenance.representation.config.UserConfiguration;
import se.christianjensen.maintenance.representation.processes.Process;
import se.christianjensen.maintenance.sigar.ProcessMetrics;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("process")
@Produces(MediaType.APPLICATION_JSON)
public class ProcessResource extends Resource {

    ProcessMetrics processMetrics;

    public ProcessResource(ProcessMetrics processMetrics) {
        this.processMetrics = processMetrics;
    }

    @Override
    @GET
    public List<Process> getRoot(@Auth UserConfiguration user) {
        return processMetrics.getProcesses();
    }

    @Path("{pid}")
    @GET
    public Process getProcessByPid(@Auth UserConfiguration user, @PathParam("pid") long pid) {
        try {
            return processMetrics.getProcessByPid(pid);
        } catch (IllegalArgumentException e) {
            throw buildWebException(Response.Status.BAD_REQUEST, e.getMessage());
        }
    }
}

package se.christianjensen.maintenance.resources;

import io.dropwizard.auth.Auth;
import se.christianjensen.maintenance.representation.config.UserConfiguration;
import se.christianjensen.maintenance.representation.processes.Process;
import se.christianjensen.maintenance.sigar.ProcessMetrics;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.List;

@Path("process")
@Produces(MediaType.APPLICATION_JSON)
public class ProcessResource extends Resource {

    ProcessMetrics processMetrics;

    public ProcessResource(ProcessMetrics processMetrics) {
        this.processMetrics = processMetrics;
    }

    @Override
    @GET
    public List<Process> getRoot(@Auth UserConfiguration user) {
        return processMetrics.getProcesses();
    }

    @Path("{pid}")
    @GET
    public Process getProcessByPid(@Auth UserConfiguration user, @PathParam("pid") long pid) {
        try {
            return processMetrics.getProcessByPid(pid);
        } catch (IllegalArgumentException e) {
            throw buildWebException(Response.Status.NOT_FOUND, e.getMessage());
        }
    }
}

Correct statuscode for when requested pid is not existent


/*
 * 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.trino.plugin.clickhouse;

import io.trino.plugin.jdbc.BaseJdbcConnectorSmokeTest;
import io.trino.testing.TestingConnectorBehavior;
import org.testng.annotations.Test;

public abstract class BaseClickHouseConnectorSmokeTest
        extends BaseJdbcConnectorSmokeTest
{
    @Override
    protected boolean hasBehavior(TestingConnectorBehavior connectorBehavior)
    {
        switch (connectorBehavior) {
            case SUPPORTS_DELETE:
                return false;
            default:
                return super.hasBehavior(connectorBehavior);
        }
    }

    @Test
    @Override
    public void testRenameSchema()
    {
        super.testRenameSchema();
    }
}

/*
 * 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.trino.plugin.clickhouse;

import io.trino.plugin.jdbc.BaseJdbcConnectorSmokeTest;
import io.trino.testing.TestingConnectorBehavior;

public abstract class BaseClickHouseConnectorSmokeTest
        extends BaseJdbcConnectorSmokeTest
{
    @Override
    protected boolean hasBehavior(TestingConnectorBehavior connectorBehavior)
    {
        switch (connectorBehavior) {
            case SUPPORTS_DELETE:
                return false;
            default:
                return super.hasBehavior(connectorBehavior);
        }
    }
}

Remove redundant overridden test in ClickHouse smoke test


/*******************************************************************************
 * Copyright 2011 See AUTHORS file.
 *
 * 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.badlogic.gdx.tests.android;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTests;

public class GdxTestActivity extends AndroidApplication {

	public void onCreate (Bundle bundle) {
		super.onCreate(bundle);

		Bundle extras = getIntent().getExtras();
		String testName = (String)extras.get("test");

		GdxTest test = GdxTests.newTest(testName);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		config.useGL20 = test.needsGL20();
		initialize(test, config);
	}
}

/*******************************************************************************
 * Copyright 2011 See AUTHORS file.
 *
 * 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.badlogic.gdx.tests.android;

import android.os.Bundle;

import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
import com.badlogic.gdx.tests.utils.GdxTest;
import com.badlogic.gdx.tests.utils.GdxTests;

public class GdxTestActivity extends AndroidApplication {

	public void onCreate (Bundle bundle) {
		super.onCreate(bundle);

		Bundle extras = getIntent().getExtras();
		String testName = (String)extras.get("test");

		GdxTest test = GdxTests.newTest(testName);
		AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
		config.useGL20 = test.needsGL20();
		config.useImmersiveMode = true;
		initialize(test, config);
	}
}

Update tests to use immersive mode


package com.github.ayltai.newspaper.app.view;

import java.util.concurrent.TimeUnit;

import android.support.annotation.NonNull;

import com.github.ayltai.newspaper.Constants;
import com.github.ayltai.newspaper.app.data.model.FeaturedItem;
import com.github.ayltai.newspaper.app.widget.FeaturedView;
import com.github.ayltai.newspaper.util.RxUtils;

import io.reactivex.Observable;

public class FeaturedPresenter extends ItemPresenter<FeaturedView> {
    @Override
    public void onViewAttached(@NonNull final FeaturedView view, final boolean isFirstTimeAttachment) {
        this.manageDisposable(Observable.interval(Constants.FEATURED_IMAGE_ROTATION, TimeUnit.SECONDS)
            .compose(RxUtils.applyObservableBackgroundToMainSchedulers())
            .subscribe(time -> {
                if (this.getModel() instanceof FeaturedItem) {
                    ((FeaturedItem)this.getModel()).next();

                    this.bindModel(this.getModel());
                }
            }));

        super.onViewAttached(view, isFirstTimeAttachment);
    }
}

package com.github.ayltai.newspaper.app.view;

import java.util.concurrent.TimeUnit;

import android.support.annotation.NonNull;
import android.util.Log;

import com.github.ayltai.newspaper.Constants;
import com.github.ayltai.newspaper.app.data.model.FeaturedItem;
import com.github.ayltai.newspaper.app.widget.FeaturedView;
import com.github.ayltai.newspaper.media.FrescoImageLoader;
import com.github.ayltai.newspaper.util.RxUtils;
import com.github.ayltai.newspaper.util.TestUtils;

import io.reactivex.Observable;

public class FeaturedPresenter extends ItemPresenter<FeaturedView> {
    @Override
    public void onViewAttached(@NonNull final FeaturedView view, final boolean isFirstTimeAttachment) {
        this.manageDisposable(Observable.interval(Constants.FEATURED_IMAGE_ROTATION, TimeUnit.SECONDS)
            .compose(RxUtils.applyObservableBackgroundToMainSchedulers())
            .subscribe(time -> {
                if (this.getModel() instanceof FeaturedItem) {
                    ((FeaturedItem)this.getModel()).next();

                    if (!this.getModel().getImages().isEmpty()) FrescoImageLoader.loadImage(this.getModel().getImages().get(0).getUrl())
                        .compose(RxUtils.applyMaybeBackgroundToMainSchedulers())
                        .subscribe(
                            bitmap -> {
                                view.setImages(this.getModel().getImages());
                                view.setTitle(this.getModel().getTitle());
                            },
                            error -> {
                                if (TestUtils.isLoggable()) Log.e(this.getClass().getSimpleName(), error.getMessage(), error);
                            }
                        );

                    this.bindModel(this.getModel());
                }
            }));

        super.onViewAttached(view, isFirstTimeAttachment);
    }
}

Synchronize featured news item image and title display


package org.springframework.ldap.odm.test.utils;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

public class CompilerInterface {
    // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API
    public static void compile(String directory, String file) throws Exception {

        ProcessBuilder pb = new ProcessBuilder(
                new String[] { "javac",
                               "-cp", "."+File.pathSeparatorChar+"target"+File.separatorChar+"classes"+
                                  File.pathSeparatorChar+System.getProperty("java.class.path"),
                                  directory+File.separatorChar+file });

        pb.redirectErrorStream(true);
        Process proc = pb.start();
        InputStream is = proc.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        char[] buf = new char[1024];
        int count;
        StringBuilder builder = new StringBuilder();
        while ((count = isr.read(buf)) > 0) {
            builder.append(buf, 0, count);
        }

        boolean ok = proc.waitFor() == 0;

        if (!ok) {
            throw new RuntimeException(builder.toString());
        }
    }
}

package org.springframework.ldap.odm.test.utils;

import java.io.File;
import java.util.Arrays;

import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class CompilerInterface {
    // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API
    public static void compile(String directory, String file) throws Exception {
        File toCompile = new File(directory, file);
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        Iterable<? extends JavaFileObject> javaFileObjects =
            fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile));
        compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call();

        fileManager.close();
    }
}

Use JavaCompiler in tests isntead of manually finding "javac"


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

package com.googlesource.gerrit.plugins.rabbitmq.message;

import com.google.common.base.Supplier;
import com.google.gerrit.reviewdb.client.Project;
import com.google.gerrit.server.events.ProjectNameKeySerializer;
import com.google.gerrit.server.events.SupplierSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.Provider;

public class GsonProvider implements Provider<Gson> {

  @Override
  public Gson get() {
    return new GsonBuilder()
            .registerTypeAdapter(Supplier.class, new SupplierSerializer())
            .registerTypeAdapter(Project.NameKey.class, new ProjectNameKeySerializer())
            .create();
  }
}

Format Java files with google-java-format