package sizebay.catalog.client.model;

import lombok.*;

@Getter
@Setter
@EqualsAndHashCode
@ToString
public class ModelingSizeMeasures   {

  String sizeName = null;
  ModelingMeasureRange chest = null;
  ModelingMeasureRange hip = null;
  ModelingMeasureRange waist = null;
  ModelingMeasureRange sleeve = null;
  ModelingMeasureRange length = null;
  ModelingMeasureRange insideLeg = null;
  ModelingMeasureRange biceps = null;
  ModelingMeasureRange height = null;
  ModelingMeasureRange fist = null;
  ModelingMeasureRange neck = null;
  ModelingMeasureRange thigh = null;
  ModelingMeasureRange centralSeam = null;
  ModelingMeasureRange underBust = null;
  ModelingMeasureRange shoulderWidth = null;
  ModelingMeasureRange insoleLength = null;
  ModelingMeasureRange insoleWidth = null;
  ModelingMeasureRange waistUpper = null;
  ModelingMeasureRange waistLower = null;

  ModelingMeasureRange label1 = null;
  ModelingMeasureRange label2 = null;
  ModelingMeasureRange label3 = null;

  ModelingMeasureRange ageChart = null;
  ModelingMeasureRange weightChart = null;
  ModelingMeasureRange equivalence = null;

}

package sizebay.catalog.client.model;

import lombok.*;

@Getter
@Setter
@EqualsAndHashCode
@ToString
public class ModelingSizeMeasures   {

  String sizeName = null;
  ModelingMeasureRange chest = null;
  ModelingMeasureRange hip = null;
  ModelingMeasureRange waist = null;
  ModelingMeasureRange sleeve = null;
  ModelingMeasureRange length = null;
  ModelingMeasureRange insideLeg = null;
  ModelingMeasureRange biceps = null;
  ModelingMeasureRange height = null;
  ModelingMeasureRange fist = null;
  ModelingMeasureRange neck = null;
  ModelingMeasureRange thigh = null;
  ModelingMeasureRange centralSeam = null;
  ModelingMeasureRange underBust = null;
  ModelingMeasureRange shoulderWidth = null;
  ModelingMeasureRange insoleLength = null;
  ModelingMeasureRange insoleWidth = null;
  ModelingMeasureRange waistUpper = null;
  ModelingMeasureRange waistLower = null;

  ModelingMeasureRange label1 = null;
  ModelingMeasureRange label2 = null;
  ModelingMeasureRange label3 = null;

  ModelingMeasureRange ageChart = null;
  ModelingMeasureRange weightChart = null;
  ModelingMeasureRange equivalence = null;
  ModelingMeasureRange headCircumference = null;

}

Add new measure -> headCircumference

Fix: Add new measure -> headCircumference


package com.github.aureliano.achmed.helper;

import java.util.Properties;

public final class ApplicationHelper {

	private ApplicationHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

	public static String help() {
		String help = FileHelper.readResource("meta/help");
		return help;
	}

	public static String version() {
		Properties properties = PropertyHelper.loadProperties("meta/version.properties");
		return new StringBuilder("achmed")
			.append(" ")
			.append(properties.get("version"))
			.append(":")
			.append(properties.get("release"))
			.append(" (")
			.append(properties.get("date"))
			.append(")")
			.toString();
	}

	public static String error(String[] args) {
		String param = StringHelper.join(args, " ");
		if ("".equals(param)) {
			return EasterEggHelper.silence();
		} else if ("greeting".equalsIgnoreCase(param)) {
			return EasterEggHelper.greeting();
		} else if ("hello".equalsIgnoreCase(param)) {
			return EasterEggHelper.hello();
		} else if ("you are dead".equalsIgnoreCase(param)) {
			return EasterEggHelper.youAreDead();
		} else if ("do you like hews?".equalsIgnoreCase(param)) {
			return EasterEggHelper.doYouLikeJews();
		} else {
			return "Don't know how to handle such command: " + param;
		}
	}
}

package com.github.aureliano.achmed.helper;

import java.util.Properties;

public final class ApplicationHelper {

	private ApplicationHelper() {
		throw new InstantiationError(this.getClass().getName() + " cannot be instantiated.");
	}

	public static String help() {
		String help = FileHelper.readResource("meta/help");
		return help;
	}

	public static String version() {
		Properties properties = PropertyHelper.loadProperties("meta/version.properties");
		return new StringBuilder("achmed")
			.append(" ")
			.append(properties.get("version"))
			.append(":")
			.append(properties.get("release"))
			.append(" (")
			.append(properties.get("date"))
			.append(")")
			.toString();
	}

	public static String error(String[] args) {
		String param = StringHelper.join(args, " ");
		if ("".equals(param)) {
			return EasterEggHelper.silence();
		} else if ("greeting".equalsIgnoreCase(param)) {
			return EasterEggHelper.greeting();
		} else if ("hello".equalsIgnoreCase(param)) {
			return EasterEggHelper.hello();
		} else if ("you are dead".equalsIgnoreCase(param)) {
			return EasterEggHelper.youAreDead();
		} else if ("do you like jews?".equalsIgnoreCase(param)) {
			return EasterEggHelper.doYouLikeJews();
		} else {
			return "Don't know how to handle such command: " + param;
		}
	}
}

Add method to say Achmed like jews.

Add method to say Achmed like jews.


package org.slc.sli.stamper.jobs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.slc.sli.stamper.mapreduce.map.ConfigurableMapReduceJob;

public class Stamper extends Configured implements Tool {

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new Stamper(), args);
        System.exit(res);
    }

	@Override
	public int run(String[] args) throws Exception {
		Configuration conf = new Configuration();
		JobConf jobConf = ConfigurableMapReduceJob.parseMapper(conf, "stamper.json");
		Job job = new Job(jobConf);
		boolean success = job.waitForCompletion(true);
		return success ? 0 : 1;
	}

}

package org.slc.sli.stamper.jobs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.slc.sli.stamper.mapreduce.map.ConfigurableMapReduceJob;

public class Stamper extends Configured implements Tool {

    public static void main(String[] args) throws Exception {
        int res = ToolRunner.run(new Configuration(), new Stamper(), args);
        System.exit(res);
    }

	@Override
	public int run(String[] args) throws Exception {
		Configuration conf = new Configuration();
		JobConf jobConf = ConfigurableMapReduceJob.parseMapper(conf, "stamper.json");
		jobConf.setNumMapTasks(30);
		jobConf.setNumReduceTasks(6);
		jobConf.setMemoryForMapTask(4096);
		jobConf.setMemoryForReduceTask(8192);
		Job job = new Job(jobConf);
		boolean success = job.waitForCompletion(true);
		return success ? 0 : 1;
	}

}

Increase the number of map/reduce tasks.


package org.spoofax.jsglr2.parser;

import org.spoofax.jsglr2.parser.result.ParseFailureCause;

public class ParseException extends Exception {

    private static final long serialVersionUID = 5070826083429554841L;

    public ParseException(ParseFailureCause.Type failureType, Position position, Integer character) {
        super(message(failureType, position, character));
    }

    private static String message(ParseFailureCause.Type failureType, Position position, Integer character) {
        StringBuilder message = new StringBuilder();

        message.append(failureType.message);

        if(position != null)
            message.append(
                " at offset " + position.offset + "(line " + position.line + ", column " + position.column + ")");

        if(character != null)
            message.append(" at character " + new String(Character.toChars(character)));

        return message.toString();
    }

}

package org.spoofax.jsglr2.parser;

import org.metaborg.parsetable.characterclasses.CharacterClassFactory;
import org.spoofax.jsglr2.parser.result.ParseFailureCause;

public class ParseException extends Exception {

    private static final long serialVersionUID = 5070826083429554841L;

    public ParseException(ParseFailureCause.Type failureType, Position position, Integer character) {
        super(message(failureType, position, character));
    }

    private static String message(ParseFailureCause.Type failureType, Position position, Integer character) {
        StringBuilder message = new StringBuilder();

        message.append(failureType.message);

        if(position != null)
            message.append(
                " at offset " + position.offset + "(line " + position.line + ", column " + position.column + ")");

        if(character != null)
            message.append(" at character " + CharacterClassFactory.intToString(character));

        return message.toString();
    }

}

Use helper to print whitespace characters with encodings


package com.ezardlabs.lostsector.ai;

import com.ezardlabs.dethsquare.Transform;

public class RangedBehaviour extends Behaviour {
	private final float range;

	RangedBehaviour(float moveSpeed, boolean willPatrol, float visionRange, float range) {
		super(moveSpeed, willPatrol, visionRange);
		this.range = range;
	}

	@Override
	protected CombatState onEnemySighted(Transform self, Transform enemy) {
		if (Math.abs(self.position.x - enemy.position.x) <= range) {
			return CombatState.ATTACKING;
		} else {
			return CombatState.TRACKING;
		}
	}

	@Override
	protected CombatState attack(Transform self, Transform target) {
		return null;
	}

	public static class Builder extends Behaviour.Builder<Builder> {
		private float range = 1500;

		public Builder setRange(float range) {
			this.range = range;
			return this;
		}

		@Override
		public RangedBehaviour create() {
			return new RangedBehaviour(moveSpeed, willPatrol, visionRange, range);
		}
	}
}

package com.ezardlabs.lostsector.ai;

import com.ezardlabs.dethsquare.Transform;
import com.ezardlabs.lostsector.ai.RangedBehaviour.Builder.ShootAction;

public class RangedBehaviour extends Behaviour {
	private final float range;
	private final ShootAction shootAction;

	RangedBehaviour(float moveSpeed, boolean willPatrol, float visionRange, float range, ShootAction shootAction) {
		super(moveSpeed, willPatrol, visionRange);
		this.range = range;
		this.shootAction = shootAction;
	}

	@Override
	protected CombatState onEnemySighted(Transform self, Transform enemy) {
		if (Math.abs(self.position.x - enemy.position.x) <= range) {
			return CombatState.ATTACKING;
		} else {
			return CombatState.TRACKING;
		}
	}

	@Override
	protected CombatState attack(Transform self, Transform target) {
		shootAction.onShoot(self, target);
		return CombatState.ATTACKING;
	}

	public static class Builder extends Behaviour.Builder<Builder> {
		private float range = 1500;
		private ShootAction shootAction;

		public Builder setRange(float range) {
			this.range = range;
			return this;
		}

		public Builder setShootAction(ShootAction shootAction) {
			this.shootAction = shootAction;
			return this;
		}

		@Override
		public RangedBehaviour create() {
			return new RangedBehaviour(moveSpeed, willPatrol, visionRange, range, shootAction);
		}

		public interface ShootAction {

			void onShoot(Transform self, Transform target);
		}
	}
}

Allow for ranged enemies to define what exactly they do when they shoot


package com.s24.redjob;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.lang.annotation.*;

/**
 * Qualifier for the {@link RedisConnectionFactory} to use for RedJob.
 */
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface RedJobRedisConnectionFactory {
}

package com.s24.redjob;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.lang.annotation.*;

/**
 * Qualifier for the {@link RedisConnectionFactory} to use for RedJob.
 */
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Qualifier
public @interface RedJobRedisConnectionFactory {
}

Introduce qualifier for connection factory to use for RedJob


package org.cyclops.commoncapabilities.core;

import net.minecraftforge.fml.relauncher.ReflectionHelper;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Helper methods.
 * @author rubensworks
 */
public class Helpers {

    public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
        if (method != null) {
            try {
                return (R) method.invoke(instance, arguments);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static <R> R getFieldValue(Object instance, @Nullable Field field) {
        if (field != null) {
            try {
                return (R) field.get(instance);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
        try {
            return ReflectionHelper.findMethod(clazz, null, new String[]{method}, methodTypes);
        } catch (ReflectionHelper.UnableToFindMethodException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Field getField(Class<?> clazz, String field) {
        try {
            return ReflectionHelper.findField(clazz, field);
        } catch (ReflectionHelper.UnableToFindFieldException e) {
            e.printStackTrace();
            return null;
        }
    }

}

package org.cyclops.commoncapabilities.core;

import net.minecraftforge.fml.relauncher.ReflectionHelper;

import javax.annotation.Nullable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Helper methods.
 * @author rubensworks
 */
public class Helpers {

    public static <R> R invokeMethod(Object instance, @Nullable Method method, Object... arguments) {
        if (method != null) {
            try {
                return (R) method.invoke(instance, arguments);
            } catch (IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static <R> R getFieldValue(Object instance, @Nullable Field field) {
        if (field != null) {
            try {
                return (R) field.get(instance);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static <E> Method getMethod(Class<? super E> clazz, String method, Class<?>... methodTypes) {
        try {
            return ReflectionHelper.findMethod(clazz, method, null, methodTypes);
        } catch (ReflectionHelper.UnableToFindMethodException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Field getField(Class<?> clazz, String field) {
        try {
            return ReflectionHelper.findField(clazz, field);
        } catch (ReflectionHelper.UnableToFindFieldException e) {
            e.printStackTrace();
            return null;
        }
    }

}

Fix compilation issue because of latest Forge RB


package com.novoda.downloadmanager;

import android.support.annotation.Nullable;

interface InternalDownloadFileStatus extends DownloadFileStatus {

    void update(FileSize fileSize, FilePath localFilePath);

    boolean isMarkedAsDownloading();

    boolean isMarkedAsQueued();

    boolean isMarkedForDeletion();

    void markAsDownloading();

    void isMarkedAsPaused();

    boolean isMarkedAsError();

    void markAsQueued();

    void markForDeletion();

    void markAsError(DownloadError.Error error);

    @Nullable
    Optional<DownloadError> error();

}

package com.novoda.downloadmanager;

interface InternalDownloadFileStatus extends DownloadFileStatus {

    void update(FileSize fileSize, FilePath localFilePath);

    boolean isMarkedAsDownloading();

    boolean isMarkedAsQueued();

    boolean isMarkedForDeletion();

    void markAsDownloading();

    void isMarkedAsPaused();

    boolean isMarkedAsError();

    void markAsQueued();

    void markForDeletion();

    void markAsError(DownloadError.Error error);

    Optional<DownloadError> error();

}

Remove Nullable annotation on Optional.

Remove Nullable annotation on Optional.


// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client.widgets.properties;

import com.google.gwt.user.client.ui.TextArea;

/**
 * Property editor for long text.  Appears as a scrollable, resizable area.
 *
 */
public class TextAreaPropertyEditor extends TextPropertyEditorBase{

  public TextAreaPropertyEditor() {
   super(new TextArea());
  }
}

// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2018 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0

package com.google.appinventor.client.widgets.properties;

import com.google.gwt.user.client.ui.TextArea;

/**
 * Property editor for long text.  Appears as a scrollable, resizable area.
 */
public class TextAreaPropertyEditor extends TextPropertyEditorBase {

  /* same as the height set in TextPropertyEditorBase */
  private static final String MIN_CSS_HEIGHT = "2em";

  /* tightly coupled with the width of properties panel:
   * 186px == width of properties panel - side paddings and borders of textarea
   *       == 194px - 8px
   */
  private static final String MAX_CSS_WIDTH = "186px";

  public TextAreaPropertyEditor() {
   super(new TextArea());

   textEdit.getElement().getStyle().setProperty("min-height", MIN_CSS_HEIGHT);
   textEdit.getElement().getStyle().setProperty("max-width", MAX_CSS_WIDTH);
  }
}

Add two css styles to textarea

Add two css styles to textarea


package com.formulasearchengine.mathmltools.converters.mathoid;

/**
 * @author Andre Greiner-Petter
 */
public enum MathoidTypes {
    TEX("tex"),
    INLINE_TEX("inline-tex"),
    MML("mml"),
    ASCII("ascii");

    private String value;

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

    public String getValue() {
        return value;
    }
}

package com.formulasearchengine.mathmltools.converters.mathoid;

/**
 * @author Andre Greiner-Petter
 */
public enum MathoidTypes {
    TEX("tex"),
    INLINE_TEX("inline-tex"),
    MML("mml"),
    ASCII("ascii"),
    CHEM("chem");

    private String value;

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

    public String getValue() {
        return value;
    }
}

Add chem type of mathoid

Add chem type of mathoid


package org.cloudfoundry.runtime.service.relational;

import org.cloudfoundry.runtime.env.*;
import org.cloudfoundry.runtime.service.AbstractDataSourceCreator;
import org.springframework.util.Assert;

import javax.sql.DataSource;

/**
 * Simplified access to RDBMS service.
 *
 * @author Thomas Risberg
 *
 */
public class RdbmsServiceCreator extends AbstractDataSourceCreator<RdbmsServiceInfo> {

	private AbstractDataSourceCreator delegate;

	@Override
	public DataSource createService(AbstractDataSourceServiceInfo serviceInfo) {
		if (serviceInfo.getLabel() != null && serviceInfo.getLabel().startsWith("postgres")) {
			this.delegate = new PostgresqlServiceCreator();
		}
		else {
			this.delegate = new MysqlServiceCreator();
		}
		return super.createService(serviceInfo);
	}

	@Override
	public String getDriverClassName() {
		Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
		return delegate.getDriverClassName();
	}

	@Override
	public String getValidationQuery() {
		Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
		return delegate.getValidationQuery();
	}
}

package org.cloudfoundry.runtime.service.relational;

import org.cloudfoundry.runtime.env.*;
import org.cloudfoundry.runtime.service.AbstractDataSourceCreator;
import org.springframework.util.Assert;

import javax.sql.DataSource;

/**
 * Simplified access to RDBMS service.
 *
 * @author Thomas Risberg
 *
 */
public class RdbmsServiceCreator extends AbstractDataSourceCreator<RdbmsServiceInfo> {

	private AbstractDataSourceCreator delegate;

	@Override
	public DataSource createService(AbstractDataSourceServiceInfo serviceInfo) {
		if (serviceInfo.getLabel() != null && (serviceInfo.getLabel().startsWith("postgres") || serviceInfo.getLabel().startsWith("elephantsql"))) {
			this.delegate = new PostgresqlServiceCreator();
		}
		else {
			this.delegate = new MysqlServiceCreator();
		}
		return super.createService(serviceInfo);
	}

	@Override
	public String getDriverClassName() {
		Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
		return delegate.getDriverClassName();
	}

	@Override
	public String getValidationQuery() {
		Assert.notNull(delegate, "DataSourceCreator delegate was not populated");
		return delegate.getValidationQuery();
	}
}

Fix driver detection for elephantsql

Fix driver detection for elephantsql


package edu.kit.iti.formal.pse.worthwhile.validation;

public class WorthwhileJavaValidator extends AbstractWorthwhileJavaValidator {

//	@Check
//	public void checkGreetingStartsWithCapital(Greeting greeting) {
//		if (!Character.isUpperCase(greeting.getName().charAt(0))) {
//			warning("Name should start with a capital", MyDslPackage.Literals.GREETING__NAME);
//		}
//	}

}

package edu.kit.iti.formal.pse.worthwhile.validation;

import org.apache.tools.ant.taskdefs.optional.testing.Funtest;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.validation.Check;

import com.google.inject.Inject;

import de.itemis.xtext.typesystem.ITypesystem;
import edu.kit.iti.formal.pse.worthwhile.model.ast.FunctionDeclaration;

public class WorthwhileJavaValidator extends AbstractWorthwhileJavaValidator {

//	@Check
//	public void checkGreetingStartsWithCapital(Greeting greeting) {
//		if (!Character.isUpperCase(greeting.getName().charAt(0))) {
//			warning("Name should start with a capital", MyDslPackage.Literals.GREETING__NAME);
//		}
//	}

	@Check
	public void checkFunctionDeclerationValidReturnStatment(FunctionDeclaration functionDeclaration) {
		ValidatorASTNodeVisitor validatorASTNodeVisitor = new ValidatorASTNodeVisitor();
		validatorASTNodeVisitor.visit(functionDeclaration);
		if(!validatorASTNodeVisitor.getValidReturnFound()) {
			error("Function has no valid return statement.", null);
		}
	}
	@Inject
	private ITypesystem ts;

	@Check
	public void checkTypesystemRules( EObject x ) {
	  ts.checkTypesystemConstraints(x, this);
	}

}

Add check for valid return statements.

[validation] Add check for valid return statements.


package nl.homeserver.energie;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Objects;

public class VerbruikenEnKosten {

    private final Collection<VerbruikKosten> all;

    public VerbruikenEnKosten(final Collection<VerbruikKosten> all) {
        this.all = all;
    }

    private BigDecimal getTotaalVerbruik() {
        return all.stream()
                  .map(VerbruikKosten::getVerbruik)
                  .filter(Objects::nonNull)
                  .reduce(BigDecimal::add)
                  .orElse(null);
    }

    private BigDecimal getTotaalKosten() {
        return all.stream()
                  .map(VerbruikKosten::getKosten)
                  .filter(Objects::nonNull)
                  .reduce(BigDecimal::add)
                  .orElse(null);
    }

    public VerbruikKosten sumToSingle() {
        return  new VerbruikKosten(getTotaalVerbruik(), getTotaalKosten());
    }
}

package nl.homeserver.energie;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Objects;

import javax.annotation.Nullable;

class VerbruikenEnKosten {

    private final Collection<VerbruikKosten> all;

    VerbruikenEnKosten(final Collection<VerbruikKosten> all) {
        this.all = all;
    }

    @Nullable
    private BigDecimal getTotaalVerbruik() {
        return all.stream()
                  .map(VerbruikKosten::getVerbruik)
                  .filter(Objects::nonNull)
                  .reduce(BigDecimal::add)
                  .orElse(null);
    }

    @Nullable
    private BigDecimal getTotaalKosten() {
        return all.stream()
                  .map(VerbruikKosten::getKosten)
                  .filter(Objects::nonNull)
                  .reduce(BigDecimal::add)
                  .orElse(null);
    }

    VerbruikKosten sumToSingle() {
        return  new VerbruikKosten(getTotaalVerbruik(), getTotaalKosten());
    }
}

Fix issues found by SonarCloud

Fix issues found by SonarCloud


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

import com.google.common.collect.Maps;

import java.util.Map;

class LifeCycleMethodsMap
{
    private final Map<Class<?>, LifeCycleMethods> map = Maps.newHashMap();

    synchronized LifeCycleMethods get(Class<?> clazz)
    {
        LifeCycleMethods methods = map.get(clazz);
        if (methods == null) {
            methods = new LifeCycleMethods(clazz);
            map.put(clazz, methods);
        }
        return methods;
    }
}

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

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

class LifeCycleMethodsMap
{
    private final Map<Class<?>, LifeCycleMethods> map = new ConcurrentHashMap<>();

    public LifeCycleMethods get(Class<?> clazz)
    {
        return map.computeIfAbsent(clazz, LifeCycleMethods::new);
    }
}

Reduce contention during lifecycle tracking


package com.boundary.camel.component.ssh;

import com.boundary.camel.component.common.ServiceInfo;

/**
 *
 * @author davidg
 *
 */
public class SshxInfo extends ServiceInfo {

	private String command;
	private String expectedOutput;

	public SshxInfo() {
		// TODO Auto-generated constructor stub
	}

	public String getCommand() {
		return command;
	}

	public String getExpectedOutput() {
		return expectedOutput;
	}

	public void setCommand(String command) {
		this.command = command;
	}

	public void setExpectedOutput(String expectedOutput) {
		this.expectedOutput = expectedOutput;
	}

	@Override
	public String toString() {
		return "SsshxInfo [expectedOutput=" + expectedOutput + "]";
	}

}

/**
 * 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 com.boundary.camel.component.ssh;

import java.io.InputStream;

import com.boundary.camel.component.common.ServiceInfo;

public class SshxResult extends ServiceInfo {

    /**
     * The value of this header is a {@link InputStream} with the standard error
     * stream of the executable.
     */
    public static final String STDERR = "CamelSshStderr";

    /**
     * The value of this header is the exit value that is returned, after the
     * execution. By convention a non-zero status exit value indicates abnormal
     * termination.

     * Note that the exit value is OS dependent.
     */
    public static final String EXIT_VALUE = "CamelSshExitValue";

    private final String command;

    private final int exitValue;

    private final InputStream stdout;

    private final InputStream stderr;

    public SshxResult(String command, int exitValue, InputStream out, InputStream err) {
        this.command = command;
        this.exitValue = exitValue;
        this.stdout = out;
        this.stderr = err;
    }

    public String getCommand() {
        return command;
    }

    public int getExitValue() {
        return exitValue;
    }

    public InputStream getStdout() {
        return stdout;
    }

    public InputStream getStderr() {
        return stderr;
    }

    public String toString() {
    	StringBuffer sb = new StringBuffer();
    	sb.append("exitValue=" + exitValue);
    	sb.append("command=" + command);
    	return sb.toString();
    }
}

Use code from Camel distribution for results


package devopsdistilled.operp.client.abstracts;

public abstract class AbstractPaneModel<PO extends PaneModelObserver> extends
		AbstractModel<PO> implements PaneModel<PO> {

	protected String title;

	@Override
	public void update() {
		setTitle(getTitle());
	}

	@Override
	public void setTitle(String title) {
		this.title = title;
		for (PaneModelObserver observer : observers) {
			observer.updateTitle(this.title);
		}
	}

}

package devopsdistilled.operp.client.abstracts;

public abstract class AbstractPaneModel<PO extends PaneModelObserver> extends
		AbstractModel<PO> implements PaneModel<PO> {

	protected String title = "";

	@Override
	public void update() {
		setTitle(getTitle());
	}

	@Override
	public void setTitle(String title) {
		this.title = title;
		for (PO observer : observers) {
			observer.updateTitle(this.title);
		}
	}

}

Use generic Observer type while notifying observers

OPEN - task 41: Design "ListItemPane" as per new MVC model
http://github.com/DevOpsDistilled/OpERP/issues/issue/41


package com.msgilligan.bitcoinj.rpcserver;

import com.msgilligan.bitcoinj.json.pojo.ServerInfo;

/**
 * Standard Bitcoin JSON-RPC service
 */
//@JsonRpcService("BitcoinRPC")
public interface BitcoinJsonRpc {
    public Integer getblockcount();
    public Integer getconnectioncount();
    // TODO: For some reason getinfo doesn't work if we say it retuns ServerInfo
    public Object getinfo();
}

package com.msgilligan.bitcoinj.rpcserver;

import com.msgilligan.bitcoinj.json.pojo.ServerInfo;

/**
 * Standard Bitcoin JSON-RPC service
 */
public interface BitcoinJsonRpc {
    public Integer getblockcount();
    public Integer getconnectioncount();
    // TODO: For some reason getinfo doesn't work if we say it returns ServerInfo
    public Object getinfo();
}

Fix comment typo, remove commented-out annotation.


/**
 * @file Introductions.java
 * @author Valery Samovich
 * @version 1
 * @date 2015/04/07
 */

/**
 * TeamTreehouse. Java Basics.
 */
package com.samovich.basics.introduction.treehouse;

import java.io.Console;

public class Introductions {

    public static void main(String[] args) {
        Console console = System.console();
        // Welcome to the Introductions program!
        String firstName = "Valery";
        // thisIsAnExampleOfCamelCasing
        console.printf("Hello, my name is %s\n", firstName);
        console.printf("%s is learning how to write Java\n", firstName);
    }

}

Add Introduction class for Team Treehouse example


package de.itemis.mosig.racecar.textconv;

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

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class TextFileReaderTest {

    @Test
    public void shouldReadContentsOfExistingFile() throws IOException {
        Path tmpFilePath = Files.createTempFile(this.getClass().getSimpleName(),"txt");
        String expectedContent = new String(new byte[]{(byte) (char) (new Random().nextInt(40) + 20)}, StandardCharsets.UTF_8);
        Files.write(tmpFilePath, expectedContent.getBytes(StandardCharsets.UTF_8));

        TextFileReader underTest = new TextFileReader(tmpFilePath);

        String result = underTest.contents();

        Assert.assertEquals(expectedContent, result);
    }
}

package de.itemis.mosig.racecar.textconv;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Random;

public class TextFileReaderTest {

    private Path tmpFilePath;

    @Before
    public void setUp() {
        try {
            tmpFilePath = Files.createTempFile(this.getClass().getSimpleName(),"txt");
        } catch (IOException e) {
            Assert.fail("Could not create temporary test file: " + e.getMessage());
        }
    }

    @After
    public void tearDown() {
        if (tmpFilePath != null) {
            try {
                Files.deleteIfExists(tmpFilePath);
            } catch (IOException e) {
                System.err.println("WARNING: Could not delete temporary test file: " + e.getMessage());
            }
        }
    }
    @Test
    public void shouldReadContentsOfExistingFile() throws IOException {
        String expectedContent = generateRandomString();
        Files.write(tmpFilePath, expectedContent.getBytes(StandardCharsets.UTF_8));

        TextFileReader underTest = new TextFileReader(tmpFilePath);

        String result = underTest.contents();

        Assert.assertEquals(expectedContent, result);
    }

    /*
     * ##### start private helper code
     */

    private String generateRandomString() {
        return new String(new byte[]{(byte) (char) (new Random().nextInt(40) + 20)}, StandardCharsets.UTF_8);
    }
}

REFACTOR: Test does now proper tmpFile creation and deletion.


package org.ovirt.engine.api.resource;

import javax.ws.rs.DELETE;
import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.WatchDog;

public interface WatchdogResource extends DeviceResource<WatchDog> {
    @DELETE
    Response remove();
}

package org.ovirt.engine.api.resource;

import javax.ws.rs.DELETE;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.ovirt.engine.api.model.WatchDog;

@Produces({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML})
public interface WatchdogResource extends DeviceResource<WatchDog> {
    @DELETE
    Response remove();
}

Add @Provides to watchdogs resource

restapi: Add @Provides to watchdogs resource

Currently the watchdogs resource doesn't have a @Provides annotation. In
theory this shouldn't be required as the annotation is in the base
class. But in practice the application server reacts differently, in
particular if the annotation isn't present the server won't use use the
JAXB or JSON providers when the "Accept" header doesn't have a value.
This means that requests like this:

  DELETE /vms/{vm:id}/watchdogs/{watchdog:id}

Will fail with the following error message:

  Could not find MessageBodyWriter for response object of type:
  org.ovirt.engine.api.model.Action of media type:
  application/octet-stream

This specific problem can be resolved adding the "Accept" header to the
request, and that is good practice. For backwards compatibility sake
this patch adds the annotation.

Change-Id: I1bcb6263450be603b21e398196c6713ad599ce25
Bug-Url: https://bugzilla.redhat.com/1250046
Signed-off-by: Juan Hernandez <59e5b8140de97cc91c3fb6c5342dce948469af8c@redhat.com>
(cherry picked from commit e494a557b00d6a4028fed172fb3ad1d8e276733a)


package ch.difty.scipamato.core.sync;

import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
@ComponentScan(basePackages = "ch.difty.scipamato")
public class BatchConfiguration {

}

package ch.difty.scipamato.core.sync;

import org.springframework.batch.core.configuration.annotation.DefaultBatchConfigurer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackageClasses = DefaultBatchConfigurer.class)
@ComponentScan(basePackages = "ch.difty.scipamato")
public class BatchConfiguration {

    // TODO currently uses the wrong datasource. Should use batchDataSource with the admin permissions but uses the sourceDataSource.
}

Add TODO about spring batch using the wrong datasource

* This is currently only an issue if the legacy application data import occurs after the first start of the project


package uk.gov.hscic;

import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.resource.OperationOutcome;
import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum;
import ca.uhn.fhir.model.dstu2.valueset.IssueTypeEnum;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;

public class OperationOutcomeFactory {

    private OperationOutcomeFactory() { }

    public static BaseServerResponseException buildOperationOutcomeException(BaseServerResponseException exception, String code, IssueTypeEnum issueTypeEnum) {
        CodeableConceptDt codeableConceptDt = new CodeableConceptDt(SystemURL.VS_GPC_ERROR_WARNING_CODE, code)
                .setText(exception.getMessage());

        OperationOutcome operationOutcome = new OperationOutcome();

        operationOutcome.addIssue()
                .setSeverity(IssueSeverityEnum.ERROR)
                .setCode(issueTypeEnum)
                .setDetails(codeableConceptDt);

        operationOutcome.getMeta()
                .addProfile(SystemURL.SD_GPC_OPERATIONOUTCOME);

        exception.setOperationOutcome(operationOutcome);
        return exception;
    }
}

package uk.gov.hscic;

import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt;
import ca.uhn.fhir.model.dstu2.resource.OperationOutcome;
import ca.uhn.fhir.model.dstu2.valueset.IssueSeverityEnum;
import ca.uhn.fhir.model.dstu2.valueset.IssueTypeEnum;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;

public class OperationOutcomeFactory {

    private OperationOutcomeFactory() { }

    public static BaseServerResponseException buildOperationOutcomeException(BaseServerResponseException exception, String code, IssueTypeEnum issueTypeEnum) {
        CodeableConceptDt codeableConceptDt = new CodeableConceptDt(SystemURL.VS_GPC_ERROR_WARNING_CODE, code)
                .setText(exception.getMessage());
        codeableConceptDt.getCodingFirstRep().setDisplay(code);

        OperationOutcome operationOutcome = new OperationOutcome();

        operationOutcome.addIssue()
                .setSeverity(IssueSeverityEnum.ERROR)
                .setCode(issueTypeEnum)
                .setDetails(codeableConceptDt);

        operationOutcome.getMeta()
                .addProfile(SystemURL.SD_GPC_OPERATIONOUTCOME);

        exception.setOperationOutcome(operationOutcome);
        return exception;
    }
}

Update Operation Outcome to include mandatory element


package org.intermine.util;

import static org.apache.commons.lang.StringUtils.isBlank;

import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;

public class Emailer {

	private static final String PREFIX = "mail.regarding.";

	private final Properties properties;

	public Emailer(Properties properties) {
		this.properties = properties;
	}

	public void email(String to, String messageKey) throws MessagingException {
		String subject = properties.getProperty(PREFIX + messageKey + ".subject");
		String body = properties.getProperty(PREFIX + messageKey + ".body");
		MailUtils.email(to, subject, body, properties);
	}

	public void email(String to, String messageKey, Object... vars) throws MessagingException {
		String subject = properties.getProperty(PREFIX + messageKey + ".subject");
		String bodyFmt = properties.getProperty(PREFIX + messageKey + ".body");
		String body = String.format(bodyFmt, vars);
		MailUtils.email(to, subject, body, properties);
	}

	public void welcome(String to) throws MessagingException {
		MailUtils.welcome(to, properties);
	}

	public String subscribeToList(String address) throws MessagingException {
		String mailingList = properties.getProperty("mail.mailing-list");
        if (!isBlank(mailingList)) {
            MailUtils.subscribe(address, properties);
            return mailingList;
        }
        return null;
	}

}

package org.intermine.util;

import static org.apache.commons.lang.StringUtils.isBlank;

import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;

import org.apache.commons.lang.StringUtils;

public class Emailer {

    private static final String PREFIX = "mail.regarding.";

    private final Properties properties;

    public Emailer(Properties properties) {
        this.properties = properties;
    }

    public void email(String to, String messageKey) throws MessagingException {
        String subject = properties.getProperty(PREFIX + messageKey + ".subject");
        String body = properties.getProperty(PREFIX + messageKey + ".body");
        MailUtils.email(to, subject, body, properties);
    }

    public void email(String to, String messageKey, Object... vars) throws MessagingException {
        String subject = properties.getProperty(PREFIX + messageKey + ".subject");
        String bodyFmt = properties.getProperty(PREFIX + messageKey + ".body");
        if (StringUtils.isBlank(bodyFmt)) {
            throw new MessagingException("No email template configured for " + messageKey);
        }
        String body = String.format(bodyFmt, vars);
        MailUtils.email(to, subject, body, properties);
    }

    public void welcome(String to) throws MessagingException {
        MailUtils.welcome(to, properties);
    }

    public String subscribeToList(String address) throws MessagingException {
        String mailingList = properties.getProperty("mail.mailing-list");
        if (!isBlank(mailingList)) {
            MailUtils.subscribe(address, properties);
            return mailingList;
        }
        return null;
    }

}

Handle missing templates nicely. Whitespace


package com.novoda.downloadmanager;

import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;

class NotificationDispatcher {

    private final Object waitForDownloadService;
    private final NotificationCreator<DownloadBatchStatus> notificationCreator;

    private DownloadService downloadService;

    NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
        this.waitForDownloadService = waitForDownloadService;
        this.notificationCreator = notificationCreator;
    }

    void updateNotification(DownloadBatchStatus downloadBatchStatus) {
        WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
                .thenPerform(executeUpdateNotification(downloadBatchStatus));
    }

    private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
        return () -> {
            NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);

            if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
                downloadService.stackNotification(notificationInformation);
            } else {
                downloadService.updateNotification(notificationInformation);
            }

            return null;
        };
    }

    void setDownloadService(DownloadService downloadService) {
        this.downloadService = downloadService;
    }
}

package com.novoda.downloadmanager;

import android.support.annotation.WorkerThread;

import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETION;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DOWNLOADED;

class NotificationDispatcher {

    private final Object waitForDownloadService;
    private final NotificationCreator<DownloadBatchStatus> notificationCreator;

    private DownloadService downloadService;

    NotificationDispatcher(Object waitForDownloadService, NotificationCreator<DownloadBatchStatus> notificationCreator) {
        this.waitForDownloadService = waitForDownloadService;
        this.notificationCreator = notificationCreator;
    }

    @WorkerThread
    void updateNotification(DownloadBatchStatus downloadBatchStatus) {
        WaitForDownloadService.<Void>waitFor(downloadService, waitForDownloadService)
                .thenPerform(executeUpdateNotification(downloadBatchStatus));
    }

    private WaitForDownloadService.ThenPerform.Action<Void> executeUpdateNotification(DownloadBatchStatus downloadBatchStatus) {
        return () -> {
            NotificationInformation notificationInformation = notificationCreator.createNotification(downloadBatchStatus);

            if (downloadBatchStatus.status() == DOWNLOADED || downloadBatchStatus.status() == DELETION) {
                downloadService.stackNotification(notificationInformation);
            } else {
                downloadService.updateNotification(notificationInformation);
            }

            return null;
        };
    }

    void setDownloadService(DownloadService downloadService) {
        this.downloadService = downloadService;
    }
}

Add worker thread annotation to update notification.


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.dsu.configuration;

/**
 * An interface containing shared properties for OAuth2 configurations.
 *
 * @author Emerson Farrugia
 */
public interface OAuth2Properties {

    public static final String CLIENT_ROLE = "ROLE_CLIENT";
    public static final String END_USER_ROLE = "ROLE_END_USER";
    public static final String DATA_POINT_RESOURCE_ID = "dataPoint";
    public static final String DATA_POINT_READ_SCOPE = "read_data_points";
    public static final String DATA_POINT_WRITE_SCOPE = "write_data_points";
    public static final String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}

/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.dsu.configuration;

/**
 * An interface containing shared properties for OAuth2 configurations.
 *
 * @author Emerson Farrugia
 */
public interface OAuth2Properties {

    String CLIENT_ROLE = "ROLE_CLIENT";
    String END_USER_ROLE = "ROLE_END_USER";
    String DATA_POINT_RESOURCE_ID = "dataPoints";
    String DATA_POINT_READ_SCOPE = "read_data_points";
    String DATA_POINT_WRITE_SCOPE = "write_data_points";
    String DATA_POINT_DELETE_SCOPE = "delete_data_points";
}

Fix typo in resource ID

Fix typo in resource ID


/*
 * Copyright (C) 2016 Jorge Ruesga
 *
 * 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.ruesga.rview.gerrit.filter;

public enum IsType {
    STARRED, WATCHED, REVIEWED, OWNER, REVIEWER, OPEN, PENDING, DRAFT,
    CLOSED, MERGED, ABANDONED, MERGEABLE, VISIBLE
}

/*
 * Copyright (C) 2016 Jorge Ruesga
 *
 * 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.ruesga.rview.gerrit.filter;

public enum IsType {
    STARRED, WATCHED, REVIEWED, OWNER, REVIEWER, OPEN, PENDING, DRAFT,
    CLOSED, MERGED, ABANDONED, MERGEABLE, VISIBLE, ASSIGNED, UNASSIGNED
}

Add new assignee 'is' types

Add new assignee 'is' types

Signed-off-by: Jorge Ruesga <33f927344e079e00d3fa45d8833b04e735223eec@ruesga.com>


/*
 * Copyright 2011 The Netty Project
 *
 * The Netty Project 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.jboss.netty.handler.codec.frame;

/**
 * An {@link Exception} which is thrown when the length of the frame
 * decoded by {@link DelimiterBasedFrameDecoder} is greater than the maximum.
 *
 * @apiviz.hidden
 */
public class TooLongFrameException extends Exception {

    private static final long serialVersionUID = -1995801950698951640L;

    /**
     * Creates a new instance.
     */
    public TooLongFrameException() {
        super();
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(String message) {
        super(message);
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(Throwable cause) {
        super(cause);
    }
}

/*
 * Copyright 2011 The Netty Project
 *
 * The Netty Project 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.jboss.netty.handler.codec.frame;

/**
 * An {@link Exception} which is thrown when the length of the frame
 * decoded is greater than the maximum.
 *
 * @apiviz.hidden
 */
public class TooLongFrameException extends Exception {

    private static final long serialVersionUID = -1995801950698951640L;

    /**
     * Creates a new instance.
     */
    public TooLongFrameException() {
        super();
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(String message) {
        super(message);
    }

    /**
     * Creates a new instance.
     */
    public TooLongFrameException(Throwable cause) {
        super(cause);
    }
}

Adjust javadocs as the usage has changed


package sagan.docs.support;

import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {

    private ProjectMetadataService service;

    @Autowired
    public DocsController(ProjectMetadataService service) {
        this.service = service;
    }

    @RequestMapping(value = "", method = { GET, HEAD })
    public String listProjects(Model model) {
        model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
        model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
        model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
        return "docs/index";
    }

    private List<Project> nonAggregatorsForCategory(String category) {
        return service.getProjectsForCategory(category).stream()
                .filter(project -> !project.isAggregator())
                .collect(Collectors.toList());
    }
}

package sagan.docs.support;

import sagan.projects.Project;
import sagan.projects.support.ProjectMetadataService;
import sagan.support.nav.NavSection;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import static org.springframework.web.bind.annotation.RequestMethod.*;

@Controller
@RequestMapping("/docs")
@NavSection("docs")
class DocsController {

    private ProjectMetadataService service;

    @Autowired
    public DocsController(ProjectMetadataService service) {
        this.service = service;
    }

    @RequestMapping(value = "", method = { GET, HEAD })
    public String listProjects(Model model) {
        model.addAttribute("activeProjects", nonAggregatorsForCategory("active"));
        model.addAttribute("atticProjects", nonAggregatorsForCategory("attic"));
        model.addAttribute("incubatorProjects", nonAggregatorsForCategory("incubator"));
        return "docs/index";
    }

    private List<Project> nonAggregatorsForCategory(String category) {
        return service.getProjectsForCategory(category).stream()
                .filter(project -> !project.isAggregator())
                .sorted((p1, p2) -> p1.getId().compareToIgnoreCase(p2.getId()))
                .collect(Collectors.toList());
    }
}

Sort projects alphabetically on /docs page


package com.github.lookout.metrics.agent;

import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public class ReportAgent {
    public static void premain(final String agentArgs, final Instrumentation inst) throws IOException {
        String host;
        try {
            host = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            host = "unknown-host";
        }

        for (final String reportingHostPort : agentArgs.split(",")) {
            final HostPortInterval hostPortInterval = new HostPortInterval(reportingHostPort);
            final StatsDClient client = new NonBlockingStatsDClient(host, hostPortInterval.getHost(), hostPortInterval.getPort());
            final StatsdReporter reporter = new StatsdReporter(hostPortInterval, client);
            reporter.start(hostPortInterval.getInterval(), TimeUnit.SECONDS);
        }
    }

    public static void main(final String[] args) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // impossible
        }
    }
}

package com.github.lookout.metrics.agent;

import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;

import java.io.IOException;
import java.lang.instrument.Instrumentation;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

public class ReportAgent {
    public static void premain(final String agentArgs, final Instrumentation inst) throws IOException {
        String host;
        try {
            host = InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            host = "unknown-host";
        }

        final String[] reportingHostPorts = (agentArgs != null) ? agentArgs.split(",") : new String[]{null};
        for (final String reportingHostPort : reportingHostPorts) {
            final HostPortInterval hostPortInterval = new HostPortInterval(reportingHostPort);
            final StatsDClient client = new NonBlockingStatsDClient(host, hostPortInterval.getHost(), hostPortInterval.getPort());
            final StatsdReporter reporter = new StatsdReporter(hostPortInterval, client);
            reporter.start(hostPortInterval.getInterval(), TimeUnit.SECONDS);
        }
    }

    public static void main(final String[] args) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // impossible
        }
    }
}

Fix the agent not starting if args are not supplied


package com.example.buck.library;

import com.foo.missing.Dep;

public class Test {}

package com.example.buck.library;

import com.foo.missing.Dep;

public class Test {
  Dep d = null;
}

Add usage of missing Dep so linters won't remove it from test

Summary: google formatter removes this import unless its used.

Reviewed By: philipjameson

fbshipit-source-id: 06c0854797


package org.joow.elevator2;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Actions {
    public final List<Action> actions = new CopyOnWriteArrayList<>();

    public void add(final Action action) {
        actions.add(action);
    }

    public void remove(final Action action) {
        actions.removeAll(Collections2.filter(actions, new Predicate<Action>() {
            @Override
            public boolean apply(final Action input) {
                return input.floor() == action.floor();
            }
        }));
    }

    public void clear() {
        actions.clear();
    }

    public Optional<Action> next(final Cabin cabin) {
        if (actions.isEmpty()) {
            return Optional.absent();
        } else {
            return Optional.of(Paths.getBestPath(actions, cabin).first());
        }
    }
}

package org.joow.elevator2;

import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Actions {
    private final List<Action> actions = new CopyOnWriteArrayList<>();

    public void add(final Action action) {
        actions.add(action);
    }

    public void remove(final Action action) {
        actions.removeAll(Collections2.filter(actions, new FloorPredicate(action.floor())));
    }

    public void clear() {
        actions.clear();
    }

    public Optional<Action> next(final Cabin cabin) {
        if (actions.isEmpty()) {
            return Optional.absent();
        } else {
            return Optional.of(Paths.getBestPath(actions, cabin).first());
        }
    }
}

Use FloorPredicate class to remove actions at given floor.


/*
 * Created on Aug 8, 2003
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package testsuite.test;

import org.objectweb.proactive.core.node.Node;

/**
 * @author adicosta
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public interface InterfaceProActiveTest {
    public void killVM();

    /**
     * @return
     */
    public Node getNode();

    /**
     * @param node
     */
    public void setNode(Node node);
}

/*
 * Created on Aug 8, 2003
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package testsuite.test;

import org.objectweb.proactive.core.node.Node;

/**
 * @author adicosta
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public interface InterfaceProActiveTest {
    public void killVM();

    /**
     * @return
     */
    public Node getNode();

    /**
     * @param node
     */
    public void setNode(Node node);

	public Node getSameVMNode();

	public Node getLocalVMNode();

	public Node getRemoteVMNode();

}

Add access to the node from manager

Add access to the node from manager

git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@579 28e8926c-6b08-0410-baaa-805c5e19b8d6


package com.ttaylorr.uhc.coloredarrows;

import com.ttaylorr.uhc.coloredarrows.listeners.ProjectileLandListener;
import com.ttaylorr.uhc.coloredarrows.listeners.ProjectileLaunchListener;
import org.bukkit.Color;

import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

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

public class ColoredArrowsPlugin extends JavaPlugin implements Listener {

    private static ColoredArrowsPlugin instance;
    private List<Color> colors;

    public static ColoredArrowsPlugin get() {
        return instance;
    }

    public List<Color> getColors() {
        return this.colors;
    }

    @Override
    public void onDisable() {

    }

    @Override
    public void onEnable() {
        instance = this;

        this.getServer().getPluginManager().registerEvents(new ProjectileLaunchListener(this), this);
        this.getServer().getPluginManager().registerEvents(new ProjectileLandListener(this), this);

        colors = new ArrayList<>();

        for(String s : this.getConfig().getStringList("colors")) {
            String[] colors = s.split(",");

            Color c = Color.fromRGB(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2]));
            this.colors.add(c);
        }
    }
}

package com.ttaylorr.uhc.coloredarrows;

import com.ttaylorr.uhc.coloredarrows.listeners.ProjectileLandListener;
import com.ttaylorr.uhc.coloredarrows.listeners.ProjectileLaunchListener;
import org.bukkit.Color;

import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

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

public class ColoredArrowsPlugin extends JavaPlugin implements Listener {

    private static ColoredArrowsPlugin instance;
    private List<Color> colors;

    public static ColoredArrowsPlugin get() {
        return instance;
    }

    public List<Color> getColors() {
        return this.colors;
    }

    @Override
    public void onDisable() {
        this.saveConfig();
    }

    @Override
    public void onEnable() {
        instance = this;

        this.saveDefaultConfig();

        this.getServer().getPluginManager().registerEvents(new ProjectileLaunchListener(this), this);
        this.getServer().getPluginManager().registerEvents(new ProjectileLandListener(this), this);

        colors = new ArrayList<>();

        for(String s : this.getConfig().getStringList("colors")) {
            String[] colors = s.split(",");

            Color c = Color.fromRGB(Integer.parseInt(colors[0]), Integer.parseInt(colors[1]), Integer.parseInt(colors[2]));
            this.colors.add(c);
        }
    }
}

Save the defualt config onEnable(), and save onDisable()


package com.github.vbauer.herald.ext.spring;

import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * @author Vladislav Bauer
 */

@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {

    @Autowired
    private CheckerBean checkerBean;

    @Test
    public void testAll() {
        checkerBean.checkBeans();
        checkerBean.checkPostProcessor();
    }

}

package com.github.vbauer.herald.ext.spring;

import com.github.vbauer.herald.core.BasicTest;
import com.github.vbauer.herald.ext.spring.bean.CheckerBean;
import com.github.vbauer.herald.ext.spring.context.SpringBootTestContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

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

/**
 * @author Vladislav Bauer
 */

@ContextConfiguration(classes = SpringBootTestContext.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringBootTest extends BasicTest {

    @Autowired
    private CheckerBean checkerBean;

    @Test
    public void testAll() {
        checkerBean.checkBeans();
        checkerBean.checkPostProcessor();
    }

    @Test
    public void testAutoConfiguration() {
        final LogAutoConfiguration configuration = new LogAutoConfiguration();
        final LogBeanPostProcessor processor = configuration.logBeanPostProcessor();

        assertThat(processor, notNullValue());
    }

}

Add unit test for LogAutoConfiguration

Add unit test for LogAutoConfiguration


package com.yammer.tenacity.client;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.Client;

import javax.ws.rs.core.MediaType;
import java.net.URI;

public class TenacityClient {
    private final Client client;

    public TenacityClient(Client client) {
        this.client = client;
    }

    public Optional<ImmutableList<String>> getTenacityPropertyKeys(URI root) {
        return Optional.of(ImmutableList.copyOf(client.resource(root)
                .path("/tenacity/propertykeys")
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get(String[].class)));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TenacityClient that = (TenacityClient) o;

        if (!client.equals(that.client)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return client.hashCode();
    }
}

package com.yammer.tenacity.client;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.sun.jersey.api.client.Client;

import javax.ws.rs.core.MediaType;
import java.net.URI;

public class TenacityClient {
    private final Client client;
    public static final String TENACITY_PROPERTYKEYS_PATH = "/tenacity/propertykeys";

    public TenacityClient(Client client) {
        this.client = client;
    }

    public Optional<ImmutableList<String>> getTenacityPropertyKeys(URI root) {
        return Optional.of(ImmutableList.copyOf(client.resource(root)
                .path(TENACITY_PROPERTYKEYS_PATH)
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .get(String[].class)));
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TenacityClient that = (TenacityClient) o;

        if (!client.equals(that.client)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return client.hashCode();
    }
}

Make the tenacity propertykeys resource path a publicly accessible static final.


package org.csstudio.opibuilder.converter.model;

public class Edm_activeShapeClass extends EdmWidget {

    @EdmAttributeAn @EdmOptionalAn private int lineWidth;

    public Edm_activeShapeClass(EdmEntity genericEntity) throws EdmException {
        super(genericEntity);
    }

    public int getLineWidth() {
        return lineWidth;
    }

}

Add new line to end of file

Add new line to end of file


package de.retest.recheck;

import java.util.prefs.Preferences;

import de.retest.recheck.auth.RehubAuthenticationHandler;
import de.retest.recheck.auth.RetestAuthentication;
import de.retest.recheck.persistence.CloudPersistence;

public class Rehub {

	private Rehub() {

	}

	public static void init() {
		final RetestAuthentication auth = RetestAuthentication.getInstance();

		if ( !auth.isAuthenticated( getToken() ) ) {
			auth.login( new RehubAuthenticationHandler() );
		}
	}

	private static String getToken() {
		final String tokenFromEnvironment = System.getenv( CloudPersistence.RECHECK_API_KEY );
		final String tokenFromPreferences =
				Preferences.userNodeForPackage( Rehub.class ).get( CloudPersistence.RECHECK_API_KEY, null );

		return tokenFromEnvironment != null ? tokenFromEnvironment : tokenFromPreferences;
	}

}

package de.retest.recheck;

import java.util.prefs.Preferences;

import de.retest.recheck.Properties.FileOutputFormat;
import de.retest.recheck.auth.RehubAuthenticationHandler;
import de.retest.recheck.auth.RetestAuthentication;
import de.retest.recheck.persistence.CloudPersistence;

public class Rehub {

	private Rehub() {

	}

	public static void init() {
		final RetestAuthentication auth = RetestAuthentication.getInstance();

		if ( !auth.isAuthenticated( getToken() ) ) {
			auth.login( new RehubAuthenticationHandler() );
		}
		System.setProperty( Properties.FILE_OUTPUT_FORMAT_PROPERTY, FileOutputFormat.CLOUD.toString() );
	}

	private static String getToken() {
		final String tokenFromEnvironment = System.getenv( CloudPersistence.RECHECK_API_KEY );
		final String tokenFromPreferences =
				Preferences.userNodeForPackage( Rehub.class ).get( CloudPersistence.RECHECK_API_KEY, null );

		return tokenFromEnvironment != null ? tokenFromEnvironment : tokenFromPreferences;
	}

}

Enable cloud persistence for rehub

Enable cloud persistence for rehub


//
// $Id: Task.java,v 1.1 2000/12/06 03:25:19 mdb Exp $

package com.samskivert.swing.util;

/**
 * A swing application requests that a task be invoked by the task
 * master. The task master invokes the task on a separate thread and
 * informs the swing application when the task has completed via the task
 * observer interface. It does so in a way that plays nicely with the
 * swing event dispatch thread (the swing application is notified of the
 * task's completion on the event dispatch thread so that it can wiggle
 * its user interface elements to its heart's desire).
 */
public interface Task
{
    /**
     * This method is called by the task master to invoke the task. The
     * task should run to completion and return some value.
     */
    public Object invoke ();

    /**
     * This method is called by the task master when it has received a
     * request to cancel this task. If the task can be cancelled, abort
     * should return true and the currently running call to
     * invoke() should immediately return (the return value
     * will be ignored). If the task cannot be cancelled, abort should
     * return false and the task master will simply abandon the task and
     * the thread on which it is running.
     */
    public boolean abort ();
}

//
// $Id: Task.java,v 1.2 2000/12/07 05:41:30 mdb Exp $

package com.samskivert.swing.util;

/**
 * A swing application requests that a task be invoked by the task
 * master. The task master invokes the task on a separate thread and
 * informs the swing application when the task has completed via the task
 * observer interface. It does so in a way that plays nicely with the
 * swing event dispatch thread (the swing application is notified of the
 * task's completion on the event dispatch thread so that it can wiggle
 * its user interface elements to its heart's desire).
 */
public interface Task
{
    /**
     * This method is called by the task master to invoke the task. The
     * task should run to completion and return some value.
     */
    public Object invoke () throws Exception;

    /**
     * This method is called by the task master when it has received a
     * request to cancel this task. If the task can be cancelled, abort
     * should return true and the currently running call to
     * invoke() should immediately return (the return value
     * will be ignored). If the task cannot be cancelled, abort should
     * return false and the task master will simply abandon the task and
     * the thread on which it is running.
     */
    public boolean abort ();
}

Allow tasks to throw an exception so that it can be caught and passed to
the task observer.

git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@24 6335cc39-0255-0410-8fd6-9bcaacd3b74c


package com.codicesoftware.plugins.hudson.util;

import hudson.Util;
import hudson.model.ParameterValue;

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

public class SelectorParametersResolver {

    private SelectorParametersResolver() { }

    public static String resolve(String text, List<ParameterValue> parameters) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return Util.replaceMacro(
                resolveLegacyFormat(text, parametersMap), parametersMap);
    }

    static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
        String result = text;
        for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
            result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
        }
        return result;
    }
}

package com.codicesoftware.plugins.hudson.util;

import hudson.EnvVars;
import hudson.Util;
import hudson.model.ParameterValue;

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

public class SelectorParametersResolver {

    private SelectorParametersResolver() { }

    public static String resolve(String text, List<ParameterValue> parameters, EnvVars environment) {
        if (parameters == null) {
            return text;
        }

        Map<String, String> parametersMap = new HashMap<>();
        for (ParameterValue parameter : parameters) {
            if ((parameter != null) && (parameter.getName() != null) && (parameter.getValue() != null)) {
                parametersMap.put(parameter.getName(), parameter.getValue().toString());
            }
        }

        return environment.expand(Util.replaceMacro(
            resolveLegacyFormat(text, parametersMap), parametersMap));
    }

    static String resolveLegacyFormat(String text, Map<String, String> parametersMap) {
        String result = text;
        for (Map.Entry<String, String> entry : parametersMap.entrySet()) {
            result = result.replaceAll("%" + entry.getKey() + "%", entry.getValue());
        }
        return result;
    }
}

Expand environment variables when resolving parameters in selector

Signed-off-by: Miguel González <967cccf84fe94e619b35e1dff246b8b33dcf8eed@unity3d.com>


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.as.quickstarts.cdi.alternative;

import javax.enterprise.inject.Alternative;

/**
 * Alternative implementation for Tax
 *
 * @author Nevin Zhu
 *
 */
@Alternative
public class TaxImpl_2 implements Tax {

    @Override
    public String getRate() {
        // TODO Auto-generated method stub
        return "Tax_2 Rate! To switch back to the default, go to /META-INF/beans.xml and comment out the 'alternatives' tag";
    }

}

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.as.quickstarts.cdi.alternative;

import javax.enterprise.inject.Alternative;

/**
 * Alternative implementation for Tax
 *
 * @author Nevin Zhu
 *
 */
@Alternative
public class TaxImpl_2 implements Tax {

    @Override
    public String getRate() {
        // TODO Auto-generated method stub
        return "Tax_2 Rate! To switch back to the default, comment out the 'alternatives' tag in the WEB-INF/beans.xml file";
    }

}

Bz1160269: Fix the location of the beans.xml file in the bean output message


package org.xcolab.portlets.contests;

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import com.ext.portlet.model.Contest;
import com.ext.portlet.service.ContestLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.theme.ThemeDisplay;

public class ContestsBean implements Serializable {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
    private static final int NUM_CONTESTS = 4;

	public List<ContestWrapper> getContests() throws SystemException, PortalException {
        List<ContestWrapper> ret = new ArrayList<>();

        List<Contest> contests = ContestLocalServiceUtil.findByActiveFlagText(true, "");
        Collections.shuffle(contests);

        for (Contest contest: contests) {
            if(ret.size() < NUM_CONTESTS)
                ret.add(new ContestWrapper(contest));
            else break;
        }
        return ret;
    }

    public ThemeDisplay getThemeDisplay() {
        return Helper.getThemeDisplay();
    }

}

package org.xcolab.portlets.contests;

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

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import com.ext.portlet.model.Contest;
import com.ext.portlet.service.ContestLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.theme.ThemeDisplay;

public class ContestsBean implements Serializable {

    /**
	 *
	 */
	private static final long serialVersionUID = 1L;
    private static final int NUM_CONTESTS = 4;

	public List<ContestWrapper> getContests() throws SystemException, PortalException {
        List<ContestWrapper> ret = new ArrayList<>();

        List<Contest> contests = ContestLocalServiceUtil.findByActiveFlagText(true, "");
        Collections.shuffle(contests);

        for (Contest contest: contests) {
            if(ret.size() < NUM_CONTESTS) {
                // Don't show private contests
                if (contest.getContestPrivate()) {
                    continue;
                }
                ret.add(new ContestWrapper(contest));
            }
            else {
                break;
            }
        }
        return ret;
    }

    public ThemeDisplay getThemeDisplay() {
        return Helper.getThemeDisplay();
    }

}

Hide private contests from contest portlet


package org.muteswan.client.data;

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

public class MuteswanServer {

	private String hostname;
	private ServerInfo serverInfo;

	public class ServerInfo {
		public String Name = "";

		public void setName(String arg) {
			this.Name = arg;
		}

		public String getName() {
			return Name;
		}
	}

	public ServerInfo getServerInfo() {
		return serverInfo;
	}

	public String getHostname() {
		return hostname;
	}

	public String toString() {
		if (serverInfo.getName() != null && serverInfo.getName() != "" && !serverInfo.getName().equals("defaultname")) {
			return serverInfo.getName();
		} else {
			return serverInfo.getName() + " (" + getHostname() + ")";
		}
	}

	public void init(String server, JSONObject jsonObj) {
		this.hostname = server;
		serverInfo = new ServerInfo();
		try {
			serverInfo.setName(jsonObj.getString("Name"));
		} catch (JSONException e) {
			e.printStackTrace();
			return;
		}

	}

}

package org.muteswan.client.data;

import org.json.JSONException;
import org.json.JSONObject;
import org.muteswan.client.MuteLog;

public class MuteswanServer {

	private String hostname;
	private ServerInfo serverInfo;

	public class ServerInfo {
		public String Name = "";

		public void setName(String arg) {
			this.Name = arg;
		}

		public String getName() {
			return Name;
		}
	}

	public ServerInfo getServerInfo() {
		return serverInfo;
	}

	public String getHostname() {
		return hostname;
	}

	public String toString() {

		if (serverInfo.getName() != null && !serverInfo.getName().equals("") && !serverInfo.getName().equals("defaultname")) {
			return serverInfo.getName();
		} else {
			return serverInfo.getName() + " (" + getHostname() + ")";
		}
	}

	public void init(String server, JSONObject jsonObj) {
		this.hostname = server;
		serverInfo = new ServerInfo();
		try {
			serverInfo.setName(jsonObj.getString("Name"));
		} catch (JSONException e) {
			e.printStackTrace();
			return;
		}

	}

}

Fix empty servername problem when initially adding server.


package fr.insee.pogues.transforms;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PipeLine {

    private String output;
    private List<Runnable> transforms = new ArrayList<>();

    public PipeLine from(InputStream input) throws Exception {
        try {
            output = IOUtils.toString(input, Charset.forName("UTF-8"));
            return this;
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    public PipeLine from(String input) {
        this.output = input;
        return this;
    }

    public PipeLine map(Transform<String, String> t, Map<String, Object> params) {
        transforms.add(() -> {
            try {
                output = t.apply(output, params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return this;
    }

    public String transform() {
        for (Runnable t : transforms) {
            t.run();
        }
        return output;
    }

    @FunctionalInterface
    public interface Transform<I, O> {
        O apply(I i, Map<String, Object> params) throws Exception;
    }

}

package fr.insee.pogues.transforms;

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class PipeLine {

    private String output;
    private List<Runnable> transforms = new ArrayList<>();

    public PipeLine from(InputStream input) throws Exception {
        try {
            output = IOUtils.toString(input, Charset.forName("UTF-8"));
            return this;
        } catch (IOException e) {
            throw e;
        }
    }

    public PipeLine from(String input) {
        this.output = input;
        return this;
    }

    public PipeLine map(Transform<String, String> t, Map<String, Object> params) throws Exception {
        transforms.add(() -> {
            try {
                output = t.apply(output, params);
            } catch (Exception e) {
                throw new RuntimeException(
                        String.format("Exception occured while executing mapping function: %s", e.getMessage())
                );
            }
        });
        return this;
    }

    public String transform() throws Exception {
        for (Runnable t : transforms) {
            try {
                t.run();
            } catch(Exception e){
                throw e;
            }
        }
        return output;
    }

    @FunctionalInterface
    public interface Transform<I, O> {
        O apply(I i, Map<String, Object> params) throws Exception;
    }

}

Enhance exception handling in transformation pipeline


package org.cohorte.studio.eclipse.ui.node;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.cohorte.studio.eclipse.ui.application"; //$NON-NLS-1$

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

}

package org.cohorte.studio.eclipse.ui.node;

import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "org.cohorte.studio.eclipse.ui.node"; //$NON-NLS-1$

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
	}

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

}

Fix plug-in ID to match bundle's symbolic name.


package io.syndesis.project.converter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    /**
     * A main method to start this application.
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

package io.syndesis.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    /**
     * A main method to start this application.
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

fix(project-generator): Fix up package name in test for generated project


package org.radargun.service;

import java.util.concurrent.ExecutionException;

import org.radargun.traits.Clustered;

public class Infinispan110ServerLifecycle extends Infinispan100ServerLifecycle {

   public Infinispan110ServerLifecycle(InfinispanServerService service) {
      super(service);
   }

   @Override
   protected void stopInternal() {
      Clustered clustered = this.service.getClustered();
      if (clustered == null) {
         throw new NullPointerException("clustered cannot be null");
      }
      if (clustered instanceof Infinispan100ServerClustered) {
         Infinispan100ServerClustered innerClustered = (Infinispan100ServerClustered) clustered;
         innerClustered.getRestAPI().stopCluster(service.stopTimeout);
         // the stop request return as fast as possible
         long now = System.currentTimeMillis();
         while (System.currentTimeMillis() - now < service.stopTimeout) {
            try {
               Thread.sleep(1000);
               try {
                  innerClustered.getRestAPI().info();
               } catch (ExecutionException e) {
                  // we should kill the inherited process
                  super.stopInternal();
                  break;
               }
            } catch (InterruptedException e) {
               throw new IllegalStateException("InterruptedException", e);
            }
         }
         // if the server still alive, fail
         if (this.service.getLifecycle().isRunning()) {
            throw new IllegalStateException("Error while stopping the server. The server is still running");
         }
      } else {
         throw new IllegalStateException("service.clustered should extends Infinispan100ServerClustered");
      }
   }
}

package org.radargun.service;

public class Infinispan110ServerLifecycle extends Infinispan100ServerLifecycle {

   public Infinispan110ServerLifecycle(InfinispanServerService service) {
      super(service);
   }

}

Remove stopping Infinispan by Rest API

Remove stopping Infinispan by Rest API


package org.openmhealth.shim.common.mapper;

import com.fasterxml.jackson.databind.ObjectMapper;

import static org.openmhealth.schema.configuration.JacksonConfiguration.newObjectMapper;

/**
 * @author Emerson Farrugia
 */
public abstract class DataPointMapperUnitTests {

    protected static final ObjectMapper objectMapper = newObjectMapper();
}

package org.openmhealth.shim.common.mapper;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.ClassPathResource;

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

import static java.lang.String.format;
import static org.openmhealth.schema.configuration.JacksonConfiguration.newObjectMapper;

/**
 * @author Emerson Farrugia
 */
public abstract class DataPointMapperUnitTests {

    protected static final ObjectMapper objectMapper = newObjectMapper();

    /**
     * @param classPathResourceName the name of the class path resource to load
     * @return the contents of the resource as a {@link JsonNode}
     * @throws RuntimeException if the resource can't be loaded
     */
    protected JsonNode asJsonNode(String classPathResourceName) {

        ClassPathResource resource = new ClassPathResource(classPathResourceName);

        try {
            InputStream resourceInputStream = resource.getInputStream();
            return objectMapper.readTree(resourceInputStream);
        }
        catch (IOException e) {
            throw new RuntimeException(
                    format("The class path resource '%s' can't be loaded as a JSON node.", classPathResourceName), e);
        }
    }
}

Add unit test support to load class path resources as JSON nodes


package org.apache.wicket.bean.validation;

import javax.validation.constraints.Size;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.FormComponent;

/**
 * A tag modifier that adds the {@code maxlength} attribute to the {@code input} tag with the max
 * value from the {@link Size} constraint annotation.
 *
 * @author igor
 *
 */
public class SizeTagModifier implements ITagModifier<Size>
{
	@Override
	public void modify(FormComponent<?> component, ComponentTag tag, Size annotation)
	{
		if ("input".equalsIgnoreCase(tag.getName()))
		{
			tag.put("maxlength", annotation.max());
		}
	}
}

package org.apache.wicket.bean.validation;

import javax.validation.constraints.Size;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.FormComponent;

/**
 * A tag modifier that adds the {@code maxlength} and  {@code minlength} attributes to the {@code input}
 * and {@code textarea} tag with the max/min value from the {@link Size} constraint annotation.
 *
 * @author igor
 *
 */
public class SizeTagModifier implements ITagModifier<Size>
{
	@Override
	public void modify(FormComponent<?> component, ComponentTag tag, Size annotation)
	{
		if (hasLengthAttribute(tag.getName()))
		{
			tag.put("maxlength", annotation.max());

			if (annotation.min() > 0)
			{
				tag.put("minlength", annotation.min());
			}
		}
	}

	protected boolean hasLengthAttribute(String tagName)
	{
		return "input".equalsIgnoreCase(tagName) || "textarea".equalsIgnoreCase(tagName);
	}
}

Add 'minlength' to <input> or <textarea> if Size.min() is bigger than 0

Fixes #144