package edu.northwestern.bioinformatics.studycalendar.restlets;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Method;
import org.restlet.Context;
import org.springframework.beans.factory.annotation.Required;

/**
 * Resource representing a study and its planned calendar, including all amendments.
 *
 * @author Rhett Sutphin
 */
public class TemplateResource extends AbstractStorableDomainObjectResource<Study> {
    private StudyDao studyDao;

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        setAllAuthorizedFor(Method.GET);
        setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN);
        // TODO: temporary
        setXmlSerializer(new StudyXmlSerializer());
    }

    @Override
    protected Study loadRequestedObject(Request request) {
        String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request);
        return studyDao.getByAssignedIdentifier(studyIdent);
    }

    ////// CONFIGURATION

    @Required
    public void setStudyDao(StudyDao studyDao) {
        this.studyDao = studyDao;
    }
}

package edu.northwestern.bioinformatics.studycalendar.restlets;

import edu.northwestern.bioinformatics.studycalendar.dao.StudyDao;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.xml.writers.StudyXmlSerializer;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Method;
import org.restlet.Context;
import org.springframework.beans.factory.annotation.Required;

/**
 * Resource representing a study and its planned calendar, including all amendments.
 *
 * @author Rhett Sutphin
 */
public class TemplateResource extends AbstractStorableDomainObjectResource<Study> {
    private StudyDao studyDao;

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        setAllAuthorizedFor(Method.GET);
        setAuthorizedFor(Method.PUT, Role.STUDY_ADMIN);
    }

    @Override
    protected Study loadRequestedObject(Request request) {
        String studyIdent = UriTemplateParameters.STUDY_IDENTIFIER.extractFrom(request);
        return studyDao.getByAssignedIdentifier(studyIdent);
    }

    ////// CONFIGURATION

    @Required
    public void setStudyDao(StudyDao studyDao) {
        this.studyDao = studyDao;
    }
}

Remove mistakenly committed manual XML serializer injection


/*
 * Created on Jul 19, 2004
 *
 */
package edu.wustl.catissuecore.util.global;

import java.util.ResourceBundle;

/**
 * This class is used to retrieve values of keys from the ApplicationResources.properties file.
 * @author kapil_kaveeshwar
 */
public class HibernateProperties
{
    private static ResourceBundle bundle;

    public static void initBundle(String baseName)
    {
    	bundle = ResourceBundle.getBundle(baseName);
    }

	public static String getValue(String theKey)
	{
		return bundle.getString(theKey);
	}
}

/*
 * Created on Jul 19, 2004
 *
 */
package edu.wustl.catissuecore.util.global;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

/**
 * This class is used to retrieve values of keys from the ApplicationResources.properties file.
 * @author kapil_kaveeshwar
 */
public class HibernateProperties
{
	private static Properties p;

    public static void initBundle(String baseName)
    {
    	try
		{
			File file = new File(baseName);
			BufferedInputStream stram = new BufferedInputStream(new FileInputStream(file));
			p = new Properties();
			p.load(stram);
			stram.close();
		}
		catch(Exception exe)
		{
			exe.printStackTrace();
			throw new RuntimeException(
				"Exception building HibernateProperties: " + exe.getMessage(), exe);
		}

    	//ResourceBundle.
    }

	public static String getValue(String theKey)
	{
		return p.getProperty(theKey);
	}
}

Use of properties class for reading resources

SVN-Revision: 864


package mezz.jei.plugins.vanilla.furnace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;

import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;

public class FuelRecipe extends VanillaRecipeWrapper {
	@Nonnull
	private final List<ItemStack> input;
	@Nullable
	private final String burnTimeString;

	public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
		this.input = new ArrayList<>(input);
		this.burnTimeString = StatCollector.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
	}

	@Nonnull
	@Override
	public List<ItemStack> getInputs() {
		return input;
	}

	@Nonnull
	@Override
	public List<ItemStack> getOutputs() {
		return Collections.emptyList();
	}

	@Override
	public void drawInfo(@Nonnull Minecraft minecraft) {
		minecraft.fontRendererObj.drawString(burnTimeString, 24, 2, Color.gray.getRGB());
	}

	@Override
	public boolean usesOreDictionaryComparison() {
		return false;
	}
}

package mezz.jei.plugins.vanilla.furnace;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.util.StatCollector;

import mezz.jei.plugins.vanilla.VanillaRecipeWrapper;

public class FuelRecipe extends VanillaRecipeWrapper {
	@Nonnull
	private final List<ItemStack> input;
	@Nullable
	private final String burnTimeString;

	public FuelRecipe(@Nonnull Collection<ItemStack> input, int burnTime) {
		this.input = new ArrayList<>(input);
		this.burnTimeString = StatCollector.translateToLocalFormatted("gui.jei.furnaceBurnTime", burnTime);
	}

	@Nonnull
	@Override
	public List<ItemStack> getInputs() {
		return input;
	}

	@Nonnull
	@Override
	public List<ItemStack> getOutputs() {
		return Collections.emptyList();
	}

	@Override
	public void drawInfo(@Nonnull Minecraft minecraft) {
		minecraft.fontRendererObj.drawString(burnTimeString, 24, 12, Color.gray.getRGB());
	}

	@Override
	public boolean usesOreDictionaryComparison() {
		return false;
	}
}

Move fuel "burn time" string down, to vertically center it more


package seedu.address.logic.parser;

import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG;

import java.util.NoSuchElementException;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.IncorrectCommand;

/**
 * Parses input arguments and creates a new AddCommand object
 */
public class AddCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the AddCommand
     * and returns an AddCommand object for execution.
     */
    public Command parse(String args) {
        ArgumentTokenizer argsTokenizer =
                new ArgumentTokenizer(PREFIX_DEADLINE, PREFIX_TAG);
        argsTokenizer.tokenize(args);
        try {
            return new AddCommand(
                    argsTokenizer.getPreamble().get(),
                    argsTokenizer.getValue(PREFIX_DEADLINE).get(),
                    ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG))
            );
        } catch (NoSuchElementException nsee) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
        } catch (IllegalValueException ive) {
            return new IncorrectCommand(ive.getMessage());
        }
    }

}

package seedu.address.logic.parser;

import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import static seedu.address.logic.parser.CliSyntax.PREFIX_DEADLINE;
import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG;

import java.util.NoSuchElementException;

import seedu.address.commons.exceptions.IllegalValueException;
import seedu.address.logic.commands.AddCommand;
import seedu.address.logic.commands.Command;
import seedu.address.logic.commands.IncorrectCommand;
/**
 * Parses input arguments and creates a new AddCommand object
 */
public class AddCommandParser {

    /**
     * Parses the given {@code String} of arguments in the context of the AddCommand
     * and returns an AddCommand object for execution.
     */
    public Command parse(String args) {
        ArgumentTokenizer argsTokenizer =
                new ArgumentTokenizer(PREFIX_DEADLINE, PREFIX_TAG);
        argsTokenizer.tokenize(args);

        String name = argsTokenizer.getPreamble().get();
        String deadline = argsTokenizer.getValue(PREFIX_DEADLINE).orElse("");

        try {
            return new AddCommand(name, deadline,
                    ParserUtil.toSet(argsTokenizer.getAllValues(PREFIX_TAG))
            );
        } catch (NoSuchElementException nsee) {
            return new IncorrectCommand(String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE));
        } catch (IllegalValueException ive) {
            return new IncorrectCommand(ive.getMessage());
        }
    }

}

Upgrade deadline implementation to optional


package com.kevinsimard.lambda.function;

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

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

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

    static class Request {
        public String message;

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

        private Request() {
            //
        }
    }

    static class Response {
        public String message;

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

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

package com.kevinsimard.lambda.function;

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

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

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

    static class Request {

        private String message;

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

        private Request() {}
    }

    static class Response {

        private String message;

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

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

Add newlines after class bracket

Add newlines after class bracket


package me.jacobcrofts.simplestructureloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.bukkit.Location;
import org.bukkit.block.Block;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public final class StructureAPI {

	private StructureAPI() {}

	public static void writeToFile(String filename, Selection selection) throws IOException {

		File structures = new File("plugins/structures");
		if (!(structures.exists())) {
			structures.mkdirs();
		}

		FileWriter writer = new FileWriter("plugins/structures/" + filename + ".json");
		writer.write(selection.toJSON().toJSONString());
		writer.close();

	}

	public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException {
		return (JSONArray) new JSONParser().parse(new FileReader(path));
	}

	@SuppressWarnings("deprecation")
	public static void placeStructure(Selection selection, Location baseLocation) {
		for (SavedBlock block : selection.getSavedBlocks()) {
			Block realBlock = baseLocation.add(block.getRelativeX(), block.getRelativeY(), block.getRelativeZ()).getBlock();
			realBlock.setType(block.getType());
			realBlock.setData(block.getData());
		}
	}

}

package me.jacobcrofts.simplestructureloader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.bukkit.Location;
import org.bukkit.block.Block;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public final class StructureAPI {

	private StructureAPI() {}

	public static void writeToFile(String filename, Selection selection) throws IOException {

		File structures = new File("plugins/structures");
		if (!(structures.exists())) {
			structures.mkdirs();
		}

		FileWriter writer = new FileWriter("plugins/structures/" + filename + ".json");
		writer.write(selection.toJSON().toJSONString());
		writer.close();

	}

	public static JSONArray readFromFile(String path) throws FileNotFoundException, IOException, ParseException {
		return (JSONArray) new JSONParser().parse(new FileReader(path));
	}

	@SuppressWarnings("deprecation")
	public static void placeStructure(Selection selection, Location baseLocation) {
		for (SavedBlock savedBlock : selection.getSavedBlocks()) {
			Block realBlock = baseLocation.clone().add(savedBlock.getRelativeX(), savedBlock.getRelativeY(), savedBlock.getRelativeZ()).getBlock();
			realBlock.setType(savedBlock.getType());
			realBlock.setData(savedBlock.getData());
		}
	}

}

Fix bug: pasting structure destructively adds to location


/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * 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.optaplanner.core.config.localsearch;

public enum LocalSearchType {
    HILL_CLIMBING,
    TABU_SEARCH,
    SIMULATED_ANNEALING,
    LATE_ACCEPTANCE,
    GREAT_DELUGE,
    VARIABLE_NEIGHBORHOOD_DESCENT;

    /**
     * @return {@link #values()} without duplicates (abstract types that end up behaving as one of the other types).
     */
    public static LocalSearchType[] getBluePrintTypes() {
        return values();
    }

}

/*
 * Copyright 2015 Red Hat, Inc. and/or its affiliates.
 *
 * 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.optaplanner.core.config.localsearch;

import java.util.Arrays;

public enum LocalSearchType {
    HILL_CLIMBING,
    TABU_SEARCH,
    SIMULATED_ANNEALING,
    LATE_ACCEPTANCE,
    GREAT_DELUGE,
    VARIABLE_NEIGHBORHOOD_DESCENT;

    /**
     * @return {@link #values()} without duplicates (abstract types that end up behaving as one of the other types).
     */
    public static LocalSearchType[] getBluePrintTypes() {
        return Arrays.stream(values())
                // Workaround for https://issues.jboss.org/browse/PLANNER-1294
                .filter(localSearchType -> localSearchType != SIMULATED_ANNEALING)
                .toArray(LocalSearchType[]::new);
    }

}

Remove SA from the blueprints

Remove SA from the blueprints


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.marvel.shield;

import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.FilterClient;
import org.elasticsearch.common.inject.Inject;

/**
 *
 */
public class SecuredClient extends FilterClient {

    private MarvelShieldIntegration shieldIntegration;

    @Inject
    public SecuredClient(Client in, MarvelShieldIntegration shieldIntegration) {
        super(in);
        this.shieldIntegration = shieldIntegration;
    }

    @Override
    protected <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
        this.shieldIntegration.bindInternalMarvelUser(request);
        super.doExecute(action, request, listener);
    }
}

/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.marvel.shield;

import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestBuilder;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.FilterClient;
import org.elasticsearch.common.inject.Inject;

/**
 *
 */
public class SecuredClient extends FilterClient {

    private MarvelShieldIntegration shieldIntegration;

    @Inject
    public SecuredClient(Client in, MarvelShieldIntegration shieldIntegration) {
        super(in);
        this.shieldIntegration = shieldIntegration;
    }

    @Override
    protected <Request extends ActionRequest<Request>, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>> void doExecute(
            Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
        this.shieldIntegration.bindInternalMarvelUser(request);
        super.doExecute(action, request, listener);
    }
}

Fix compilation error after core shifted

Core is slowly removing raw types. Slowly. And one such removal broke shield.

Original commit: elastic/x-pack-elasticsearch@aa1b668c63fba5c8af9e2dd984a456953b100a19


package org.jboss.maven.extension.dependency;

import org.apache.maven.model.building.DefaultModelBuilder;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelBuildingResult;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.annotations.Requirement;

@Component(role = DefaultModelBuilder.class)
public class ExtDepMgmtModelBuilder implements ModelBuilder {

    // Seems that having this requirement may cause issues, since jars in lib/ext/ are loaded before the main jars
    // Need to see this works if we add this as a build extension in the pom (the other way of using an extension)
    // See http://maven.apache.org/examples/maven-3-lifecycle-extensions.html
    // It's also possible that we could insert this jar after the main jars are loaded? This isn't documented though.
    // See /usr/share/maven/bin/m2.conf 's [plexus.core] section

    //@Requirement(hint = "model-builder-internal")
    //private DefaultModelBuilder modelBuilderDelegate;

    public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
        System.out.println(">>>> build 1 called <<<<");
        return null;
    }

    public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
        System.out.println(">>>> build 2 called <<<<");
        return null;
    }
}

package org.jboss.maven.extension.dependency;

import org.apache.maven.model.building.DefaultModelBuilder;
import org.apache.maven.model.building.ModelBuilder;
import org.apache.maven.model.building.ModelBuildingException;
import org.apache.maven.model.building.ModelBuildingRequest;
import org.apache.maven.model.building.ModelBuildingResult;
import org.codehaus.plexus.component.annotations.Component;

@Component(role = DefaultModelBuilder.class)
public class ExtDepMgmtModelBuilder extends DefaultModelBuilder implements ModelBuilder {

    @Override
    public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
        System.out.println(">>>> build(ModelBuildingRequest) called: [" + request + "]");
        return super.build(request);
    }

    @Override
    public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
        System.out.println(">>>> build(ModelBuildingRequest, ModelBuildingResult) called: [" + request + "] [" + result + "]");
        return super.build(request, result);
    }
}

Modify ModelBuilder override to something that doesn't crash maven.

By extending the class we're overriding through plexus, we can avoid the problem of requiring a reference to it before it is loaded.
This commit should allow maven to continue normally, but with some extra messages output by our own class.


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

import java.io.Closeable;

import org.apache.jmeter.report.core.Sample;

/**
 * Describes sample writer basic operations.

 *

 * Basically a sample writer is able to write samples to an unknown destination
 * and close itself.

 *
 * @since 2.14
 */
abstract public class SampleWriter implements Closeable {

    /**
     * Write a sample to the underlying destination
     *
     * @param s
     *            The sample to be written
     * @return The number of samples written at this time to the undernlying
     *         destination
     */
    abstract public long write(Sample s);
}

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

import java.io.Closeable;

import org.apache.jmeter.report.core.Sample;

/**
 * Describes sample writer basic operations.

 *

 * Basically a sample writer is able to write samples to an unknown destination
 * and close itself.

 *
 * @since 2.14
 */
abstract public class SampleWriter implements Closeable {

    /**
     * Write a sample to the underlying destination
     *
     * @param sample
     *            The sample to be written (Must not be {@code null})
     * @return The number of samples written at this time to the underlying
     *         destination
     */
    abstract public long write(Sample sample);
}

Use a more descriptive variable name and point out, that the parameter must not be null.

git-svn-id: https://svn.apache.org/repos/asf/jmeter/trunk@1721006 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: fb9867332588c499f86ee40c8f2e9e01fbce65af


package io.digdag.cli.client;

import io.digdag.cli.SystemExitException;
import io.digdag.client.DigdagClient;
import io.digdag.client.api.RestProject;
import io.digdag.client.api.RestProjectCollection;

import static io.digdag.cli.SystemExitException.systemExit;

public class ShowProjects
        extends ClientCommand
{
    @Override
    public void mainWithClientException()
            throws Exception
    {
        DigdagClient client = buildClient();

        RestProjectCollection projects = client.getProjects();
        for (RestProject proj : projects.getProjects()) {
            ln(" " + proj.getName());
            ln("  id: " + proj.getId());
            ln("  revision: " + proj.getRevision());
            ln("  archive type: " + proj.getArchiveType());

            if (proj.getDeletedAt().isPresent()) {
                ln("  project deleted at:" + proj.getDeletedAt());
            }
            else {
                ln("  project created at: " + proj.getCreatedAt());
                ln("  revision updated at: " + proj.getUpdatedAt());
            }
        }

        ln("");
        err.println("Use `" + programName + " workflows <project-name>` to show details.");
    }

    public SystemExitException usage(String error)
    {
        err.println("Usage: " + programName + " projects");
        showCommonOptions();
        return systemExit(error);
    }
}

package io.digdag.cli.client;

import io.digdag.cli.SystemExitException;
import io.digdag.client.DigdagClient;
import io.digdag.client.api.RestProject;
import io.digdag.client.api.RestProjectCollection;

import static io.digdag.cli.SystemExitException.systemExit;

public class ShowProjects
        extends ClientCommand
{
    @Override
    public void mainWithClientException()
            throws Exception
    {
        DigdagClient client = buildClient();

        RestProjectCollection projects = client.getProjects();
        for (RestProject proj : projects.getProjects()) {
            ln(proj.getName());
            ln("  id: " + proj.getId());
            ln("  revision: " + proj.getRevision());
            ln("  archive type: " + proj.getArchiveType());

            if (proj.getDeletedAt().isPresent()) {
                ln("  project deleted at:" + proj.getDeletedAt());
            }
            else {
                ln("  project created at: " + proj.getCreatedAt());
                ln("  revision updated at: " + proj.getUpdatedAt());
            }
        }

        ln("");
        err.println("Use `" + programName + " workflows <project-name>` to show details.");
    }

    public SystemExitException usage(String error)
    {
        err.println("Usage: " + programName + " projects");
        showCommonOptions();
        return systemExit(error);
    }
}

Remove space before project name

Remove space before project name


/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package cx2x.translator.transformation;

import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Translator;
import cx2x.xcodeml.xnode.XcodeProgram;

/**
 * Simple transformation for documentation example
 */
public class MyFirstTransformation extends ClawTransformation {

  // Constructor that received the analyzed pragma as argument
  public MyFirstTransformation(ClawLanguage directive) {
    super(directive);
  }

  // The analyzis step
  public boolean analyze(XcodeProgram xcodeml, Translator translator) {
    return true;
  }

  // The transformation step
  public void transform(XcodeProgram xcodeml, Translator translator,
                        Transformation other) throws Exception
  {
    _claw.delete();
  }

  // Only used by dependent transformation
  public boolean canBeTransformedWith(Transformation other) {
    return false; // Independent transformation
  }
}

/*
 * This file is released under terms of BSD license
 * See LICENSE file for more information
 */
package cx2x.translator.transformation;

import cx2x.translator.language.base.ClawLanguage;
import cx2x.translator.transformation.ClawTransformation;
import cx2x.xcodeml.transformation.Transformation;
import cx2x.xcodeml.transformation.Translator;
import cx2x.xcodeml.xnode.XcodeProgram;

/**
 * Simple transformation for documentation example
 */
public class MyFirstTransformation extends ClawTransformation {

  // Constructor that received the analyzed pragma as argument
  public MyFirstTransformation(ClawLanguage directive) {
    super(directive);
  }

  // The analyzis step
  public boolean analyze(XcodeProgram xcodeml, Translator translator) {
    return true;
  }

  // The transformation step
  public void transform(XcodeProgram xcodeml, Translator translator,
                        Transformation other) throws Exception
  {
    removePragma();
  }

  // Only used by dependent transformation
  public boolean canBeTransformedWith(Transformation other) {
    return false; // Independent transformation
  }
}

Update code with new Transformation method


/*******************************************************************************
 * Copyright 2011-2014 SirSengir
 *
 * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details.
 ******************************************************************************/
package forestry.api.arboriculture;

import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;

import com.mojang.authlib.GameProfile;

import net.minecraftforge.common.util.ForgeDirection;

import forestry.api.world.ITreeGenData;

/**
 * Implements the tree generation for a tree species.
 */
public interface ITreeGenerator {
	WorldGenerator getWorldGenerator(ITreeGenData tree);
	void setLogBlock(World world, int x, int y, int z, ForgeDirection facing);
	void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative);
}

/*******************************************************************************
 * Copyright 2011-2014 SirSengir
 *
 * This work (the API) is licensed under the "MIT" License, see LICENSE.txt for details.
 ******************************************************************************/
package forestry.api.arboriculture;

import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenerator;

import com.mojang.authlib.GameProfile;

import net.minecraftforge.common.util.ForgeDirection;

import forestry.api.world.ITreeGenData;

/**
 * Implements the tree generation for a tree species.
 */
public interface ITreeGenerator {
	WorldGenerator getWorldGenerator(ITreeGenData tree);

	void setLogBlock(ITreeGenome genome, World world, int x, int y, int z, ForgeDirection facing);

	void setLeaves(ITreeGenome genome, World world, GameProfile owner, int x, int y, int z, boolean decorative);

	/**
	 * @deprecated since Forestry 4.2. use the genome version
	 */
	@Deprecated
	void setLogBlock(World world, int x, int y, int z, ForgeDirection facing);

	/**
	 * @deprecated since Forestry 4.2. use the genome version
	 */
	@Deprecated
	void setLeaves(World world, GameProfile owner, int x, int y, int z, boolean decorative);
}

Add genome-aware tree generation methods for logs and leaves


package org.apache.calcite.adapter.jdbc;

import io.pivotal.beach.calcite.programs.BasicForcedRule;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalTableModify;

/**
 * Created by tzoloc on 11/25/16.
 */

public class JournalledInsertRule implements BasicForcedRule {
	@Override
	public RelNode apply(RelNode originalRel, JdbcRelBuilderFactory relBuilderFactory) {

		if (!(originalRel instanceof LogicalTableModify)) {
			return null;
		}

		LogicalTableModify tableModify = (LogicalTableModify) originalRel;

		if (!tableModify.getOperation().equals(Operation.INSERT)) {
			return null;
		}

		if (!(tableModify.getInput() instanceof LogicalProject)) {
			return null;
		}

		return LogicalTableModify.create(
				tableModify.getTable(),
				tableModify.getCatalogReader(),
				((LogicalProject) tableModify.getInput()).getInput(),
				Operation.INSERT,
				null, //List < String > updateColumnList,
				null, //List < RexNode > sourceExpressionList,
				tableModify.isFlattened()
		);
	}
}

package org.apache.calcite.adapter.jdbc;

import io.pivotal.beach.calcite.programs.BasicForcedRule;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilder;
import org.apache.calcite.adapter.jdbc.tools.JdbcRelBuilderFactory;
import org.apache.calcite.plan.RelOptTable;
import org.apache.calcite.rel.RelNode;
import org.apache.calcite.rel.core.TableModify.Operation;
import org.apache.calcite.rel.logical.LogicalProject;
import org.apache.calcite.rel.logical.LogicalTableModify;

/**
 * Created by tzoloc on 11/25/16.
 */

public class JournalledInsertRule implements BasicForcedRule {
	@Override
	public RelNode apply(RelNode originalRel, JdbcRelBuilderFactory relBuilderFactory) {
		if (!(originalRel instanceof LogicalTableModify)) {
			return null;
		}

		LogicalTableModify tableModify = (LogicalTableModify) originalRel;

		if (!tableModify.getOperation().equals(Operation.INSERT)) {
			return null;
		}

		if (!(tableModify.getInput() instanceof LogicalProject)) {
			return null;
		}

		// Bypass the projection
		tableModify.replaceInput(0, tableModify.getInput(0).getInput(0));

		return tableModify;
	}
}

Clarify functionality of JournalledInsertNode by simplifying code


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

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

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,

    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,

    COCOAPODS,
    HEX,

    R,
    CRATE;

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

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

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

    MAVEN,
    GRADLE,

    NPM,
    BOWER,
    GRUNT,

    GO,

    PYTHON,

    RUBY,

    NUGET,
    PHP,

    RPM,
    DEBIAN,

    COCOAPODS,
    HEX,

    R,
    CRATE,
    CABAL,
    OPAM;

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

Add Cabal & Opam dependency types

Add Cabal & Opam dependency types


package org.postgresql.test.xa;

import java.sql.Connection;

import junit.framework.TestSuite;

import org.postgresql.test.TestUtil;

public class XATestSuite extends TestSuite {
    public static TestSuite suite() throws Exception {
        Class.forName("org.postgresql.Driver");
        TestSuite suite = new TestSuite();
        Connection connection = TestUtil.openDB();

        try
        {
            if (TestUtil.haveMinimumServerVersion(connection, "8.1"))
            {
                suite.addTestSuite(XADataSourceTest.class);
            }
        }
        finally
        {
            connection.close();
        }
        return suite;
    }
}

package org.postgresql.test.xa;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;

import junit.framework.TestSuite;

import org.postgresql.test.TestUtil;

public class XATestSuite extends TestSuite {
    public static TestSuite suite() throws Exception {
        Class.forName("org.postgresql.Driver");
        TestSuite suite = new TestSuite();
        Connection connection = TestUtil.openDB();

        try
        {
            if (TestUtil.haveMinimumServerVersion(connection, "8.1"))
            {
                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery("SHOW max_prepared_transactions");
                rs.next();
                int mpt = rs.getInt(1);
                if (mpt > 0) {
                    suite.addTestSuite(XADataSourceTest.class);
                } else {
                    System.out.println("Skipping XA tests because max_prepared_transactions = 0.");
                }
                rs.close();
                stmt.close();
            }
        }
        finally
        {
            connection.close();
        }
        return suite;
    }
}

Disable the XA tests if the server doesn't allow any prepared transactions, which is the default starting with the 8.4 release.


/* 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.activiti.rest.editor.main;

import java.io.InputStream;

import org.activiti.engine.ActivitiException;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Tijs Rademakers
 */
@RestController
public class StencilsetRestResource {

  @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json")
  public @ResponseBody String getStencilset() {
    InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
    try {
      return IOUtils.toString(stencilsetStream);
    } catch (Exception e) {
      throw new ActivitiException("Error while loading stencil set", e);
    }
  }
}

/* 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.activiti.rest.editor.main;

import java.io.InputStream;

import org.activiti.engine.ActivitiException;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Tijs Rademakers
 */
@RestController
public class StencilsetRestResource {

  @RequestMapping(value="/editor/stencilset", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
  public @ResponseBody String getStencilset() {
    InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json");
    try {
      return IOUtils.toString(stencilsetStream, "utf-8");
    } catch (Exception e) {
      throw new ActivitiException("Error while loading stencil set", e);
    }
  }
}

Fix read stencilset.json gibberish when in other languages


package org.commonjava.indy.schedule.datastax;

public class ScheduleDBUtil
{

    public static String getSchemaCreateTableSchedule( String keyspace )
    {
        return "CREATE TABLE IF NOT EXISTS " + keyspace + ".schedule ("
                        + "jobtype varchar,"
                        + "jobname varchar,"
                        + "storekey varchar,"
                        + "scheduletime timestamp,"
                        + "lifescan bigint,"
                        + "expiration varchar,"
                        + "PRIMARY KEY (storekey, jobname)"
                        + ");";
    }

}

package org.commonjava.indy.schedule.datastax;

public class ScheduleDBUtil
{

    public static final String TABLE_SCHEDULE = "schedule";

    public static String getSchemaCreateTableSchedule( String keyspace )
    {
        return "CREATE TABLE IF NOT EXISTS " + keyspace + "." + TABLE_SCHEDULE + " ("
                        + "jobtype varchar,"
                        + "jobname varchar,"
                        + "storekey varchar,"
                        + "scheduletime timestamp,"
                        + "lifescan bigint,"
                        + "expiration varchar,"
                        + "PRIMARY KEY (storekey, jobname)"
                        + ");";
    }

    public static String getSchemaCreateTypeIndex4Schedule( String keyspace )
    {
        return "CREATE INDEX IF NOT EXISTS type_idx on " + keyspace + "." + TABLE_SCHEDULE + " (jobtype)";
    }

}

Add jobtype as index for schedule

Add jobtype as index for schedule


package ru.vyarus.dropwizard.guice.test;

import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import net.sourceforge.argparse4j.inf.Namespace;
import org.eclipse.jetty.util.component.ContainerLifeCycle;

/**
 * Lightweight variation of server command for testing purposes.
 * Handles managed objects lifecycle.
 *
 * @param <C> configuration type
 * @author Vyacheslav Rusakov
 * @since 23.10.2014
 */
public class TestCommand<C extends Configuration> extends EnvironmentCommand<C> {

    private final Class<C> configurationClass;
    private ContainerLifeCycle container;

    public TestCommand(final Application<C> application) {
        super(application, "guicey-test", "Specific command to run guice context without jetty server");
        configurationClass = application.getConfigurationClass();
    }

    @Override
    protected void run(final Environment environment, final Namespace namespace,
                       final C configuration) throws Exception {
        // simulating managed objects lifecycle support
        container = new ContainerLifeCycle();
        environment.lifecycle().attach(container);
        container.start();
    }

    public void stop() {
        try {
            container.stop();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to stop managed objects container", e);
        }
        container.destroy();
    }

    @Override
    protected Class<C> getConfigurationClass() {
        return configurationClass;
    }
}

package ru.vyarus.dropwizard.guice.test;

import io.dropwizard.Application;
import io.dropwizard.Configuration;
import io.dropwizard.cli.EnvironmentCommand;
import io.dropwizard.setup.Environment;
import net.sourceforge.argparse4j.inf.Namespace;
import org.eclipse.jetty.util.component.ContainerLifeCycle;

/**
 * Lightweight variation of server command for testing purposes.
 * Handles managed objects lifecycle.
 *
 * @param <C> configuration type
 * @author Vyacheslav Rusakov
 * @since 23.10.2014
 */
public class TestCommand<C extends Configuration> extends EnvironmentCommand<C> {

    private final Class<C> configurationClass;
    private ContainerLifeCycle container;

    public TestCommand(final Application<C> application) {
        super(application, "guicey-test", "Specific command to run guice context without jetty server");
        cleanupAsynchronously();
        configurationClass = application.getConfigurationClass();
    }

    @Override
    protected void run(final Environment environment, final Namespace namespace,
                       final C configuration) throws Exception {
        // simulating managed objects lifecycle support
        container = new ContainerLifeCycle();
        environment.lifecycle().attach(container);
        container.start();
    }

    public void stop() {
        try {
            container.stop();
        } catch (Exception e) {
            throw new IllegalStateException("Failed to stop managed objects container", e);
        }
        container.destroy();
        cleanup();
    }

    @Override
    protected Class<C> getConfigurationClass() {
        return configurationClass;
    }
}

Make test command clean up asynchornously


package org.opencds.cqf.ruler.plugin.sdc;

import ca.uhn.fhir.jpa.starter.annotations.OnDSTU3Condition;
import ca.uhn.fhir.jpa.starter.annotations.OnR4Condition;

import org.opencds.cqf.ruler.api.OperationProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(prefix = "hapi.fhir.sdc", name ="enabled", havingValue = "true")
public class SDCConfig {

    @Bean
    public SDCProperties sdcProperties() {
        return new SDCProperties();
    }

    @Bean
    @Conditional(OnR4Condition.class)
    public OperationProvider r4ExtractProvider() {
        return new org.opencds.cqf.ruler.plugin.sdc.r4.ExtractProvider();
    }

    @Bean
    @Conditional(OnDSTU3Condition.class)
    public OperationProvider dstu3ExtractProvider() {
        return new org.opencds.cqf.ruler.plugin.sdc.dstu3.ExtractProvider();
    }

    // TODO: OAuth meta-data extenders
}

package org.opencds.cqf.ruler.plugin.sdc;

import ca.uhn.fhir.jpa.starter.annotations.OnDSTU3Condition;
import ca.uhn.fhir.jpa.starter.annotations.OnR4Condition;

import org.opencds.cqf.ruler.api.OperationProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(prefix = "hapi.fhir.sdc", name ="enabled", havingValue = "true")
public class SDCConfig {

    @Bean
    public SDCProperties SDCProperties() {
        return new SDCProperties();
    }

    @Bean
    @Conditional(OnR4Condition.class)
    public OperationProvider r4ExtractProvider() {
        return new org.opencds.cqf.ruler.plugin.sdc.r4.ExtractProvider();
    }

    @Bean
    @Conditional(OnDSTU3Condition.class)
    public OperationProvider dstu3ExtractProvider() {
        return new org.opencds.cqf.ruler.plugin.sdc.dstu3.ExtractProvider();
    }

    // TODO: OAuth meta-data extenders
}

Fix bug in SDC configuration. Initial running version.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.org.rbc1b.roms.controller.person;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import uk.org.rbc1b.roms.db.Person;

/**
 * Control access to the underlying person data.
 *
 * @author oliver
 */
@Controller
@RequestMapping("/persons")
public class PersonsController {

    @Autowired
    private PersonDao personDao;

    /**
     * Person search. Pass in a candidate, match this against the user
     * first/last name and return the person object in JSON format
     *
     * @param query person match lookup
     * @return model containing the list of qualifications
     */
    @RequestMapping(value = "search", method = RequestMethod.GET, headers = "Accept=application/json")
    //@PreAuthorize - not clear who will not be allowed to access
    @Transactional(readOnly = true)
    public List<Person> handleList(@PathVariable String query) {
        return personDao.findPersons(query);
    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package uk.org.rbc1b.roms.controller.person;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import uk.org.rbc1b.roms.db.Person;

/**
 * Control access to the underlying person data.
 *
 * @author oliver
 */
@Controller
@RequestMapping("/persons")
public class PersonsController {

    @Autowired
    private PersonDao personDao;

    /**
     * Person search. Pass in a candidate, match this against the user
     * first/last name and return the person object in JSON format
     *
     * @param query person match lookup
     * @return model containing the list of people
     */
    @RequestMapping(value = "search", method = RequestMethod.GET, headers = "Accept=application/json")
    //@PreAuthorize - not clear who will not be allowed to access
    @Transactional(readOnly = true)
    @ResponseBody
    public List<Person> handleList(@RequestParam String query) {
        return personDao.findPersons(query);
    }
}

Correct controller for person look up (for type ahead). It returns the full list of objects matching the person


package com.otogami.freemarker.config;

import javax.inject.Inject;
import javax.inject.Provider;

import com.otogami.freemarker.GlobalVariables;
import com.otogami.freemarker.MacroRegister;
import com.otogami.freemarker.viewlet.ViewletFactory;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

public class DefaultConfigurationProvider implements Provider<Configuration> {

	@Inject
	private GlobalVariables globalVariables;

	@Inject
	private ViewletFactory viewletFactory;

	@Inject
	private FunsteroidMacrosRegister funsteroidMacrosRegister;

	@Inject
	private MacroRegister macroRegister;

	@Override
	public Configuration get() {
		FunsteroidFreemarkerConfiguration cfg = new FunsteroidFreemarkerConfiguration(globalVariables, funsteroidMacrosRegister, viewletFactory);
		cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
		cfg.setNumberFormat("0");
		cfg.setClassForTemplateLoading(getClass(), "/tpl");
		if (macroRegister!=null) {
			macroRegister.accept(cfg);
		}
		return cfg;
	}

}

package com.otogami.freemarker.config;

import javax.inject.Inject;
import javax.inject.Provider;

import com.otogami.freemarker.GlobalVariables;
import com.otogami.freemarker.MacroRegister;
import com.otogami.freemarker.viewlet.ViewletFactory;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;

public class DefaultConfigurationProvider implements Provider<Configuration> {

	@Inject
	private GlobalVariables globalVariables;

	@Inject
	private ViewletFactory viewletFactory;

	@Inject
	private FunsteroidMacrosRegister funsteroidMacrosRegister;

	@Inject
	private MacroRegister macroRegister;

	@Override
	public Configuration get() {
		FunsteroidFreemarkerConfiguration cfg = new FunsteroidFreemarkerConfiguration(globalVariables, funsteroidMacrosRegister, viewletFactory);
		cfg.setObjectWrapper(new DefaultObjectWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
		cfg.setNumberFormat("0");
		cfg.setDefaultEncoding("UTF-8");
		cfg.setClassForTemplateLoading(getClass(), "/tpl");
		if (macroRegister!=null) {
			macroRegister.accept(cfg);
		}
		return cfg;
	}

}

Configure Freemarker to UTF-8 by default


package utm.csc492.diamondfire;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
//import com.badlogic.gdx.graphics.GL10;
//import com.badlogic.gdx.graphics.Texture;
//import com.badlogic.gdx.graphics.g2d.SpriteBatch;

import utm.csc492.diamondfire.screens.CityScreen;
import utm.csc492.diamondfire.screens.Test;

public class DiamondFire extends ApplicationAdapter {

    private Screen screen;

	//SpriteBatch batch;
	//Texture img;

	@Override
	public void create () {
		//batch = new SpriteBatch();
		//img = new Texture("badlogic.jpg");
//		try {
//			new FreeTypeFontGenerator(Gdx.files.internal("test.fnt"));
//		} catch(Exception e) {
//			e.printStackTrace();
//		}
//		Bullet.init();

        setScreen(new CityScreen(this));
	}

	@Override
	public void render () {
		/*
		Gdx.gl.glClearColor(1, 0, 0, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		batch.begin();
		batch.draw(img, 0, 0);
		batch.end();
		*/

        if (screen != null) screen.render(Gdx.graphics.getDeltaTime());
    }

    /** use to set current screen **/
    public void setScreen (Screen screen) {
        if (this.screen != null) this.screen.hide();
        this.screen = screen;
        if (this.screen != null) {
            this.screen.show();
            this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        }
    }

    /** return currently active screen **/
    public Screen getScreen () {
        return screen;
    }
}

package utm.csc492.diamondfire;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;

import utm.csc492.diamondfire.screens.CityScreen;

public class DiamondFire extends ApplicationAdapter {

    private Screen screen;

	@Override
	public void create () {
        setScreen(new CityScreen(this));
	}

	@Override
	public void render () {
        if (screen != null) screen.render(Gdx.graphics.getDeltaTime());
    }

    /** use to set current screen **/
    public void setScreen (Screen screen) {
        if (this.screen != null) this.screen.hide();
        this.screen = screen;
        if (this.screen != null) {
            this.screen.show();
            this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
        }
    }

    /** return currently active screen **/
    public Screen getScreen () {
        return screen;
    }
}

Remove some commented out code.

Remove some commented out code.


package org.col.resources;

import java.util.List;
import javax.ws.rs.core.GenericType;

import org.col.api.model.TreeNode;
import org.col.db.mapper.InitMybatisRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import static org.col.dw.ApiUtils.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class TreeResourceTest extends ResourceTestBase {

  static GenericType<List<TreeNode>> LIST_TYPE = new GenericType<List<TreeNode>>() {};

  @Rule
  public InitMybatisRule initMybatisRule = InitMybatisRule.apple(RULE.getSqlSessionFactory());

  public TreeResourceTest() {
    super("/dataset");
  }

  @Test
  public void get() {
    List<TreeNode> root = base.path("/11/tree").request().get(LIST_TYPE);
    assertEquals(2, root.size());
  }

  @Test
  @Ignore("TODO: under construction")
  public void create() {
    TreeNode tn = new TreeNode();
    tn.setDatasetKey(11);
    tn.setId("root-1");

    String id = editorCreds(base.path("/11/tree")
        .queryParam("datasetKey", 12)
    ).post(json(tn), String.class);

    assertNotNull(id);
  }

}

package org.col.resources;

import javax.ws.rs.core.GenericType;

import org.col.api.model.ResultPage;
import org.col.api.model.TreeNode;
import org.col.db.mapper.InitMybatisRule;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import static org.col.dw.ApiUtils.editorCreds;
import static org.col.dw.ApiUtils.json;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class TreeResourceTest extends ResourceTestBase {

  static GenericType<ResultPage<? extends TreeNode>> RESP_TYPE = new GenericType<ResultPage<? extends TreeNode>>() {};

  @Rule
  public InitMybatisRule initMybatisRule = InitMybatisRule.apple(RULE.getSqlSessionFactory());

  public TreeResourceTest() {
    super("/dataset");
  }

  @Test
  public void get() {
    ResultPage<? extends TreeNode> root = base.path("/11/tree").request().get(RESP_TYPE);
    assertEquals(2, root.size());
  }

  @Test
  @Ignore("TODO: under construction")
  public void create() {
    TreeNode tn = new TreeNode();
    tn.setDatasetKey(11);
    tn.setId("root-1");

    String id = editorCreds(base.path("/11/tree")
        .queryParam("datasetKey", 12)
    ).post(json(tn), String.class);

    assertNotNull(id);
  }

}

Fix tree resource test to expect a paging response


package xyz.upperlevel.uppercore.config.parser;

import org.bukkit.plugin.Plugin;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeId;
import org.yaml.snakeyaml.nodes.ScalarNode;
import xyz.upperlevel.uppercore.placeholder.PlaceholderUtil;
import xyz.upperlevel.uppercore.placeholder.PlaceholderValue;

public class PlaceholderValueParser extends ConfigParser {
    private final ConfigParser valueParser;

    public PlaceholderValueParser(ConfigParser valueParser) {
        super(PlaceholderValue.class);
        this.valueParser = valueParser;
    }

    @Override
    public PlaceholderValue parse(Node root) {
        checkNodeId(root, NodeId.scalar);
        ScalarNode node = (ScalarNode) root;// TODO: support more complex types like PlaceholderValue<List<String>> or similar
        //TODO Test Translate colors and such
        if (!PlaceholderUtil.hasPlaceholders(node.getValue())) {
            return PlaceholderValue.fake(valueParser.parse(node));
        } else {
            // Replace the node's value with the resolved placeholders value
            return (player, local) ->
                    valueParser.parse(replaceValue(node, PlaceholderUtil.resolve(player, node.getValue(), local)));
        }
    }
}

package xyz.upperlevel.uppercore.config.parser;

import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeId;
import org.yaml.snakeyaml.nodes.ScalarNode;
import xyz.upperlevel.uppercore.placeholder.PlaceholderUtil;
import xyz.upperlevel.uppercore.placeholder.PlaceholderValue;
import xyz.upperlevel.uppercore.util.TextUtil;

public class PlaceholderValueParser extends ConfigParser {
    private final ConfigParser valueParser;
    private final boolean translateColors;

    public PlaceholderValueParser(ConfigParser valueParser) {
        this(valueParser, valueParser.getHandleClass().equals(String.class));
    }

    public PlaceholderValueParser(ConfigParser valueParser, boolean translateColors) {
        super(PlaceholderValue.class);
        this.valueParser = valueParser;
        this.translateColors = translateColors;
    }

    @Override
    public PlaceholderValue parse(Node root) {
        checkNodeId(root, NodeId.scalar);
        ScalarNode node = (ScalarNode) root;// TODO: support more complex types like PlaceholderValue<List<String>> or similar
        if (translateColors) {
            node = replaceValue(node, TextUtil.translatePlain(node.getValue()));
        }
        if (!PlaceholderUtil.hasPlaceholders(node.getValue())) {
            return PlaceholderValue.fake(valueParser.parse(node));
        } else {
            // Replace the node's value with the resolved placeholders value
            ScalarNode n = node;
            return (player, local) ->
                    valueParser.parse(replaceValue(n, PlaceholderUtil.resolve(player, n.getValue(), local)));
        }
    }
}

Add color translation to PlaceholderValue parsing


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

import javax.servlet.http.HttpSession;

import org.apache.webbeans.spi.conversation.ConversationService;
import org.apache.webbeans.util.JSFUtil;

public class JSFConversationServiceImpl implements ConversationService
{

    public String getConversationId()
    {
        return JSFUtil.getConversationId();
    }

    public String getConversationSessionId()
    {
        HttpSession session = JSFUtil.getSession();
        if(session != null)
        {
            return session.getId();
        }

        return null;
    }

}

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

import javax.servlet.http.HttpSession;

import org.apache.webbeans.spi.ConversationService;
import org.apache.webbeans.util.JSFUtil;

public class JSFConversationServiceImpl implements ConversationService
{

    public String getConversationId()
    {
        return JSFUtil.getConversationId();
    }

    public String getConversationSessionId()
    {
        HttpSession session = JSFUtil.getSession();
        if(session != null)
        {
            return session.getId();
        }

        return null;
    }

}

Update for reflecting SPI module

Update for reflecting SPI module

git-svn-id: 6e2e506005f11016269006bf59d22f905406eeba@904686 13f79535-47bb-0310-9956-ffa450edef68


package com.bbn.kbp.events2014.assessmentDiff.observers;

import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;

public class AETObserver extends ConfusionMatrixAssessmentPairObserver {

    @Override
    protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
        return true;
    }

    @Override
    protected Symbol toKey(ResponseAssessment assessment) {
        return Symbol.from(assessment.justificationSupportsEventType().toString());
    }
}

package com.bbn.kbp.events2014.assessmentDiff.observers;

import com.bbn.bue.common.symbols.Symbol;
import com.bbn.kbp.events2014.Response;
import com.bbn.kbp.events2014.ResponseAssessment;
import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver;

public class AETObserver extends ConfusionMatrixAssessmentPairObserver {

    @Override
    protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) {
        return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent();
    }

    @Override
    protected Symbol toKey(ResponseAssessment assessment) {
        return Symbol.from(assessment.justificationSupportsEventType().get().toString());
    }
}

Update AET diff observer for possibility AET is absent


package hu.bme.mit.codemodel.rifle.database;

import java.util.Map;

import hu.bme.mit.codemodel.rifle.database.querybuilder.Query;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.graphdb.GraphDatabaseService;

import neo4j.driver.testkit.EmbeddedTestkitDriver;

/**
 * Provides database services like transaction handling and query executing.
 */
public class DbServices {
    protected final Driver driver;
    protected Session session;
    protected Transaction transaction;

    public DbServices(Driver driver) {
        this.driver = driver;
        this.session = this.driver.session();
    }

    public Transaction beginTx() {
        this.transaction = session.beginTransaction();
        return this.transaction;
    }

    public StatementResult execute(String statement) {
        return this.transaction.run(statement);
    }

    public StatementResult execute(String statementTemplate, Map<String, Object> statementParameters) {
        return this.transaction.run(statementTemplate, statementParameters);
    }

    public StatementResult execute(Query q) {
        return this.execute(q.getStatementTemplate(), q.getStatementParameters());
    }

    public GraphDatabaseService getUnderlyingDatabaseService() {
        if (driver instanceof EmbeddedTestkitDriver) {
            return ((EmbeddedTestkitDriver) driver).getUnderlyingDatabaseService();
        } else {
            throw new IllegalStateException("Cannot get underyling database service.");
        }
    }
}

package hu.bme.mit.codemodel.rifle.database;

import java.util.Map;

import hu.bme.mit.codemodel.rifle.database.querybuilder.Query;
import org.neo4j.driver.v1.Driver;
import org.neo4j.driver.v1.Session;
import org.neo4j.driver.v1.StatementResult;
import org.neo4j.driver.v1.Transaction;
import org.neo4j.graphdb.GraphDatabaseService;

import neo4j.driver.testkit.EmbeddedTestkitDriver;

/**
 * Provides database services like transaction handling and query executing.
 */
public class DbServices {
    protected final Driver driver;
    protected Transaction transaction;

    public DbServices(Driver driver) {
        this.driver = driver;
    }

    public Transaction beginTx() {
        Session session = driver.session();
        this.transaction = session.beginTransaction();
        return this.transaction;
    }

    public StatementResult execute(String statement) {
        return this.transaction.run(statement);
    }

    public StatementResult execute(String statementTemplate, Map<String, Object> statementParameters) {
        return this.transaction.run(statementTemplate, statementParameters);
    }

    public StatementResult execute(Query q) {
        return this.execute(q.getStatementTemplate(), q.getStatementParameters());
    }

    public GraphDatabaseService getUnderlyingDatabaseService() {
        if (driver instanceof EmbeddedTestkitDriver) {
            return ((EmbeddedTestkitDriver) driver).getUnderlyingDatabaseService();
        } else {
            throw new IllegalStateException("Cannot get underyling database service.");
        }
    }
}

Revert "There is no need for a separate session for each transaction"

This reverts commit 5863051c57182ee6fc61a6b63061cf63b95308e2.


package com.topsy.jmxproxy;

import com.topsy.jmxproxy.jmx.ConnectionManager;
import com.topsy.jmxproxy.JMXProxyResource;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

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

public class JMXProxyApplication extends Application<JMXProxyConfiguration> {
    private static final Logger LOG = LoggerFactory.getLogger(JMXProxyApplication.class);

    public static void main(String[] args) throws Exception {
        LOG.info("starting jmxproxy service");
        new JMXProxyApplication().run(args);
    }

    @Override
    public String getName() {
        return "jmxproxy";
    }

    @Override
    public void initialize(Bootstrap<JMXProxyConfiguration> bootstrap) {
        bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
    }

    @Override
    public void run(JMXProxyConfiguration configuration, Environment environment) {
        final ConnectionManager manager = new ConnectionManager(configuration.getApplicationConfiguration());
        final JMXProxyResource resource = new JMXProxyResource(manager);
        final JMXProxyHealthCheck healthCheck = new JMXProxyHealthCheck(manager);

        environment.jersey().setUrlPattern("/jmxproxy/*");

        environment.lifecycle().manage(manager);
        environment.jersey().register(resource);
        environment.healthChecks().register("manager", healthCheck);
    }
}

package com.topsy.jmxproxy;

import com.topsy.jmxproxy.jmx.ConnectionManager;

import io.dropwizard.Application;
import io.dropwizard.assets.AssetsBundle;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;

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

public class JMXProxyApplication extends Application<JMXProxyConfiguration> {
    private static final Logger LOG = LoggerFactory.getLogger(JMXProxyApplication.class);

    public static void main(String[] args) throws Exception {
        LOG.info("starting jmxproxy service");
        new JMXProxyApplication().run(args);
    }

    @Override
    public String getName() {
        return "jmxproxy";
    }

    @Override
    public void initialize(Bootstrap<JMXProxyConfiguration> bootstrap) {
        bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
    }

    @Override
    public void run(JMXProxyConfiguration configuration, Environment environment) {
        final ConnectionManager manager = new ConnectionManager(configuration.getApplicationConfiguration());
        final JMXProxyResource resource = new JMXProxyResource(manager);
        final JMXProxyHealthCheck healthCheck = new JMXProxyHealthCheck(manager);

        environment.jersey().setUrlPattern("/jmxproxy/*");

        environment.lifecycle().manage(manager);
        environment.jersey().register(resource);
        environment.healthChecks().register("manager", healthCheck);
    }
}

Remove unnecessary import of a class in the same package.


package com.nurkiewicz.monkeys.actions;

import com.google.common.collect.ImmutableSet;
import com.nurkiewicz.monkeys.simulation.Population;
import com.nurkiewicz.monkeys.simulation.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Clock;
import java.time.Duration;
import java.util.Set;

public class Probe extends Action {

    private static final Logger log = LoggerFactory.getLogger(Probe.class);
    private final Population population;

    public Probe(Clock simulationTime, Duration delay, Population population) {
        super(simulationTime, delay);
        this.population = population;
    }

    @Override
    public void run() {
        final Statistics stats = population.statistics();
        log.info("At {} population: {}", getSchedule(), stats);
    }
}

package com.nurkiewicz.monkeys.actions;

import com.nurkiewicz.monkeys.behaviours.Cheater;
import com.nurkiewicz.monkeys.behaviours.Grudger;
import com.nurkiewicz.monkeys.behaviours.Sucker;
import com.nurkiewicz.monkeys.simulation.Population;
import com.nurkiewicz.monkeys.simulation.Statistics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.Clock;
import java.time.Duration;

public class Probe extends Action {

    private static final Logger log = LoggerFactory.getLogger(Probe.class);
    private final Population population;

    public Probe(Clock simulationTime, Duration delay, Population population) {
        super(simulationTime, delay);
        this.population = population;
    }

    @Override
    public void run() {
        final Statistics stats = population.statistics();
        final Integer suckers = stats.getPerType().getOrDefault(Sucker.class.getSimpleName(), 0);
        final Integer grudgers = stats.getPerType().getOrDefault(Grudger.class.getSimpleName(), 0);
        final Integer cheaters = stats.getPerType().getOrDefault(Cheater.class.getSimpleName(), 0);
        System.out.println(cheaters + "\t" + grudgers + "\t" + suckers);
    }
}

Print statistics easier to parse

Print statistics easier to parse


package com.williamschris;

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

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

@RestController
public class CustomerController {
    private HashMap<String, Customer> customerMap = new HashMap<>();
    private long customerIdGenerator = 1;

    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public void addCustomer(@RequestBody Customer c) {
        c.setId(customerIdGenerator);
        customerMap.put(String.valueOf(customerIdGenerator++), c);
    }

    @RequestMapping("/customer/{id}")
    public Customer getCustomer(@PathVariable String id){
        return customerMap.get(id);
    }

    @RequestMapping("/customer")
    public List<Customer> getCustomers(){
        List<Customer> customers = new ArrayList<>();

        for(long i = 1; i < customerIdGenerator; ++i){
            Customer customer = customerMap.get(String.valueOf(i));
            customers.add(customer);
        }

        return customers;
    }

    @RequestMapping(value = "/customer/{id}", method = RequestMethod.DELETE)
    public void deleteCustomer(@PathVariable String id){
        customerMap.remove(id);
    }
}

package com.williamschris;

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

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

@RestController
public class CustomerController {
    private HashMap<String, Customer> customerMap = new HashMap<>();
    private long customerIdGenerator = 1;

    @RequestMapping(value = "/customer", method = RequestMethod.POST)
    public void addCustomer(@RequestBody Customer c) {
        c.setId(customerIdGenerator);
        customerMap.put(String.valueOf(customerIdGenerator++), c);
    }

    @RequestMapping("/customer/{id}")
    public Customer getCustomer(@PathVariable String id){
        return customerMap.get(id);
    }

    @RequestMapping("/customer")
    public List<Customer> getCustomers(){
        return new ArrayList<>(customerMap.values());
    }

    @RequestMapping(value = "/customer/{id}", method = RequestMethod.DELETE)
    public void deleteCustomer(@PathVariable String id){
        customerMap.remove(id);
    }
}

Fix Map to list problem.

Fix Map to list problem.


package fi.csc.microarray.client;

import fi.csc.microarray.client.operation.OperationDefinition;
import fi.csc.microarray.config.DirectoryLayout;

public class HelpMapping {

    public static final String MANUAL_ROOT = DirectoryLayout.getInstance().getConfiguration().getString("client", "manual-root");

	public static String mapToHelppage(OperationDefinition definition) {

		String page = definition.getID();
		if (page.contains(".")) {
			page = page.substring(0, page.lastIndexOf(".")) + ".html";
		}
		return MANUAL_ROOT + page;
	}
}

package fi.csc.microarray.client;

import fi.csc.microarray.client.operation.OperationDefinition;
import fi.csc.microarray.config.DirectoryLayout;

public class HelpMapping {

    public static final String MANUAL_ROOT = DirectoryLayout.getInstance().getConfiguration().getString("client", "manual-root");

	public static String mapToHelppage(OperationDefinition definition) {

		String page = definition.getID();
		if (page.contains(".")) {
			page = page.substring(0, page.lastIndexOf(".")) + ".html";
		} else {
			page += ".html";
		}
		return MANUAL_ROOT + page;
	}
}

Fix help page link for tools without file extension


/*
 * Copyright (c) 2008-2019 The Aspectran 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.aspectran.shell.jline.console;

import com.aspectran.shell.console.Console;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 *
Created: 2017. 3. 5.

 */
class JLine3ConsoleTest {

    @Test
    void testAnsiColor() throws IOException {
        JLineConsole console = new JLineConsole();
        console.writeLine("--- JLineConsoleTest ---");
    }

    public static void main(String[] argv) throws IOException {
        Console console = new JLineConsole();
        String prompt = "JLine3> ";
        while (true) {
            String line = console.readLine(prompt);
            if ("quit".equals(line)) {
                break;
            }
        }
    }

}

/*
 * Copyright (c) 2008-2019 The Aspectran 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.aspectran.shell.jline.console;

import com.aspectran.shell.console.Console;
import org.junit.jupiter.api.Test;

import java.io.IOException;

/**
 *
Created: 2017. 3. 5.

 */
class JLineConsoleTest {

    @Test
    void testAnsiColor() throws IOException {
        JLineConsole console = new JLineConsole();
        console.writeLine("--- JLineConsoleTest ---");
    }

    public static void main(String[] argv) throws IOException {
        Console console = new JLineConsole();
        String prompt = "JLine3> ";
        while (true) {
            String line = console.readLine(prompt);
            if ("quit".equals(line)) {
                break;
            }
        }
    }

}

Rename JLine3ConsoleTest to match class name


package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;

public class GrammarTest {

    protected static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";

    protected ByteArrayOutputStream errContent;
    protected ByteArrayOutputStream outContent;
    protected File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testGrammar() {
        for (File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals("", errContent.toString());
            System.setErr(null);
        }
    }

}

package com.sleekbyte.tailor.grammar;

import com.sleekbyte.tailor.Tailor;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;

import static org.junit.Assert.assertEquals;

@RunWith(MockitoJUnitRunner.class)
public class GrammarTest {

    private static final String TEST_INPUT_DIR = "src/test/java/com/sleekbyte/tailor/grammar/";

    private ByteArrayOutputStream errContent;
    private ByteArrayOutputStream outContent;
    private File[] swiftFiles;

    @Before
    public void setUp() {
        File curDir = new File(TEST_INPUT_DIR);
        swiftFiles = curDir.listFiles((File file, String name) -> name.endsWith(".swift"));
        outContent = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void tearDown() {
        System.setOut(null);
    }

    @Test
    public void testGrammar() {
        for (File swiftFile: swiftFiles) {
            errContent = new ByteArrayOutputStream();
            System.setErr(new PrintStream(errContent));
            String[] command = { (TEST_INPUT_DIR + swiftFile.getName()) };
            Tailor.main(command);
            assertEquals("", errContent.toString());
            System.setErr(null);
        }
    }

}

Change protected members to private

Change protected members to private


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglass.state;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;

/**
 */
public class ToolBarWindowIsActiveState extends State {
    public ToolBarWindowIsActiveState() {
        super("WindowIsActive");
    }

    protected boolean isInState(JComponent c) {
        Component parent = c;
        while (parent.getParent() != null) {
            if (parent instanceof JInternalFrame || parent instanceof JFrame) {
                break;
            }
            parent = parent.getParent();
        }
        if (parent instanceof JInternalFrame) {
            return ((JInternalFrame) parent).isSelected();
        } else if (parent instanceof JFrame) {
            return ((JFrame) parent).isActive();
        }
        // Default to true.
        return true;
    }
}

/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglass.state;

import java.awt.Component;
import java.awt.Window;

import javax.swing.JComponent;
import javax.swing.JInternalFrame;

/**
 */
public class ToolBarWindowIsActiveState extends State {
    public ToolBarWindowIsActiveState() {
        super("WindowIsActive");
    }

    protected boolean isInState(JComponent c) {
        Component parent = c;
        while (parent.getParent() != null) {
            if (parent instanceof JInternalFrame || parent instanceof Window) {
                break;
            }
            parent = parent.getParent();
        }
        if (parent instanceof JInternalFrame) {
            return ((JInternalFrame) parent).isSelected();
        } else if (parent instanceof Window) {
            return ((Window) parent).isFocused();
        }
        // Default to true.
        return true;
    }
}

Use Window instead of JFrame to find top-level parent.


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.entitytype.UEntityType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.entity.BetterEnderPearlEntity;
import net.minecraft.entity.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.*;

public class TestEntityTypes {

	public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, TestMod.MODID);

	public static final EntityType<BetterEnderPearlEntity> BETTER_ENDERPEARL = UEntityType.UBuilder.<BetterEnderPearlEntity> create("better_enderpearl", BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true).build();

	public static void register(IEventBus bus) {
		ENTITY_TYPES.register(bus);
	}
}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.entitytype.UEntityType;
import info.u_team.u_team_test.TestMod;
import info.u_team.u_team_test.entity.BetterEnderPearlEntity;
import net.minecraft.entity.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.*;

public class TestEntityTypes {

	public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, TestMod.MODID);

	public static final RegistryObject<EntityType<BetterEnderPearlEntity>> BETTER_ENDERPEARL = ENTITY_TYPES.register("better_enderpearl", () -> UEntityType.UBuilder.<BetterEnderPearlEntity> create("better_enderpearl", BetterEnderPearlEntity::new, EntityClassification.MISC).size(0.25F, 0.25F).setTrackingRange(128).setUpdateInterval(20).setShouldReceiveVelocityUpdates(true).build());

	public static void register(IEventBus bus) {
		ENTITY_TYPES.register(bus);
	}
}

Change the test entity type register for the better ender pearl to use the deferred register


// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.testsystems.fit;

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

public class SocketDealer {
  private Map<Integer, SocketSeeker> waitingList = new HashMap<Integer, SocketSeeker>(17);
  private int ticketCounter = 1;

  public int seekingSocket(SocketSeeker seeker) {
    int ticket = ticketCounter++;
    waitingList.put(new Integer(ticket), seeker);
    return ticket;
  }

  public Collection<SocketSeeker> getWaitingList() {
    return waitingList.values();
  }

  public void dealSocketTo(int ticket, SocketDoner doner) throws Exception {
    Integer key = new Integer(ticket);
    SocketSeeker seeker = waitingList.get(key);
    seeker.acceptSocketFrom(doner);
    waitingList.remove(key);
  }

  public boolean isWaiting(int ticket) {
    return waitingList.containsKey(new Integer(ticket));
  }
}

// Copyright (C) 2003-2009 by Object Mentor, Inc. All rights reserved.
// Released under the terms of the CPL Common Public License version 1.0.
package fitnesse.testsystems.fit;

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

public class SocketDealer {
  private Map<Integer, SocketSeeker> waitingList = new HashMap<Integer, SocketSeeker>(17);
  private int ticketCounter = 1;

  public int seekingSocket(SocketSeeker seeker) {
    int ticket = ticketCounter++;
    waitingList.put(ticket, seeker);
    return ticket;
  }

  public Collection<SocketSeeker> getWaitingList() {
    return waitingList.values();
  }

  public void dealSocketTo(int ticket, SocketDoner doner) throws Exception {
    SocketSeeker seeker = waitingList.get(ticket);
    seeker.acceptSocketFrom(doner);
    waitingList.remove(ticket);
  }

  public boolean isWaiting(int ticket) {
    return waitingList.containsKey(ticket);
  }
}

Remove inefficient boxing of int.

Remove inefficient boxing of int.


package name.webdizz.fault.tolerance.gateway.endpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
import lombok.Data;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.client.command.TimeOutInventoryRequestCommand;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;

@RestController
@RequestMapping("/api/products")
public class ProductDetailsEndpoint {

    private final InventoryRequester inventoryRequester;

    @Autowired
    public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) {
        this.inventoryRequester = inventoryRequester;
    }

    @RequestMapping("/{store}/{product}")
    public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) {
        Store store = new Store(storeId);
        Product product = new Product(productId);
        Inventory inventory = new TimeOutInventoryRequestCommand(inventoryRequester, store, product, 1000).execute();
        return new ProductDetails(inventory);
    }

    @Data
    @AllArgsConstructor
    class ProductDetails {
        private Inventory inventory;
    }
}

package name.webdizz.fault.tolerance.gateway.endpoint;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.AllArgsConstructor;
import lombok.Data;
import name.webdizz.fault.tolerance.inventory.client.InventoryRequester;
import name.webdizz.fault.tolerance.inventory.client.command.CircuitBreakerInventoryRequestCommand;
import name.webdizz.fault.tolerance.inventory.domain.Inventory;
import name.webdizz.fault.tolerance.inventory.domain.Product;
import name.webdizz.fault.tolerance.inventory.domain.Store;

@RestController
@RequestMapping("/api/products")
public class ProductDetailsEndpoint {

    private final InventoryRequester inventoryRequester;

    @Autowired
    public ProductDetailsEndpoint(final InventoryRequester inventoryRequester) {
        this.inventoryRequester = inventoryRequester;
    }

    @RequestMapping("/{store}/{product}")
    public ProductDetails inventory(@PathVariable("store") String storeId, @PathVariable("product") String productId) {
        Store store = new Store(storeId);
        Product product = new Product(productId);
        Inventory inventory = new CircuitBreakerInventoryRequestCommand(inventoryRequester, store, product, false).execute();
        return new ProductDetails(inventory);
    }

    @Data
    @AllArgsConstructor
    class ProductDetails {
        private Inventory inventory;
    }
}

Switch to another command to call inventory service


package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Block targetBlock = getTargetBlock();
        Location targetLocation = targetBlock.getLocation();

        if (!targetBlock.getType().isSolid()
                && !targetBlock.getRelative(BlockFace.UP).getType().isSolid()
                && !getApi().getEnvironment().isAliveEntityAt(targetLocation)
                && getApi().getEnvironment().contains(targetLocation)) {
            getApi().moveTo(targetLocation, false);

            while (!targetBlock.getRelative(BlockFace.DOWN).getType().isSolid() && targetBlock.getY() > 0) {
                targetBlock = targetBlock.getRelative(BlockFace.DOWN);
            }
            getApi().moveTo(targetBlock.getLocation(), false);
        }

        return LuaValue.NIL;
    }

    /**
     * Gets the block this function will move the entity to.
     *
     * @return target block
     */
    protected Block getTargetBlock() {
        return getApi().getBlockAhead();
    }
}

package de.craften.plugins.educraft.luaapi.functions;

import de.craften.plugins.educraft.luaapi.EduCraftApiFunction;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;

/**
 * Lua API function to move one block forward.
 */
public class MoveForwardFunction extends EduCraftApiFunction {
    @Override
    public Varargs execute(Varargs varargs) {
        Block targetBlock = getTargetBlock();
        Location targetLocation = targetBlock.getLocation();

        if (!targetBlock.getType().isSolid()
                && !targetBlock.getRelative(BlockFace.UP).getType().isSolid()
                && !getApi().getEnvironment().isAliveEntityAt(targetLocation)
                && getApi().getEnvironment().contains(targetLocation)) {
            getApi().moveTo(targetLocation, false);

            //fall on solid block (without falling out of the environment)
            while (!targetBlock.getRelative(BlockFace.DOWN).getType().isSolid()
                    && getApi().getEnvironment().contains(targetBlock.getLocation().subtract(0, -1, 0))) {
                targetBlock = targetBlock.getRelative(BlockFace.DOWN);
            }
            getApi().moveTo(targetBlock.getLocation(), false);
        }

        return LuaValue.NIL;
    }

    /**
     * Gets the block this function will move the entity to.
     *
     * @return target block
     */
    protected Block getTargetBlock() {
        return getApi().getBlockAhead();
    }
}

Fix moveForward() not checking environment range when the bot falls.