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

package com.googlesource.gerrit.plugins.deleteproject;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.inject.Inject;

public class HttpModule extends HttpPluginModule {
  private final Configuration cfg;

  @Inject
  HttpModule(Configuration cfg) {
    this.cfg = cfg;
  }

  @Override
  protected void configureServlets() {
    if (cfg.enablePreserveOption()) {
      DynamicSet.bind(binder(), WebUiPlugin.class)
          .toInstance(new JavaScriptPlugin("delete-project.js"));
    } else {
      DynamicSet.bind(binder(), WebUiPlugin.class)
          .toInstance(new JavaScriptPlugin("delete-project-with-preserve-disabled.js"));
    }
  }
}

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

package com.googlesource.gerrit.plugins.deleteproject;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.extensions.webui.JavaScriptPlugin;
import com.google.gerrit.extensions.webui.WebUiPlugin;
import com.google.inject.Inject;
import com.google.inject.servlet.ServletModule;

public class HttpModule extends ServletModule {
  private final Configuration cfg;

  @Inject
  HttpModule(Configuration cfg) {
    this.cfg = cfg;
  }

  @Override
  protected void configureServlets() {
    if (cfg.enablePreserveOption()) {
      DynamicSet.bind(binder(), WebUiPlugin.class)
          .toInstance(new JavaScriptPlugin("delete-project.js"));
    } else {
      DynamicSet.bind(binder(), WebUiPlugin.class)
          .toInstance(new JavaScriptPlugin("delete-project-with-preserve-disabled.js"));
    }
  }
}

Extend ServletModule instead of HttpPluginModule

As described in I3b89150d1.

Change-Id: Ic91ce95719c6bccc73cc29a2139a2274f20d1939


package com.thebuerkle.dropwizard.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thebuerkle.dropwizard.core.Car;

@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {

    private static final Logger log = LoggerFactory.getLogger(TestResource.class);

    private final Client _client;

    public TestResource(Client client) {
        _client = client;
    }

    @Path("/produce")
    @GET
    public Car produce() {
        return new Car("Elantra", "gray");
    }

    @Path("/consume")
    @GET
    public void consume() {
        WebTarget target = _client.target("http://localhost:8080/produce");
        Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
        Response response = invocation.get();

        log.info(response.readEntity(Car.class).toString());
    }
}

package com.thebuerkle.dropwizard.resources;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thebuerkle.dropwizard.core.Car;

@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public class TestResource {

    private static final Logger log = LoggerFactory.getLogger(TestResource.class);

    private final Client _client;

    public TestResource(Client client) {
        _client = client;
    }

    @Path("/produce")
    @GET
    public Car produce() {
        return new Car("Elantra", "gray");
    }

    @Path("/consume")
    @GET
    public void consume(@QueryParam("string") boolean asString) {
        WebTarget target = _client.target("http://localhost:8080/produce");
        Invocation.Builder invocation = target.request(MediaType.APPLICATION_JSON);
        Response response = invocation.get();

        log.info("Status code: " + Response.Status.fromStatusCode(response.getStatus()));

        if (asString) {
            log.info("Response as string: " + response.readEntity(String.class));
        }
        else {
            log.info("Response as car: " + response.readEntity(Car.class).toString());
        }
    }
}

Add getting response as a string

Add getting response as a string


package cells;

import com.jme3.math.ColorRGBA;
import geometry.Position;
import inventory.InventoryItem;
import world.World;

/**
 * A cell whose state is known for any given tick
 */
public enum AnimatedCell implements InventoryItem, WorldCell {
    OSCILLATOR("Oscillator", (tick) -> {
        if (tick % 2 == 0) {
            return ColorRGBA.Magenta;
        } else {
            return ColorRGBA.Yellow;
        }
    });

    private final String name;
    private final F function;

    /**
     * A color function of tick and position
     */
    interface F { ColorRGBA f(int tick); }

    /**
     * Create an animated cell with given name and a color function
     * @param name name of the animated cell
     * @param function color generating function
     */
    AnimatedCell(String name, F function) {
        this.name = name;
        this.function = function;
    }

    /**
     * Produce the name of this animated cell
     * @return name of this animated cell
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * Produce the color of this animated cell from the given tick and position
     * @param tick current tick
     * @return current color of this animated cell
     */
    @Override
    public ColorRGBA getColor(int tick, Position position) {
        return function.f(tick);
    }

    @Override
    public void use(Position placeCursor, Position removeCursor, Position player) {
        World.getInstance().add(placeCursor, this);
    }
}

package cells;

import com.jme3.math.ColorRGBA;
import geometry.Position;
import inventory.InventoryItem;
import world.World;

/**
 * A cell whose state is known for any given tick
 */
public enum AnimatedCell implements InventoryItem, WorldCell {
    OSCILLATOR("Oscillator", (tick) -> {
        if (tick % 2 == 0) {
            return ColorRGBA.Magenta;
        } else {
            return ColorRGBA.Yellow;
        }
    });

    private final String name;
    private final Function function;

    /**
     * A color function of tick and position
     */
    private interface Function { ColorRGBA apply(int tick); }

    /**
     * Create an animated cell with given name and a color function
     * @param name name of the animated cell
     * @param function color generating function
     */
    AnimatedCell(String name, Function function) {
        this.name = name;
        this.function = function;
    }

    /**
     * Produce the name of this animated cell
     * @return name of this animated cell
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * Produce the color of this animated cell from the given tick and position
     * @param tick current tick
     * @return current color of this animated cell
     */
    @Override
    public ColorRGBA getColor(int tick, Position position) {
        return function.apply(tick);
    }

    @Override
    public void use(Position placeCursor, Position removeCursor, Position player) {
        World.getInstance().add(placeCursor, this);
    }
}

Rename F to Function and f() to apply()

Rename F to Function and f() to apply()


package org.pentaho.di.run.sortedmerge;

import junit.framework.TestCase;

import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;

public class RunSortedMerge extends TestCase
{
    public void test_SORTED_MERGE_00()
    {
        System.out.println();
        System.out.println("SORTED MERGE");
        System.out.println("==================");
    }

    public void test_SORTED_MERGE_01_SIMPLE() throws Exception
    {
        TimedTransRunner timedTransRunner = new TimedTransRunner(
                "test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
                LogWriter.LOG_LEVEL_ERROR,
                AllRunTests.getOldTargetDatabase(),
                AllRunTests.getNewTargetDatabase(),
                1000
            );
        timedTransRunner.runOldAndNew();

        be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
        assertTrue(oldResult.getNrErrors()==0);

        Result newResult = timedTransRunner.getNewResult();
        assertTrue(newResult.getNrErrors()==0);
    }
}

package org.pentaho.di.run.sortedmerge;

import junit.framework.TestCase;

import org.pentaho.di.core.Result;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.run.AllRunTests;
import org.pentaho.di.run.TimedTransRunner;

public class RunSortedMerge extends TestCase
{
    public void test_SORTED_MERGE_00()
    {
        System.out.println();
        System.out.println("SORTED MERGE");
        System.out.println("==================");
    }

    public void test_SORTED_MERGE_01_SIMPLE() throws Exception
    {
        TimedTransRunner timedTransRunner = new TimedTransRunner(
                "test/org/pentaho/di/run/sortedmerge/SortedMergeSimple.ktr",
                LogWriter.LOG_LEVEL_ERROR,
                AllRunTests.getOldTargetDatabase(),
                AllRunTests.getNewTargetDatabase(),
                1000000
            );
        timedTransRunner.runOldAndNew();

        be.ibridge.kettle.core.Result oldResult = timedTransRunner.getOldResult();
        assertTrue(oldResult.getNrErrors()==0);

        Result newResult = timedTransRunner.getNewResult();
        assertTrue(newResult.getNrErrors()==0);
    }
}

Fix for the sorted merge step

Fix for the sorted merge step

git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@4014 5fb7f6ec-07c1-534a-b4ca-9155e429e800


package io.liveoak.security.spi;

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

/**
 * @author Bob McWhirter
 */
public class AuthzPolicyGroup {

    public AuthzPolicyGroup() {
        this.entries = new ArrayList<>();
    }

    public AuthzPolicyGroup(List<AuthzPolicyEntry> entries) {
        this.entries = entries;
    }

    public List<AuthzPolicyEntry> entries() {
        return this.entries;
    }

    public void entries(List<AuthzPolicyEntry> entries) {
        this.entries = entries;
    }

    private List<AuthzPolicyEntry> entries;

}

package io.liveoak.security.spi;

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

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * @author Bob McWhirter
 */
public class AuthzPolicyGroup {

    public AuthzPolicyGroup() {
        this.entries = new ArrayList<>();
    }

    public AuthzPolicyGroup(List<AuthzPolicyEntry> entries) {
        this.entries = entries;
    }

    public List<AuthzPolicyEntry> entries() {
        return this.entries;
    }

    public void entries(List<AuthzPolicyEntry> entries) {
        this.entries = entries;
    }

    @JsonProperty("policies")
    private List<AuthzPolicyEntry> entries;

}

Fix root element of authz-config.json to be 'policies'


package uk.ac.ebi.atlas.model.resource;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public abstract class AtlasResource<T> {

    protected final Path path;

    AtlasResource(Path path) {
        this.path = path;
    }

    public boolean exists() {
        return Files.exists(path);
    }

    public boolean existsAndIsNonEmpty() {
        return exists() && (
                path.toFile().isDirectory()
                        ? path.toFile().list().length > 0
                        : path.toFile().length() > 0
        );
    }

    public boolean isReadable() {
        return Files.isReadable(path);
    }

    public abstract T get();

    public Reader getReader() throws IOException {
        return Files.newBufferedReader(path, StandardCharsets.UTF_8);
    }

    public long size() {
        return path.toFile().length();
    }

    @Override
    public String toString() {
        return this.getClass().getName() + " with path " + path.toString();
    }

}

package uk.ac.ebi.atlas.model.resource;

import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public abstract class AtlasResource<T> {

    protected final Path path;

    AtlasResource(Path path) {
        this.path = path;
    }

    public boolean exists() {
        return Files.exists(path);
    }

    public boolean existsAndIsNonEmpty() {
        return exists() && (
                path.toFile().isDirectory()
                        ? path.toFile().list().length > 0
                        : path.toFile().length() > 0
        );
    }

    public boolean isReadable() {
        return Files.isReadable(path);
    }

    public abstract T get();

    public Reader getReader() throws IOException {
        return Files.newBufferedReader(path, StandardCharsets.UTF_8);
    }

    public long size() {
        return path.toFile().length();
    }

    @Override
    public String toString() {
        return this.getClass().getSimpleName() + " with path " + path.toString();
    }

}

Simplify log messages in bioentities/buildIndex/status


package helloworld;

import static org.requirementsascode.UseCaseModelBuilder.newBuilder;

import java.util.function.Consumer;

import org.requirementsascode.UseCaseModel;
import org.requirementsascode.UseCaseModelBuilder;
import org.requirementsascode.UseCaseModelRunner;

public class HelloWorld01_PrintHelloUserExample {

	public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) {
		UseCaseModel useCaseModel =
			modelBuilder.useCase("Get greeted")
				.basicFlow()
					.step("S1").system(greetUser())
				.build();
		return useCaseModel;
	}

	private Consumer<UseCaseModelRunner> greetUser() {
		return r -> System.out.println("Hello, User.");
	}

	public static void main(String[] args){
		HelloWorld01_PrintHelloUserExample example = new HelloWorld01_PrintHelloUserExample();
		example.start();
	}

	private void start() {
		UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner();
		UseCaseModel useCaseModel = buildWith(newBuilder());
		useCaseModelRunner.run(useCaseModel);
	}
}

package helloworld;

import static org.requirementsascode.UseCaseModelBuilder.newBuilder;

import org.requirementsascode.UseCaseModel;
import org.requirementsascode.UseCaseModelBuilder;
import org.requirementsascode.UseCaseModelRunner;

public class HelloWorld01_PrintHelloUserExample {

	public UseCaseModel buildWith(UseCaseModelBuilder modelBuilder) {
		UseCaseModel useCaseModel =
			modelBuilder.useCase("Get greeted")
				.basicFlow()
					.step("S1").system(this::greetUser)
				.build();
		return useCaseModel;
	}

	private void greetUser(UseCaseModelRunner runner) {
		System.out.println("Hello, User.");
	}

	public static void main(String[] args){
		HelloWorld01_PrintHelloUserExample example = new HelloWorld01_PrintHelloUserExample();
		example.start();
	}

	private void start() {
		UseCaseModelRunner useCaseModelRunner = new UseCaseModelRunner();
		UseCaseModel useCaseModel = buildWith(newBuilder());
		useCaseModelRunner.run(useCaseModel);
	}
}

Refactor to use method references

Refactor to use method references


package app;

import java.util.Observable;
import java.util.Observer;

/**
 * Created by Benjamin on 03/02/2016.
 */
public class ShippingTrackerObserver implements Observer {
	@Override
	public void update(Observable o, Object arg) {

	}
}

package app;

import app.action.Action;
import app.action.ActionEvent;
import app.action.Drop;
import app.shipper.BasicShipper;

import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * Created by Benjamin on 03/02/2016.
 */
public class ShippingTrackerObserver implements Observer {
	List<String> achievedDeliveries = new ArrayList<>();

	@Override
	public void update(Observable o, Object arg) {
		ActionEvent actionEvent = (ActionEvent) arg;

		if(o instanceof Drop && actionEvent.equals(ActionEvent.ENDED)) {

			Drop action = (Drop) o;
			System.out.printf("\n\t[DELIVERY DONE] %s has performed package %s\n", action.getTarget().getName(), action.getTarget().getPack());

		}
	}
}

Add basic code into new Spy

Add basic code into new Spy


package com.sequenceiq.environment.environment.validation.validators;

import static com.sequenceiq.cloudbreak.common.mappable.CloudPlatform.GCP;

import java.util.Map;
import java.util.Optional;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors;
import com.sequenceiq.cloudbreak.cloud.model.CloudPlatformVariant;
import com.sequenceiq.cloudbreak.cloud.model.Platform;
import com.sequenceiq.cloudbreak.cloud.model.Variant;
import com.sequenceiq.cloudbreak.validation.ValidationResult;

@Component
public class TagValidator {

    private final CloudPlatformConnectors cloudPlatformConnectors;

    public TagValidator(CloudPlatformConnectors cloudPlatformConnectors) {
        this.cloudPlatformConnectors = cloudPlatformConnectors;
    }

    public ValidationResult validateTags(String cloudPlatform, Map<String, String> tags) {
        //TODO gcp ignored due to special tag handling in gcp. remove this when cb factory tags (like Owner) sanitized in the env request
        if (GCP.name().equalsIgnoreCase(cloudPlatform)) {
            return ValidationResult.empty();
        }
        Optional<com.sequenceiq.cloudbreak.cloud.TagValidator> tagValidatorConnector = getTagValidatorConnector(cloudPlatform);
        if (tagValidatorConnector.isEmpty()) {
            return ValidationResult.empty();
        }
        return tagValidatorConnector.get().validateTags(tags);

    }

    private Optional<com.sequenceiq.cloudbreak.cloud.TagValidator> getTagValidatorConnector(String cloudPlatform) {
        CloudPlatformVariant cloudPlatformVariant = new CloudPlatformVariant(Platform.platform(cloudPlatform), Variant.variant(cloudPlatform));
        return Optional.ofNullable(cloudPlatformConnectors.get(cloudPlatformVariant).parameters().tagValidator());
    }
}

package com.sequenceiq.environment.environment.validation.validators;

import java.util.Map;
import java.util.Optional;

import org.springframework.stereotype.Component;

import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors;
import com.sequenceiq.cloudbreak.cloud.model.CloudPlatformVariant;
import com.sequenceiq.cloudbreak.cloud.model.Platform;
import com.sequenceiq.cloudbreak.cloud.model.Variant;
import com.sequenceiq.cloudbreak.validation.ValidationResult;

@Component
public class TagValidator {

    private final CloudPlatformConnectors cloudPlatformConnectors;

    public TagValidator(CloudPlatformConnectors cloudPlatformConnectors) {
        this.cloudPlatformConnectors = cloudPlatformConnectors;
    }

    public ValidationResult validateTags(String cloudPlatform, Map<String, String> tags) {
        Optional<com.sequenceiq.cloudbreak.cloud.TagValidator> tagValidatorConnector = getTagValidatorConnector(cloudPlatform);
        if (tagValidatorConnector.isEmpty()) {
            return ValidationResult.empty();
        }
        return tagValidatorConnector.get().validateTags(tags);

    }

    private Optional<com.sequenceiq.cloudbreak.cloud.TagValidator> getTagValidatorConnector(String cloudPlatform) {
        CloudPlatformVariant cloudPlatformVariant = new CloudPlatformVariant(Platform.platform(cloudPlatform), Variant.variant(cloudPlatform));
        return Optional.ofNullable(cloudPlatformConnectors.get(cloudPlatformVariant).parameters().tagValidator());
    }
}

Revert "CB-11008 in case of gcp the tag validation will be switched off on environmentcreationdto until the gcp tag sanitization is used only cluster request"

This reverts commit eeb479886c91dee6b2216874f00a09a68265d803.


/*
 * Copyright 2015-2020 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * https://www.eclipse.org/legal/epl-v20.html
 */

package org.junit.platform.launcher.listeners;

import static org.apiguardian.api.API.Status.EXPERIMENTAL;

import org.apiguardian.api.API;
import org.junit.platform.launcher.TestExecutionListener;

/**
 * A {@link TestExecutionListener} that generates Java Flight Recorder
 * events.
 *
 * @see JEP 328: Flight Recorder
 * @since 1.7
 */
@API(status = EXPERIMENTAL, since = "1.7")
public class FlightRecordingListener implements TestExecutionListener {
}

/*
 * Copyright 2015-2020 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v2.0 which
 * accompanies this distribution and is available at
 *
 * https://www.eclipse.org/legal/epl-v20.html
 */

package org.junit.platform.launcher.listeners;

import static org.apiguardian.api.API.Status.EXPERIMENTAL;

import org.apiguardian.api.API;
import org.junit.platform.engine.TestExecutionResult;
import org.junit.platform.launcher.TestExecutionListener;
import org.junit.platform.launcher.TestIdentifier;
import org.junit.platform.launcher.TestPlan;

/**
 * A {@link TestExecutionListener} that generates Java Flight Recorder
 * events.
 *
 * @see JEP 328: Flight Recorder
 * @since 1.7
 */
@API(status = EXPERIMENTAL, since = "1.7")
public class FlightRecordingListener implements TestExecutionListener {

	@Override
	public void testPlanExecutionStarted(TestPlan testPlan) {

	}

	@Override
	public void testPlanExecutionFinished(TestPlan testPlan) {

	}

	@Override
	public void dynamicTestRegistered(TestIdentifier testIdentifier) {

	}

	@Override
	public void executionSkipped(TestIdentifier testIdentifier, String reason) {

	}

	@Override
	public void executionStarted(TestIdentifier testIdentifier) {

	}

	@Override
	public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {

	}
}

Synchronize API of base type and versioned type


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

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

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

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add 'type' field to tab enumeration JSON protocol

Review URL: https://codereview.chromium.org/12036084

git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@1132 fc8a088e-31da-11de-8fef-1f5ae417a2df


package com.squareup.seismic.sample;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.seismic.ShakeDetector;

import static android.view.Gravity.CENTER;
import static android.view.ViewGroup.LayoutParams;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class Demo extends Activity implements ShakeDetector.Listener {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    ShakeDetector sd = new ShakeDetector(this);
    sd.start(sensorManager);

    TextView tv = new TextView(this);
    tv.setGravity(CENTER);
    tv.setText("Shake me, bro!");
    setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
  }

  public void hearShake() {
    Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
  }
}

package com.squareup.seismic.sample;

import android.app.Activity;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.seismic.ShakeDetector;

import static android.view.Gravity.CENTER;
import static android.view.ViewGroup.LayoutParams;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;

public class Demo extends Activity implements ShakeDetector.Listener {
  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    ShakeDetector sd = new ShakeDetector(this);
    sd.start(sensorManager);

    TextView tv = new TextView(this);
    tv.setGravity(CENTER);
    tv.setText("Shake me, bro!");
    setContentView(tv, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
  }

  @Override public void hearShake() {
    Toast.makeText(this, "Don't shake me, bro!", Toast.LENGTH_SHORT).show();
  }
}

Add @Override annotation for implemented method

`hearShake` is implemented from `ShakeDetector.Listener`.


package com.opencredo.concourse.mapping.events.methods.ordering;

import com.opencredo.concourse.domain.events.Event;
import com.opencredo.concourse.domain.events.EventType;

import java.util.Comparator;
import java.util.Map;

public final class CausalOrdering {

    public static final int INITIAL = Integer.MIN_VALUE;
    public static final int TERMINAL = Integer.MAX_VALUE;
    public static final int PRE_TERMINAL = TERMINAL - 1;

    private CausalOrdering() {
    }

    public static Comparator<Event> onEventTypes(Map<EventType, Integer> eventTypeMap) {
        return Comparator.comparing((Event evt) -> eventTypeMap.getOrDefault(EventType.of(evt), PRE_TERMINAL))
                .thenComparing(Event::getEventTimestamp);
    }
}

package com.opencredo.concourse.mapping.events.methods.ordering;

import com.opencredo.concourse.domain.events.Event;
import com.opencredo.concourse.domain.events.EventCharacteristics;
import com.opencredo.concourse.domain.events.EventType;

import java.util.Comparator;
import java.util.Map;

public final class CausalOrdering {

    public static final int INITIAL = Integer.MIN_VALUE;
    public static final int TERMINAL = Integer.MAX_VALUE;
    public static final int PRE_TERMINAL = TERMINAL - 1;

    private CausalOrdering() {
    }

    public static Comparator<Event> onEventTypes(Map<EventType, Integer> eventTypeMap) {
        return Comparator.comparing((Event evt) -> eventTypeMap.getOrDefault(EventType.of(evt),
                getDefaultOrderBasedOnCharacteristics(evt)))
                .thenComparing(Event::getEventTimestamp);
    }

    private static int getDefaultOrderBasedOnCharacteristics(Event evt) {
        return evt.hasCharacteristic(EventCharacteristics.IS_INITIAL)
            ? INITIAL
            : evt.hasCharacteristic(EventCharacteristics.IS_TERMINAL)
                ? TERMINAL
                : PRE_TERMINAL;
    }
}

Use event characteristics in causal ordering


package net.happygiraffe.jslint;

/**
 * Base class for an {@link Option} binding.
 *
 * @author dom
 * @version $Id$
 */
public abstract class AbstractOptionInstance implements OptionInstance {

    private final Option option;

    /**
     * Create a new instance and associate it with <i>option</i>.
     */
    public AbstractOptionInstance(Option option) {
        this.option = option;
    }

    /**
     * Return the option associated with this instance.
     */
    public Option getOption() {
        return option;
    }

}

package net.happygiraffe.jslint;

/**
 * Base class for an {@link Option} binding.
 *
 * @author dom
 * @version $Id$
 */
public abstract class AbstractOptionInstance implements OptionInstance {

    private final Option option;

    /**
     * Create a new instance and associate it with <i>option</i>.
     */
    public AbstractOptionInstance(Option option) {
        this.option = option;
    }

    /**
     * Return the option associated with this instance.
     */
    public Option getOption() {
        return option;
    }

    @Override
    public String toString() {
        return option.getLowerName() + "=" + getValue();
    }

}

Add a default toString() for OptionInstances.


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

/** Critical logging level for items that are not errors but still important. */
public class Level extends org.apache.log4j.Level {

    /** Integer representation of logging level. */
    public static final int CRITICAL_INT = 60000;

    /** Critical logging level. */
    public static final Level CRITICAL = new Level();

    /** Serial version UID. */
    private static final long serialVersionUID = -104586023689772363L;

    /** Constructor. */
    protected Level(){
        super(CRITICAL_INT, "CRITICAL", 0);
    }
}

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

/**
 * Additional logging levels.
 *
 *

 *
CRITIAL - for messages that should always be logged but not be errors

 *
TRAIL - equivalent to TRACE introduced in later versions of Log4j

 *

 */
public class Level extends org.apache.log4j.Level {

    /** Integer representation of CRITICIAL logging level. */
    public static final int CRITICAL_INT = 60000;

    /** Integer representation of TRAIL logging level. */
    public static final int TRAIL_INT = 5000;

    /** Critical logging level. */
    public static final Level CRITICAL = new Level(CRITICAL_INT, "CRITICAL", 0);

    /** Trail logging level. */
    public static final Level TRAIL = new Level(TRAIL_INT, "TRACE", 7);

    /** Serial version UID. */
    private static final long serialVersionUID = -8920329210711643389L;

    /**
     * Constructor.
     *
     * @param level integer representation of the logging level
     * @param name human readable name for the logging level
     * @param sysLogLevel corresponding syslog level
     */
    protected Level(int level, String name, int sysLogLevel){
        super(level, name, sysLogLevel);
    }
}

Add TRACE-equivalent level (that won't conflict with TRACE if people are using newer log4j levels)

git-svn-id: 46308aa6df3a13aea5930e6665b35c8b83c3a711@395 9fbd0cf9-a10c-0410-82c1-be8c084f3200


class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n)
				throws ClassNotFoundException {
				return findSystemClass(n);
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n, boolean resolve)
				      throws ClassNotFoundException {
				Class cl = findSystemClass(n);
				if (resolve) {
				      resolveClass(cl);
				}
				return cl;
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

Update wrt. new JDK 1.2 ClassLoader scheme.


/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.rest.utils;

public class Utility {

    @FunctionalInterface
    public interface Action {
        void doIt();
    }

    /**
     * Perform the given action if the object is not null
     *
     * @param obj The object to check for null
     * @param action The action to perform if object is not null
     */
    public static void performIfNotNull(Object obj, Action action) {
        if(obj != null) {
            action.doIt();
        }
    }

}

/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.rest.utils;

public class Utility {

    /**
     * Perform the given action if the object is not null
     *
     * @param obj The object to check for null
     * @param action The action to perform if object is not null
     */
    public static void performIfNotNull(Object obj, Runnable action) {
        if(obj != null) {
            action.run();
        }
    }

}

Use standard jdk functional interface in rest utility method performIfNotNull


package net.optifine.render;

public class ChunkVisibility {

}

package net.optifine.render;

public class ChunkVisibility {
    private static int counter;
    private static int iMaxStatic;

    private static int iMaxStaticFinal;

    //private static World worldLast = null;
    private static int pcxLast;
    private static int pczLast;
}

Fix some mixin warnings aboufields that d don't exist


package org.seqdoop.hadoop_bam;

import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class TestVCFFormat {

  @Test
  public void testInferFromFilePath() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
    assertNull(VCFFormat.inferFromFilePath("test.sam"));
  }

  @Test
  public void testInferFromData() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
    assertNull(VCFFormat.inferFromData(stream("test.sam")));
  }

  private InputStream stream(String resource) throws IOException {
    return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
  }
}

package org.seqdoop.hadoop_bam;

import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

public class TestVCFFormat {

  @Test
  public void testInferFromFilePath() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.bgzf.gz"));
    assertNull(VCFFormat.inferFromFilePath("test.sam"));
  }

  @Test
  public void testInferFromData() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.gz")));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.bgzf.gz")));
    assertNull(VCFFormat.inferFromData(stream("test.sam")));
  }

  private InputStream stream(String resource) throws IOException {
    return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
  }
}

Add .gz and bgzf.gz files to infer unit tests


package com.google.sps.data;

import java.util.List;

public class GenerateScheduleRequest {
  List<Course> courses;
  InputCriterion criterion;
  BasicInfo basicInfo;

  public GenerateScheduleRequest(){};

  public List<Course> getCourses() {
    return this.courses;
  }

  public List<TimeRange> getTimePreferences() {
    return this.criterion.timePreferences;
  }

  public String getPreferredSubject() {
    return this.criterion.preferredSubject;
  }

  public Invariants getCredits() {
    return this.basicInfo.credits;
  }

  public String getTermStartDate() {
    return this.basicInfo.termDates.startDate;
  }

  public String getTermEndDate() {
    return this.basicInfo.termDates.endDate;
  }
}

class InputCriterion {
  List<TimeRange> timePreferences;
  String preferredSubject;
}

class BasicInfo {
  Invariants credits;
  TermDates termDates;
}

class TermDates {
  String startDate;
  String endDate;
}

package com.google.sps.data;

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

public class GenerateScheduleRequest {
  List<Course> courses;
  InputCriterion criterion;
  BasicInfo basicInfo;

  public GenerateScheduleRequest(){};

  public List<Course> getCourses() {
    return this.courses;
  }

  public List<TimeRange> getTimePreferences() {
    return this.criterion.timePreferences;
  }

  public String getPreferredSubject() {
    return this.criterion.preferredSubject;
  }

  public HashMap<String, Integer> getCourseScores() {
    return this.criterion.courseScores;
  }

  public Invariants getCredits() {
    return this.basicInfo.credits;
  }

  public String getTermStartDate() {
    return this.basicInfo.termDates.startDate;
  }

  public String getTermEndDate() {
    return this.basicInfo.termDates.endDate;
  }
}

class InputCriterion {
  List<TimeRange> timePreferences;
  String preferredSubject;
  HashMap<String, Integer> courseScores;
}

class BasicInfo {
  Invariants credits;
  TermDates termDates;
}

class TermDates {
  String startDate;
  String endDate;
}

Add courseScores hashmap for course priority ranking


package com.vaguehope.onosendai.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashHelper {

	private HashHelper () {
		throw new AssertionError();
	}

	public static BigInteger md5String (final String s) {
		final MessageDigest md = MD_MD5_FACTORY.get();
		md.update(getBytes(s), 0, s.length());
		return new BigInteger(1, md.digest());
	}

	private static byte[] getBytes (final String s) {
		try {
			return s.getBytes("UTF-8");
		}
		catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	/**
	 * MessageDigest.getInstance("MD5") can take up to a second, so using this
	 * to cache it and improve performance.
	 */
	private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
		@Override
		protected MessageDigest initialValue () {
			try {
				final MessageDigest md = MessageDigest.getInstance("MD5");
				md.reset();
				return md;
			}
			catch (final NoSuchAlgorithmException e) {
				throw new IllegalStateException("JVM is missing MD5.", e);
			}
		}
	};

}

package com.vaguehope.onosendai.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashHelper {

	private HashHelper () {
		throw new AssertionError();
	}

	public static BigInteger md5String (final String s) {
		final MessageDigest md = MD_MD5_FACTORY.get();
		md.update(getBytes(s));
		return new BigInteger(1, md.digest());
	}

	private static byte[] getBytes (final String s) {
		try {
			return s.getBytes("UTF-8");
		}
		catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	/**
	 * MessageDigest.getInstance("MD5") can take up to a second, so using this
	 * to cache it and improve performance.
	 */
	private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
		@Override
		protected MessageDigest initialValue () {
			try {
				final MessageDigest md = MessageDigest.getInstance("MD5");
				md.reset();
				return md;
			}
			catch (final NoSuchAlgorithmException e) {
				throw new IllegalStateException("JVM is missing MD5.", e);
			}
		}
	};

}

Fix possible issue when MD5ing multibyte strings.


package net.christophermerrill.FancyFxTree;

import javafx.event.*;
import javafx.scene.control.*;
import javafx.scene.input.*;

/**
 * Intercepts double-click events BEFORE the tree can use it for expand/collapsing of nodes. Provided
 * with a MouseListener, this allows the double-click event to be used for editing the node, rather than
 * expand/collapse.
 *
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
class DoubleClickInterceptor implements EventDispatcher
    {
    DoubleClickInterceptor(TreeCell cell, EventHandler<MouseEvent> double_click_listener)
        {
        _original_dispatcher = cell.getEventDispatcher();
        cell.setEventDispatcher(this);
        _double_click_listener = double_click_listener;
        }

    @Override
    public Event dispatchEvent(Event event, EventDispatchChain tail)
        {
        if (event instanceof MouseEvent)
            {
            MouseEvent mouse_event = (MouseEvent) event;
            if (mouse_event.getEventType().equals(MouseEvent.MOUSE_PRESSED)
                && mouse_event.getButton() == MouseButton.PRIMARY
                && mouse_event.getClickCount() >= 2
                && !event.isConsumed())
                {
                _double_click_listener.handle(mouse_event);
                event.consume();
                }
            }
        return _original_dispatcher.dispatchEvent(event, tail);
        }

    private final EventDispatcher _original_dispatcher;
    private final EventHandler<MouseEvent> _double_click_listener;
    }

package net.christophermerrill.FancyFxTree;

import javafx.event.*;
import javafx.scene.control.*;
import javafx.scene.input.*;

/**
 * Intercepts double-click events BEFORE the tree can use it for expand/collapsing of nodes. Provided
 * with a MouseListener, this allows the double-click event to be used for editing the node, rather than
 * expand/collapse.
 *
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
class DoubleClickInterceptor
    {
    DoubleClickInterceptor(TreeCell cell, EventHandler<MouseEvent> double_click_listener)
        {
        _double_click_listener = double_click_listener;
        cell.addEventHandler(MouseEvent.ANY, event ->
	        {
	        if (event.getClickCount() == 2 && event.getButton().equals(MouseButton.PRIMARY))
		        {
		        if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED))
		        	_double_click_listener.handle(event);
	            event.consume();
		        }
	        });
        }

    private final EventHandler<MouseEvent> _double_click_listener;
    }

Switch to using a mouse event handler instead of EventDispatcher


import mmcorej.TaggedImage;

import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.TaggedImageStorage;

public class ReadDataSet {

   public static void main(String[] args) {
      //String rootName = "C:/AcqusitionData/Tests/Test-A_1";
      String rootName = "C:/AcqusitionData/20130813 Oxidative Stress Test 3/NIH3T3_1";

      try {
         TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName);
         JSONObject summary = storage.getSummaryMetadata();
         System.out.println(summary.toString(3));

         int numChannels = summary.getInt("Channels");
         int numSlices = summary.getInt("Slices");
         int numFrames = summary.getInt("Frames");
         int numPositions = summary.getInt("Positions");

         for (int pos=0; pos < numPositions; pos++) {
            for (int fr=0; fr<numFrames; fr++) {
               TaggedImage img = storage.getImage(0, 0, fr, pos);
               System.out.println(img.tags.toString(3));
            }
         }

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

   }

}

import mmcorej.TaggedImage;

import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.MMTags;
import org.micromanager.api.TaggedImageStorage;

public class ReadDataSet {

   public static void main(String[] args) {
      String rootName = "C:/AcqusitionData/Tests/Test-A_1";

      try {
         TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName);
         JSONObject summary = storage.getSummaryMetadata();
         System.out.println(summary.toString(3));

         int numChannels = summary.getInt(MMTags.Summary.CHANNELS);
         int numSlices = summary.getInt(MMTags.Summary.SLICES);
         int numFrames = summary.getInt(MMTags.Summary.FRAMES);
         int numPositions = summary.getInt(MMTags.Summary.POSITIONS);

         for (int pos=0; pos < numPositions; pos++) {
            for (int t=0; t<numFrames; t++) {
               for (int z=0; z<numSlices; z++) {
                  for (int ch=0; ch<numChannels; ch++) {
                     TaggedImage img = storage.getImage(ch, z, t, pos);
                     Object pixels = img.pix;
                     // TODO: do something with pixels

                     System.out.println(img.tags.toString(3));
                  }
               }
            }
         }

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

   }

}

Read data set up updated

Read data set up updated

git-svn-id: 03a8048b5ee8463be5048a3801110fb50f378627@11903 d0ab736e-dc22-4aeb-8dc9-08def0aa14fd


/*******************************************************************************
 * Copyright (c) 2012-2016 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package org.eclipse.che.api.core;

/**
 * Error codes that are used in exceptions.
 *
 * @author Igor Vinokur
 */
public class ErrorCodes {
    private ErrorCodes() {
    }

    public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216;
    public static final int UNABLE_GET_PRIVATE_SSH_KEY         = 32068;
    public static final int UNAUTHORIZED_GIT_OPERATION         = 32080;
    public static final int MERGE_CONFLICT                     = 32062;
    public static final int FAILED_CHECKOUT                    = 32063;
    public static final int FAILED_CHECKOUT_WITH_START_POINT   = 32064;
    public static final int INIT_COMMIT_WAS_NOT_PERFORMED      = 32082;
}

/*******************************************************************************
 * Copyright (c) 2012-2016 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package org.eclipse.che.api.core;

/**
 * Error codes that are used in exceptions.
 * Defined error codes MUST BE in range <b>15000-32999</b> inclusive.
 *
 * @author Igor Vinokur
 */
public class ErrorCodes {
    private ErrorCodes() {
    }

    public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216;
    public static final int UNABLE_GET_PRIVATE_SSH_KEY         = 32068;
    public static final int UNAUTHORIZED_GIT_OPERATION         = 32080;
    public static final int MERGE_CONFLICT                     = 32062;
    public static final int FAILED_CHECKOUT                    = 32063;
    public static final int FAILED_CHECKOUT_WITH_START_POINT   = 32064;
    public static final int INIT_COMMIT_WAS_NOT_PERFORMED      = 32082;
}

Add comment which defines error codes range


/** Defines classes and interfaces of the Processor API. */
module processor {
  requires java.compiler;
  requires jdk.javadoc;

  provides com.sun.source.util.Plugin with
      processor.ShowPlugin;
  provides javax.annotation.processing.Processor with
      processor.ShowProcessor;
}

/** Defines classes and interfaces of the Processor API. */
module processor {
  requires jdk.compiler;
  requires jdk.javadoc;

  provides com.sun.source.util.Plugin with
      processor.ShowPlugin;
  provides javax.annotation.processing.Processor with
      processor.ShowProcessor;
}

Read `jdk.compiler` module in processing-code example


package com.alexrnl.commons.io;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utility methods for IO stuff.

 * @author Alex
 */
public final class IOUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(IOUtils.class.getName());

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private IOUtils () {
		super();
	}

	/**
	 * Read the next line on the buffered reader provided.

	 * @param reader
	 *        the stream to read.
	 * @return the next line in the stream.
	 * @throws IOException
	 *         if there was an issue when reading the stream.
	 * @throws EOFException
	 *         if the line returned is null.
	 */
	public static String readLine (final BufferedReader reader) throws IOException, EOFException {
		Objects.requireNonNull(reader);
		final String line = reader.readLine();
		if (lg.isLoggable(Level.FINE)) {
			lg.fine("Read line: " + line);
		}
		if (line == null) {
			throw new EOFException("End of stream reached");
		}
		return line;
	}
}

package com.alexrnl.commons.io;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utility methods for IO stuff.

 * @author Alex
 */
public final class IOUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(IOUtils.class.getName());

	/** The byte order mark used at the beginning of unicode files */
	public static final Character UNICODE_BYTE_ORDER_MARK = '\ufeff';

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private IOUtils () {
		super();
	}

	/**
	 * Read the next line on the buffered reader provided.

	 * @param reader
	 *        the stream to read.
	 * @return the next line in the stream.
	 * @throws IOException
	 *         if there was an issue when reading the stream.
	 * @throws EOFException
	 *         if the line returned is null.
	 */
	public static String readLine (final BufferedReader reader) throws IOException, EOFException {
		Objects.requireNonNull(reader);
		final String line = reader.readLine();
		if (lg.isLoggable(Level.FINE)) {
			lg.fine("Read line: " + line);
		}
		if (line == null) {
			throw new EOFException("End of stream reached");
		}
		return line;
	}
}

Add constant for unicode byte order mark


package com.uwetrottmann.shopr.settings;

import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Quick access to some app settings.
 */
public class AppSettings {

    private static final String KEY_MAX_RECOMMENDATIONS = "com.uwetrottmann.shopr.maxrecommendations";

    public static int getMaxRecommendations(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                KEY_MAX_RECOMMENDATIONS, 8);
    }
}

package com.uwetrottmann.shopr.settings;

import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Quick access to some app settings.
 */
public class AppSettings {

    private static final String KEY_MAX_RECOMMENDATIONS = "com.uwetrottmann.shopr.maxrecommendations";

    public static int getMaxRecommendations(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                KEY_MAX_RECOMMENDATIONS, 9);
    }
}

Set max recs to 9.

Set max recs to 9.


package net.darkhax.bookshelf.api.registry;

import net.minecraft.resources.ResourceLocation;

import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public interface IRegistryReader<T> extends Iterable<T> {

    @Nullable
    T get(ResourceLocation id);

    @Nullable
    ResourceLocation getId(T value);

    default Stream<T> streamValues() {

        return StreamSupport.stream(spliterator(), false);
    }

    default Stream<T> parallelStreamValues() {

        return StreamSupport.stream(spliterator(), true);
    }
}

package net.darkhax.bookshelf.api.registry;

import net.minecraft.resources.ResourceLocation;

import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public interface IRegistryReader<T> extends Iterable<T> {

    @Nullable
    T get(ResourceLocation id);

    @Nullable
    ResourceLocation getId(T value);

    default ResourceLocation getId(T value, ResourceLocation fallback) {

        final ResourceLocation id = this.getId(value);
        return id != null ? id : fallback;
    }

    default Stream<T> streamValues() {

        return StreamSupport.stream(spliterator(), false);
    }

    default Stream<T> parallelStreamValues() {

        return StreamSupport.stream(spliterator(), true);
    }
}

Add a registry reader method that gets an ID with an optional fallback.


package com.codepath.simpletodo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

package com.codepath.simpletodo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    ArrayList<String> items;
    ArrayAdapter<String> itemsAdapter;
    ListView lvItems;

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

        lvItems = (ListView) findViewById(R.id.lvItems);
        items = new ArrayList<String>();
        itemsAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items);

        lvItems.setAdapter(itemsAdapter);
        items.add("First Item");
        items.add("Second Item");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Add static items to the list view

Add static items to the list view


package org.ops4j.pax.jdbc.test.pool;

import javax.inject.Inject;

import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.util.Filter;
import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory;
import org.ops4j.pax.jdbc.test.AbstractJdbcTest;

public class PoolAriesTest extends AbstractJdbcTest {

    @Inject @Filter("(pool=aries)(xa=false)")
    PooledDataSourceFactory pool;

    @Configuration
    public Option[] config() {
        return new Option[] { //
                regressionDefaults(), //
                poolDefaults(), //
                mvnBundle("org.apache.geronimo.components", "geronimo-connector"),
                mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"),
                mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"),
                };
    }

    @Test
    public void testPooledDataSourceFactoryServicesPresent() {
    }

}

package org.ops4j.pax.jdbc.test.pool;

import javax.inject.Inject;

import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.util.Filter;
import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory;
import org.ops4j.pax.jdbc.test.AbstractJdbcTest;

public class PoolAriesTest extends AbstractJdbcTest {

    @Inject @Filter("(pool=aries)(xa=false)")
    PooledDataSourceFactory pool;

    @Configuration
    public Option[] config() {
        return new Option[] { //
                regressionDefaults(), //
                poolDefaults(), //
                mvnBundle("commons-logging", "commons-logging"),
                mvnBundle("org.apache.geronimo.components", "geronimo-connector"),
                mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"),
                mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"),
                };
    }

    @Test
    public void testPooledDataSourceFactoryServicesPresent() {
    }

}

[PAXJDBC-124] Fix missing itest dependency for aries-pool


package chart_parser;

import java.util.HashMap;

import cat_combination.SuperCategory;

public class CategoryEquivalence {
	/*
	 * keys are triples of (position, span, SuperCategory); value becomes the *last*
	 * SuperCategory in the linked list of equivalents
	 */
	// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
	private HashMap<EquivKey, SuperCategory> equiv;

	public CategoryEquivalence(int initCapacity) {
		equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
	}

	/*
	 * returns true if equivalent category not already there, false otherwise
	 */
	public boolean add(int position, int span, SuperCategory superCat) {
		EquivKey equivKey = new EquivKey(position, span, superCat);
		SuperCategory value = equiv.get(equivKey);
		equiv.put(equivKey, superCat);
		// overrides the previous value (if there was one)

		if (value != null) {
			value.next = superCat;
			return false;
		} else {
			return true;
		}
	}

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

package chart_parser;

import java.util.HashMap;

import cat_combination.SuperCategory;

public class CategoryEquivalence {
	/*
	 * keys are triples of (position, span, SuperCategory); value becomes the *last*
	 * SuperCategory in the linked list of equivalents
	 */
	// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
	private HashMap<EquivKey, SuperCategory> equiv;

	public CategoryEquivalence(int initCapacity) {
		equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
	}

	/*
	 * returns true if equivalent category not already there, false otherwise
	 */
	public boolean add(int position, int span, SuperCategory superCat) {
		EquivKey equivKey = new EquivKey(position, span, superCat);
		SuperCategory previousValue = equiv.put(equivKey, superCat);
		// put() returns the previous value, or null if there was no mapping for the key

		if (previousValue != null) {
			previousValue.next = superCat;
			return false;
		} else {
			return true;
		}
	}

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

Modify add() to save one extra get() call to HashMap.


package com.opera.core.systems.scope.stp;

import java.util.logging.Logger;

import com.opera.core.systems.util.SocketMonitor;
import com.opera.core.systems.scope.handlers.IConnectionHandler;

/**
 *
 * @author Jan Vidar Krey
 */
public class StpThread extends Thread {

    private final Logger logger = Logger.getLogger(this.getClass().getName());
    private StpConnectionListener listener;
    private StpConnection stpConnection;
    private boolean running = true;

    public StpThread(int port, IConnectionHandler handler) throws java.io.IOException
    {
        super("StpThread");
        SocketMonitor.instance();
        listener = new StpConnectionListener(port, handler);
        start();
    }

    public void shutdown() {
        running = false;
        SocketMonitor.instance().stop();
    }

    @Override
    public void run() {
        logger.info("Started StpThread.");
        while (running)
        {
            SocketMonitor.poll(50);
        }
        logger.info("Stopping StpThread.");
    }

}

package com.opera.core.systems.scope.stp;

import java.util.logging.Logger;

import com.opera.core.systems.util.SocketMonitor;
import com.opera.core.systems.scope.handlers.IConnectionHandler;

/**
 *
 * @author Jan Vidar Krey
 */
public class StpThread extends Thread {

    private final Logger logger = Logger.getLogger(this.getClass().getName());
    private StpConnectionListener listener;
    private StpConnection stpConnection;
    private boolean running = true;

    public StpThread(int port, IConnectionHandler handler) throws java.io.IOException
    {
        super("StpThread");
        SocketMonitor.instance();
        listener = new StpConnectionListener(port, handler);
        start();
    }

    public void shutdown() {
        running = false;
        listener.stop();
        SocketMonitor.instance().stop();
    }

    @Override
    public void run() {
        logger.info("Started StpThread.");
        while (running)
        {
            SocketMonitor.poll(50);
        }
        logger.info("Stopping StpThread.");
    }

}

Make sure we close the STP connection listener when stopping the STP thread.


/**
 *
 */
package ca.eandb.jmist.framework.geometry.mesh;

import java.util.stream.StreamSupport;

import ca.eandb.jmist.framework.BoundingBoxBuilder3;
import ca.eandb.jmist.math.Box3;
import ca.eandb.jmist.math.Sphere;

/**
 * @author bwkimmel
 *
 */
public final class MeshUtil {

  private MeshUtil() {}

  public static Mesh triangulate(Mesh mesh) {
    return mesh.getMaxFaceVertexCount() == 3
        ? mesh : new TriangulatedMesh(mesh);
  }

  public static Sphere getBoundingSphere(Mesh mesh) {
    return getBoundingSphere(mesh.getVertices());
  }

  public static Sphere getBoundingSphere(Mesh.Face face) {
    return getBoundingSphere(face.getVertices());
  }

  private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) {
    return Sphere.smallestContaining(() ->
        StreamSupport.stream(vertices.spliterator(), false)
            .map(v -> v.getPosition())
            .iterator());
  }

  public static Box3 getBoundingBox(Mesh mesh) {
    return getBoundingBox(mesh.getVertices());
  }

  public static Box3 getBoundingBox(Mesh.Face face) {
    return getBoundingBox(face.getVertices());
  }

  private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) {
    BoundingBoxBuilder3 builder = new BoundingBoxBuilder3();
    for (Mesh.Vertex vertex : vertices) {
      builder.add(vertex.getPosition());
    }
    return builder.getBoundingBox();
  }

}

/**
 *
 */
package ca.eandb.jmist.framework.geometry.mesh;

import java.util.stream.StreamSupport;

import ca.eandb.jmist.framework.BoundingBoxBuilder3;
import ca.eandb.jmist.math.Box3;
import ca.eandb.jmist.math.Sphere;

/**
 * @author bwkimmel
 *
 */
public final class MeshUtil {

  private MeshUtil() {}

  public static Mesh triangulate(Mesh mesh) {
    return mesh.getMaxFaceVertexCount() == 3
        ? mesh : new TriangulatedMesh(mesh);
  }

  public static Sphere getBoundingSphere(Mesh mesh) {
    return getBoundingSphere(mesh.getVertices());
  }

  public static Sphere getBoundingSphere(Mesh.Face face) {
    return getBoundingSphere(face.getVertices());
  }

  private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) {
    return Sphere.smallestContaining(() ->
        StreamSupport.stream(vertices.spliterator(), false)
            .map(Mesh.Vertex::getPosition)
            .iterator());
  }

  public static Box3 getBoundingBox(Mesh mesh) {
    return getBoundingBox(mesh.getVertices());
  }

  public static Box3 getBoundingBox(Mesh.Face face) {
    return getBoundingBox(face.getVertices());
  }

  private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) {
    BoundingBoxBuilder3 builder = new BoundingBoxBuilder3();
    for (Mesh.Vertex vertex : vertices) {
      builder.add(vertex.getPosition());
    }
    return builder.getBoundingBox();
  }

}

Use method reference instead of lambda

Use method reference instead of lambda


/*
 * Copyright 2016 kohii
 *
 * 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.smoothcsv.commons.utils;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author kohii
 */
public class CollectionUtils {

  public static <T> void add(Collection<T> c, T t, int size) {
    c.addAll(Arrays.asList(ArrayUtils.createAndFill(size, t)));
  }
}

/*
 * Copyright 2016 kohii
 *
 * 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.smoothcsv.commons.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * @author kohii
 */
public class CollectionUtils {

  public static <T> void add(Collection<T> c, T t, int size) {
    c.addAll(Arrays.asList(ArrayUtils.createAndFill(size, t)));
  }

  public static <T> List<T> unique(List<T> list) {
    List<T> ret = new ArrayList<>();
    for (T t : list) {
      if (!ret.contains(t)) {
        ret.add(t);
      }
    }
    return ret;
  }
}

Modify CsvMetaPanel so that it remembers user selection history


/*
 *
 *
 * Copyright (C) 2007 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2007 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * Triggers system to start up, then find a requested bean, then runs it.
 */
public class SystemTaskRunner {

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            System.err.println("bean to run is required as first argument");
            System.exit(1);
        }

        new SystemTaskRunner().runMain(args);
    }

    void runMain(String[] args) {
        BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
        BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
        ApplicationContext app = (ApplicationContext) bfr.getFactory();
        SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
        task.runSystemTask(args);
    }
}

/*
 *
 *
 * Copyright (C) 2007 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2007 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * Triggers system to start up, then find a requested bean, then runs it.
 */
public class SystemTaskRunner {

    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new IllegalArgumentException("bean to run is required as first argument");
        }

        new SystemTaskRunner().runMain(args);
    }

    void runMain(String[] args) {
        BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
        BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
        ApplicationContext app = (ApplicationContext) bfr.getFactory();
        SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
        task.runSystemTask(args);
    }
}

Remove checkstyle warning about System.err

git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@9328 a612230a-c5fa-0310-af8b-88eea846685b


package org.jvirtanen.parity.top;

/**
 * MarketListener is the interface for outbound events from the
 * order book reconstruction.
 */
public interface MarketListener {

    /**
     * An event indicating that the best bid and offer (BBO) has changed.
     *
     * @param instrument the instrument
     * @param bidPrice the bid price or zero if there are no bids
     * @param bidSize the bid size or zero if there are no bids
     * @param askPrice the ask price or zero if there are no asks
     * @param askSize the ask size or zero if there are no asks
     */
    void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize);

    /**
     * An event indicating that a trade has taken place.
     *
     * @param instrument the instrument
     * @param side the side of the resting order
     * @param price the trade price
     * @param size the trade size
     */
    void trade(long instrument, Side side, long price, long size);

}

package org.jvirtanen.parity.top;

/**
 * The interface for outbound events from the order book reconstruction.
 */
public interface MarketListener {

    /**
     * An event indicating that the best bid and offer (BBO) has changed.
     *
     * @param instrument the instrument
     * @param bidPrice the bid price or zero if there are no bids
     * @param bidSize the bid size or zero if there are no bids
     * @param askPrice the ask price or zero if there are no asks
     * @param askSize the ask size or zero if there are no asks
     */
    void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize);

    /**
     * An event indicating that a trade has taken place.
     *
     * @param instrument the instrument
     * @param side the side of the resting order
     * @param price the trade price
     * @param size the trade size
     */
    void trade(long instrument, Side side, long price, long size);

}

Tweak documentation for market listener in order book reconstruction


/**
 * Command-line option processing for Java
 *
 *
The Options class:
 *
 *

 *
parses command-line options and sets fields in your program accordingly,
 *
creates usage messages (such as printed by a `--help` option), and
 *
creates documentation suitable for a manual or manpage.
 *

 *
 * Thus, the programmer is freed from writing duplicative, boilerplate code. The user documentation
 * is automatically generated and never gets out of sync with the rest of the program.
 *
 *
The programmer does not have to write any code, only declare and document variables. For each
 * field that you want to set from a command-line argument, you write Javadoc and an {@code @}{@link
 * Option} annotation. Then, the field is automatically set from a command-line option of the same
 * name, and usage messages and printed documentation are generated automatically.
 */
package org.plumelib.options;

/**
 * Command-line option processing for Java.
 *
 *
The Options class:
 *
 *

 *
parses command-line options and sets fields in your program accordingly,
 *
creates usage messages (such as printed by a `--help` option), and
 *
creates documentation suitable for a manual or manpage.
 *

 *
 * Thus, the programmer is freed from writing duplicative, boilerplate code. The user documentation
 * is automatically generated and never gets out of sync with the rest of the program.
 *
 *
The programmer does not have to write any code, only declare and document variables. For each
 * field that you want to set from a command-line argument, you write Javadoc and an {@code @}{@link
 * Option} annotation. Then, the field is automatically set from a command-line option of the same
 * name, and usage messages and printed documentation are generated automatically.
 */
package org.plumelib.options;

Add missing period in Javadoc descriptions


/*
 * Copyright 2016 Martin Kamp Jensen
 *
 * 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.github.mkjensen.dml.test;

import static org.junit.Assert.assertFalse;

import android.database.Cursor;

/**
 * Helper methods for working with {@link Cursor}.
 */
public final class CursorUtils {

  private CursorUtils() {
  }

  /**
   * Delegates to {@link Cursor#getColumnIndex(String)}. Also asserts that the returned index is not
   * {@code -1}.
   */
  public static int getColumnIndex(Cursor cursor, String columnName) {
    int columnIndex = cursor.getColumnIndex(columnName);
    assertFalse(columnIndex == -1);
    return columnIndex;
  }

  /**
   * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to
   * get the column index for the specified column name.
   */
  public static String getString(Cursor cursor, String columnName) {
    int columnIndex = getColumnIndex(cursor, columnName);
    return cursor.getString(columnIndex);
  }
}

/*
 * Copyright 2016 Martin Kamp Jensen
 *
 * 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.github.mkjensen.dml.test;

import static org.junit.Assert.assertFalse;

import android.database.Cursor;

/**
 * Helper methods for working with {@link Cursor}.
 */
public final class CursorUtils {

  private CursorUtils() {
  }

  /**
   * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to
   * get the column index for the specified column name.
   */
  public static String getString(Cursor cursor, String columnName) {
    int columnIndex = getColumnIndex(cursor, columnName);
    return cursor.getString(columnIndex);
  }

  private static int getColumnIndex(Cursor cursor, String columnName) {
    int columnIndex = cursor.getColumnIndex(columnName);
    assertFalse(columnIndex == -1);
    return columnIndex;
  }
}

Change getColumnIndex method to be private


/*
 *  Copyright 2017, Sascha Häberling
 *
 *  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.retrostore.request;

/**
 * Resolves content types.
 */
final class ContentType {
  /** Return a content type depending on the filename. */
  static Responder.ContentType fromFilename(String filename) {
    filename = filename.toLowerCase();
    if (filename.endsWith(".html")) {
      return Responder.ContentType.HTML;
    } else if (filename.endsWith(".css")) {
      return Responder.ContentType.CSS;
    } else if (filename.endsWith(".js")) {
      return Responder.ContentType.JS;
    } else if (filename.endsWith(".json")) {
      return Responder.ContentType.JSON;
    } else if (filename.endsWith(".jpeg")) {
      return Responder.ContentType.JPEG;
    } else if (filename.endsWith(".png")) {
      return Responder.ContentType.PNG;
    } else {
      return Responder.ContentType.PLAIN;
    }
  }
}

/*
 *  Copyright 2017, Sascha Häberling
 *
 *  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.retrostore.request;

/**
 * Resolves content types.
 */
final class ContentType {
  /** Return a content type depending on the filename. */
  static Responder.ContentType fromFilename(String filename) {
    filename = filename.toLowerCase();
    if (filename.endsWith(".html") || filename.endsWith(".htm")) {
      return Responder.ContentType.HTML;
    } else if (filename.endsWith(".css")) {
      return Responder.ContentType.CSS;
    } else if (filename.endsWith(".js")) {
      return Responder.ContentType.JS;
    } else if (filename.endsWith(".json")) {
      return Responder.ContentType.JSON;
    } else if (filename.endsWith(".jpeg") || filename.endsWith(".jpg")) {
      return Responder.ContentType.JPEG;
    } else if (filename.endsWith(".png")) {
      return Responder.ContentType.PNG;
    } else {
      return Responder.ContentType.PLAIN;
    }
  }
}

Expand content type detection to jpg and htm.


package com.hivedi.statfscompat;

import android.os.Build;
import android.os.StatFs;

import java.io.File;

/**
 * Created by Hivedi2 on 2015-11-24.
 *
 */
public class StatFsCompat {

	@SuppressWarnings("deprecation")
	public static long getStatFsTotal(File f) {
		StatFs statFs = new StatFs(f.getAbsolutePath());
		if (Build.VERSION.SDK_INT >= 18) {
			return statFs.getTotalBytes();
		} else {
			return statFs.getBlockCount() * statFs.getBlockSize();
		}
	}

	@SuppressWarnings("deprecation")
	public static long getStatFsFree(File f) {
		StatFs statFs = new StatFs(f.getAbsolutePath());
		if (Build.VERSION.SDK_INT >= 18) {
			return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
		} else {
			return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
		}
	}

}

package com.hivedi.statfscompat;

import android.os.Build;
import android.os.StatFs;

import java.io.File;

/**
 * Created by Hivedi2 on 2015-11-24.
 *
 */
public class StatFsCompat {

	public static final long STAT_FS_ERROR = -1L;

	@SuppressWarnings("deprecation")
	public static long getStatFsTotal(File f) {
		try {
			StatFs statFs = new StatFs(f.getAbsolutePath());
			if (Build.VERSION.SDK_INT >= 18) {
				return statFs.getTotalBytes();
			} else {
				return statFs.getBlockCount() * statFs.getBlockSize();
			}
		} catch (IllegalArgumentException e) {
			return STAT_FS_ERROR;
		}
	}

	@SuppressWarnings("deprecation")
	public static long getStatFsFree(File f) {
		try {
			StatFs statFs = new StatFs(f.getAbsolutePath());
			if (Build.VERSION.SDK_INT >= 18) {
				return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
			} else {
				return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
			}
		} catch (IllegalArgumentException e) {
			return STAT_FS_ERROR;
		}
	}

}

Handle error if file not exists

Handle error if file not exists


package com.martindisch.chronoscopy.logic;

import com.orm.SugarRecord;

/**
 * Represents a usage of an activity, with a date and duration.
 */
public class ChrUsage extends SugarRecord {

    private ChrActivity activity;
    private String date;
    private String time;

    /**
     * Default constructor, necessary for SugarRecord.
     */
    public ChrUsage() {}

    /**
     * Instantiate a new activity usage.
     *
     * @param activity Reference to the activity
     * @param date The date in ISO 8601 (YYYY-MM-DD)
     * @param time The duration in minutes or h:mm/hh:mm
     */
    public ChrUsage(ChrActivity activity, String date, String time) {
        this.activity = activity;
        this.date = date;
        this.time = time;
    }

    public ChrActivity getActivity() {
        return activity;
    }

    public void setActivity(ChrActivity activity) {
        this.activity = activity;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

package com.martindisch.chronoscopy.logic;

import com.orm.SugarRecord;

/**
 * Represents a usage of an activity, with a date and duration.
 */
public class ChrUsage extends SugarRecord {

    private long activityId;
    private String date;
    private String time;

    /**
     * Default constructor, necessary for SugarRecord.
     */
    public ChrUsage() {}

    /**
     * Instantiate a new activity usage.
     *
     * @param activityId Id of the activity
     * @param date The date in ISO 8601 (YYYY-MM-DD)
     * @param time The duration in minutes or h:mm/hh:mm
     */
    public ChrUsage(long activityId, String date, String time) {
        this.activityId = activityId;
        this.date = date;
        this.time = time;
    }

    public long getActivityId() {
        return activityId;
    }

    public void setActivity(long activityId) {
        this.activityId = activityId;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

Store activity id directly to prevent issues


package io.undertow.servlet.api;

/**
 * @author Stuart Douglas
 */
public enum ServletStackTraces {

    NONE,
    LOCAL_ONLY,
    ALL
}

package io.undertow.servlet.api;

/**
 * @author Stuart Douglas
 */
public enum ServletStackTraces {

    NONE("none"),
    LOCAL_ONLY("local-only"),
    ALL("all");

    private final String value;

    private ServletStackTraces(String value) {
        this.value = value;
    }

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

Add string representation to enum

Add string representation to enum


package tars.commons.util;

import org.junit.Test;

import tars.commons.util.StringUtil;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StringUtilTest {

    @Test
    public void isUnsignedPositiveInteger() {
        assertFalse(StringUtil.isUnsignedInteger(null));
        assertFalse(StringUtil.isUnsignedInteger(""));
        assertFalse(StringUtil.isUnsignedInteger("a"));
        assertFalse(StringUtil.isUnsignedInteger("aaa"));
        assertFalse(StringUtil.isUnsignedInteger("  "));
        assertFalse(StringUtil.isUnsignedInteger("-1"));
        assertFalse(StringUtil.isUnsignedInteger("0"));
        assertFalse(StringUtil.isUnsignedInteger("+1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger("-1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger(" 10")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("10 ")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("1 0")); //should not contain whitespaces

        assertTrue(StringUtil.isUnsignedInteger("1"));
        assertTrue(StringUtil.isUnsignedInteger("10"));
    }

}

package tars.commons.util;

import org.junit.Test;

import tars.commons.util.StringUtil;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class StringUtilTest {

    @Test
    public void isUnsignedPositiveInteger() {
        assertFalse(StringUtil.isUnsignedInteger(null));
        assertFalse(StringUtil.isUnsignedInteger(""));
        assertFalse(StringUtil.isUnsignedInteger("a"));
        assertFalse(StringUtil.isUnsignedInteger("aaa"));
        assertFalse(StringUtil.isUnsignedInteger("  "));
        assertFalse(StringUtil.isUnsignedInteger("-1"));
        assertFalse(StringUtil.isUnsignedInteger("0"));
        assertFalse(StringUtil.isUnsignedInteger("+1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger("-1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger(" 10")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("10 ")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("1 0")); //should not contain whitespaces

        assertTrue(StringUtil.isUnsignedInteger("1"));
        assertTrue(StringUtil.isUnsignedInteger("10"));
    }

    @Test
    public void containsIgnoreCase() {
        String upperCaseString = "TASK ABC";
        String lowerCaseString = "task";

        assertTrue(StringUtil.containsIgnoreCase(upperCaseString, lowerCaseString));
    }

}

Increase test coverage for StringUtil

Increase test coverage for StringUtil


package com.zenika.cudf.parser.model;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Antoine Rouaze <antoine.rouaze@zenika.com>
 */
public class CUDFParsedDescriptor {

    public static final String PREAMBLE_START_LINE = "preamble:";
    public static final String PACKAGE_START_LINE = "package: ";
    public static final String REQUEST_START_LINE = "request:";

    private ParsedPreamble preamble;
    private ParsedRequest request;
    private Set<ParsedBinary> packages = new HashSet<ParsedBinary>();

    public ParsedPreamble getPreamble() {
        return preamble;
    }

    public void setPreamble(ParsedPreamble preamble) {
        this.preamble = preamble;
    }

    public ParsedRequest getRequest() {
        return request;
    }

    public void setRequest(ParsedRequest request) {
        this.request = request;
    }

    public Set<ParsedBinary> getPackages() {
        return packages;
    }

    public void setPackages(Set<ParsedBinary> packages) {
        this.packages = packages;
    }
}

package com.zenika.cudf.parser.model;

import java.util.HashSet;
import java.util.Set;

/**
 * @author Antoine Rouaze <antoine.rouaze@zenika.com>
 */
public class CUDFParsedDescriptor {

    public static final String PREAMBLE_START_LINE = "preamble: ";
    public static final String PACKAGE_START_LINE = "package: ";
    public static final String REQUEST_START_LINE = "request: ";

    private ParsedPreamble preamble;
    private ParsedRequest request;
    private Set<ParsedBinary> packages = new HashSet<ParsedBinary>();

    public ParsedPreamble getPreamble() {
        return preamble;
    }

    public void setPreamble(ParsedPreamble preamble) {
        this.preamble = preamble;
    }

    public ParsedRequest getRequest() {
        return request;
    }

    public void setRequest(ParsedRequest request) {
        this.request = request;
    }

    public Set<ParsedBinary> getPackages() {
        return packages;
    }

    public void setPackages(Set<ParsedBinary> packages) {
        this.packages = packages;
    }
}

Add a space into the end of preamble and request lines to respect the CUDF specification.


package com.sleekbyte.tailor.output;

public class ViolationMessage implements Comparable<ViolationMessage> {
    private final String filePath;
    private final int lineNumber;
    private final int columnNumber;
    private final String classification;
    private final String violationMessage;

    public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
        this.filePath = filePath;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
        this.classification = classification;
        this.violationMessage = violationMessage;
    }

    @Override
    public int compareTo(final ViolationMessage message) {
        int ret = this.lineNumber - message.lineNumber;
        return ret;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ViolationMessage)) {
            return false;
        }
        ViolationMessage message;
        message = (ViolationMessage)o;
        return this.filePath == message.filePath
                && this.lineNumber == message.lineNumber
                && this.columnNumber == message.columnNumber
                && this.classification == message.classification
                && this.violationMessage == message.violationMessage;
    }

    public String toString() {
        if (columnNumber == 0) {
            return String.format("%s:%d: %s: %s", this.filePath, this.lineNumber, this.classification, this.violationMessage);
        }
        return String.format("%s:%d:%d: %s: %s", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
    }
}

package com.sleekbyte.tailor.output;

public class ViolationMessage implements Comparable<ViolationMessage> {
    private final String filePath;
    private final int lineNumber;
    private final int columnNumber;
    private final String classification;
    private final String violationMessage;

    public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
        this.filePath = filePath;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
        this.classification = classification;
        this.violationMessage = violationMessage;
    }

    @Override
    public int compareTo(final ViolationMessage message) {
        int ret = this.lineNumber - message.lineNumber;
        if (ret == 0) {
            ret = this.columnNumber - message.columnNumber;
        }
        return ret;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ViolationMessage)) {
            return false;
        }
        ViolationMessage message;
        message = (ViolationMessage)o;
        return this.filePath == message.filePath
                && this.lineNumber == message.lineNumber
                && this.columnNumber == message.columnNumber
                && this.classification == message.classification
                && this.violationMessage == message.violationMessage;
    }

    public String toString() {
        if (columnNumber == 0) {
            return String.format("%s:%d: %s: %s", this.filePath, this.lineNumber, this.classification, this.violationMessage);
        }
        return String.format("%s:%d:%d: %s: %s", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
    }
}

Sort on col num if line num are equal

Sort on col num if line num are equal