package edu.northwestern.bioinformatics.studycalendar.testing;

import edu.nwu.bioinformatics.commons.testing.DbTestCase;

import org.springframework.context.ApplicationContext;

import javax.sql.DataSource;

/**
 * @author Rhett Sutphin
 */
public class DaoTestCase extends DbTestCase {
    private static ApplicationContext applicationContext = null;

    protected DataSource getDataSource() {
        return (DataSource) getApplicationContext().getBean("dataSource");
    }

    public ApplicationContext getApplicationContext() {
        synchronized (DaoTestCase.class) {
            if (applicationContext == null) {
                applicationContext = ContextTools.createDeployedApplicationContext();
            }
            return applicationContext;
        }
    }
}

package edu.northwestern.bioinformatics.studycalendar.testing;

import edu.nwu.bioinformatics.commons.testing.DbTestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor;

import javax.sql.DataSource;

/**
 * @author Rhett Sutphin
 */
public class DaoTestCase extends DbTestCase {
    private static ApplicationContext applicationContext = null;
    protected final Log log = LogFactory.getLog(getClass());

    protected MockHttpServletRequest request = new MockHttpServletRequest();
    protected MockHttpServletResponse response = new MockHttpServletResponse();
    private boolean shouldFlush = true;

    protected void setUp() throws Exception {
        super.setUp();
        beginSession();
    }

    protected void tearDown() throws Exception {
        endSession();
        findOpenSessionInViewInterceptor().setFlushModeName("FLUSH_NEVER");
        super.tearDown();
    }

    public void runBare() throws Throwable {
        setUp();
        try {
            runTest();
        } catch (Throwable throwable) {
            shouldFlush = false;
            throw throwable;
        } finally {
            tearDown();
        }
    }

    private void beginSession() {
        log.info("-- beginning DaoTestCase interceptor session --");
        findOpenSessionInViewInterceptor().preHandle(request, response, null);
    }

    private void endSession() {
        log.info("--    ending DaoTestCase interceptor session --");
        OpenSessionInViewInterceptor interceptor = findOpenSessionInViewInterceptor();
        if (shouldFlush) {
            interceptor.postHandle(request, response, null, null);
        }
        interceptor.afterCompletion(request, response, null, null);
    }

    protected void interruptSession() {
        endSession();
        log.info("-- interrupted DaoTestCase session --");
        beginSession();
    }

    private OpenSessionInViewInterceptor findOpenSessionInViewInterceptor() {
        return (OpenSessionInViewInterceptor) getApplicationContext().getBean("openSessionInViewInterceptor");
    }

    protected DataSource getDataSource() {
        return (DataSource) getApplicationContext().getBean("dataSource");
    }

    public ApplicationContext getApplicationContext() {
        synchronized (DaoTestCase.class) {
            if (applicationContext == null) {
                applicationContext = ContextTools.createDeployedApplicationContext();
            }
            return applicationContext;
        }
    }
}

Add open session in view filter support to tests


package kernitus.plugin.OldCombatMechanics.module;

import kernitus.plugin.OldCombatMechanics.OCMMain;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.ProjectileSource;

public class ModuleDisableProjectileRandomness extends Module {

    public ModuleDisableProjectileRandomness(OCMMain plugin){
        super(plugin, "disable-projectile-randomness");
    }

    @EventHandler
    public void onProjectileLaunch(ProjectileLaunchEvent e){
        Projectile projectile = e.getEntity(); //Getting the projectile
        ProjectileSource shooter = projectile.getShooter(); //Getting the shooter
        if(shooter instanceof Player){ //If the shooter was a player
            Player player = (Player) shooter;
            if(!isEnabled(player.getWorld())) return; //If this module is enabled in this world
            debug("Making projectile go straight", player);
            //Here we get a unit vector of the direction the player is looking in and multiply it by the projectile's vector's magnitude
            //We then assign this to the projectile as its new velocity
            projectile.setVelocity(player.getLocation().getDirection().normalize().multiply(projectile.getVelocity().length()));
        }
    }
}

package kernitus.plugin.OldCombatMechanics.module;

import kernitus.plugin.OldCombatMechanics.OCMMain;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.entity.ProjectileLaunchEvent;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.util.Vector;

/**
 * Prevents the noise introduced when shooting with a bow to make arrows go straight.
 */
public class ModuleDisableProjectileRandomness extends Module {

    public ModuleDisableProjectileRandomness(OCMMain plugin){
        super(plugin, "disable-projectile-randomness");
    }

    @EventHandler
    public void onProjectileLaunch(ProjectileLaunchEvent e){
        Projectile projectile = e.getEntity();
        ProjectileSource shooter = projectile.getShooter();

        if(shooter instanceof Player){
            Player player = (Player) shooter;
            if(!isEnabled(player.getWorld())) return;
            debug("Making projectile go straight", player);

            Vector playerDirection = player.getLocation().getDirection().normalize();
            // keep original speed
            Vector arrowVelocity = playerDirection.multiply(projectile.getVelocity().length());

            projectile.setVelocity(arrowVelocity);
        }
    }
}

Remove unnecessary comments and add javadoc


package com.cjm721.overloaded;

import com.cjm721.overloaded.block.ModBlocks;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;

public class OverloadedItemGroups {

  public static final ItemGroup TECH =
      new ItemGroup("Overloaded_Tech") {
        @Override
        public ItemStack createIcon() {
          return new ItemStack(ModBlocks.creativeGenerator);
        }
      };
}

package com.cjm721.overloaded;

import com.cjm721.overloaded.block.ModBlocks;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;

import java.util.Comparator;

public class OverloadedItemGroups {

  public static final ItemGroup TECH =
      new ItemGroup("Overloaded_Tech") {
        @Override
        public ItemStack createIcon() {
          return new ItemStack(ModBlocks.creativeGenerator);
        }

        @Override
        public void fill(NonNullList<ItemStack> items) {
          super.fill(items);

          items.sort(Comparator.<ItemStack, String>comparing(is -> is.getDisplayName().toString()));
        }
      };
}

Sort item group so easier to find things


package com.modesteam.urutau.service;

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

import javax.inject.Inject;

import com.modesteam.urutau.dao.LayerDAO;
import com.modesteam.urutau.model.system.Layer;

public class KanbanService {

	private static final Long FIRST_DEFAULT_LAYER_ID = 1L;

	private static final Long LAST_DEFAULT_LAYER_ID = 4L;

	private final LayerDAO layerDAO;

	public KanbanService() {
		this(null);
	}

	@Inject
	public KanbanService(LayerDAO layerDAO) {
		this.layerDAO = layerDAO;
	}

	/**
	 * Get Default layers of all project:
	 * Backlog, In Progress, Do, Done.
	 *
	 * @return {@link List} of default layers above
	 */
	public List<Layer> getDefaultLayers() {
		List<Layer> defaultLayers = new ArrayList<Layer>();

		for(Long id = FIRST_DEFAULT_LAYER_ID; id <= LAST_DEFAULT_LAYER_ID; id++) {
			Layer found = layerDAO.find(id);
			defaultLayers.add(found);
		}

		return defaultLayers;
	}

	/**
	 * Returns first layer, that is backlog
	 */
	public Layer getBackLogLayer() {
		return layerDAO.find(FIRST_DEFAULT_LAYER_ID);
	}

}

package com.modesteam.urutau.service;

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

import javax.inject.Inject;

import com.modesteam.urutau.dao.LayerDAO;
import com.modesteam.urutau.exception.SystemBreakException;
import com.modesteam.urutau.model.system.Layer;

public class KanbanService {

	private static final Long FIRST_DEFAULT_LAYER_ID = 1L;

	private static final Long LAST_DEFAULT_LAYER_ID = 4L;

	private final LayerDAO layerDAO;

	public KanbanService() {
		this(null);
	}

	@Inject
	public KanbanService(LayerDAO layerDAO) {
		this.layerDAO = layerDAO;
	}

	/**
	 * Get Default layers of all project:
	 * Backlog, In Progress, Do, Done.
	 *
	 * @return {@link List} of default layers above
	 */
	public List<Layer> getDefaultLayers() {
		List<Layer> defaultLayers = new ArrayList<Layer>();

		for(Long id = FIRST_DEFAULT_LAYER_ID; id <= LAST_DEFAULT_LAYER_ID; id++) {
			Layer found = layerDAO.find(id);
			defaultLayers.add(found);
		}

		return defaultLayers;
	}

	/**
	 * Returns first layer, that is backlog
	 */
	public Layer getBackLogLayer() {
		Layer backLogLayer = layerDAO.find(FIRST_DEFAULT_LAYER_ID);;

		if(backLogLayer == null) {
			throw new SystemBreakException("The backlog layer is invalid");
		}

		return backLogLayer;
	}

}

Throw exception if backlog layer are null


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuBar;

public class MenuBar extends JMenuBar {

	private static final long serialVersionUID = 5179328504511930019L;

	private FileMenu fileMenu;
	private DocumentMenu documentMenu;

	public MenuBar() {
		this.addMenus();
	}

	private void addMenus() {
		this.fileMenu = new FileMenu();
		this.documentMenu = new DocumentMenu();

		super.add(this.fileMenu);
		super.add(this.documentMenu);
	}
}

package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuBar;

public class MenuBar extends JMenuBar {

	private static final long serialVersionUID = 5179328504511930019L;

	private FileMenu fileMenu;
	private DocumentMenu documentMenu;
	private HelpMenu helpMenu;

	public MenuBar() {
		this.addMenus();
	}

	private void addMenus() {
		this.fileMenu = new FileMenu();
		this.documentMenu = new DocumentMenu();
		this.helpMenu = new HelpMenu();

		super.add(this.fileMenu);
		super.add(this.documentMenu);
		super.add(this.helpMenu);
	}
}

Add help menu to menu bar.

Add help menu to menu bar.


package com.ushahidi.android;

/**
 * Provides config common to all available test
 *
 * @author Henry Addo
 */
public class DefaultConfig {

    // The api level that Roboelectric will use to run the unit tests
    public static final int EMULATE_SDK = 21;

    private DefaultConfig() {
        // No instance
    }

}

package com.ushahidi.android;

/**
 * Provides config common to all available test
 *
 * @author Henry Addo
 */
public final class DefaultConfig {

    /**
     * The api level that Roboelectric will use to run the unit tests
     */
    public static final int EMULATE_SDK = 21;

    private DefaultConfig() {
        // No instance
    }

}

Make defaul config final so it can't be instantiated


package org.ihtsdo.otf.mapping.rf2.jpa;

import org.hibernate.search.annotations.ContainedIn;

import com.fasterxml.jackson.annotation.JsonBackReference;

import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;

import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;

/**
 * Abstract implementation of {@link DescriptionRefSetMember}.
 */
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
		AbstractRefSetMember implements DescriptionRefSetMember {

	@ManyToOne(targetEntity=DescriptionJpa.class)
/*	*//** The Description associated with this element *//*
	@ManyToOne(cascade = {
			   CascadeType.PERSIST, CascadeType.MERGE
			 }, targetEntity=DescriptionJpa.class)*/
	@JsonBackReference
	@ContainedIn
	private Description description;

	/**
     * {@inheritDoc}
     */
	@Override
	@XmlIDREF
	@XmlAttribute
	public DescriptionJpa getDescription() {
		return (DescriptionJpa)this.description;
	}

	/**
     * {@inheritDoc}
     */
	@Override
	public void setDescription(Description description) {
		this.description = description;

	}
}

package org.ihtsdo.otf.mapping.rf2.jpa;

import org.hibernate.search.annotations.ContainedIn;

import com.fasterxml.jackson.annotation.JsonBackReference;

import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlIDREF;

import org.hibernate.envers.Audited;
import org.ihtsdo.otf.mapping.rf2.Description;
import org.ihtsdo.otf.mapping.rf2.DescriptionRefSetMember;

/**
 * Abstract implementation of {@link DescriptionRefSetMember}.
 */
@MappedSuperclass
@Audited
public abstract class AbstractDescriptionRefSetMember extends
		AbstractRefSetMember implements DescriptionRefSetMember {

	@ManyToOne(targetEntity=DescriptionJpa.class, optional=false)
/*	*//** The Description associated with this element *//*
	@ManyToOne(cascade = {
			   CascadeType.PERSIST, CascadeType.MERGE
			 }, targetEntity=DescriptionJpa.class)*/
	@JsonBackReference
	@ContainedIn
	private Description description;

	/**
     * {@inheritDoc}
     */
	@Override
	@XmlIDREF
	@XmlAttribute
	public DescriptionJpa getDescription() {
		return (DescriptionJpa)this.description;
	}

	/**
     * {@inheritDoc}
     */
	@Override
	public void setDescription(Description description) {
		this.description = description;

	}
}

Add another optional=false for the description refset member.


package br.odb.menu;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

import br.odb.knights.R;

public class ShowOutcomeActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.outcome_layout);

        boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY;
        ((TextView) findViewById(R.id.tvOutcome)).setText( getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad ) );
        ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000);
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MedievalSharp.ttf");
        ( (TextView)findViewById(R.id.tvOutcome) ).setTypeface( font );
    }
}

package br.odb.menu;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.TextView;

import br.odb.knights.R;

public class ShowOutcomeActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.outcome_layout);

        boolean outcomeIsGood = KnightsOfAlentejoSplashActivity.GameOutcome.valueOf( getIntent().getStringExtra( KnightsOfAlentejoSplashActivity.MAPKEY_SUCCESSFUL_LEVEL_OUTCOME) ) == KnightsOfAlentejoSplashActivity.GameOutcome.VICTORY;
        String text = getString( outcomeIsGood ? R.string.outcome_good : R.string.outcome_bad );
        setTitle( text );
        ((TextView) findViewById(R.id.tvOutcome)).setText( text );
        ((TextView) findViewById(R.id.tvOutcome)).setTextColor(outcomeIsGood ? 0xFF00FF00 : 0xFFFF0000);
        Typeface font = Typeface.createFromAsset(getAssets(), "fonts/MedievalSharp.ttf");
        ( (TextView)findViewById(R.id.tvOutcome) ).setTypeface( font );

    }
}

Use outcome for activity title in said activity


package com.tozny.sdk.realm.methods.link_challenge;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;

import javax.annotation.Nullable;

/**
 * Constructs a Request for invoking the "realm.link_challenge" method.
 */
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class LinkChallengeRequest implements ToznyApiRequest {
    @JsonProperty(required=true) private String method = "realm.link_challenge";
    @JsonProperty(required=true) private String destination;
    @JsonProperty private String context;
    @JsonProperty private String callback;
    @JsonProperty private String hostname;
    @JsonProperty private String send;

    public LinkChallengeRequest(String destination, @Nullable String context, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
        this.destination = destination;
        this.context = context;
        this.callback = callback;
        this.hostname = hostname;

        if (send == null) {
            this.send = "yes";
        } else {
            this.send = "no";
        }
    }

    public String getMethod() {
        return method;
    }

    public String getDestination() {
        return destination;
    }

    @Nullable
    public String getContext() {
        return context;
    }

    @Nullable
    public String getCallback() {
        return callback;
    }

    @Nullable
    public String getHostname() {
        return hostname;
    }

    @Nullable
    public Boolean getSend() {
        return send.equals("yes");
    }
}

package com.tozny.sdk.realm.methods.link_challenge;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.tozny.sdk.ToznyApiRequest;

import javax.annotation.Nullable;

/**
 * Constructs a Request for invoking the "realm.link_challenge" method.
 */
@JsonAutoDetect(getterVisibility = JsonAutoDetect.Visibility.NONE)
public class LinkChallengeRequest implements ToznyApiRequest {
    @JsonProperty(required=true) private String method = "realm.link_challenge";
    @JsonProperty(required=true) private String destination;
    @JsonProperty private String context;
    @JsonProperty private String callback;
    @JsonProperty private String hostname;
    @JsonProperty private String send;

    public LinkChallengeRequest(String destination, @Nullable String context, @Nullable String callback, @Nullable String hostname, @Nullable Boolean send) {
        this.destination = destination;
        this.context = context;
        this.callback = callback;
        this.hostname = hostname;

        if (send == null || send ) {
            this.send = "yes";
        } else {
            this.send = "no";
        }
    }

    public String getMethod() {
        return method;
    }

    public String getDestination() {
        return destination;
    }

    @Nullable
    public String getContext() {
        return context;
    }

    @Nullable
    public String getCallback() {
        return callback;
    }

    @Nullable
    public String getHostname() {
        return hostname;
    }

    @Nullable
    public Boolean getSend() {
        return send.equals("yes");
    }
}

Check the value of the Boolean as well. Props @m4dc4p


package com.box.androidsdk.content.requests;

import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.BoxFutureTask;
import com.box.androidsdk.content.models.BoxIteratorRecentItems;
import com.box.androidsdk.content.models.BoxSession;

/**
 * BoxRequest to perform operations on the global recents endpoint
 */
public class BoxRequestRecentItems {

    /**
     * Request to get the Recent Items
     */
    public static class GetRecentItems extends BoxRequestList<BoxIteratorRecentItems, BoxRequestRecentItems.GetRecentItems> implements BoxCacheableRequest<BoxIteratorRecentItems> {
        private static final long serialVersionUID = 8123965031279971506L;

        /**
         * Creates a get recent items request
         *
         * @param recentItemsUrl    URL of the recents items endpoint.
         * @param session   the authenticated session that will be used to make the request with.
         */
        public GetRecentItems(String recentItemsUrl, BoxSession session) {
            super(BoxIteratorRecentItems.class, null, recentItemsUrl, session);
        }

        @Override
        public BoxIteratorRecentItems sendForCachedResult() throws BoxException {
            return super.handleSendForCachedResult();
        }

        @Override
        public BoxFutureTask<BoxIteratorRecentItems> toTaskForCachedResult() throws BoxException {
            return super.handleToTaskForCachedResult();
        }
    }
}

package com.box.androidsdk.content.requests;

import com.box.androidsdk.content.BoxException;
import com.box.androidsdk.content.BoxFutureTask;
import com.box.androidsdk.content.models.BoxIteratorRecentItems;
import com.box.androidsdk.content.models.BoxSession;

/**
 * BoxRequest to perform operations on the global recents endpoint
 */
public class BoxRequestRecentItems {

    /**
     * Request to get the Recent Items
     */
    public static class GetRecentItems extends BoxRequestList<BoxIteratorRecentItems, BoxRequestRecentItems.GetRecentItems> implements BoxCacheableRequest<BoxIteratorRecentItems> {
        private static final long serialVersionUID = 8123965031279971506L;
        private static final String LIMIT = "limit";
        private static final String DEFAULT_LIMIT = "100";

        /**
         * Creates a get recent items request
         *
         * @param recentItemsUrl    URL of the recents items endpoint.
         * @param session   the authenticated session that will be used to make the request with.
         */
        public GetRecentItems(String recentItemsUrl, BoxSession session) {
            super(BoxIteratorRecentItems.class, null, recentItemsUrl, session);
            mQueryMap.put(LIMIT, DEFAULT_LIMIT);
        }

        @Override
        public BoxIteratorRecentItems sendForCachedResult() throws BoxException {
            return super.handleSendForCachedResult();
        }

        @Override
        public BoxFutureTask<BoxIteratorRecentItems> toTaskForCachedResult() throws BoxException {
            return super.handleToTaskForCachedResult();
        }
    }
}

AND-7076: Set limit for GET request for recents endpoint

The default limit of 100 is set for GET recent items.


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

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

/**
 * Provides range faceting capabilities.
 */
package org.apache.lucene.facet.range;

LUCENE-7013: Fix javadocs by reverting to previous state (script failure possibly)


package com.bookbase.bookbase.fragments.behaviour;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;

public class FABScrollBehaviour extends FloatingActionButton.Behavior{

    public FABScrollBehaviour(Context context, AttributeSet attrs){
        super();
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
                                       FloatingActionButton child,
                                       View directTargetChild,
                                       View target,
                                       int nestedScrollAxes){
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
                super.onStartNestedScroll(coordinatorLayout,
                        child, directTargetChild, target, nestedScrollAxes);
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout,
                                    FloatingActionButton child,
                                    View target,
                                    int dxConsumed,
                                    int dyConsumed,
                                    int dxUnconsumed,
                                    int dyUnconsumed){
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);

        if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
            child.hide();
        } else if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
            child.show();
        }
    }

}

package com.bookbase.bookbase.fragments.behaviour;

import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;

public class FABScrollBehaviour extends FloatingActionButton.Behavior{

    public FABScrollBehaviour(Context context, AttributeSet attrs){
        super();
    }

    @Override
    public boolean onStartNestedScroll(CoordinatorLayout coordinatorLayout,
                                       FloatingActionButton child,
                                       View directTargetChild,
                                       View target,
                                       int nestedScrollAxes){
        return nestedScrollAxes == ViewCompat.SCROLL_AXIS_VERTICAL ||
                super.onStartNestedScroll(coordinatorLayout,
                        child, directTargetChild, target, nestedScrollAxes);
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout,
                                    FloatingActionButton child,
                                    View target,
                                    int dxConsumed,
                                    int dyConsumed,
                                    int dxUnconsumed,
                                    int dyUnconsumed){
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);

        if(dyConsumed > 0 && child.getVisibility() == View.VISIBLE){
            child.hide();
        } else if(dyConsumed < 0 && child.getVisibility() != View.VISIBLE){
            child.show();
        }
    }

}

Fix logical error in FAB scroll behaviour

FAB was not re-drawing on scroll up in recycler view.


package io.github.izzyleung.zhihudailypurify.task;

import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication;
import io.github.izzyleung.zhihudailypurify.bean.DailyNews;

import java.util.List;

public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> {
    protected boolean isRefreshSuccess = true;
    protected boolean isContentSame = false;
    protected String date;

    private OnTaskFinishedCallback mCallback;

    public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) {
        this.date = date;
        this.mCallback = callback;
    }

    @Override
    protected void onPreExecute() {
        mCallback.beforeTaskStart();
    }

    @Override
    protected void onPostExecute(List<DailyNews> resultNewsList) {
        mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame);
    }

    protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) {
        return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date));
    }

    public interface OnTaskFinishedCallback {
        public void beforeTaskStart();

        public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame);
    }
}

package io.github.izzyleung.zhihudailypurify.task;

import io.github.izzyleung.zhihudailypurify.ZhihuDailyPurifyApplication;
import io.github.izzyleung.zhihudailypurify.bean.DailyNews;

import java.util.List;

public abstract class BaseGetNewsTask extends BaseDownloadTask<Void, Void, List<DailyNews>> {
    protected boolean isRefreshSuccess = true;
    protected boolean isContentSame = false;
    protected String date;

    private OnTaskFinishedCallback mCallback;

    public BaseGetNewsTask(String date, OnTaskFinishedCallback callback) {
        this.date = date;
        this.mCallback = callback;
    }

    @Override
    protected void onPreExecute() {
        mCallback.beforeTaskStart();
    }

    @Override
    protected void onPostExecute(List<DailyNews> resultNewsList) {
        mCallback.afterTaskFinished(resultNewsList, isRefreshSuccess, isContentSame);
        mCallback = null;
    }

    protected boolean checkIsNewsListEquals(List<DailyNews> newsListFromWeb) {
        return newsListFromWeb.equals(ZhihuDailyPurifyApplication.getInstance().getDataSource().newsOfTheDay(date));
    }

    public interface OnTaskFinishedCallback {
        public void beforeTaskStart();

        public void afterTaskFinished(List<DailyNews> resultList, boolean isRefreshSuccess, boolean isContentSame);
    }
}

Remove callback when the job is done

Remove callback when the job is done


package at.fhtw.mcs;

import java.util.Scanner;

import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.model.TrackFactory;

class Main {

	public static void main(String[] args) throws InterruptedException {
		String filename = args[0];
		System.out.println("Loading " + filename);
		Track track = TrackFactory.loadTrack(filename);
		track.play();

		try (Scanner scanner = new Scanner(System.in)) {
			while (true) {
				switch (scanner.nextLine()) {
					case "p":
						track.togglePlayPause();
						break;
					case "s":
						track.stop();
						break;
					case "q":
						return;
				}
			}
		}
	}
}

package at.fhtw.mcs;

import java.util.Scanner;

import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.model.TrackFactory;

class Main {

	public static void main(String[] args) throws InterruptedException {
		if (args.length != 1) {
			System.err.println("Usage: ./mcs AUDIO_FILE");
		}

		String filename = args[0];
		System.out.println("Loading " + filename);
		Track track = TrackFactory.loadTrack(filename);
		track.play();

		try (Scanner scanner = new Scanner(System.in)) {
			while (true) {
				switch (scanner.nextLine()) {
					case "p":
						track.togglePlayPause();
						break;
					case "s":
						track.stop();
						break;
					case "q":
						return;
				}
			}
		}
	}
}

Print usage if argument count != 1

Print usage if argument count != 1


package io.akessler.elixircounter;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.view.MotionEvent;
import android.view.View;

/**
 * Created by Andy on 9/15/2017.
 */
public class CounterButton extends AppCompatButton implements View.OnTouchListener, View.OnClickListener {

    private int counterValue;

    public CounterButton(Context context, int counterValue) {
        super(context);
        this.counterValue = counterValue;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }
}

package io.akessler.elixircounter;

import android.content.Context;
import android.support.v7.widget.AppCompatButton;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Toast;

/**
 * Created by Andy on 9/15/2017.
 */
public class CounterButton extends AppCompatButton implements OnTouchListener, OnClickListener {

    private Context context;
    private int counterValue;

    public CounterButton(Context context, int counterValue) {
        super(context);
        this.context = context;
        this.counterValue = counterValue;
        setOnTouchListener(this);
        setOnClickListener(this);
        setText(String.valueOf(counterValue));
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(context, String.valueOf(counterValue), Toast.LENGTH_SHORT).show();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return false;
    }
}

Add event handlers, set text as number, temporarily toast on click


package org.metaborg.spoofax.core.style;

import org.metaborg.core.style.ICategory;

public class SortConsCategory implements ICategory {
    private static final long serialVersionUID = 8423515260404604295L;

	public final String sort;
    public final String cons;

    public SortConsCategory(String sort, String cons) {
        this.sort = sort;
        this.cons = cons;
    }

    @Override public String name() {
        return sort + "." + cons;
    }

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

package org.metaborg.spoofax.core.style;

import java.util.Objects;

import org.metaborg.core.style.ICategory;

public class SortConsCategory implements ICategory {
    private static final long serialVersionUID = 8423515260404604295L;

    public final String sort;
    public final String cons;

    public SortConsCategory(String sort, String cons) {
        this.sort = sort;
        this.cons = cons;
    }

    @Override public String name() {
        return sort + "." + cons;
    }

    @Override public boolean equals(Object o) {
        if(this == o)
            return true;
        if(o == null || getClass() != o.getClass())
            return false;
        SortConsCategory that = (SortConsCategory) o;
        return Objects.equals(sort, that.sort) && Objects.equals(cons, that.cons);
    }

    @Override public int hashCode() {
        return Objects.hash(sort, cons);
    }

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

Fix SortCons styling bug: add equals and hashCode


/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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.gravitee.repository.api;

import io.gravitee.repository.model.Api;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApiRepository {

    Optional<Api> findByName(String apiName);

    Set<Api> findAll();

    Set<Api> findByTeam(String teamName);

    Api create(Api api);

    Api update(Api api);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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.gravitee.repository.api;

import io.gravitee.repository.model.Api;

import java.util.Optional;
import java.util.Set;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public interface ApiRepository {

    Optional<Api> findByName(String apiName);

    Set<Api> findAll();

    Set<Api> findByTeam(String teamName);

    Set<Api> findByUser(String username);

    Api create(Api api);

    Api update(Api api);

    void delete(String apiName);

    int countByUser(String username);

    int countByTeam(String teamName);
}

Add service to retrieve list of APIs by user


package de.oppermann.pomutils.commands;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;

import de.oppermann.pomutils.select.SelectionStrategy;

public class SelectionStrategyConverter implements IStringConverter<SelectionStrategy> {

	@Override
	public SelectionStrategy convert(String value) {
		if (value == null) {
			return SelectionStrategy.OUR;
		}

		try {
			return SelectionStrategy.valueOf(value.toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new ParameterException("--select must be one of 'ours', 'theirs', or 'prompt'");
		}
	}

}

package de.oppermann.pomutils.commands;

import com.beust.jcommander.IStringConverter;
import com.beust.jcommander.ParameterException;

import de.oppermann.pomutils.select.SelectionStrategy;

public class SelectionStrategyConverter implements IStringConverter<SelectionStrategy> {

	@Override
	public SelectionStrategy convert(String value) {
		if (value == null) {
			return SelectionStrategy.OUR;
		}

		try {
			return SelectionStrategy.valueOf(value.toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new ParameterException("--select must be one of 'our', 'their', or 'prompt'");
		}
	}

}

Fix error message for illegal select value


/*
 * Copyright 2015 Ivan Pribela
 *
 * 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.svetovid.demo;

import org.svetovid.Svetovid;

public class MaxArray {

    public static void main(String[] args) {

        // Ask for an array of numbers
        double[] numbers = Svetovid.in.readDoubleLine("Please enter the numbers:");

        // Find the maximum
        double maximum = Double.NEGATIVE_INFINITY;
        for (double number : numbers) {
            if (number > maximum) {
                maximum = number;
            }
        }

        // Print the result
        Svetovid.out.println("Maximum number:", maximum);
        Svetovid.out.println(numbers);

    }
}

/*
 * Copyright 2015 Ivan Pribela
 *
 * 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.svetovid.demo;

import org.svetovid.Svetovid;

public class MaxArray {

    public static void main(String[] args) {

        // Ask for an array of numbers
        double[] numbers = Svetovid.in.readDoubleArray("Please enter the numbers:");

        // Find the maximum
        double maximum = Double.NEGATIVE_INFINITY;
        for (double number : numbers) {
            if (number > maximum) {
                maximum = number;
            }
        }

        // Print the result
        Svetovid.out.println("Maximum number:", maximum);
        Svetovid.out.println(numbers);

    }
}

Fix demos to use new iolib

Fix demos to use new iolib


package de.sormuras.bach.execution;

import java.nio.file.Path;

/** Snippet producer and default Java source code helpers. */
interface Scribe {

  /** Convert the string representation of the given object into a {@code String} literal. */
  default String $(Object object) {
    if (object == null) return "null";
    return '"' + object.toString().replace("\\", "\\\\") + '"';
  }

  /** Create {@code Path.of("some/path/...")} literal. */
  default String $(Path path) {
    return "Path.of(" + $((Object) path) + ")";
  }

  /** Create {@code "first" [, "second" [, ...]]} literal. */
  default String $(String[] strings) {
    if (strings.length == 0) return "";
    if (strings.length == 1) return $(strings[0]);
    if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
    return String.join(", ", strings);
  }

  /** Return source code snippet. */
  Snippet toSnippet();
}

package de.sormuras.bach.execution;

import java.nio.file.Path;
import java.util.StringJoiner;

/** Snippet producer and default Java source code helpers. */
interface Scribe {

  /** Convert the string representation of the given object into a {@code String} literal. */
  default String $(Object object) {
    if (object == null) return "null";
    return '"' + object.toString().replace("\\", "\\\\") + '"';
  }

  /** Create {@code Path.of("some/path/...")} literal. */
  default String $(Path path) {
    return "Path.of(" + $((Object) path) + ")";
  }

  /** Create {@code "first" [, "second" [, ...]]} literal. */
  default String $(String[] strings) {
    if (strings.length == 0) return "";
    if (strings.length == 1) return $(strings[0]);
    if (strings.length == 2) return $(strings[0]) + ", " + $(strings[1]);
    var joiner = new StringJoiner(", ");
    for(var string : strings) joiner.add($(string));
    return joiner.toString();
  }

  /** Return source code snippet. */
  Snippet toSnippet();
}

Fix generation of string literals

Fix generation of string literals


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"));
    }

    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"));
    }

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

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

Add EnhancedListView project to licenses list.


package io.github.plastix.forage.util;

public class PermissionUtilsTest {
}

package io.github.plastix.forage.util;

import org.junit.Test;

import static com.google.common.truth.Truth.assertThat;

public class PermissionUtilsTest {

    @Test
    public void isPermissionRequestCancelled_shouldBeCancelled() {
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{})).isTrue();
    }

    @Test
    public void isPermissionRequestCancelled_isNotCancelled() {
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1, -1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0, 0})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0, -1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1, 0})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{-1})).isFalse();
        assertThat(PermissionUtils.isPermissionRequestCancelled(new int[]{0})).isFalse();

    }

    @Test
    public void hasAllPermissionsGranted_allGranted() {
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0})).isTrue();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, 0})).isTrue();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, 0, 0})).isTrue();
    }

    @Test
    public void hasAllPermissionsGranted_notAllGranted() {
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{-1})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, -1})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{0, -1, 0})).isFalse();
        assertThat(PermissionUtils.hasAllPermissionsGranted(new int[]{-1, -1, 0})).isFalse();
    }
}

Add a few PermissionUtils unit tests

Add a few PermissionUtils unit tests


/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.queue.backed.map;

import net.openhft.chronicle.wire.DocumentContext;
import net.openhft.chronicle.wire.MethodWriterWithContext;
import net.openhft.chronicle.wire.UnrecoverableTimeoutException;

// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
    /**
     * @param key       to put
     * @param value     to put
     * @param timestamp last batch timestamp
     */
    void $put(String name, K key, V value, long timestamp);

    /**
     * @param key       to remove
     * @param timestamp last batch timestamp
     */
    void $remove(String name, K key, long timestamp);

    /**
     * Remove all entries
     *
     * @param timestamp last batch timestamp
     */
    void $clear(String name, long timestamp);

    /**
     * @param hostId which caused the checkpoint
     */
    void $checkPoint(String name, int hostId);
}

/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.queue.backed.map;

// TODO add queue names and only read the ones for it.
public interface QueueEvents<K, V> {
    /**
     * @param key       to put
     * @param value     to put
     * @param timestamp last batch timestamp
     */
    void $put(String name, K key, V value, long timestamp);

    /**
     * @param key       to remove
     * @param timestamp last batch timestamp
     */
    void $remove(String name, K key, long timestamp);

    /**
     * Remove all entries
     *
     * @param timestamp last batch timestamp
     */
    void $clear(String name, long timestamp);

    /**
     * @param hostId which caused the checkpoint
     */
    void $checkPoint(String name, int hostId);
}

Make ring use the default isClosed

Make ring use the default isClosed


package com.capgemini.resilience.employer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmployerServiceTmp {

  private final Random random = new Random();

  private static final double SUCCESS_PROBABILITY = 0.6;

  /**
   * "Primary method" with defined fallback method.
   * @return Standard answer
   */
  @HystrixCommand(fallbackMethod = "getFallbackEmployer")
  public String getEmployer() {

    double randomDouble = random.nextDouble();
    if (randomDouble <= SUCCESS_PROBABILITY) {
      return "Success employer";
    }

    throw new IllegalStateException("Test exception");
  }

  /**
   * Example fallback method.
   * @return Fallback answer
   */
  public String getFallbackEmployer() {
    return "Fallback employer";
  }

}

package com.capgemini.resilience.employer.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class EmployerServiceTmp {

  private final Random random = new Random();

  private static final double SUCCESS_PROBABILITY = 0.6;

  /**
   * "Primary method" with defined fallback method.
   *
   * @return Standard answer
   */
  @HystrixCommand(fallbackMethod = "getFallbackEmployer")
  public String getEmployer() {

    double randomDouble = random.nextDouble();
    if (randomDouble <= SUCCESS_PROBABILITY) {
      return "Success employer";
    }

    throw new IllegalStateException("Test exception");
  }

  /**
   * Example fallback method.
   * @return Fallback answer
   */
  public String getFallbackEmployer() {
    return "Fallback employer";
  }

}

Comment modified (testing github email configuration)


//
// $Id: Cluster.java,v 1.2 2003/02/13 23:01:35 mdb Exp $

package com.threerings.whirled.spot.data;

import com.threerings.presents.dobj.DSet;

/**
 * Contains information on clusters.
 */
public class Cluster
    implements DSet.Entry
{
    /** A unique identifier for this cluster (also the distributed object
     * id of the cluster chat object). */
    public int clusterOid;

    /** The x-coordinate of the cluster in the scene. */
    public int x;

    /** The y-coordinate of the cluster in the scene. */
    public int y;

    /** The number of occupants in this cluster. */
    public int occupants;

    // documentation inherited
    public Comparable getKey ()
    {
        if (_key == null) {
            _key = new Integer(clusterOid);
        }
        return _key;
    }

    // documentation inherited
    public boolean equals (Object other)
    {
        if (other instanceof Cluster) {
            return ((Cluster)other).clusterOid == clusterOid;
        } else {
            return false;
        }
    }

    // documentation inherited
    public int hashCode ()
    {
        return clusterOid;
    }

    /** Used for {@link #geyKey}. */
    protected transient Integer _key;
}

//
// $Id: Cluster.java,v 1.3 2003/03/25 03:16:11 mdb Exp $

package com.threerings.whirled.spot.data;

import com.threerings.io.SimpleStreamableObject;
import com.threerings.presents.dobj.DSet;

/**
 * Contains information on clusters.
 */
public class Cluster extends SimpleStreamableObject
    implements DSet.Entry
{
    /** A unique identifier for this cluster (also the distributed object
     * id of the cluster chat object). */
    public int clusterOid;

    /** The x-coordinate of the cluster in the scene. */
    public int x;

    /** The y-coordinate of the cluster in the scene. */
    public int y;

    /** The number of occupants in this cluster. */
    public int occupants;

    // documentation inherited
    public Comparable getKey ()
    {
        if (_key == null) {
            _key = new Integer(clusterOid);
        }
        return _key;
    }

    // documentation inherited
    public boolean equals (Object other)
    {
        if (other instanceof Cluster) {
            return ((Cluster)other).clusterOid == clusterOid;
        } else {
            return false;
        }
    }

    // documentation inherited
    public int hashCode ()
    {
        return clusterOid;
    }

    /** Used for {@link #geyKey}. */
    protected transient Integer _key;
}

Extend SimpleStreamableObject so that we get a useful default toString().

git-svn-id: a1a4b28b82a3276cc491891159dd9963a0a72fae@2321 542714f4-19e9-0310-aa3c-eee0fc999fb1


package io.castle.client;

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

/**
 * This suite runs all tests that can be run without user interaction. {@link io.castle.client.PairingINTTest} contains MFA tests.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({ EventINTTest.class, MonitorINTTest.class, SessionINTTest.class, UsersINTTest.class })
public class AutomaticTestSuite {
}

package io.castle.client;

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

/**
 * This suite runs all tests that can be run without user interaction. {@link io.castle.client.PairingINTTest} contains MFA tests.
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({ SessionINTTest.class, MonitorINTTest.class, UsersINTTest.class})
public class AutomaticTestSuite {
}

Remove test cases requiring manual steps


package org.ihtsdo.buildcloud.controller;

import org.ihtsdo.buildcloud.controller.helper.HypermediaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping
public class RootController {

	@Autowired
	private HypermediaGenerator hypermediaGenerator;

	private static final String[] ROOT_LINK = {"centres"};

	@RequestMapping
	@ResponseBody
	public Map getRoot(HttpServletRequest request) {
		return hypermediaGenerator.getEntityHypermedia(new HashMap<String, String>(), request, ROOT_LINK);
	}

}

package org.ihtsdo.buildcloud.controller;

import org.ihtsdo.buildcloud.controller.helper.HypermediaGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping
public class RootController {

	@Autowired
	private HypermediaGenerator hypermediaGenerator;

	private static final String[] ROOT_LINK = {"centres", "builds"};

	@RequestMapping
	@ResponseBody
	public Map getRoot(HttpServletRequest request) {
		return hypermediaGenerator.getEntityHypermedia(new HashMap<String, String>(), request, ROOT_LINK);
	}

}

Add builds link to API root controller.

Add builds link to API root controller.


/*
 * Copyright 2015 Blazebit.
 *
 * 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.blazebit.persistence;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.blazebit.persistence.entity.Document;

/**
 *
 * @author Christian Beikov
 * @since 1.1.0
 */
public class GroupByTest extends AbstractCoreTest {

    @Test
    public void testGroupByEntitySelect() {
        CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d");
        criteria.groupBy("d.owner");
        assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.name, d.nonJoinable, d.owner", criteria.getQueryString());
        criteria.getResultList();
    }
}

/*
 * Copyright 2015 Blazebit.
 *
 * 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.blazebit.persistence;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import com.blazebit.persistence.entity.Document;

/**
 *
 * @author Christian Beikov
 * @since 1.1.0
 */
public class GroupByTest extends AbstractCoreTest {

    @Test
    public void testGroupByEntitySelect() {
        CriteriaBuilder<Long> criteria = cbf.create(em, Long.class).from(Document.class, "d");
        criteria.groupBy("d.owner");
        assertEquals("SELECT d FROM Document d JOIN d.owner owner_1 GROUP BY owner_1, d.age, d.archived, d.creationDate, d.creationDate2, d.documentType, d.id, d.idx, d.intIdEntity, d.lastModified, d.lastModified2, d.name, d.nonJoinable, d.owner", criteria.getQueryString());
        criteria.getResultList();
    }
}

Fix failing test because of new fields

Fix failing test because of new fields


package org.jboss.as.quickstarts.helloworld;

/**
 * A simple CDI service which is able to say hello to someone
 *
 * @author Pete Muir
 *
 */
public class HelloService {

    String createHelloMessage(String name) {
        return "Hello " + name + "!";
    }

}

package org.jboss.as.quickstarts.helloworld;

/**
 * A simple CDI service which is able to say hello to someone
 *
 * @author Pete Muir
 *
 */
public class HelloService {

    String createHelloMessage(String name) {
        return "'ello 'ello " + name + "!";
    }

}

Change service to force new build

Change service to force new build


/*
 * 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.skife.jdbi.v2.sqlobject.stringtemplate;

import org.skife.jdbi.v2.sqlobject.SqlQuery;

@UseStringTemplate3StatementLocator(value = "/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.sql.stg", cacheable = true)
public interface Kombucha
{
    @SqlQuery
    String getIngredients();
}

/*
 * 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.skife.jdbi.v2.sqlobject.stringtemplate;

import org.antlr.stringtemplate.StringTemplateErrorListener;
import org.skife.jdbi.v2.sqlobject.SqlQuery;

@UseStringTemplate3StatementLocator(value = "/org/skife/jdbi/v2/sqlobject/stringtemplate/Kombucha.sql.stg", errorListener = StringTemplateErrorListener.class, cacheable = true)
public interface Kombucha
{
    @SqlQuery
    String getIngredients();
}

Use the default error listener for this class


package com.sdsmdg.kd.trianglify.models;

import android.graphics.Point;

public class Triangle {
    public Point a;
    public Point b;
    public Point c;

    public Triangle (Point a, Point b, Point c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

package com.sdsmdg.kd.trianglify.models;

import android.graphics.Point;

public class Triangle {
    public Point a;
    public Point b;
    public Point c;

    public Triangle (Point a, Point b, Point c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    private float sign (Point p1, Point p2, Point p3) {
        return (p1.x - p3.x) * (p2.y - p3.y) - (p1.y - p3.y) * (p2.x - p3.x);
    }

    public boolean contains (Point p) {
        boolean pab, pbc, pca;

        pab = sign(p, a, b) < 0f;
        pbc = sign(p, b, c) < 0f;

        if (pab == pbc)
            return false;

        pca = sign(p, c, a) < 0f;

        return (pab == pca);
    }
}

Add 'contains()' to check if a point is in interior of triangle.


/**
 * @file MyClass.java
 * @author Valery Samovich
 * @version 1
 * @date 2014/01/09
 *
 *  Example of Class Declaration
 */

package com.samovich.java.basics.concepts.classes;

/*
 * Class declaration
 */
public class MyClass {
    // Field(s), Constructor, and Method declarations
}

/**
 * @file MyClass.java
 * @author Valery Samovich
 * @version 1
 * @date 2014/01/09
 *
 *  Example of Class Declaration
 * 1. Modifiers such as public, private, and a number of others that you will
 *    encounter later.
 * 2. The class name, with the initial letter capitalized by convention.
 * 3. The name of the class's parent (superclass), if any, preceded by the
 *    keyword extends. A class can only extend (subclass) one parent.
 * 4. A comma-separated list of interfaces implemented by the class, if any,
 *    preceded by the keyword implements. A class can implement more than one
 *    interface.
The class body, surrounded by braces, {}.
 */

package com.samovich.java.basics.concepts.classes;

/*
 * Class declaration
 */
public class MyClass {
    // Field(s), Constructor, and Method declarations
}

Add Javadoc for Class Declaration.

Add Javadoc for Class Declaration.


/*
 * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved.
 * See LICENSE in the project root directory.
 */
package edu.jhu.hlt.utilt.sys;

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

/**
 * Disable/enable System.err calls.
 *

 * Mainly used to quiet the large amount of output from Stanford CoreNLP.
 */
public class SystemErrDisabler {

  private final PrintStream err;

  /**
   * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled.
   */
  public SystemErrDisabler() {
    this.err = System.err;
  }

  /**
   * Disable writing to System.err.
   */
  public void disable() {
    System.setErr(new PrintStream(new OutputStream() {
      public void write(int b) {
      }
    }));
  }

  /**
   * Enable writing to System.err.
   */
  public void enable() {
    System.setErr(this.err);
  }
}

/*
 * Copyright 2012-2015 Johns Hopkins University HLTCOE. All rights reserved.
 * See LICENSE in the project root directory.
 */
package edu.jhu.hlt.utilt.sys;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

/**
 * Disable/enable System.err calls.
 *

 * Mainly used to quiet the large amount of output from Stanford CoreNLP.
 */
public class SystemErrDisabler {

  private final PrintStream err;

  /**
   * Default ctor. Save a pointer to the current System.err so it can be enabled/disabled.
   */
  public SystemErrDisabler() {
    this.err = System.err;
  }

  /**
   * Disable writing to System.err.
   *
   * @throws UnsupportedEncodingException if the system does not support {@link StandardCharsets#UTF_8}.
   */
  public void disable() throws UnsupportedEncodingException {
    PrintStream ps = new PrintStream(new EmptyOutputStream(), false, StandardCharsets.UTF_8.toString());
    System.setErr(ps);
  }

  private static class EmptyOutputStream extends OutputStream {

    /* (non-Javadoc)
     * @see java.io.OutputStream#write(int)
     */
    @Override
    public void write(int b) throws IOException {

    }
  }

  /**
   * Enable writing to System.err.
   */
  public void enable() {
    System.setErr(this.err);
  }
}

Refactor into a named static inner class. Depend upon UTF-8 encoding for proper handling of text.


package de.marza.firstspirit.modules.logging.console.utilities;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

public class ClipboardAccessTest {

  private ClipboardAccess testling;

  @Before
  public void setUp() throws Exception {
    testling = new ClipboardAccess();
  }

  @Test
  public void transfer() throws Exception {
    testling.copy("Test 123");

    assertThat(testling.paste(), is("Test 123"));
  }

}

package de.marza.firstspirit.modules.logging.console.utilities;

import org.junit.Before;
import org.junit.Test;

import java.awt.GraphicsEnvironment;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeFalse;

public class ClipboardAccessTest {

  private ClipboardAccess testling;

  @Before
  public void setUp() throws Exception {
    assumeFalse("Run only in desktop", GraphicsEnvironment.isHeadless());
    testling = new ClipboardAccess();
  }

  @Test
  public void transfer() throws Exception {
    testling.copy("Test 123");

    assertThat(testling.paste(), is("Test 123"));
  }

}

Disable test in headless environments

Disable test in headless environments


package com.github.aureliano.verbum_domini.dao;

import java.io.Serializable;
import java.util.List;

public interface IDao<T> {

	public List<T> list();

	public T load(Serializable id);
}

package com.github.aureliano.verbum_domini.dao;

import java.io.Serializable;
import java.util.List;

import com.github.aureliano.verbum_domini.web.ServiceParams;

public interface IDao<T> {

	public abstract List<Pagination<T>> list();

	public abstract List<Pagination<T>> list(T filter);

	public abstract List<Pagination<T>> list(T filter, ServiceParams params);

	public abstract T load(Serializable id);
}

Prepare data access object interface.

Prepare data access object interface.


package controllers;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
        return ok(index.render("Your new application is ready."));
    }

}

package controllers;

import java.lang.management.ManagementFactory;
import java.util.List;

import play.*;
import play.mvc.*;

import views.html.*;

public class Application extends Controller {

    public static Result index() {
    	List<String> inputArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
        return ok(index.render("Input arguments: " + inputArguments));
    }

}

Return JVM input parameters from Play application

[#52708279]


package working;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

import playground.FastTest;

class TagsDisplayNamesAndDependencyInjectionTests {

	// --include-tag fast
	// --exclude-tag fast
	// @Test
	// @Tag("fast")
	@FastTest
	@DisplayName("Fast test with a cool name! 😱")
	void fastTest(TestInfo testInfo) {
		System.out.println(testInfo);
	}

	@Test
	void normalTest(TestInfo testInfo) {
		System.out.println(testInfo);
	}

}

package working;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;

import playground.FastTest;

class TagsDisplayNamesAndDependencyInjectionTests {

	// --include-tag fast
	// --exclude-tag fast

	// @Test
	// @Tag("fast")
	@FastTest
	@DisplayName("Fast test! 😱")
	void fastTest(TestInfo testInfo) {
		System.err.println(testInfo);
	}

	@Tag("normal")
	@Test
	void normalTest() {
	}

}

Update based on live coding

Update based on live coding


package com.nilhcem.droidcontn.core.dagger.module;

import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;

import com.nilhcem.droidcontn.data.database.DbOpenHelper;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import timber.log.Timber;

@Module
public class DatabaseModule {

    static final String TAG = "database";

    @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
        return new DbOpenHelper(application);
    }

    @Provides @Singleton SqlBrite provideSqlBrite() {
        return SqlBrite.create(message -> Timber.tag(TAG).v(message));
    }

    @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) {
        return sqlBrite.wrapDatabaseHelper(helper);
    }
}

package com.nilhcem.droidcontn.core.dagger.module;

import android.app.Application;
import android.database.sqlite.SQLiteOpenHelper;

import com.nilhcem.droidcontn.data.database.DbOpenHelper;
import com.squareup.sqlbrite.BriteDatabase;
import com.squareup.sqlbrite.SqlBrite;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import timber.log.Timber;

@Module
public class DatabaseModule {

    static final String TAG = "database";

    @Provides @Singleton SQLiteOpenHelper provideSQLiteOpenHelper(Application application) {
        return new DbOpenHelper(application);
    }

    @Provides @Singleton SqlBrite provideSqlBrite() {
        return SqlBrite.create(Timber.tag(TAG)::v);
    }

    @Provides @Singleton BriteDatabase provideBriteDatabase(SqlBrite sqlBrite, SQLiteOpenHelper helper) {
        return sqlBrite.wrapDatabaseHelper(helper);
    }
}

Replace lambda with a method reference

Replace lambda with a method reference


package com.continuuity.gateway.router;

import com.continuuity.security.auth.TokenState;
import com.continuuity.security.auth.TokenValidator;
import com.google.common.util.concurrent.AbstractService;

/**
 * Simple {@link com.continuuity.security.auth.TokenValidator} implementation for test cases, which always
 * returns {@link com.continuuity.security.auth.TokenState#VALID} for all tokens.
 */
public class SuccessTokenValidator extends AbstractService implements TokenValidator {
  @Override
  protected void doStart() {
    // no-op
  }

  @Override
  protected void doStop() {
    // no-op
  }

  @Override
  public TokenState validate(String token) {
    return TokenState.VALID;
  }
}

package com.continuuity.gateway.router;

import com.continuuity.security.auth.TokenState;
import com.continuuity.security.auth.TokenValidator;
import com.google.common.util.concurrent.AbstractService;

/**
 * Simple {@link com.continuuity.security.auth.TokenValidator} implementation for test cases, which always
 * returns {@link com.continuuity.security.auth.TokenState#VALID} for all tokens.
 */
public class SuccessTokenValidator extends AbstractService implements TokenValidator {
  @Override
  protected void doStart() {
    notifyStarted();
  }

  @Override
  protected void doStop() {
    notifyStopped();
  }

  @Override
  public TokenState validate(String token) {
    return TokenState.VALID;
  }
}

Fix start & stop handling of test TokenValidator


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

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <T> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<T> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    T getLogger(String name);
}

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

import java.io.Closeable;

/**
 * A basic registry for {@link LoggerContext} objects and their associated external
 * Logger classes. This registry should not be used for Log4j Loggers; it is instead used for creating bridges to
 * other external log systems.
 *
 * @param <L> the external logger class for this registry (e.g., {@code org.slf4j.Logger})
 * @since 2.1
 */
public interface LoggerAdapter<L> extends Closeable {

    /**
     * Gets a named logger. Implementations should defer to the abstract methods in {@link AbstractLoggerAdapter}.
     *
     * @param name the name of the logger to get
     * @return the named logger
     */
    L getLogger(String name);
}

Revert "Use the more common type name T instead of L."

This reverts commit 146fa40dd6b6889277a86f6e5858ffacb672480c.


package edu.northwestern.bioinformatics.studycalendar.web.schedule;

import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;

import java.util.Calendar;

public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
    private ScheduleReconsentCommand command;
    private StudyService studyService;
    private NowFactory nowFactory;

    protected void setUp() throws Exception {
        super.setUp();
        studyService = registerMockFor(StudyService.class);
        nowFactory = registerMockFor(NowFactory.class);
        command = new ScheduleReconsentCommand(studyService, nowFactory);
    }

    public void testValidate() throws Exception {
        command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));

        expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)).times(2);
        replayMocks();
        command.validate(null);
        verifyMocks();
        assertSameDay("Expected Date different than actual", DateTools.createDate(2007, Calendar.AUGUST, 3), command.getStartDate());
    }
}

package edu.northwestern.bioinformatics.studycalendar.web.schedule;

import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;
import org.springframework.validation.Errors;
import org.springframework.validation.BindException;

import java.util.Calendar;

public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
    private ScheduleReconsentCommand command;
    private StudyService studyService;
    private NowFactory nowFactory;

    protected void setUp() throws Exception {
        super.setUp();
        studyService = registerMockFor(StudyService.class);
        nowFactory = registerMockFor(NowFactory.class);
        command = new ScheduleReconsentCommand(studyService, nowFactory);
    }

    public void testValidate() throws Exception {
        BindException errors = new BindException(command, "startDate");
        command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));
        expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3));
        replayMocks();

        command.validate(errors);
        verifyMocks();

        assertEquals("There should be one error: ", 1, errors.getAllErrors().size());
    }
}

Fix broken test.. was testing the old way of validation of the reconsent command.


/**
 * Copyright (C) 2010 the original author or authors.
 * See the notice.md file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.beust.jcommander;

/**
 * Thrown when a command was expected.
 *
 * @author Cedric Beust <cedric@beust.com>
 */
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {

  /**
   * the command passed by the user.
   */
  private final String unknownCommand;

  public MissingCommandException(String message) {
    super(message);
    this.unknownCommand = null;
  }

  public MissingCommandException(String message, String command) {
    super(message);
    this.unknownCommand = command;
  }

  public String getUnknownCommand() {
    return unknownCommand;
  }

}

/**
 * Copyright (C) 2010 the original author or authors.
 * See the notice.md file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * 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.beust.jcommander;

/**
 * Thrown when a command was expected.
 *
 * @author Cedric Beust <cedric@beust.com>
 */
@SuppressWarnings("serial")
public class MissingCommandException extends ParameterException {

  /**
   * the command passed by the user.
   */
  private final String unknownCommand;

  public MissingCommandException(String message) {
    this(message, null);
  }

  public MissingCommandException(String message, String command) {
    super(message);
    this.unknownCommand = command;
  }

  public String getUnknownCommand() {
    return unknownCommand;
  }

}

Use the `this` constructor as suggested by @cbeust

This makes constructors more maintainable: one constructor does the
processing.


package ru.yandex.qatools.allure.data.utils;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;

import java.io.*;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 31.10.13
 */
public final class AllureReportUtils {

    private AllureReportUtils() {
    }

    public static void serialize(final File directory, String name, Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            AnnotationIntrospector ai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
            mapper.getSerializationConfig().with(ai);

            mapper.writerWithDefaultPrettyPrinter().writeValue(new File(directory, name), obj);
        } catch (IOException e) {
            throw new ReportGenerationException(e);
        }
    }
}

package ru.yandex.qatools.allure.data.utils;

import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
import ru.yandex.qatools.allure.data.ReportGenerationException;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author Dmitry Baev charlie@yandex-team.ru
 *         Date: 31.10.13
 */
public final class AllureReportUtils {

    private AllureReportUtils() {
    }

    public static void serialize(final File directory, String name, Object obj) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            AnnotationIntrospector annotatoinInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
            mapper.getSerializationConfig().with(annotatoinInspector);
            OutputStreamWriter writer = new OutputStreamWriter(
                    new FileOutputStream(new File(directory, name)), StandardCharsets.UTF_8);
            mapper.writerWithDefaultPrettyPrinter().writeValue(writer, obj);
        } catch (IOException e) {
            throw new ReportGenerationException(e);
        }
    }
}

Use UTF-8 while write testcases json

Use UTF-8 while write testcases json


package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

package org.nuxeo.drive.service.impl;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.nuxeo.ecm.core.api.IdRef;

/**
 * Helper to handle synchronization root definitions.
 *
 * @author Antoine Taillefer
 */
public class RootDefinitionsHelper {

    private RootDefinitionsHelper() {
        // Utility class
    }

    /**
     * Parses the given synchronization root definitions string.
     */
    public static Map<String, Set<IdRef>> parseRootDefinitions(
            String rootDefinitions) {
        Map<String, Set<IdRef>> lastActiveRootRefs = new LinkedHashMap<String, Set<IdRef>>();
        if (rootDefinitions != null) {
            String[] rootDefinitionComponents = StringUtils.split(
                    rootDefinitions, ",");
            for (String rootDefinition : rootDefinitionComponents) {
                String[] rootComponents = StringUtils.split(rootDefinition, ":");
                String repoName = rootComponents[0].trim();
                Set<IdRef> refs = lastActiveRootRefs.get(repoName);
                if (refs == null) {
                    refs = new HashSet<IdRef>();
                    lastActiveRootRefs.put(repoName, refs);
                }
                refs.add(new IdRef(rootComponents[1].trim()));
            }
        }
        return lastActiveRootRefs;
    }

}

Fix Sonar Major violation: Javadoc Type

NXP-11577: Fix Sonar Major violation: Javadoc Type


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

/**
 * Enum for describing the type of dependency sent to the server.
 *
 * @author tom.shapira
 */
public enum DependencyType {

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,

    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,

    COCOAPODS,
    HEX,

    R,
    CRATE,
    CABAL,
    OPAM;

    @Override
    public String toString() {
        switch(this) {
            case COCOAPODS: return "CocoaPods";
            case CRATE: return "Crate";
            case CABAL: return "Cabal";
            case OPAM: return "Opam";
            default: return super.toString();
        }
    }
}

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

/**
 * Enum for describing the type of dependency sent to the server.
 *
 * @author tom.shapira
 */
public enum DependencyType {

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,
    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,
    ALPINE,
    ARCH_LINUX,

    COCOAPODS,
    HEX,

    R,
    CRATE,
    CABAL,
    OPAM;

    @Override
    public String toString() {
        switch(this) {
            case COCOAPODS: return "CocoaPods";
            case CRATE: return "Crate";
            case CABAL: return "Cabal";
            case OPAM: return "Opam";
            case DEBIAN: return "Debian";
            case ALPINE: return "Alpine";
            case ARCH_LINUX: return "Arch Linux";
            default: return super.toString();
        }
    }
}

Add Alpine,Arch Linux, RPM & Debian to agents-api


package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }

    public void sendBuffer(byte[] buf, short length, APDU apdu) {
        short le = apdu.setOutgoing();

        apdu.setOutgoingLength(le);
        apdu.sendBytesLong(buf, (short) 0, le);
    }
}

package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }

    public void sendBuffer(byte[] buf, short length, APDU apdu) {
        short le = apdu.setOutgoing();

        if(le == 0) {
            le = apdu.getOutBlockSize();
        }

        apdu.setOutgoingLength(le);
        apdu.sendBytesLong(buf, (short) 0, le);
    }
}

Handle zero value Le in APDU

Handle zero value Le in APDU


package info.u_team.u_team_core.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> {

	public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background) {
		super(container, playerInventory, title, background);
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}

}

package info.u_team.u_team_core.screen;

import com.mojang.blaze3d.matrix.MatrixStack;

import net.minecraft.entity.player.PlayerInventory;
import net.minecraft.inventory.container.Container;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.ITextComponent;

public class UBasicContainerScreen<T extends Container> extends UContainerScreen<T> {

	public UBasicContainerScreen(T container, PlayerInventory playerInventory, ITextComponent title, ResourceLocation background, int xSize, int ySize) {
		super(container, playerInventory, title, background);
		setSize(xSize, ySize);
	}

	@Override
	public void func_230430_a_(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) {
		func_230446_a_(matrixStack);
		super.func_230430_a_(matrixStack, mouseX, mouseY, partialTicks);
		field_230710_m_.forEach(widget -> widget.func_230443_a_(matrixStack, mouseX, mouseY));
		func_230459_a_(matrixStack, mouseX, mouseY);
	}

}

Add args to ctor with size

Add args to ctor with size


package com.instagram.common.json.annotation.processor.parent;

import com.instagram.common.json.annotation.JsonType;

/**
 * Interface parent to test that polymorphic deserialization works.
 */
@JsonType(
        valueExtractFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".parseFromJson(${parser_object})",
        serializeCodeFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".serializeToJson(${generator_object}, (com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)${object_varname}.${field_varname}, true)")
public interface InterfaceParentUUT {
}

package com.instagram.common.json.annotation.processor.parent;

import com.instagram.common.json.annotation.JsonType;

/**
 * Interface parent to test that polymorphic deserialization works.
 */
@JsonType(
        valueExtractFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".parseFromJson(${parser_object})",
        serializeCodeFormatter =
                "com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT__JsonHelper"
                + ".serializeToJson(${generator_object}, "
                + "(com.instagram.common.json.annotation.processor.parent.InterfaceImplementationUUT)"
                + "${object_varname}.${field_varname}, "
                + "true)")
public interface InterfaceParentUUT {
}

Clean up formatting a bit

Clean up formatting a bit


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

import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration
public class RouteConfigWithCamelContextInjected {

    @Autowired
    private CamelContext camelContext;

    @Bean
    public RoutesBuilder routeCreatedWithInjectedCamelContext() {
        Assert.notNull(camelContext);
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:test").to("seda:test");
            }
        };
    }

}

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

import org.apache.camel.CamelContext;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

@Configuration
public class RouteConfigWithCamelContextInjected {

    @Autowired
    private CamelContext camelContext;

    @Bean
    public RoutesBuilder routeCreatedWithInjectedCamelContext() {
        Assert.notNull(camelContext, "camelContext must not be null");
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("seda:test").to("seda:test");
            }
        };
    }

}

Clean up use of deprecated method

[Minor] Clean up use of deprecated method

Signed-off-by: Gregor Zurowski <5fdc67d2166bcdd1d3aa4ed45ea5a25e9b21bc20@zurowski.org>