package org.vaadin.mcont.demo;

import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.VaadinRequest;
import com.vaadin.ui.Table;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

@Theme("demo")
@Title("MCont Add-on Demo")
@SuppressWarnings("serial")
public class DemoUI extends UI
{

    @Override
    protected void init(VaadinRequest request) {
    	Table table = new Table();
    	// TODO create and set container

    	final VerticalLayout layout = new VerticalLayout();
        layout.setStyleName("demoContentLayout");
        layout.setSizeFull();
        layout.addComponent(table);
        setContent(layout);

    }

}

Reformat source code according to Vaadin conventions


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

class InvalidRequestException extends Exception {
    public InvalidRequestException(String reason) {
        super(reason);
    }
}

// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

class InvalidRequestException extends Exception {
    private int mErrorCode;

    public InvalidRequestException(String reason) {
        super(reason);
    }

    public InvalidRequestException(String reason, int errorCode) {
        super(reason);
        mErrorCode = errorCode;
    }

    /**
     * @return The error code or 0 if none.
     */
    public int getErrorCode() {
        return mErrorCode;
    }
}

Add http error code to constructor.


package seedu.taskell.logic.commands;

import seedu.taskell.commons.core.EventsCenter;
import seedu.taskell.commons.core.Messages;
import seedu.taskell.commons.events.ui.IncorrectCommandAttemptedEvent;
import seedu.taskell.model.Model;

/**
 * Represents a command with hidden internal logic and the ability to be executed.
 */
public abstract class Command {
    protected Model model;

    /**
     * Constructs a feedback message to summarise an operation that displayed a listing of tasks.
     *
     * @param displaySize used to generate summary
     * @return summary message for tasks displayed
     */
    public static String getMessageForTaskListShownSummary(int displaySize) {
        return String.format(Messages.MESSAGE_TASKS_LISTED_OVERVIEW, displaySize);
    }

    /**
     * Executes the command and returns the result message.
     *
     * @return feedback message of the operation result for display
     */
    public abstract CommandResult execute();

    /**
     * Provides any needed dependencies to the command.
     * Commands making use of any of these should override this method to gain
     * access to the dependencies.
     */
    public void setData(Model model) {
        this.model = model;
    }

    /**
     * Raises an event to indicate an attempt to execute an incorrect command
     */
    protected void indicateAttemptToExecuteIncorrectCommand() {
        EventsCenter.getInstance().post(new IncorrectCommandAttemptedEvent(this));
    }
}

package seedu.taskell.logic.commands;

import seedu.taskell.commons.core.EventsCenter;
import seedu.taskell.commons.core.Messages;
import seedu.taskell.commons.events.ui.IncorrectCommandAttemptedEvent;
import seedu.taskell.commons.events.ui.JumpToListRequestEvent;
import seedu.taskell.model.Model;

/**
 * Represents a command with hidden internal logic and the ability to be executed.
 */
public abstract class Command {
    protected Model model;

    /**
     * Constructs a feedback message to summarise an operation that displayed a listing of tasks.
     *
     * @param displaySize used to generate summary
     * @return summary message for tasks displayed
     */
    public static String getMessageForTaskListShownSummary(int displaySize) {
        return String.format(Messages.MESSAGE_TASKS_LISTED_OVERVIEW, displaySize);
    }

    /**
     * Executes the command and returns the result message.
     *
     * @return feedback message of the operation result for display
     */
    public abstract CommandResult execute();

    /**
     * Provides any needed dependencies to the command.
     * Commands making use of any of these should override this method to gain
     * access to the dependencies.
     */
    public void setData(Model model) {
        this.model = model;
    }

    /**
     * Raises an event to indicate an attempt to execute an incorrect command
     */
    protected void indicateAttemptToExecuteIncorrectCommand() {
        EventsCenter.getInstance().post(new IncorrectCommandAttemptedEvent(this));
    }

    //@@author A0139257X-reused
    /**
     * Raises an event to jump to the given index
     */
    protected void jumpToIndex(int index) {
        EventsCenter.getInstance().post(new JumpToListRequestEvent(index));
    }
    //@@author
}

Add method to scroll to selected index


package liquibase.database.typeconversion.core;

import liquibase.database.Database;
import liquibase.database.structure.type.UUIDType;
import liquibase.exception.DatabaseException;

public class Postgres83TypeConverter extends PostgresTypeConverter {

    @Override
    public int getPriority() {
        return super.getPriority()+1;
    }

    @Override
    public boolean supports(Database database) {
        if (database.getConnection() == null) {
            return false;
        }
        try {
            return super.supports(database) && database.getDatabaseMajorVersion() >= 8 && database.getDatabaseMinorVersion() >= 3;
        } catch (DatabaseException e) {
            return false;
        }
    }

    @Override
    public UUIDType getUUIDType() {
        return new UUIDType("UUID");
    }

}

package liquibase.database.typeconversion.core;

import liquibase.database.Database;
import liquibase.database.structure.type.UUIDType;
import liquibase.exception.DatabaseException;

public class Postgres83TypeConverter extends PostgresTypeConverter {

    @Override
    public int getPriority() {
        return super.getPriority()+1;
    }

    @Override
    public boolean supports(Database database) {
        if (database==null || database.getConnection() == null) {
            return false;
        }
        try {
            return super.supports(database) && database.getDatabaseMajorVersion() >= 8 && database.getDatabaseMinorVersion() >= 3;
        } catch (DatabaseException e) {
            return false;
        }
    }

    @Override
    public UUIDType getUUIDType() {
        return new UUIDType("UUID");
    }

}

Check for null database to allow ValidatingVisitorTest to pass


package no.steria.skuldsku.testrunner.common;

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

import no.steria.skuldsku.testrunner.httprunner.result.HttpCallResult;

public final class HttpClientIdentifierMapper implements ClientIdentifierMapper {

    private final Map<String, String> map;

    public HttpClientIdentifierMapper(List<HttpCallResult> results) {
        map = new HashMap<>();
        for (HttpCallResult r : results) {
            map.put(r.getExpected().getClientIdentifier(), r.getActual().getClientIdentifier());
        }
        map.put(null, null);
        map.put("", "");
    }

    @Override
    public String translateToActual(String expectedClientIdentifier) {
        return map.get(expectedClientIdentifier);
    }

}

package no.steria.skuldsku.testrunner.common;

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

import no.steria.skuldsku.testrunner.httprunner.result.HttpCallResult;

public final class HttpClientIdentifierMapper implements ClientIdentifierMapper {

    private final Map<String, String> map;

    public HttpClientIdentifierMapper(List<HttpCallResult> results) {
        map = new HashMap<>();
        for (HttpCallResult r : results) {
            map.put(r.getExpected().getClientIdentifier(), r.getActual().getClientIdentifier());
        }
        map.put(null, null);
        map.put("", "");
    }

    @Override
    public String translateToActual(String expectedClientIdentifier) {
        final String value = map.get(expectedClientIdentifier);
        return (value != null) ? value : expectedClientIdentifier;
    }

}

Use expected identifier as actual if no match can be found.


package com.pushtorefresh.storio.db.operation.delete;

import android.support.annotation.NonNull;

import java.util.Collections;
import java.util.Map;

public class DeleteCollectionOfObjectsResult<T> {

    @NonNull private final Map<T, DeleteResult> results;

    public DeleteCollectionOfObjectsResult(@NonNull Map<T, DeleteResult> results) {
        this.results = Collections.unmodifiableMap(results);
    }

    @NonNull public Map<T, DeleteResult> results() {
        return results;
    }

    public boolean wasDeleted(T object) {
        return results.containsKey(object);
    }

    public boolean wasNotDeleted(T object) {
        return !results.containsKey(object);
    }
}

package com.pushtorefresh.storio.db.operation.delete;

import android.support.annotation.NonNull;

import java.util.Collections;
import java.util.Map;

public class DeleteCollectionOfObjectsResult<T> {

    @NonNull private final Map<T, DeleteResult> results;

    public DeleteCollectionOfObjectsResult(@NonNull Map<T, DeleteResult> results) {
        this.results = Collections.unmodifiableMap(results);
    }

    @NonNull public Map<T, DeleteResult> results() {
        return results;
    }

    public boolean wasDeleted(@NonNull T object) {
        return results.containsKey(object);
    }

    public boolean wasNotDeleted(@NonNull T object) {
        return !results.containsKey(object);
    }
}

Add @NonNull annotations for wasDeleted() and wasNotDeleted()


package org.optaplanner.benchmark.impl.report;

public class ReportHelper {

    /**
     * Escape illegal HTML element id characters, such as a dot.
     * <p/>
     * This escape function guarantees that 2 distinct strings will result into 2 distinct escape strings
     * (presuming that both have been escaped by this method).
     * @param rawHtmlId never null
     * @return never null
     */
    public static String escapeHtmlId(String rawHtmlId) {
        return rawHtmlId
                .replaceAll("-", "--") // make '-' the escape character
                .replaceAll("\\.", "-d")
                .replaceAll(":", "-c")
                .replaceAll(";", "-s")
                .replaceAll("\\$", "-m");
    }

}

package org.optaplanner.benchmark.impl.report;

public class ReportHelper {

    /**
     * Escape illegal HTML element id characters, such as a dot.
     * <p/>
     * This escape function guarantees that 2 distinct strings will result into 2 distinct escape strings
     * (presuming that both have been escaped by this method).
     * @param rawHtmlId never null
     * @return never null
     */
    public static String escapeHtmlId(String rawHtmlId) {
        // Uses unicode numbers to escape, see http://unicode-table.com
        // Uses '-' as the escape character
        return rawHtmlId
                .replaceAll(" ", "-0020")
                .replaceAll("!", "-0021")
                .replaceAll("#", "-0023")
                .replaceAll("\\$", "-0024")
                .replaceAll(",", "-002C")
                .replaceAll("-", "-002D")
                .replaceAll("\\.", "-002E")
                .replaceAll("\\(", "-0028")
                .replaceAll("\\)", "-0029")
                .replaceAll(":", "-003A")
                .replaceAll(";", "-003B")
                .replaceAll("\\?", "-003F");
    }

}

Improve escapeHtmlId with unicode escape numbers and space and ()


package com.edulify.modules.geolocation;

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

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.*;

/**
 * @deprecated Deprecated as of 2.2.0. Source should be removed.
 */
@Deprecated
public class GeolocationServiceTest {

  @Test
  public void shouldGetAGeolocationForAGivenIp() throws Exception {

    final GeolocationProvider provider = mock(GeolocationProvider.class);

    String ipAddress = "192.30.252.129";
    String countryCode = "BR";
    final Geolocation geolocation = new Geolocation(ipAddress, countryCode);
    when(provider.get(ipAddress)).thenReturn(CompletableFuture.completedFuture(geolocation));
    final GeolocationCache cache = mock(GeolocationCache.class);

    GeolocationService service = new GeolocationService(provider, cache);
    Geolocation target = service.getGeolocation(ipAddress).toCompletableFuture().get(1, TimeUnit.SECONDS);

    verify(cache).set(geolocation);

    Assert.assertSame(target, geolocation);
  }
}

package com.edulify.modules.geolocation;

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

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.*;

/**
 * @deprecated Deprecated as of 2.2.0. Source should be removed.
 */
@Deprecated
public class GeolocationServiceTest {

  @Test
  public void shouldGetAGeolocationForAGivenIp() throws Exception {

    final GeolocationProvider provider = mock(GeolocationProvider.class);

    String ipAddress = "192.30.252.129";
    String countryCode = "BR";
    final Geolocation geolocation = new Geolocation(ipAddress, countryCode);
    when(provider.get(ipAddress)).thenReturn(CompletableFuture.completedFuture(geolocation));
    final GeolocationCache cache = mock(GeolocationCache.class);

    GeolocationService service = new GeolocationService(provider, cache);
    Geolocation target = service.getGeolocation(ipAddress).toCompletableFuture().get(1, TimeUnit.SECONDS);

    verify(cache, timeout(100).times(1)).set(geolocation);

    Assert.assertSame(target, geolocation);
  }
}

Adjust test for concurrent environment


package org.springframework.data.cloudant.core;

import com.google.gson.*;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.lang.reflect.Type;

/**
 * Created by kevin on 7/14/15.
 */
public class DateTimeDataAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
    private final DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();

    @Override
    public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(fmt.print(src));
    }

    @Override
    public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
            throws JsonParseException {
        return fmt.parseDateTime(json.getAsString());
    }
}

package org.springframework.data.cloudant.core;

import com.google.gson.*;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Locale;

/**
 * Created by kevin on 7/14/15.
 */
public class DateTimeDataAdapter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> {
    private final DateTimeFormatter fmt = ISODateTimeFormat.dateTime().withZoneUTC();
    private static final String[] DATE_FORMATS = new String[] {
            "yyyy-MM-dd'T'HH:mm:ssZ",
            "yyyy-MM-dd HH:mm:ss Z",
            "yyyy-MM-dd HH:mm:ss z"
    };

    @Override
    public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) {
        return new JsonPrimitive(fmt.print(src));
    }

    @Override
    public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context)
            throws JsonParseException {
        for (String format : DATE_FORMATS) {
            try {
                return DateTime.parse(json.getAsString(), DateTimeFormat.forPattern(format));
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        throw new JsonParseException("Unparseable date: \"" + json.getAsString()
                + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));

    }
}

Enable deserializer to support multi date formats


/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.azure.credentials;

public class UserTokenCredentialsTests {

}

/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.azure.credentials;

import com.microsoft.aad.adal4j.AuthenticationResult;

import org.junit.Assert;

import org.junit.Test;

import java.io.IOException;
import java.util.Date;

public class UserTokenCredentialsTests {
    MockUserTokenCredentials credentials = new MockUserTokenCredentials(
            "clientId",
            "domain",
            "username",
            "password",
            "redirect",
            AzureEnvironment.AZURE
    );

    @Test
    public void testAcquireToken() throws Exception {
        credentials.refreshToken();
        Assert.assertEquals("token1", credentials.getToken());
        Thread.sleep(1000);
        Assert.assertEquals("token2", credentials.getToken());
    }

    public class MockUserTokenCredentials extends UserTokenCredentials {
        private AuthenticationResult authenticationResult;

        public MockUserTokenCredentials(String clientId, String domain, String username, String password, String clientRedirectUri, AzureEnvironment environment) {
            super(clientId, domain, username, password, clientRedirectUri, environment);
        }

        @Override
        public String getToken() throws IOException {
            if (authenticationResult != null &&
                    authenticationResult.getExpiresOnDate().before(new Date())) {
                acquireAccessTokenFromRefreshToken();
            } else {
                acquireAccessToken();
            }
            return authenticationResult.getAccessToken();
        }

        @Override
        public void refreshToken() throws IOException {
            acquireAccessToken();
        }

        private void acquireAccessToken() throws IOException {
            this.authenticationResult = new AuthenticationResult(
                    null,
                    "token1",
                    "refresh",
                    0,
                    null,
                    null,
                    false);
        }

        private void acquireAccessTokenFromRefreshToken() throws IOException {
            this.authenticationResult = new AuthenticationResult(
                    null,
                    "token2",
                    "refresh",
                    0,
                    null,
                    null,
                    false);
        }
    }
}

Add a test for user credentials


package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.08.06-RC";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ "" };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.08.08-RC";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ "" };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

Prepare version number for next beta


package org.rabix.executor.pathmapper.local;

import java.io.File;
import java.io.IOException;
import java.util.Map;

import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;

import com.google.inject.Inject;

public class LocalPathMapper implements FilePathMapper {

  private final StorageConfiguration storageConfig;

  @Inject
  public LocalPathMapper(final StorageConfiguration storageConfig) {
    this.storageConfig = storageConfig;
  }

  @Override
  public String map(String path, Map<String, Object> config) throws FileMappingException {
    if (!path.startsWith(File.separator)) {
      try {
        return new File(storageConfig.getPhysicalExecutionBaseDir(), path).getCanonicalPath();
      } catch (IOException e) {
        throw new FileMappingException(e);
      }
    }
    return path;
  }

}

package org.rabix.executor.pathmapper.local;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Map;

import org.rabix.bindings.mapper.FileMappingException;
import org.rabix.bindings.mapper.FilePathMapper;
import org.rabix.executor.config.StorageConfiguration;

import com.google.inject.Inject;

public class LocalPathMapper implements FilePathMapper {

  private final StorageConfiguration storageConfig;

  @Inject
  public LocalPathMapper(final StorageConfiguration storageConfig) {
    this.storageConfig = storageConfig;
  }

  @Override
  public String map(String path, Map<String, Object> config) throws FileMappingException {
    if (!Paths.get(path).isAbsolute()) {
      try {
        return new File(storageConfig.getPhysicalExecutionBaseDir(), path).getCanonicalPath();
      } catch (IOException e) {
        throw new FileMappingException(e);
      }
    }
    return path;
  }

}

Fix issue with Windows paths


package de.schunterkino.kinoapi.websocket.messages.christie;

import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

import de.schunterkino.kinoapi.websocket.messages.BaseMessage;

public class LampOffMessage extends BaseMessage {
	public String timestamp;

	public LampOffMessage(Instant lampOffTime) {
		super("playback", "lamp_off");

		DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.systemDefault());
		this.timestamp = formatter.format(lampOffTime);
	}
}

package de.schunterkino.kinoapi.websocket.messages.christie;

import java.time.Instant;

import de.schunterkino.kinoapi.websocket.messages.BaseMessage;

public class LampOffMessage extends BaseMessage {
	public String timestamp;

	public LampOffMessage(Instant lampOffTime) {
		super("playback", "lamp_off");

		this.timestamp = lampOffTime.toString();
	}
}

Fix timestamp format in lamp_off message


package dynamo.backlog.tasks.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import dynamo.manager.DownloadableManager;

public class MoveFileTaskExecutor extends FileOperationTaskExecutor<MoveFileTask> {

	private Path source;
	private Path destination;

	public MoveFileTaskExecutor(MoveFileTask item) {
		super(item);
		this.source = item.getSource();
		this.destination = item.getDestination();
	}

	@Override
	public void execute() throws IOException {

		if (!Files.exists(source)) {
			throw new IOException( String.format("Source file %s does not exist", source.toAbsolutePath().toString() ));
		}

		if (Files.isWritable(source.getParent()) && !source.toAbsolutePath().equals( destination.toAbsolutePath() )) {
			Files.createDirectories( destination.getParent() );
			Files.move( source, destination, StandardCopyOption.REPLACE_EXISTING);
			DownloadableManager.getInstance().addFile( task.getDownloadable(), destination );
		}
		boolean parentFolderEmpty = FileUtils.isDirEmpty( source.getParent() );
		if (parentFolderEmpty) {
			Files.delete( source.getParent() );
		}

	}

	@Override
	public boolean isFinished() {
		if (!Files.exists( source )) {
			return true;
		}
		return Files.exists( destination );
	}

}

package dynamo.backlog.tasks.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import dynamo.manager.DownloadableManager;

public class MoveFileTaskExecutor extends FileOperationTaskExecutor<MoveFileTask> {

	private Path source;
	private Path destination;

	public MoveFileTaskExecutor(MoveFileTask item) {
		super(item);
		this.source = item.getSource();
		this.destination = item.getDestination();
	}

	@Override
	public void execute() throws IOException {

		if (!Files.exists(source)) {
			throw new IOException( String.format("Source file %s does not exist", source.toAbsolutePath().toString() ));
		}

		if (Files.isWritable(source.getParent()) && !source.toAbsolutePath().equals( destination.toAbsolutePath() )) {
			Files.createDirectories( destination.getParent() );
			Files.copy( source, destination, StandardCopyOption.REPLACE_EXISTING);
			Files.delete( source );
			DownloadableManager.getInstance().addFile( task.getDownloadable(), destination );
		}
		boolean parentFolderEmpty = FileUtils.isDirEmpty( source.getParent() );
		if (parentFolderEmpty) {
			Files.delete( source.getParent() );
		}

	}

	@Override
	public boolean isFinished() {
		if (!Files.exists( source )) {
			return true;
		}
		return Files.exists( destination );
	}

}

Replace move by copy then delete


/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.web.server.push.analytics.formatting;

import com.opengamma.engine.value.ValueSpecification;

/**
 * Formats null values for display in the client.
 */
/* package */ class NullFormatter extends AbstractFormatter<Object> {

  /* package */ NullFormatter() {
    super(Object.class);
    addFormatter(new Formatter<Object>(Format.HISTORY) {
      @Override
      Object format(Object value, ValueSpecification valueSpec) {
        return null;
      }
    });
    addFormatter(new Formatter<Object>(Format.EXPANDED) {
      @Override
      Object format(Object value, ValueSpecification valueSpec) {
        return null;
      }
    });
  }

  @Override
  public Object formatCell(Object value, ValueSpecification valueSpec) {
    return "";
  }

  @Override
  public DataType getDataType() {
    return DataType.PRIMITIVE;
  }
}

/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.web.server.push.analytics.formatting;

import com.opengamma.engine.value.ValueSpecification;

/**
 * Formats null values for display in the client.
 */
/* package */ class NullFormatter extends AbstractFormatter<Object> {

  /* package */ NullFormatter() {
    super(Object.class);
    addFormatter(new Formatter<Object>(Format.HISTORY) {
      @Override
      Object format(Object value, ValueSpecification valueSpec) {
        return null;
      }
    });
    addFormatter(new Formatter<Object>(Format.EXPANDED) {
      @Override
      Object format(Object value, ValueSpecification valueSpec) {
        return "";
      }
    });
  }

  @Override
  public Object formatCell(Object value, ValueSpecification valueSpec) {
    return "";
  }

  @Override
  public DataType getDataType() {
    return DataType.PRIMITIVE;
  }
}

Format expanded null as empty string


package org.apache.wicket.bean.validation;

import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IPropertyReflectionAwareModel;

/**
 * Resolves the property to be validated for the given form component. Implementations, incuding the
 * default one, usually check the form component's model for some subclass that can provide the
 * necessary meta information to resolve the property.
 *
 * @see DefaultPropertyResolver
 * @see IPropertyReflectionAwareModel
 *
 * @author igor
 *
 */
@FunctionalInterface
public interface IPropertyResolver
{
	Property resolveProperty(FormComponent<?> component);
}

package org.apache.wicket.bean.validation;

import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.model.IPropertyReflectionAwareModel;

/**
 * Resolves the property to be validated for the given form component. Implementations, including the
 * default one, usually check the form component's model for some subclass that can provide the
 * necessary meta information to resolve the property.
 *
 * @see DefaultPropertyResolver
 * @see IPropertyReflectionAwareModel
 *
 * @author igor
 *
 */
@FunctionalInterface
public interface IPropertyResolver
{
	Property resolveProperty(FormComponent<?> component);
}

Fix a typo in javadoc


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

/**
 * Classes related to JVM dependencies and components
 */
@NonNullApi
package org.gradle.api.plugins.jvm;

import org.gradle.api.NonNullApi;

Add missing newline from EOF


package org.usfirst.frc.team3335.robot.subsystems;

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;

import com.ctre.CANTalon;

import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.command.Subsystem;

public class Intake extends Subsystem implements LoggableSubsystem {

	private CANTalon motor;

	private double motorValue = 0.5;

	public Intake() {
		motor = new CANTalon(RobotMap.INTAKE_MOTOR);
		motor.set(0);
		//motor.setControlMode();
	}
	public void turnOn(){
		set(motorValue);
	}

	public void turnOff(){
		set(0);
	}

	public void set(double value) {
		motor.set(value);
	}

	@Override
	protected void initDefaultCommand() {
		// TODO Auto-generated method stub

	}

	@Override
	public void log() {
		SmartDashboard.putNumber("Intake Value",motor.get());
	}
}

package org.usfirst.frc.team3335.robot.subsystems;

import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.RobotMap;

import com.ctre.CANTalon;

import edu.wpi.first.wpilibj.CANSpeedController;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import edu.wpi.first.wpilibj.DoubleSolenoid.Value;
import edu.wpi.first.wpilibj.command.Subsystem;

public class Intake extends Subsystem implements LoggableSubsystem {

	private CANTalon motor;

	private double motorValue = 1.0; //0.5;

	public Intake() {
		motor = new CANTalon(RobotMap.INTAKE_MOTOR);
		motor.set(0);
		//motor.setControlMode();
	}
	public void turnOn(){
		set(motorValue);
	}

	public void turnOff(){
		set(0);
	}

	public void set(double value) {
		motor.set(value);
	}

	@Override
	protected void initDefaultCommand() {
		// TODO Auto-generated method stub

	}

	@Override
	public void log() {
		SmartDashboard.putNumber("Intake Value",motor.get());
	}
}

Increase intake motor value to 1.0.


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

package com.nokia.dempsy.messagetransport.blockingqueue;

import java.util.concurrent.BlockingQueue;

import com.nokia.dempsy.messagetransport.Destination;

public class BlockingQueueDestination implements Destination
{
   protected BlockingQueue<byte[]> queue = null;

   public BlockingQueueDestination(BlockingQueue<byte[]> queue) { this.queue = queue; }

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

   @Override
   public boolean equals(Object other) { return queue.equals(((BlockingQueueDestination) other).queue); }
}

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

package com.nokia.dempsy.messagetransport.blockingqueue;

import java.util.concurrent.BlockingQueue;

import com.nokia.dempsy.messagetransport.Destination;

public class BlockingQueueDestination implements Destination
{
   protected BlockingQueue<byte[]> queue = null;

   public BlockingQueueDestination(BlockingQueue<byte[]> queue) { this.queue = queue; }

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

   @Override
   public boolean equals(Object other) { return other == null ? false : queue.equals(((BlockingQueueDestination) other).queue); }
}

Fix a NPE plaguing tests that use the BlockingQueue transport.


package com.kii.thingif.command;

/**
 * Represents base cass of Action.
 */
public interface Action{
}

package com.kii.thingif.command;

/**
 * Marks a class as group of actions of command. The class implements Acton defines single actions
 * as fields of the class.
 *
The class must define {@link ActionAnnotation} for each field of the class, SDK uses the
 * defined annotations to serialize the class to json data or deserialize json data to a instance
 * of the class.
 *
 *
Serialize Principles

 *

 *
Name of action after serialized.
 *

 *

 *             If value of actionName of {@link ActionAnnotation} is not an empty string, SDK uses
 *             this value as key of action in serialized json object.
 *

 *

 *             If value of actionName annotation is empty string, SDK will name of attribute of
 *             the class as key of action in serialized json object.
 *

 *

 *

 *
Value of action is serialized with Gson.
 *

 *

 *             If action value is null, SDK does not include the action into serialized json data.
 *

 *

 *             If action value is primitive type(like int, boolean, float, double), SDK serializes
 *             it by its type.
 *

 *

 *             If action value is simple data type(like String, Number or subclass of Number(Integer,
 *             Float, etc.)), SDK serializes it by its type.
 *

 *

 *             If action value is customized object defined by developer, SDK serializes it using Gson.
 *

 *

 *            If action value is Collection type, SDK serializes it using Gson.
 *

 *

 *            If action value is array(like int[]), SDK serialized it using Gson.
 *

 *

 *

 *

 */
public interface Action {
}

Add description of serialize and deserialize(not completed)


package me.konsolas.conditionalcommands.placeholders;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class AbstractParameteredPlaceholder implements Placeholder {
    private final Pattern pattern;

    AbstractParameteredPlaceholder(String base) {
        this.pattern = Pattern.compile("-" + base + ":([A-Za-z0-9%.]*)-");
    }

    @Override
    public boolean shouldApply(String test) {
        return pattern.matcher(test).find();
    }

    protected abstract String getSub(Player player, String param);

    @Override
    public String doSubstitution(String input, Player player) {
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            input = input.replaceAll(Pattern.quote(matcher.group()), getSub(player, matcher.group(1)));
        }

        return input;
    }

    @Override
    public void init(Plugin plugin) {
    }
}

package me.konsolas.conditionalcommands.placeholders;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class AbstractParameteredPlaceholder implements Placeholder {
    private final Pattern pattern;

    AbstractParameteredPlaceholder(String base) {
        this.pattern = Pattern.compile("-" + base + ":([A-Za-z0-9%._]*)-");
    }

    @Override
    public boolean shouldApply(String test) {
        return pattern.matcher(test).find();
    }

    protected abstract String getSub(Player player, String param);

    @Override
    public String doSubstitution(String input, Player player) {
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            input = input.replaceAll(Pattern.quote(matcher.group()), getSub(player, matcher.group(1)));
        }

        return input;
    }

    @Override
    public void init(Plugin plugin) {
    }
}

Add _ as valid parameter symbol


package org.ovirt.engine.core.bll;

import java.util.List;

import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;

public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {

    public GetImagesListQueryBase(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
        getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
    }

    /**
     * @return The storage domain to get the images from
     */
    protected abstract Guid getStorageDomainIdForQuery();

    protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
        return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
                (getStorageDomainIdForQuery(), getParameters().getImageType(), getParameters().getForceRefresh());
    }
}

package org.ovirt.engine.core.bll;

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

import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.queries.GetImagesListParametersBase;
import org.ovirt.engine.core.compat.Guid;

public abstract class GetImagesListQueryBase<P extends GetImagesListParametersBase> extends QueriesCommandBase<P> {

    public GetImagesListQueryBase(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        // Fetch all the Iso files of a given type for storage pool with active storage domain of this domain Id.
        getQueryReturnValue().setReturnValue(getUserRequestForStorageDomainRepoFileList());
    }

    /**
     * @return The storage domain to get the images from
     */
    protected abstract Guid getStorageDomainIdForQuery();

    protected List<RepoImage> getUserRequestForStorageDomainRepoFileList() {
        Guid storageDomainId = getStorageDomainIdForQuery();
        if (Guid.Empty.equals(storageDomainId)) {
            return new ArrayList<>();
        }

        return IsoDomainListSyncronizer.getInstance().getUserRequestForStorageDomainRepoFileList
                (storageDomainId, getParameters().getImageType(), getParameters().getForceRefresh());
    }
}

Fix ISO Domain List refresh NPE


/*
 * Copyright 2016 Daniel Nordhoff-Vergien
 *
 * 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.vergien.vaadinator.webdriver.touchkit;

import org.vaadin.addonhelpers.TServer;

import com.vaadin.annotations.Widgetset;

@Widgetset("org.vergien.vaadinator.webdriver.touchkit.MobileWidgetset")
public class Demo extends TServer {

	public Demo(String string) {
		super(string);
	}

	public static void main(String[] args) throws Exception {
		Demo demo = new Demo("target/WebDriverExampleTouchkit-0.20-SNAPSHOT");
		demo.startServer();
	}
}

/*
 * Copyright 2016 Daniel Nordhoff-Vergien
 *
 * 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.vergien.vaadinator.webdriver.touchkit;

import org.vaadin.addonhelpers.TServer;

import com.vaadin.annotations.Widgetset;

@Widgetset("org.vergien.vaadinator.webdriver.touchkit.MobileWidgetset")
public class Demo extends TServer {

	public Demo(String string) {
		super(string);
	}

	public static void main(String[] args) throws Exception {
		Demo demo = new Demo("target/WebDriverExampleTouchkit-0.20-SNAPSHOTstage");
		demo.startServer();
	}
}

Adjust path to new stage profile


package org.metaborg.spoofax.core.messages;

public interface ISourceRegion {
    public int startOffset();

    public int startRow();

    public int startColumn();

    public int endOffset();

    public int endRow();

    public int endColumn();
}

package org.metaborg.spoofax.core.messages;

/**
 * Interface for representing a finite region in source code text. A region has:
 *

 *
Offset - number of characters from the beginning of the source text, with interval [0,#chars).

 *
Row - row or line in the source text, with interval [0,#rows).

 *
Column - column in the source text, with interval [0,#columns@row).

 *

 * Both the starting and ending locations for these numbers are available.
 */
public interface ISourceRegion {
    public int startOffset();

    public int startRow();

    public int startColumn();

    public int endOffset();

    public int endRow();

    public int endColumn();
}

Clarify intervals of source region.


package com.kevinsimard.lambda.function;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

@SuppressWarnings("unused")
public class Example implements RequestHandler<Example.Request, Example.Response> {

    public Response handleRequest(Request request, Context context) {
        return new Response(request.message);
    }

    protected static class Request {

        private String message;

        private Request() {}

        public void setMessage(String message) {
            this.message = message;
        }
    }

    protected static class Response {

        private String message;

        private Response(String message) {
            this.message = message;
        }

        public String getMessage() {
            return this.message;
        }
    }
}

package com.kevinsimard.lambda.function;

import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;

@SuppressWarnings("unused")
public class Example implements RequestHandler<Example.Request, Example.Response> {

    public Response handleRequest(Request request, Context context) {
        return new Response(request.message);
    }

    static class Request {
        public String message;
    }

    static class Response {
        public String message;

        Response(String message) {
            this.message = message;
        }
    }
}

Update Request & Response classes


package com.bitmovin.bitcodin.api.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.bitmovin.bitcodin.api.output.FTPOutputConfig;
import com.bitmovin.bitcodin.api.output.S3OutputConfig;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;

public class Settings {

    @Expose
    public String apikey;
    @Expose
    public S3OutputConfig s3OutputEUWest;
    @Expose
    public FTPOutputConfig ftpOutput;

    static private Settings settings = null;
    static private String settingsfile  = "settings.json";

    static public Settings getInstance() throws FileNotFoundException
    {
        if (settings == null)
        {
            InputStream inputStream = Settings.class.getClassLoader().getResourceAsStream(Settings.settingsfile);

            if (inputStream == null)
                throw new FileNotFoundException("Cloud not find config file: " + Settings.settingsfile);

            BufferedReader  reader = new BufferedReader(new InputStreamReader(inputStream));
            Gson            gson   = new Gson();

            settings = gson.fromJson(reader, Settings.class);
        }

        return settings;
    }
}

package com.bitmovin.bitcodin.api.test;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.bitmovin.bitcodin.api.output.FTPOutputConfig;
import com.bitmovin.bitcodin.api.output.S3OutputConfig;
import com.google.gson.Gson;
import com.google.gson.annotations.Expose;

public class Settings {
    @Expose
    public String apikey;
    @Expose
    public S3OutputConfig s3OutputEUWest;
    @Expose
    public FTPOutputConfig ftpOutput;

    static private Settings settings = null;
    static private String settingsfile  = "settings.json";
    static private String localSettingsfile = "local_settings.json";

    static public Settings getInstance() throws FileNotFoundException
    {
        if (settings == null)
        {
            InputStream inputStream = Settings.class.getClassLoader().getResourceAsStream(Settings.settingsfile);

            if (inputStream == null)
            {
                inputStream = Settings.class.getClassLoader().getResourceAsStream(Settings.localSettingsfile);

                if (inputStream == null)
                  throw new FileNotFoundException("Cloud not find any config file: " + Settings.settingsfile);
            }

            BufferedReader  reader = new BufferedReader(new InputStreamReader(inputStream));
            Gson            gson   = new Gson();

            settings = gson.fromJson(reader, Settings.class);
        }

        return settings;
    }
}

Use local_settings.json when ci settings are not available


package com.miguelgaeta.bootstrap.mg_preference;

import android.content.Context;

import java.lang.reflect.Type;

import lombok.NonNull;

/**
 * Created by Miguel Gaeta on 9/25/15.
 */
public class MGPrefStoreTypeByeStream implements MGPrefStoreInterface {

    @Override
    public void init(@NonNull Context context) {

    }

    @Override
    public Object get(@NonNull String key, Type typeOfObject, boolean versioned) {
        return null;
    }

    @Override
    public void set(@NonNull String key, Object value, Type typeOfObject, boolean versioned) {

    }

    @Override
    public void clear() {

    }
}

package com.miguelgaeta.bootstrap.mg_preference;

import android.content.Context;

import com.esotericsoftware.kryo.Kryo;

import java.lang.reflect.Type;

import lombok.Getter;
import lombok.NonNull;

/**
 * Created by Miguel Gaeta on 9/25/15.
 */
public class MGPrefStoreTypeByeStream implements MGPrefStoreInterface {

    @Getter(lazy = true)
    private final ThreadLocal<Kryo> kryos = new ThreadLocal<Kryo>() {

        protected Kryo initialValue() {

            return new Kryo();
        }
    };

    @Override
    public void init(@NonNull Context context) {

    }

    @Override
    public Object get(@NonNull String key, Type typeOfObject, boolean versioned) {

        return null;
    }

    @Override
    public void set(@NonNull String key, Object value, Type typeOfObject, boolean versioned) {

    }

    @Override
    public void clear() {

    }
}

Add kryo thread pool instance.


package org.cryptonit;

import javacard.framework.JCSystem;

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

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
    }
}

package org.cryptonit;

import javacard.framework.JCSystem;

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

    private boolean [] bools = null;
    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
    }
}

Add array of booleans to maintain state


package devopsdistilled.operp.server.data.repo.items;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import devopsdistilled.operp.server.data.entity.items.Product;
import devopsdistilled.operp.server.data.repo.items.custom.ProductRepositoryCustom;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long>,
		ProductRepositoryCustom {

	public List<Product> findByProductName(String productName);

}

package devopsdistilled.operp.server.data.repo.items;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import devopsdistilled.operp.server.data.entity.items.Product;
import devopsdistilled.operp.server.data.repo.items.custom.ProductRepositoryCustom;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long>,
		ProductRepositoryCustom {

	public Product findByProductName(String productName);

}

Change return type to Product for findByProductName()


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapp;

import java.util.StringTokenizer;
import Hardware.windmill;

/**
 *
 * @author André
 */
public class DeviceLib {

    private windmill lib;

    public DeviceLib() {
        //AULA 3 - inicializar as lib
        lib = new windmill();
    }

    protected String callHardware(String content) {

        String reply = null;
        StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
        String operation = st.nextToken();
        if (operation.equals("ChangeState")) {
            // AULA 3 - Chamar a DLL para mudar o estado
            int state = Integer.parseInt(st.nextToken());
            String error=lib.errorString();
            System.err.println(error);            //Deve desaparecer
        }
        //Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
        System.err.println("ERROR: Impossible to collect data");                //Deve desaparecer
        reply = "-1" + utilities.constants.token +                              //Deve desaparecer
                "-1" + utilities.constants.token +                              //Deve desaparecer
                "-1" + utilities.constants.token;                               //Deve desaparecer
        return reply;
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package serverapp;

import java.util.StringTokenizer;
import Hardware.windmill;

/**
 *
 * @author André
 */
public class DeviceLib {

    private windmill lib;

    public DeviceLib() {
        //AULA 3 - inicializar as lib
        lib = new windmill();
    }

    protected String callHardware(String content) {

        String reply = null;
        StringTokenizer st = new StringTokenizer(content, utilities.constants.token);
        String operation = st.nextToken();
        if (operation.equals("ChangeState")) {
            // AULA 3 - Chamar a DLL para mudar o estado
            int state = Integer.parseInt(st.nextToken());
            int rval = lib.turn_on(state);
            if(rval==0){
                System.err.println("System was already in pretended state!");
            }
        }
        //Aula 3 - Esta parte deve ser removida e a chamada à DLL deve ser feita aqui
        //System.err.println("ERROR: Impossible to collect data");
        int isOn=lib.is_on();
        float power = lib.energy_production();
        String err = lib.errorString();
        reply = isOn + utilities.constants.token +                              //Deve desaparecer
                power + utilities.constants.token +                              //Deve desaparecer
                err + utilities.constants.token;                               //Deve desaparecer
        return reply;
    }
}

Update ServerApp :+1: :rocket: ->18


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

import javax.jcr.observation.EventListener;

/**
 * Defines a marker interface for {@link javax.jcr.observation.EventListener}
 * implementations that wish a synchronous notification of changes to the
 * workspace. That is, a SynchronousEventListener is called before
 * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
 * {@link javax.jcr.observation.EventListener} might be called after
 * save() returns.
 */
public interface SynchronousEventListener extends EventListener {
}

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

import javax.jcr.observation.EventIterator;
import javax.jcr.observation.EventListener;

/**
 * Defines a marker interface for {@link javax.jcr.observation.EventListener}
 * implementations that wish a synchronous notification of changes to the
 * workspace. That is, a SynchronousEventListener is called before
 * the call to {@link javax.jcr.Item#save()} returns. In contrast, a regular
 * {@link javax.jcr.observation.EventListener} might be called after
 * save() returns.
 *

 * Important note: an implementation of {@link SynchronousEventListener}
 * must not modify content with the thread that calls {@link
 * #onEvent(EventIterator)} otherwise inconsistencies may occur.
 */
public interface SynchronousEventListener extends EventListener {
}

Duplicate entries in the index - javadoc


package org.jboss.shamrock.security;

import java.util.List;

import org.jboss.builder.item.MultiBuildItem;
import org.jboss.shamrock.runtime.RuntimeValue;

/**
 * Information about an authentication mechanism to enable. This is used to call the
 * {@linkplain SecurityTemplate#configureUndertowIdentityManager(RuntimeValue, List)} method to register the auth methods
 * enabled.
 *
 * Custom authentication mechanisms would need to have the {@linkplain io.undertow.servlet.ServletExtension} that
 * registers the {@linkplain io.undertow.security.api.AuthenticationMechanismFactory} for the method.
 */
public final class AuthConfigBuildItem extends MultiBuildItem {
    private AuthConfig authConfig;

    public AuthConfigBuildItem(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }

    public AuthConfig getAuthConfig() {
        return authConfig;
    }
}

package org.jboss.shamrock.security;

import java.util.List;

import org.jboss.builder.item.MultiBuildItem;
import org.jboss.shamrock.runtime.RuntimeValue;

/**
 * Information about an authentication mechanism to enable. This is used to call the
 * {@linkplain SecurityTemplate#configureUndertowIdentityManager(RuntimeValue, List)} method to register the auth methods
 * enabled.
 *
 * Custom authentication mechanisms would need to have the {@linkplain io.undertow.servlet.ServletExtension} that
 * registers the {@linkplain io.undertow.security.api.AuthenticationMechanismFactory} for the method.
 */
public final class AuthConfigBuildItem extends MultiBuildItem {
    private final AuthConfig authConfig;

    public AuthConfigBuildItem(AuthConfig authConfig) {
        this.authConfig = authConfig;
    }

    public AuthConfig getAuthConfig() {
        return authConfig;
    }
}

Make the authConfig field final.


package server.threads;

import java.util.List;
import java.util.Random;

import util.match.Match;
import util.statemachine.Move;

public final class RandomPlayRequestThread extends PlayRequestThread
{
	private Move move;

	public RandomPlayRequestThread(Match match, List<Move> legalMoves)
	{
		super(null, match, null, null, null, null, 0, null, true);
		move = legalMoves.get(new Random().nextInt(legalMoves.size()));
	}

	@Override
	public Move getMove()
	{
		return move;
	}

	@Override
	public void run()
	{
		;
	}
}

package server.threads;

import java.util.List;
import java.util.Random;

import util.match.Match;
import util.statemachine.Move;

public final class RandomPlayRequestThread extends PlayRequestThread
{
	private Move move;

	public RandomPlayRequestThread(Match match, List<Move> legalMoves)
	{
		super(null, match, null, legalMoves, null, null, 0, null, true);
		move = legalMoves.get(new Random().nextInt(legalMoves.size()));
	}

	@Override
	public Move getMove()
	{
		return move;
	}

	@Override
	public void run()
	{
		;
	}
}

Fix another bug with the random play request thread initialization.


package uk.ac.ebi.atlas.search.analyticsindex.baseline;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {

    private static final String SOLR_BASE_URL = "http://TEST";
    private static final String JSON_FACET = "{}";

    @Mock
    private RestTemplate restTemplate;

    private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);

    @Test
    public void buildQueryParameters() {
        assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=expressionLevel:%5B0.5%20TO%20*%5D"));
    }

}

package uk.ac.ebi.atlas.search.analyticsindex.baseline;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.web.client.RestTemplate;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@RunWith(MockitoJUnitRunner.class)
public class BaselineAnalyticsSearchDaoTest {

    private static final String SOLR_BASE_URL = "http://TEST";
    private static final String JSON_FACET = "{}";

    @Mock
    private RestTemplate restTemplate;

    private final BaselineAnalyticsSearchDao subject = new BaselineAnalyticsSearchDao(restTemplate, SOLR_BASE_URL, JSON_FACET);

    @Test
    public void buildQueryParameters() {
        assertThat(subject.buildQueryParameters("identifierSearch:ENSG00000126549", 0.5, 0), is("query?q=identifierSearch:ENSG00000126549&rows=0&omitHeader=true&fq=(experimentType:rnaseq_mrna_baseline%20AND%20expressionLevel:%5B0.5%20TO%20*%5D)%20OR%20(experimentType:proteomics_baseline%20AND%20expressionLevel:%5B0%20TO%20*%5D)"));
    }

}

Fix unit test after adding separate baseline/proteomics filtering


package org.jaxen.javabean;

import junit.framework.TestCase;

public class DocumentNavigatorTest
    extends TestCase
{

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

package org.jaxen.javabean;

import junit.framework.TestCase;
import org.jaxen.saxpath.helpers.XPathReaderFactory;

public class DocumentNavigatorTest
    extends TestCase
{

    protected void setUp() throws Exception
    {
        System.setProperty( XPathReaderFactory.DRIVER_PROPERTY,
                            "" );
    }

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

Set property in case it has been set wrong previously


package me.duncte123.skybot.commands;

import me.duncte123.skybot.Command;
import me.duncte123.skybot.utils.HelpEmbeds;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class HelpCommand extends Command {

    public final static String help = "shows a list of all the commands.";

    @Override
    public boolean called(String[] args, MessageReceivedEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void action(String[] args, MessageReceivedEvent event) {

        event.getAuthor().openPrivateChannel().queue( (pc) -> {
            event.getTextChannel().sendMessage(event.getMember().getAsMention() +" check your DM's").queue();
            pc.sendMessage(HelpEmbeds.mainCommands).queue();
            pc.sendMessage(HelpEmbeds.musicCommands).queue();
            pc.sendMessage(HelpEmbeds.funCommands).queue();
            pc.sendMessage(HelpEmbeds.modCommands).queue();
        },
                err -> event.getChannel().sendMessage("ERROR: " + err.getMessage()).queue() );
    }

    @Override
    public String help() {
        // TODO Auto-generated method stub
        return help;
    }
}

package me.duncte123.skybot.commands;

import me.duncte123.skybot.Command;
import me.duncte123.skybot.utils.HelpEmbeds;
import net.dv8tion.jda.core.entities.TextChannel;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class HelpCommand extends Command {

    public final static String help = "shows a list of all the commands.";

    @Override
    public boolean called(String[] args, MessageReceivedEvent event) {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void action(String[] args, MessageReceivedEvent event) {

        event.getAuthor().openPrivateChannel().queue( (pc) -> {
            pc.sendMessage(HelpEmbeds.mainCommands).queue( msg -> {
                        pc.sendMessage(HelpEmbeds.musicCommands).queue();
                        pc.sendMessage(HelpEmbeds.funCommands).queue();
                        pc.sendMessage(HelpEmbeds.modCommands).queue();
                        event.getTextChannel().sendMessage(event.getMember().getAsMention() +" check your DM's").queue();
                    },
                    //When sending fails, send to the channel
                    err -> {
                        TextChannel currentChann = event.getTextChannel();
                        currentChann.sendMessage(HelpEmbeds.mainCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.musicCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.funCommands).queue();
                        currentChann.sendMessage(HelpEmbeds.modCommands).queue();
                        currentChann.sendMessage("Message could not be delivered to dm's and has been send in this channel.").queue();
                    }
            );
        },
                err -> event.getChannel().sendMessage("ERROR: " + err.getMessage()).queue()
        );
    }

    @Override
    public String help() {
        // TODO Auto-generated method stub
        return help;
    }
}

Create failover for if the helpmessage fails to send


package info.bitrich.xchangestream.bitfinex.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;

import java.math.BigDecimal;

/**
 * Created by Lukas Zaoralek on 7.11.17.
 */
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
    public long tradeId;
    public long timestamp;
    public BigDecimal amount;
    public BigDecimal price;

    public BitfinexWebSocketTrade() {
    }

    public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
        this.tradeId = tradeId;
        this.timestamp = timestamp;
        this.amount = amount;
        this.price = price;
    }

    public long getTradeId() {
        return tradeId;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public BitfinexTrade toBitfinexTrade() {
        String type;
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            type = "sell";
        } else {
            type = "buy";
        }

        return new BitfinexTrade(price, amount, timestamp / 1000, "bitfinex", tradeId, type);
    }
}

package info.bitrich.xchangestream.bitfinex.dto;

import com.fasterxml.jackson.annotation.JsonFormat;
import org.knowm.xchange.bitfinex.v1.dto.marketdata.BitfinexTrade;

import java.math.BigDecimal;

/**
 * Created by Lukas Zaoralek on 7.11.17.
 */
@JsonFormat(shape = JsonFormat.Shape.ARRAY)
public class BitfinexWebSocketTrade {
    public long tradeId;
    public long timestamp;
    public BigDecimal amount;
    public BigDecimal price;

    public BitfinexWebSocketTrade() {
    }

    public BitfinexWebSocketTrade(long tradeId, long timestamp, BigDecimal amount, BigDecimal price) {
        this.tradeId = tradeId;
        this.timestamp = timestamp;
        this.amount = amount;
        this.price = price;
    }

    public long getTradeId() {
        return tradeId;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public BigDecimal getAmount() {
        return amount;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public BitfinexTrade toBitfinexTrade() {
        String type;
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            type = "sell";
        } else {
            type = "buy";
        }
        return new BitfinexTrade(price, amount.abs(), timestamp / 1000, "bitfinex", tradeId, type);
    }
}

Fix trade signs on Bitfinex * Trades from all other exchanges are presented with positive amounts (with the trade type indicating direction). On Bitfinex, sells were arriving negative and buys positive.


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

package org.springframework.boot.actuate.autoconfigure;

import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jmx.export.MBeanExporter;

@Configuration
@ConditionalOnBean({ MBeanExporter.class })
@AutoConfigureAfter({ EndpointAutoConfiguration.class })
class EndpointMBeanExportAutoConfiguration {

	@Bean
	public EndpointMBeanExporter endpointMBeanExporter() {
		return new EndpointMBeanExporter();
	}

}

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

package org.springframework.boot.actuate.autoconfigure;

import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.jmx.EndpointMBeanExporter;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jmx.export.MBeanExporter;

/**
 * {@link EnableAutoConfiguration Auto-configuration} to enable JMX export for
 * {@link Endpoint}s.
 *
 * @author Christian Dupuis
 */
@Configuration
@ConditionalOnBean({ MBeanExporter.class })
@AutoConfigureAfter({ EndpointAutoConfiguration.class })
@ConditionalOnExpression("${endpoints.jmx.enabled:true}")
class EndpointMBeanExportAutoConfiguration {

	@Bean
	public EndpointMBeanExporter endpointMBeanExporter() {
		// TODO add configuration for domain name
		return new EndpointMBeanExporter();
	}

}

Allow Endpoint JMX export to be switched off


package com.peterphi.std.guice.common.serviceprops.net;

import com.google.inject.AbstractModule;

public class NetworkConfigReloadModule extends AbstractModule
{
	@Override
	protected void configure()
	{
		bind(NetworkConfigReloadDaemon.class).asEagerSingleton();
	}
}

package com.peterphi.std.guice.common.serviceprops.net;

import com.google.inject.AbstractModule;
import com.google.inject.Provides;
import com.google.inject.Singleton;
import com.peterphi.std.guice.config.rest.iface.ConfigRestService;
import com.peterphi.std.guice.restclient.JAXRSProxyClientFactory;

public class NetworkConfigReloadModule extends AbstractModule
{
	@Override
	protected void configure()
	{
		bind(NetworkConfigReloadDaemon.class).asEagerSingleton();
	}

	@Provides
	@Singleton
	public ConfigRestService getConfigService(JAXRSProxyClientFactory factory)
	{
		return factory.getClient(ConfigRestService.class);
	}
}

Add explicit jax-rs client provider for ConfigRestService so that scan.packages doesn't have to include ConfigRestService


package org.openscore.lang.tools.build.tester.parse;

import java.io.Serializable;
import java.util.Map;

/**
 * Created by stoneo on 3/15/2015.
 **/
public class SlangTestCase {

    private final String description;

    private final String testSuits;

    private final String systemPropertiesFile;

    private final Map<String, Serializable> inputs;

    private final Boolean throwsException;

    private final String result;

    public SlangTestCase(String description, String testSuits, String systemPropertiesFile,
                         Map<String, Serializable> inputs, Boolean throwsException, String result){
        this.description = description;
        this.testSuits = testSuits;
        this.systemPropertiesFile = systemPropertiesFile;
        this.inputs = inputs;
        this.throwsException = throwsException;
        this.result = result;
    }

    public String getDescription() {
        return description;
    }

    public String getTestSuits() {
        return testSuits;
    }

    public String getSystemPropertiesFile() {
        return systemPropertiesFile;
    }

    public Map<String, Serializable> getInputs() {
        return inputs;
    }

    public Boolean getThrowsException() {
        return throwsException;
    }

    public String getResult() {
        return result;
    }
}

package org.openscore.lang.tools.build.tester.parse;

import org.apache.commons.collections4.CollectionUtils;

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

/**
 * Created by stoneo on 3/15/2015.
 **/
public class SlangTestCase {

    private final String description;

    private final List<String> testSuits;

    private final String systemPropertiesFile;

    private final Map<String, Serializable> inputs;

    private final Boolean throwsException;

    private final String result;

    public static final String BASE_TEST_SUITE = "base";

    public SlangTestCase(String description, List<String> testSuits, String systemPropertiesFile,
                         Map<String, Serializable> inputs, Boolean throwsException, String result){
        this.description = description;
        this.systemPropertiesFile = systemPropertiesFile;
        if(CollectionUtils.isEmpty(testSuits)){
            this.testSuits = new ArrayList<>();
            this.testSuits.add(BASE_TEST_SUITE);
        } else {
            this.testSuits = testSuits;
        }
        this.inputs = inputs;
        this.throwsException = throwsException;
        this.result = result;
    }

    public String getDescription() {
        return description;
    }

    public List<String> getTestSuits() {
        return testSuits;
    }

    public String getSystemPropertiesFile() {
        return systemPropertiesFile;
    }

    public Map<String, Serializable> getInputs() {
        return inputs;
    }

    public Boolean getThrowsException() {
        return throwsException;
    }

    public String getResult() {
        return result;
    }
}

Change testSuites to be a list with default value


package fixtures.azurespecials;

import com.microsoft.rest.ServiceResponse;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class HeaderOperationsTests {
    private static AutoRestAzureSpecialParametersTestClient client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestAzureSpecialParametersTestClientImpl("http://localhost.:3000");
    }

    @Test
    public void customNamedRequestId() throws Exception {
        ServiceResponse<Void> response = client.getHeaderOperations().customNamedRequestId("9C4D50EE-2D56-4CD3-8152-34347DC9F2B0");
        Assert.assertEquals(200, response.getResponse().code());
    }
}

package fixtures.azurespecials;

import com.microsoft.rest.ServiceResponseWithHeaders;
import fixtures.azurespecials.models.HeaderCustomNamedRequestIdHeaders;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class HeaderOperationsTests {
    private static AutoRestAzureSpecialParametersTestClient client;

    @BeforeClass
    public static void setup() {
        client = new AutoRestAzureSpecialParametersTestClientImpl("http://localhost.:3000");
    }

    @Test
    public void customNamedRequestId() throws Exception {
        ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> response = client.getHeaderOperations().customNamedRequestId("9C4D50EE-2D56-4CD3-8152-34347DC9F2B0");
        Assert.assertEquals(200, response.getResponse().code());
        Assert.assertEquals("123", response.getHeaders().getFooRequestId());
    }
}

Add test on response typed headers


package org.nuxeo.drive.service.impl;

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

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

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

    private RootDefinitionsHelper() {
        // Utility class
    }

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

}

package org.nuxeo.drive.service.impl;

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

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

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

    private RootDefinitionsHelper() {
        // Utility class
    }

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

}

Fix Sonar Major violations: Final Class


package org.spoofax.jsglr2.recovery;

import org.metaborg.parsetable.productions.IProduction;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;

public class RecoveryMessages {

    public static Message get(IProduction production, Position start, Position end) {
        SourceRegion region = new SourceRegion(start, end);

        String message;

        if("WATER".equals(production.constructor()))
            message = "Not expected";
        else if("INSERTION".equals(production.constructor())) {
            String insertion;

            if (production.isLiteral())
                insertion = production.lhs().descriptor().replaceAll("^\"|\"$", "");
            else
                insertion = "Token";

            message = insertion + " expected";
        } else
            message = "Invalid syntax";

        return Message.error(message, region);
    }

}

package org.spoofax.jsglr2.recovery;

import org.metaborg.parsetable.productions.IProduction;
import org.metaborg.parsetable.symbols.ILiteralSymbol;
import org.spoofax.jsglr2.messages.Message;
import org.spoofax.jsglr2.messages.SourceRegion;
import org.spoofax.jsglr2.parser.Position;

public class RecoveryMessages {

    public static Message get(IProduction production, Position start, Position end) {
        SourceRegion region = new SourceRegion(start, end);

        String message;

        if("WATER".equals(production.constructor()))
            message = "Not expected";
        else if("INSERTION".equals(production.constructor())) {
            String insertion;

            if (production.isLiteral())
                insertion = ((ILiteralSymbol) production.lhs()).literal();
            else
                insertion = "Token";

            message = insertion + " expected";
        } else
            message = "Invalid syntax";

        return Message.error(message, region);
    }

}

Simplify retrieval of literal for insertion recovery messages


package org.spongepowered.server.mixin.core.item.crafting;

import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(CraftingManager.class)
public abstract class CraftingManagerMixin_Vanilla {

    @Inject(method = "register(Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/item/crafting/IRecipe;)V", at = @At(value = "NEW"), cancellable = true)
    private static void register(final ResourceLocation name, final IRecipe recipe, final CallbackInfo ci) {
        final int id = CraftingManager.REGISTRY.getIDForObject(CraftingManager.REGISTRY.getObject(name));
        CraftingManager.REGISTRY.register(id, name, recipe);
        ci.cancel();
    }

}

package org.spongepowered.server.mixin.core.item.crafting;

import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.ResourceLocation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

@Mixin(CraftingManager.class)
public abstract class CraftingManagerMixin_Vanilla {

    @Inject(method = "register(Lnet/minecraft/util/ResourceLocation;Lnet/minecraft/item/crafting/IRecipe;)V", at = @At(value = "NEW"), cancellable = true)
    private static void vanilla$register(final ResourceLocation name, final IRecipe recipe, final CallbackInfo ci) {
        final int id = CraftingManager.REGISTRY.getIDForObject(CraftingManager.REGISTRY.getObject(name));
        CraftingManager.REGISTRY.register(id, name, recipe);
        ci.cancel();
    }

}

Update injection name to match new naming scheme


/*
 * Copyright 2014 Josef Hardi <josef.hardi@gmail.com>
 *
 * 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.github.johardi.r2rmlparser.exception;

import io.github.johardi.r2rmlparser.util.StringUtils;

public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException
{
   private static final long serialVersionUID = 1681949L;

   private String mPropertyLabel;
   private String mExceptionDetail;

   public InvalidPropertyAttributeException(String propertyLabel)
   {
      mPropertyLabel = propertyLabel;
   }

   public void setExceptionDetail(String detail)
   {
      mExceptionDetail = detail;
   }

   @Override
   public String getMessage()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("Invalid property attribute for");
      sb.append("\"").append(mPropertyLabel).append("\"");
      if (!StringUtils.isEmpty(mExceptionDetail)) {
         sb.append(" ");
         sb.append(mExceptionDetail);
      }
      return sb.toString();
   }
}

/*
 * Copyright 2014 Josef Hardi <josef.hardi@gmail.com>
 *
 * 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.github.johardi.r2rmlparser.exception;

import io.github.johardi.r2rmlparser.util.StringUtils;

public class InvalidPropertyAttributeException extends JR2RmlParserRuntimeException
{
   private static final long serialVersionUID = 1681949L;

   private String mPropertyLabel;
   private String mExceptionDetail;

   public InvalidPropertyAttributeException(String propertyLabel)
   {
      mPropertyLabel = propertyLabel;
   }

   public void setExceptionDetail(String detail)
   {
      mExceptionDetail = detail;
   }

   @Override
   public String getMessage()
   {
      StringBuilder sb = new StringBuilder();
      sb.append("Invalid property attribute for ");
      sb.append("\"").append(mPropertyLabel).append("\"");
      if (!StringUtils.isEmpty(mExceptionDetail)) {
         sb.append(" ");
         sb.append(mExceptionDetail);
      }
      return sb.toString();
   }
}

Add space in the error message.


package com.github.verhagen.textadventure.core.domain;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;

public class TextVisitorTest {

	@Test
	public void visitEmptyHall() {
		String description = "There is a front door on the south and a door on the east.";
		IRoom hall = new Room("hall", description);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), description);
	}

	@Test
	public void visitHallWithABook() {
		String description = "There is a front door on the south and a door on the east.";
		String title = "TRS-80 Assembly-Language Programming";
		IRoom hall = new Room("hall", description);
		IItem book = new Item("book", title);
		hall.add(book);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), description + "Items: " + book.getName());
	}

}

package com.github.verhagen.textadventure.core.domain;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.github.verhagen.textadventure.core.impl.domain.Item;
import com.github.verhagen.textadventure.core.impl.domain.Room;
import com.github.verhagen.textadventure.core.impl.domain.TextVisitor;

public class TextVisitorTest {

	@Test
	public void visitEmptyHall() {
		String description = "There is a front door on the south and a door on the east.";
		IRoom hall = new Room("hall", description);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), "You are in a hall. " + description);
	}

	@Test
	public void visitHallWithABook() {
		String description = "There is a front door on the south and a door on the east.";
		String title = "TRS-80 Assembly-Language Programming";
		IRoom hall = new Room("hall", description);
		IItem book = new Item("book", title);
		hall.add(book);

		TextVisitor visitor = new TextVisitor();
		hall.accept(visitor);

		assertEquals(visitor.asText(), "You are in a hall. " + description + " Items: " + book.getName());
	}

}

Update test cases asserts, to update TextVisitor creating better description


package co.codesharp.jwampsharp.defaultBinding;

import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;

import java.net.URI;

/**
 * Created by Elad on 7/11/2014.
 */
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {
    public <TMessage> WampChannel createChannel
            (URI address,
             String realm,
             WampTextBinding<TMessage> binding) {
        WebsocketWampTextConnection<TMessage> connection =
                new WebsocketWampTextConnection<TMessage>(address, binding);

        return this.createChannel(realm, connection, binding);
    }

    public WampChannel createJsonChannel(URI address,
                                          String realm) {
        JsonNodeBinding binding = new JsonNodeBinding();

        return this.createChannel(address, realm, binding);
    }
}

package co.codesharp.jwampsharp.defaultBinding;

import co.codesharp.jwampsharp.api.client.WampChannel;
import co.codesharp.jwampsharp.api.client.WampChannelFactoryImpl;
import co.codesharp.jwampsharp.core.binding.WampTextBinding;
import co.codesharp.jwampsharp.defaultBinding.jsr.WebsocketWampTextConnection;

import java.net.URI;

/**
 * Created by Elad on 7/11/2014.
 */
public class DefaultWampChannelFactory extends WampChannelFactoryImpl {

    private JsonNodeBinding jsonNodeBinding = new JsonNodeBinding();

    public <TMessage> WampChannel createChannel
            (URI address,
             String realm,
             WampTextBinding<TMessage> binding) {
        WebsocketWampTextConnection<TMessage> connection =
                new WebsocketWampTextConnection<TMessage>(address, binding);

        return this.createChannel(realm, connection, binding);
    }

    public WampChannel createJsonChannel(URI address,
                                          String realm) {
        return this.createChannel(address, realm, jsonNodeBinding);
    }
}

Use the same reference for all method calls


package org.shipkit.internal.gradle.util;

import org.gradle.api.GradleException;
import org.shipkit.gradle.git.GitPushTask;

public class CannotPushToGithubException extends RuntimeException {
    public static final String GH_WRITE_TOKEN_NOT_SET_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN not set or you don't have write access to remote. Please recheck your configuration.";
    public static final String GH_WRITE_TOKEN_INVALID_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN is set but possibly invalid. Please recheck your configuration.";

    private CannotPushToGithubException(String message, Throwable cause) {
        super(message, cause);
    }

    public static CannotPushToGithubException create(Exception e, GitPushTask task) {
        String message;
        if (task.getSecretValue() == null) {
            message = GH_WRITE_TOKEN_NOT_SET_MSG;
        } else {
            message = GH_WRITE_TOKEN_INVALID_MSG;
        }
        return new CannotPushToGithubException(message, e);
    }

    public static boolean matchException(GradleException e) {
        return e.getMessage().contains("Authentication failed") || e.getMessage().contains("unable to access");
    }
}

package org.shipkit.internal.gradle.util;

import org.gradle.api.GradleException;
import org.shipkit.gradle.git.GitPushTask;

public class CannotPushToGithubException extends RuntimeException {
    public static final String GH_WRITE_TOKEN_NOT_SET_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN env variable not set or you don't have write access to remote. Please recheck your configuration.";
    public static final String GH_WRITE_TOKEN_INVALID_MSG = "Cannot push to remote repository. GH_WRITE_TOKEN env variable is set but possibly invalid. Please recheck your configuration.";

    private CannotPushToGithubException(String message, Throwable cause) {
        super(message, cause);
    }

    public static CannotPushToGithubException create(Exception e, GitPushTask task) {
        String message;
        if (task.getSecretValue() == null) {
            message = GH_WRITE_TOKEN_NOT_SET_MSG;
        } else {
            message = GH_WRITE_TOKEN_INVALID_MSG;
        }
        return new CannotPushToGithubException(message, e);
    }

    public static boolean matchException(GradleException e) {
        return e.getMessage().contains("Authentication failed") || e.getMessage().contains("unable to access");
    }
}

Make error message more specific.


package org.knowm.xchange.bitfinex.v1.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;

public class BitfinexCancelOrderRequest {

  @JsonProperty("request")
  protected String request;

  @JsonProperty("nonce")
  protected String nonce;

  @JsonProperty("order_id")
  @JsonRawValue
  private int orderId;

  /**
   * Constructor
   *
   * @param nonce
   * @param orderId
   */
  public BitfinexCancelOrderRequest(String nonce, int orderId) {

    this.request = "/v1/order/cancel";
    this.orderId = orderId;
    this.nonce = nonce;
  }

  public String getOrderId() {

    return String.valueOf(orderId);
  }

}

package org.knowm.xchange.bitfinex.v1.dto.trade;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRawValue;

public class BitfinexCancelOrderRequest {

  @JsonProperty("request")
  protected String request;

  @JsonProperty("nonce")
  protected String nonce;

  @JsonProperty("order_id")
  @JsonRawValue
  private long orderId;

  /**
   * Constructor
   *
   * @param nonce
   * @param orderId
   */
  public BitfinexCancelOrderRequest(String nonce, long orderId) {

    this.request = "/v1/order/cancel";
    this.orderId = orderId;
    this.nonce = nonce;
  }

  public String getOrderId() {

    return String.valueOf(orderId);
  }

}

Order id is now long type