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

import javax.jcr.observation.EventListener;

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

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

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

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

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

JCR-2357: Duplicate entries in the index
- javadoc

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@828343 13f79535-47bb-0310-9956-ffa450edef68


package com.codeski.nbt;

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

public class Main
{
	public static void main(String[] args) throws FileNotFoundException, IOException
	{
		File f = new File(args[0]);
		System.out.println("Start reading " + f.getAbsolutePath() + "...");
		System.out.println(new NBTReader(f).read());
		System.out.println("Finished reading " + f.getAbsolutePath() + "...");
	}
}

package com.codeski.nbt;

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

import com.codeski.nbt.tags.NBTCompound;

public class Main
{
	public static void main(String[] args) throws FileNotFoundException, IOException
	{
		File f = new File(args[0]);
		System.out.println("Start reading " + f.getAbsolutePath() + "...");
		NBTCompound root = (NBTCompound) new NBTReader(f).read();
		System.out.println("Finished reading " + f.getAbsolutePath() + "...");
		System.out.println();
		System.out.println("{ " + root.toJSON() + " }");
		System.out.println();
		System.out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + root.toXML());
		System.out.println();
		System.out.println("Done!");
	}
}

Clean up main class and show JSON and XML output


package hello.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurerAdapter;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.core.EvoInflectorRelProvider;

@Configuration
public class Hateoas {

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

	@Bean
	public RelProvider relProvider() {
		log.info("Using EvoInflectorRelProvider for HATEOAS relations");

		return new EvoInflectorRelProvider();
	}

	@Bean
	public RepositoryRestConfigurer repositoryRestConfigurer() {

		return new RepositoryRestConfigurerAdapter() {

			@Override
			public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
				config.setBasePath("/api");
			}
		};
	}
}

package hello.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.rest.core.config.RepositoryRestConfiguration;
import org.springframework.data.rest.webmvc.config.RepositoryRestConfigurer;
import org.springframework.hateoas.RelProvider;
import org.springframework.hateoas.core.EvoInflectorRelProvider;

@Configuration
public class Hateoas {

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

	@Bean
	public RelProvider relProvider() {
		log.info("Using EvoInflectorRelProvider for HATEOAS relations");

		return new EvoInflectorRelProvider();
	}

	@Bean
	public RepositoryRestConfigurer repositoryRestConfigurer() {

		return new RepositoryRestConfigurer() {

			@Override
			public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
				config.setBasePath("/api");
			}
		};
	}
}

Fix deprecated RepositoryRestConfigurerAdapter in the configs.


/**
 * 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.commons.crypto.cipher;

public class JceCipherTest extends AbstractCipherTest {

    @Override
    public void init() {
        transformations = new CipherTransformation[] {
                CipherTransformation.AES_CBC_NOPADDING,
                CipherTransformation.AES_CBC_PKCS5PADDING,
                CipherTransformation.AES_CTR_NOPADDING };
        cipherClass = JceCipher.class.getName();
    }

}

/**
 * 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.commons.crypto.cipher;

import java.security.NoSuchAlgorithmException;

import javax.crypto.Cipher;

import org.junit.Assert;
import org.junit.BeforeClass;

public class JceCipherTest extends AbstractCipherTest {

    private static final int MAX_KEY_LEN_LOWER_BOUND = 256;

    @Override
    public void init() {
        transformations = new CipherTransformation[] {
                CipherTransformation.AES_CBC_NOPADDING,
                CipherTransformation.AES_CBC_PKCS5PADDING,
                CipherTransformation.AES_CTR_NOPADDING };
        cipherClass = JceCipher.class.getName();
    }

    @BeforeClass
    public void checkJceUnlimitedStrength() throws NoSuchAlgorithmException {
        int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
        Assert.assertTrue(String.format(
                "Testing requires support for an AES key length of %d, but " +
                "the detected maximum key length is %d.  This may indicate " +
                "that the test environment is missing the JCE Unlimited " +
                "Strength Jurisdiction Policy Files.",
                MAX_KEY_LEN_LOWER_BOUND, maxKeyLen),
                maxKeyLen >= MAX_KEY_LEN_LOWER_BOUND);
    }
}

[CRYPTO-52] Improve assertion message when test fails due to lack of JCE
Unlimited Strength Jurisdiction Policy Files. Applied patch and changed
@Before to @BeforeClass.


/*
 * Licensed to the University of California, Berkeley 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 tachyon.client;

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

/**
 * Tests {@link ClientUtils}.
 */
public final class ClientUtilsTest {

  /**
   * Tests if output of getRandomNonNegativeLong from {@link ClientUtils} is non-negative.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
  }

}

/*
 * Licensed to the University of California, Berkeley 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 tachyon.client;

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

/**
 * Tests {@link ClientUtils}.
 */
public final class ClientUtilsTest {

  /**
   * Tests if output of {@link ClientUtils#getRandomNonNegativeLong()} is non-negative.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    Assert.assertTrue(ClientUtils.getRandomNonNegativeLong() > 0);
  }

}

[TACHYON-1559] Update doc to reference method directly and defend against IDE refactors


package info.u_team.u_team_core.item.armor;

import net.minecraftforge.fml.RegistryObject;

public class ArmorSet {

	private final RegistryObject<UHelmetItem> helmet;
	private final RegistryObject<UChestplateItem> chestplate;
	private final RegistryObject<ULeggingsItem> leggings;
	private final RegistryObject<UBootsItem> boots;

	public ArmorSet(RegistryObject<UHelmetItem> helmet, RegistryObject<UChestplateItem> chestplate, RegistryObject<ULeggingsItem> leggings, RegistryObject<UBootsItem> boots) {
		this.helmet = helmet;
		this.chestplate = chestplate;
		this.leggings = leggings;
		this.boots = boots;
	}

	public RegistryObject<UHelmetItem> getHelmet() {
		return helmet;
	}

	public RegistryObject<UChestplateItem> getChestplate() {
		return chestplate;
	}

	public RegistryObject<ULeggingsItem> getLeggings() {
		return leggings;
	}

	public RegistryObject<UBootsItem> getBoots() {
		return boots;
	}
}

package info.u_team.u_team_core.item.armor;

import java.util.Iterator;

import com.google.common.collect.Iterators;

import net.minecraftforge.fml.RegistryObject;

public class ArmorSet implements Iterable<RegistryObject<? extends UArmorItem>> {

	private final RegistryObject<UHelmetItem> helmet;
	private final RegistryObject<UChestplateItem> chestplate;
	private final RegistryObject<ULeggingsItem> leggings;
	private final RegistryObject<UBootsItem> boots;

	public ArmorSet(RegistryObject<UHelmetItem> helmet, RegistryObject<UChestplateItem> chestplate, RegistryObject<ULeggingsItem> leggings, RegistryObject<UBootsItem> boots) {
		this.helmet = helmet;
		this.chestplate = chestplate;
		this.leggings = leggings;
		this.boots = boots;
	}

	public RegistryObject<UHelmetItem> getHelmet() {
		return helmet;
	}

	public RegistryObject<UChestplateItem> getChestplate() {
		return chestplate;
	}

	public RegistryObject<ULeggingsItem> getLeggings() {
		return leggings;
	}

	public RegistryObject<UBootsItem> getBoots() {
		return boots;
	}

	@Override
	public Iterator<RegistryObject<? extends UArmorItem>> iterator() {
		return Iterators.forArray(helmet, chestplate, leggings, boots);
	}
}

Add iterator to the armor set for convenience


package com.agilemods.materiamuto.common.core;

import com.agilemods.materiamuto.common.core.MMItems;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;

public class MMRecipes {

    public static void initialize() {
        ItemStack dustLow = new ItemStack(MMItems.covalenceDust, 1, 0);
        ItemStack dustMedium = new ItemStack(MMItems.covalenceDust, 1, 1);
        ItemStack dustHigh = new ItemStack(MMItems.covalenceDust, 1, 2);

        GameRegistry.addShapelessRecipe(
                dustLow,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                new ItemStack(Items.coal, 1, 1)
        );

        GameRegistry.addShapelessRecipe(
                dustMedium,
                Items.iron_ingot,
                Items.redstone
        );

        GameRegistry.addShapelessRecipe(
                dustHigh,
                Items.diamond,
                new ItemStack(Items.coal, 1, 0)
        );
    }
}

package com.agilemods.materiamuto.common.core;

import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;

public class MMRecipes {

    public static void initialize() {
        ItemStack dustLow = new ItemStack(MMItems.covalenceDust, 40, 0);
        ItemStack dustMedium = new ItemStack(MMItems.covalenceDust, 40, 1);
        ItemStack dustHigh = new ItemStack(MMItems.covalenceDust, 40, 2);

        GameRegistry.addShapelessRecipe(
                dustLow,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                Blocks.cobblestone,
                new ItemStack(Items.coal, 1, 1)
        );

        GameRegistry.addShapelessRecipe(
                dustMedium,
                Items.iron_ingot,
                Items.redstone
        );

        GameRegistry.addShapelessRecipe(
                dustHigh,
                Items.diamond,
                new ItemStack(Items.coal, 1, 0)
        );
    }
}

Make dust recipes actually give 40 dust

Make dust recipes actually give 40 dust


package brlyman;

import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import java.util.*;

import org.junit.runner.Description;
import org.junit.runner.Result;

import brlyman.results.*;
import brlyman.results.processes.*;

public class TurboListener extends RunListener
{
    public TurboListener(final Logger log)
    {
        this.log = log;
        this.root = new Context("Test Suite");
    }

    public void
    testRunStarted(final Description description) throws Exception
    {
    }

    public void
    testRunFinished(final Result result) throws Exception
    {
        root.apply(new PrintContexts(log));
        root = new Context("Test Suite");
    }

    public void
    testStarted(final Description description) throws Exception
    {
    }

    public void
    testFinished(final Description description) throws Exception
    {
        root.addTestResult(
            Arrays.asList(
                description.getClassName().split("\\$")),
            new Pass(
                description.getMethodName()));
    }

    public void
    testFailure(final Failure failure) throws Exception
    {
        root.addTestResult(
            Arrays.asList(
                failure.getDescription().getClassName().split("\\$")),
            new Fail(
                failure.getDescription().getMethodName(),
                failure.getMessage()));
    }

    public void
    testAssumptionFailure(final Failure failure)
    {
        log.error(failure.getMessage());
    }

    public void
    testIgnored(final Description description) throws Exception
    {
        log.warn(description.getMethodName() + " ignored");
    }

    private Context root;
    private final Logger log;
}

package brlyman;

import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunListener;

import java.util.*;

import org.junit.runner.Description;
import org.junit.runner.Result;

import brlyman.results.*;
import brlyman.results.processes.*;

public class TurboListener extends RunListener
{
    public TurboListener(final Logger log)
    {
        this.log = log;
        this.root = new Context("Test Suite");
    }

    public void
    testRunStarted(final Description description) throws Exception
    {
    }

    public void
    testRunFinished(final Result result) throws Exception
    {
        root.apply(new PrintContexts(log));
        root = new Context("Test Suite");
    }

    public void
    testStarted(final Description description) throws Exception
    {
    }

    public void
    testFinished(final Description description) throws Exception
    {
        root.addTestResult(
            Arrays.asList(
                description.getClassName().split("\\$")),
            new Pass(
                description.getMethodName()));
    }

    public void
    testFailure(final Failure failure) throws Exception
    {
        root.addTestResult(
            Arrays.asList(
                failure.getDescription().getClassName().split("\\$")),
            new Fail(
                failure.getDescription().getMethodName(),
                failure.getMessage() + "\n" + failure.getTrace()));
    }

    public void
    testAssumptionFailure(final Failure failure)
    {
        log.error(failure.getMessage());
    }

    public void
    testIgnored(final Description description) throws Exception
    {
        log.warn(description.getMethodName() + " ignored");
    }

    private Context root;
    private final Logger log;
}

Add stacktrace to java test failures

Add stacktrace to java test failures


class Dog {
  String name, says;
}

class BarkingDogs {
  public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.name = "spot";
    dog1.says = "Ruff!";

    Dog dog2 = new Dog();
    dog2.name = "scruffy";
    dog2.says = "Wurf!";

    System.out.println(dog1.name + ": " + dog1.says);
    System.out.println(dog2.name + ": " + dog2.says);
  }
}

class Dog {
  String name, says;
}

class BarkingDogs {
  public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.name = "spot";
    dog1.says = "Ruff!";

    Dog dog2 = new Dog();
    dog2.name = "scruffy";
    dog2.says = "Wurf!";

    Dog spot = new Dog();
    spot.name = "spot";
    spot.says = "Ruff!";

    System.out.println(dog1.name + ": " + dog1.says);
    System.out.println(dog2.name + ": " + dog2.says);

    System.out.println(dog1.equals(spot));
    System.out.println(dog1 == spot);
    System.out.println(dog1.name == spot.name);
    System.out.println(dog1.says == spot.says);

    System.out.println(dog1.equals(dog2));
  }
}

Add exercise 6, test for comparison for all references


package org.real2space;

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

import static org.junit.Assert.*;

/**
 * Created by sryosuke on 2016/10/09.
 */
public class HogeTest {
    private Hoge hoge;
    @Before
    public void setUp() throws Exception {
        System.out.println ("setup");
        hoge = new Hoge ("aiueo");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println ("test");
    }

    @Test
    public void show() throws Exception {
        System.out.println ("testest");
        hoge.show();
    }

}

package org.real2space;

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

import static org.junit.Assert.*;

/**
 * Created by sryosuke on 2016/10/09.
 */
public class HogeTest {
    private Hoge hoge;
    @Before
    public void setUp() throws Exception {
        System.out.println ("setup");
        hoge = new Hoge ("created Hoge instance");
    }

    @After
    public void tearDown() throws Exception {
        System.out.println ("tear down");
    }

    @Test
    public void show() throws Exception {
        System.out.println ("invoked show");
        hoge.show();
    }

}

Test 01 - Constructing jUnit and traivis ci


package hudson.plugins.copyProjectLink;

import hudson.model.Action;
import hudson.model.AbstractProject;
import hudson.model.Hudson;

public class CopyProjectAction implements Action {

	final private AbstractProject<?, ?> project;

	public CopyProjectAction(AbstractProject project) {
		this.project = project;
	}

	public String getCloneName() {
		return project.getDisplayName() + "-clone";
	}

	public String getProjectName() {
		return project.getDisplayName();
	}

	public String getIconFileName() {
		if (hasPermission()) {
			return "/plugin/copy-project-link/img/edit-copy.png";
		}
		return null;
	}

	public String getDisplayName() {
		if (hasPermission()) {
			return "Copy project";
		}
		return null;
	}

	public String getUrlName() {
		if(hasPermission()) {
			return "copy-project";
		}
		return null;
	}

	private boolean hasPermission(){
		return Hudson.getInstance().hasPermission(project.CONFIGURE);
	}

}

package hudson.plugins.copyProjectLink;

import hudson.model.Action;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.security.AccessControlled;

public class CopyProjectAction implements Action {

	final private AbstractProject<?, ?> project;

	public CopyProjectAction(AbstractProject project) {
		this.project = project;
	}

	public String getCloneName() {
		return project.getDisplayName() + "-clone";
	}

	public String getProjectName() {
		return project.getDisplayName();
	}

	public String getIconFileName() {
		if (hasPermission()) {
			return "/plugin/copy-project-link/img/edit-copy.png";
		}
		return null;
	}

	public String getDisplayName() {
		if (hasPermission()) {
			return "Copy project";
		}
		return null;
	}

	public String getUrlName() {
		if(hasPermission()) {
			return "copy-project";
		}
		return null;
	}

	private boolean hasPermission(){
    ItemGroup parent = project.getParent();
    if (parent instanceof AccessControlled) {
      AccessControlled accessControlled = (AccessControlled)parent;
      return accessControlled.hasPermission(Item.CREATE);
    }
    return Hudson.getInstance().hasPermission(Item.CREATE);
	}

}

Use static Item.CREATE rather than Item.CONFIGURE and check permission from the given container.


package io.specto.hoverfly.junit.api.model;

import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.List;

@JsonInclude(JsonInclude.Include.NON_NULL)
public class ModeArguments {

    private List<String> headersWhitelist;

    public ModeArguments() {
    }

    public ModeArguments(List<String> headersWhitelist) {
        this.headersWhitelist = headersWhitelist;
    }

    public List<String> getHeadersWhitelist() {
        return headersWhitelist;
    }

    public void setHeadersWhitelist(List<String> headersWhitelist) {
        this.headersWhitelist = headersWhitelist;
    }
}

package io.specto.hoverfly.junit.api.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;

import java.util.List;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ModeArguments {

    private List<String> headersWhitelist;
    private String matchingStrategy;

    public ModeArguments() {
    }

    public ModeArguments(List<String> headersWhitelist) {
        this.headersWhitelist = headersWhitelist;
    }

    public List<String> getHeadersWhitelist() {
        return headersWhitelist;
    }

    public void setHeadersWhitelist(List<String> headersWhitelist) {
        this.headersWhitelist = headersWhitelist;
    }

    public String getMatchingStrategy() {
        return matchingStrategy;
    }

    public void setMatchingStrategy(String matchingStrategy) {
        this.matchingStrategy = matchingStrategy;
    }
}

Fix unknown properties in hoverfly info view

Former-commit-id: 8b13c7dee16d75cde6192a7c7df6cab4c57f978b


package net.buycraft.plugin.shared;

import net.buycraft.plugin.shared.util.FakeProxySelector;
import net.buycraft.plugin.shared.util.Ipv4PreferDns;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

import java.io.File;
import java.net.ProxySelector;
import java.util.concurrent.TimeUnit;

public final class Setup {
    private Setup() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }

    public static OkHttpClient okhttp(File base) {
        return okhttpBuilder().cache(new Cache(new File(base, "cache"), 1024 * 1024 * 10)).build();
    }

    public static OkHttpClient.Builder okhttpBuilder() {
        return new OkHttpClient.Builder()
                .connectTimeout(3, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .dns(new Ipv4PreferDns())
                .proxySelector(ProxySelector.getDefault() == null ? FakeProxySelector.INSTANCE : ProxySelector.getDefault());
    }
}

package net.buycraft.plugin.shared;

import net.buycraft.plugin.shared.util.FakeProxySelector;
import net.buycraft.plugin.shared.util.Ipv4PreferDns;
import okhttp3.Cache;
import okhttp3.OkHttpClient;

import java.io.File;
import java.net.ProxySelector;
import java.util.concurrent.TimeUnit;

public final class Setup {
    private Setup() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }

    public static OkHttpClient okhttp(File base) {
        return okhttpBuilder().cache(new Cache(new File(base, "cache"), 1024 * 1024 * 10)).build();
    }

    public static OkHttpClient.Builder okhttpBuilder() {
        return new OkHttpClient.Builder()
                .connectTimeout(6, TimeUnit.SECONDS)
                .writeTimeout(7, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .dns(new Ipv4PreferDns())
                .proxySelector(ProxySelector.getDefault() == null ? FakeProxySelector.INSTANCE : ProxySelector.getDefault());
    }
}

Increase timeout values to max that were used in last API class


package com.siftscience;

import okhttp3.Response;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.io.IOException;

public class UnlabelResponse extends SiftResponse {
    UnlabelResponse(Response okResponse, FieldSet requestBody) throws IOException {
        super(okResponse, requestBody);
    }

    /**
     * This should never be called because the unlabel API doesn't return a response body.
     *
     * @param jsonBody
     */
    @Override
    void populateBodyFromJson(String jsonBody) {
        throw new NotImplementedException();
    }
}

package com.siftscience;

import okhttp3.Response;

import java.io.IOException;

public class UnlabelResponse extends SiftResponse {
    UnlabelResponse(Response okResponse, FieldSet requestBody) throws IOException {
        super(okResponse, requestBody);
    }

    /**
     * This should never be called because the unlabel API doesn't return a response body.
     *
     * @param jsonBody
     */
    @Override
    void populateBodyFromJson(String jsonBody) {
        throw new UnsupportedOperationException();
    }
}

Replace use of internal Sun API class

Replace use of internal Sun API class


package edu.chl.proton.model;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * @author Stina Werme
 * Created by stinawerme on 11/05/17.
 */
public class FolderTest {

    @Test
    public void removeFolderTest() {

        Folder parent = new Folder("parent");
        Folder child = new Folder("child", parent);

        parent.removeFolder(child);
        System.out.print(child.getParentFolder());

        assertTrue("Instance of Folder should not be null", child != null);
    }

    @Test
    public void removeFileTest() {

        File file = new File("file");
        Folder folder = new Folder("folder");
    }
}

package edu.chl.proton.model;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * @author Stina Werme
 * Created by stinawerme on 11/05/17.
 */
public class FolderTest {

    @Test
    public void removeFolderTest() {

        Folder parent = new Folder("parent");
        Folder child = new Folder("child", parent);

        parent.removeFolder(child);

        assertTrue("The folder parent should not be null", parent != null);
        assertTrue("The folder child should not be null", child != null);
        assertTrue("ParentFolder should be null", child.getParentFolder() == null);
    }

    @Test
    public void removeFileTest() {

        File file = new File("file");
        Folder folder = new Folder("folder");

        folder.removeFile(file);

        assertTrue("The file file should not be null", file != null);
        assertTrue("The folder folder should not be null", folder != null);
        assertTrue("ParentFolder should be null", file.getParentFolder() == null);
    }
    }
}

Add test for removeFile and removeFolder


package jwebform.validation;

import jwebform.validation.criteria.Criteria;
import jwebform.validation.criteria.MaxLength;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * Validator, that checks a field
 *
 * @author jochen
 *
 */
public class Validator {

  private final List<Criterion> criteria = new ArrayList<>();
  private static final Validator EMPTY_VALIDATOR = new Validator();

  public Validator(Criterion... inputCriterium) {
    Collections.addAll(criteria, inputCriterium);
  }

  public static Validator emptyValidator() {
    return EMPTY_VALIDATOR;
  }

  public boolean isRequired() {
    for (Criterion criterion : criteria) {
      if (criterion == Criteria.required()) { // this is ok, because it uses a sigelton
        return true;
      }
    }
    return false;
  }

  public Optional<MaxLength> getMaxLen() {
    for (Criterion criterion : criteria) {
      if (criterion instanceof MaxLength) { // this
        return Optional.of((MaxLength) criterion);
      }
    }
    return Optional.empty();
  }

  public ValidationResult validate(String value) { // RFE: Better just
                                                   // object??
    return allCriteriaSatisfied(value);
  }

  // RFE: Maybe return here an array? So we can have more than one
  // error-message per field.
  private ValidationResult allCriteriaSatisfied(String value) {
    for (Criterion criterion : criteria) {
      ValidationResult vr = criterion.validate(value);
      if (!vr.isValid()) {
        return vr;
      }
    }

    return ValidationResult.ok();
  }

}

package jwebform.validation;

import jwebform.validation.criteria.Criteria;
import jwebform.validation.criteria.MaxLength;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * Validator, that checks a field
 *
 * @author jochen
 *
 */
public class Validator {

  private final Criterion [] criteria;
  private static final Validator EMPTY_VALIDATOR = new Validator();

  public Validator(Criterion... inputCriterium) {
    criteria = inputCriterium;
  }

  public static Validator emptyValidator() {
    return EMPTY_VALIDATOR;
  }

  public boolean isRequired() {
    for (Criterion criterion : criteria) {
      if (criterion == Criteria.required()) { // this is ok, because it uses a sigelton
        return true;
      }
    }
    return false;
  }

  public Optional<MaxLength> getMaxLen() {
    for (Criterion criterion : criteria) {
      if (criterion instanceof MaxLength) { // this
        return Optional.of((MaxLength) criterion);
      }
    }
    return Optional.empty();
  }

  public ValidationResult validate(String value) { // RFE: Better just
                                                   // object??
    return allCriteriaSatisfied(value);
  }

  // RFE: Maybe return here an array? So we can have more than one
  // error-message per field.
  private ValidationResult allCriteriaSatisfied(String value) {
    for (Criterion criterion : criteria) {
      ValidationResult vr = criterion.validate(value);
      if (!vr.isValid()) {
        return vr;
      }
    }

    return ValidationResult.ok();
  }

}

Use internally an array for performance reasons


open module easyfxml {
    requires java.annotation;

    requires javafx.controls;
    requires javafx.fxml;
    requires javafx.graphics;

    requires spring.beans;
    requires spring.boot;
    requires spring.boot.autoconfigure;
    requires spring.context;
    requires spring.core;

    requires slf4j.api;

    requires io.vavr;
    requires awaitility;

    requires org.testfx;

    exports moe.tristan.easyfxml;
    exports moe.tristan.easyfxml.api;
    exports moe.tristan.easyfxml.util;
    exports moe.tristan.easyfxml.model.beanmanagement;
    exports moe.tristan.easyfxml.model.components.listview;
    exports moe.tristan.easyfxml.model.exception;
    exports moe.tristan.easyfxml.model.fxml;
    exports moe.tristan.easyfxml.model.system;
}

open module easyfxml {
    requires java.annotation;

    requires javafx.controls;
    requires javafx.fxml;
    requires javafx.graphics;

    requires spring.beans;
    requires spring.boot;
    requires spring.boot.autoconfigure;
    requires spring.context;
    requires spring.core;

    requires slf4j.api;

    requires io.vavr;
    requires awaitility;

    exports moe.tristan.easyfxml;
    exports moe.tristan.easyfxml.api;
    exports moe.tristan.easyfxml.util;
    exports moe.tristan.easyfxml.model.beanmanagement;
    exports moe.tristan.easyfxml.model.components.listview;
    exports moe.tristan.easyfxml.model.exception;
    exports moe.tristan.easyfxml.model.fxml;
    exports moe.tristan.easyfxml.model.system;
}

Reduce span of ducktape for TestFX + JPMS


package com.example.android.quakereport;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Don on 6/6/2017.
 */

public class SettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
    }

    public static class EarthquakePreferenceFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_xml);
        }
    }
}

package com.example.android.quakereport;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;

/**
 * Created by Don on 6/6/2017.
 */

public class SettingsActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings_activity);
    }

    public static class EarthquakePreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_xml);

            Preference minMagnitude = findPreference(getString(R.string.settings_min_magnitude_key));
            bindPreferenceSummaryToValue(minMagnitude);
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object o) {
            String stringValue = o.toString();
            preference.setSummary(stringValue);
            return true;
        }

        private void bindPreferenceSummaryToValue(Preference preference) {
            preference.setOnPreferenceChangeListener(this);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
            String preferenceString = preferences.getString(preference.getKey(), "");
            onPreferenceChange(preference, preferenceString);
        }
    }
}

Add preference value on settings activity

Allows for value of set preference to be visually seen from settings activity without going into specific setting


package cofh.api;

public class CoFHAPIProps {

    private CoFHAPIProps() {

    }

    public static final String VERSION = "1.7.10R1.0.0";

}

package cofh.api;

public class CoFHAPIProps {

    private CoFHAPIProps() {

    }

    public static final String VERSION = "1.7.10R1.0.1";

}

Update CoFH to R1.0.1 (No changes to IEnergyContainerItem)


package executors;

public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443" + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            default :
                return null;
        }
    }
}

package executors;

public class CommandCreator {

    public String createCommand(String userCommand) {
        String[] tokens =  userCommand.split("\\s+");

        switch(tokens[0]) {
            case "security":
                switch (tokens[1]) {
                    case "tls":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "ecrypt2lvl":
                        return "nmap --script ssl-enum-ciphers -p 443 " + tokens[2];
                    case "open_ports":
                        return "nmap " + tokens[2];
                    default :
                        return null;
                }
            default :
                return null;
        }
    }
}

Add space to separate arguments.

Add space to separate arguments.


package ai.h2o.automl.targetencoding;

import water.Iced;

public class BlendingParams extends Iced<BlendingParams> {
  private long k;
  private long f;

  public BlendingParams(long k, long f) {
    this.k = k;
    this.f = f;
  }

  public long getK() {
    return k;
  }

  public long getF() {
    return f;
  }
}

package ai.h2o.automl.targetencoding;

import water.Iced;

public class BlendingParams extends Iced<BlendingParams> {
  private double k;
  private double f;

  public BlendingParams(double k, double f) {
    this.k = k;
    this.f = f;
  }

  public double getK() {
    return k;
  }

  public double getF() {
    return f;
  }
}

PUBDEV-5378: Change type of blending parameters from long to double.


package org.mongodb.morphia.utils;

public enum IndexDirection {
    ASC(1),
    DESC(-1),
    GEO2D("2d");

    private final Object direction;

    IndexDirection(final Object o) {
        direction = o;
    }

    public Object toIndexValue() {
        return direction;
    }
}

package org.mongodb.morphia.utils;

public enum IndexDirection {
    ASC(1),
    DESC(-1),
    GEO2D("2d"),
    GEO2DSPHERE("2dsphere");

    private final Object direction;

    IndexDirection(final Object o) {
        direction = o;
    }

    public Object toIndexValue() {
        return direction;
    }
}

Add support for 2dsphere (Mongo 2.4+)

Add support for 2dsphere (Mongo 2.4+)

See http://docs.mongodb.org/manual/core/2dsphere/


public class Client {
    public static void main(String args[]) {
        int status = 0;
        Ice.Communicator ic = null;
        try {
            ic = Ice.Util.initialize(args);
            Ice.ObjectPrx base = ic.stringToProxy("SimplePrinter:default -p 10000");
            Demo.PrinterPrx printer = Demo.PrinterPrxHelper.checkedCast(base);
            if (printer == null) throw new Error("Invalid proxy");
            printer.printString("Hello World!");
        } catch (Ice.LocalException e) {
            e.printStackTrace();
            status = 1;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            status = 1;
        }
        if (ic != null) {
            // Clean up
            try {
                ic.destroy();
            } catch (Exception e) {
                System.err.println(e.getMessage());
                status = 1;
            }
        }
        System.exit(status);
    }
}

public class Client {
    public static void main(String args[]) {
        int status = 0;
        Ice.Communicator ic = null;
        try {
            ic = Ice.Util.initialize(args);
            Ice.ObjectPrx base = ic.stringToProxy("Portal: default -p 10000");
            Demo.PortalPrx portal = Demo.PortalPrxHelper.checkedCast(base);
            if (portal == null) throw new Error("Invalid proxy");
            portal.print("Hello Portal!");

            base = ic.stringToProxy("Server: default -p 10001");
            Demo.ServerPrx server = Demo.ServerPrxHelper.checkedCast(base);
            if (server == null) throw new Error("Invalid proxy");
            server.print("Hello Server!");
        } catch (Ice.LocalException e) {
            e.printStackTrace();
            status = 1;
        } catch (Exception e) {
            System.err.println(e.getMessage());
            status = 1;
        }
        if (ic != null) {
            try {
                ic.destroy();
            } catch (Exception e) {
                System.err.println(e.getMessage());
                status = 1;
            }
        }
        System.exit(status);
    }
}

Connect with portal and server

Connect with portal and server

Signed-off-by: Nuno Azevedo <8c1e4f9df2ead62a44323c12422702b1d8dd9c90@gmail.com>


// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build;

import org.jetbrains.annotations.ApiStatus;

import java.io.Closeable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface BuildEventDispatcher extends Appendable, Closeable, BuildProgressListener {
  @Override
  BuildEventDispatcher append(CharSequence csq);

  @Override
  BuildEventDispatcher append(CharSequence csq, int start, int end);

  @Override
  BuildEventDispatcher append(char c);

  @Override
  void close();

  void setStdOut(boolean stdOut);
}

// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.build;

import org.jetbrains.annotations.ApiStatus;

import java.io.Closeable;

/**
 * @author Vladislav.Soroka
 */
@ApiStatus.Experimental
public interface BuildEventDispatcher extends Appendable, Closeable, BuildProgressListener {
  @Override
  default BuildEventDispatcher append(CharSequence csq) {return this;}

  @Override
  default BuildEventDispatcher append(CharSequence csq, int start, int end) {return this;}

  @Override
  default BuildEventDispatcher append(char c) {return this;}

  @Override
  default void close() {}

  default void setStdOut(boolean stdOut) {}
}

Build tw: fix fetching models of android projects w/o output parsing IDEA-209457

GitOrigin-RevId: 4476671907a478bebc377d3922d723f093c389f1


package net.avatar.realms.spigot.commandsign;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

public class CommandSignCommands implements CommandExecutor{

	private CommandSign plugin;

	public CommandSignCommands (CommandSign plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

		if (!(sender instanceof Player)) {
			return false;
		}

		return true ;
	}

}

package net.avatar.realms.spigot.commandsign;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import net.md_5.bungee.api.ChatColor;

public class CommandSignCommands implements CommandExecutor{

	private CommandSign plugin;

	public CommandSignCommands (CommandSign plugin) {
		this.plugin = plugin;
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {

		if (!(sender instanceof Player)) {
			sender.sendMessage(ChatColor.RED + "You must be a played to execute this command.");
			return false;
		}

		if (args.length < 1 ) {
			sender.sendMessage(ChatColor.RED + "You need an argument to use this command.");
			return false;
		}

		String subCmd = args[0];

		if (subCmd.equalsIgnoreCase("Create") || subCmd.equalsIgnoreCase("Cr")) {
			return create((Player) sender);
		}
		else if (subCmd.equalsIgnoreCase("Edit")) {
			return edit((Player) sender);
		}
		else if (subCmd.equalsIgnoreCase("Delete") || subCmd.equalsIgnoreCase("Del")) {
			return delete ((Player) sender);
		}
		else {
			sender.sendMessage(ChatColor.RED + "Invalid Subcommand. Must be : create, edit or delete");
			return false;
		}
	}

	private boolean create (Player player) {
		return true;
	}

	private boolean edit (Player player) {
		return true;
	}

	private boolean delete (Player player) {
		return true;
	}

}

Set the bases of command signs management


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.*;
import edu.northwestern.bioinformatics.studycalendar.StudyCalendarError;
import edu.nwu.bioinformatics.commons.CollectionUtils;

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

public class UserDao extends StudyCalendarMutableDomainObjectDao<User> implements Serializable {
    @Override public Class<User> domainClass() { return User.class; }

    public List<User> getAll() {
        return getHibernateTemplate().find("from User order by name");
    }

    public User getByName(String name) {
        List<User> results = getHibernateTemplate().find("from User where name = ?", name);
        if (results.size() == 0) {
            return null;
        }
        return results.get(0);
    }

    public List getByCsmUserId(Long csmUserId) {
        List<User> results = getHibernateTemplate().find("from User where csm_user_id = ?", csmUserId);
        return results;
    }

    public List<StudySubjectAssignment> getAssignments(User user) {
        List<StudySubjectAssignment> results = getHibernateTemplate().find(
                "from StudySubjectAssignment a where a.subjectCoordinator = ? ", user);
        return results;
    }

    public List<User> getAllSubjectCoordinators() {
        return getByRole(Role.SUBJECT_COORDINATOR);
    }

    public List<User> getByRole(Role role) {
        return getHibernateTemplate()
                .find("select u from User u join u.userRoles r where r.role = ? order by u.name", role);
    }
}

package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import edu.northwestern.bioinformatics.studycalendar.domain.StudySubjectAssignment;
import edu.northwestern.bioinformatics.studycalendar.domain.User;
import edu.nwu.bioinformatics.commons.CollectionUtils;

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

public class UserDao extends StudyCalendarMutableDomainObjectDao<User> implements Serializable {
    @Override public Class<User> domainClass() { return User.class; }

    @SuppressWarnings({ "unchecked" })
    public List<User> getAll() {
        return getHibernateTemplate().find("from User order by name");
    }

    @SuppressWarnings({ "unchecked" })
    public User getByName(String name) {
        return (User) CollectionUtils.firstElement(getHibernateTemplate().find("from User where name = ?", name));
    }

    @SuppressWarnings({ "unchecked" })
    public List<StudySubjectAssignment> getAssignments(User user) {
        return (List<StudySubjectAssignment>) getHibernateTemplate().find(
                "from StudySubjectAssignment a where a.subjectCoordinator = ? ", user);
    }

    public List<User> getAllSubjectCoordinators() {
        return getByRole(Role.SUBJECT_COORDINATOR);
    }

    @SuppressWarnings({ "unchecked" })
    public List<User> getByRole(Role role) {
        return getHibernateTemplate()
                .find("select u from User u join u.userRoles r where r.role = ? order by u.name", role);
    }
}

Remove unused method; suppress unchecked cast warnings

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1836 0d517254-b314-0410-acde-c619094fa49f


package com.yammer.dropwizard.views;

import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Timer;

public abstract class View {
    private final String templateName;
    private final Timer renderingTimer;

    protected View(String templateName) {
        this.templateName = templateName;
        this.renderingTimer = Metrics.newTimer(getClass(), "rendering");
    }

    public String getTemplateName() {
        return templateName;
    }

    Timer getRenderingTimer() {
        return renderingTimer;
    }
}

package com.yammer.dropwizard.views;

import com.yammer.metrics.Metrics;
import com.yammer.metrics.core.Timer;
import org.codehaus.jackson.annotate.JsonIgnore;

public abstract class View {
    private final String templateName;
    private final Timer renderingTimer;

    protected View(String templateName) {
        this.templateName = templateName;
        this.renderingTimer = Metrics.newTimer(getClass(), "rendering");
    }

    @JsonIgnore
    public String getTemplateName() {
        return templateName;
    }

    @JsonIgnore
    Timer getRenderingTimer() {
        return renderingTimer;
    }
}

Make sure Jackson ignores the view getters.


package awesomefb;

import com.mongodb.BasicDBObject;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by earl on 5/25/2015.
 */
public class Post {
    private String mMessage;
    private User mCreator;
    private Date mCreatedTime;
    private CommentsList mCommentsList;

    public Post(JSONObject post) {
        mMessage = post.getString("message");
        mCreator = new User(post.getJSONObject("from"));
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        try {
            mCreatedTime = format.parse(post.getString("created_time"));
        } catch (ParseException e) {
            System.out.println(e.toString());
        }
        mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data"));
    }

    public BasicDBObject toDBObject() {
        BasicDBObject doc = new BasicDBObject("message", mMessage)
                .append("creator", mCreator.toDBObject())
                .append("time", mCreatedTime)
                .append("comments", mCommentsList.toDBObject());
        return doc;
    }
}

package awesomefb;

import com.mongodb.BasicDBObject;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by earl on 5/25/2015.
 */
public class Post {
    private String mMessage;
    private User mCreator;
    private Date mCreatedTime;
    private CommentsList mCommentsList;

    public Post(JSONObject post) {
        mMessage = post.getString("message");
        mCreator = new User(post.getJSONObject("from"));
        mCreatedTime = parseTime(post.getString("created_time"));
        mCommentsList = new CommentsList(post.getJSONObject("comments").getJSONArray("data"));
    }

    private Date parseTime(String dateString) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        try {
            Date time = format.parse(dateString);
            return time;
        } catch (ParseException e) {
            System.out.println(e.toString());
        }
        return null;
    }

    public BasicDBObject toDBObject() {
        BasicDBObject doc = new BasicDBObject("message", mMessage)
                .append("creator", mCreator.toDBObject())
                .append("time", mCreatedTime)
                .append("comments", mCommentsList.toDBObject());
        return doc;
    }
}

Move statements to parseTime method

Move statements to parseTime method


package com.jenzz.materialpreference.sample;

import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBarActivity;

/**
 * Created by jenzz on 28/01/15.
 */
public class SettingsActivity extends ActionBarActivity {

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // workaround for https://code.google.com/p/android/issues/detail?id=78701
    new Handler().post(new Runnable() {
      @Override public void run() {
        getFragmentManager().beginTransaction()
            .replace(android.R.id.content, new SettingsFragment())
            .commit();
      }
    });
  }

  public static class SettingsFragment extends PreferenceFragment {

    @Override public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.prefs);
    }
  }
}

package com.jenzz.materialpreference.sample;

import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBarActivity;

/**
 * Simple Activity to display example preferences.
 *
 * Created by jenzz on 28/01/15.
 */
public class SettingsActivity extends ActionBarActivity {

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
      getFragmentManager().beginTransaction()
          .add(android.R.id.content, new SettingsFragment())
          .commit();
    }
  }

  public static class SettingsFragment extends PreferenceFragment {

    @Override public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.prefs);
    }
  }
}

Fix rotation duplicating fragment in sample


package edu.harvard.iq.dataverse.actionlogging;

import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * A service bean that persists {@link ActionLogRecord}s to the DB.
 * @author michael
 */
@Stateless
public class ActionLogServiceBean {

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    /**
     * Log the record. Set default values.
     * @param rec
     */
    public void log( ActionLogRecord rec ) {
        if ( rec.getEndTime() == null ) {
            rec.setEndTime( new Date() );
        }
        if ( rec.getActionResult() == null
                && rec.getActionType() != ActionLogRecord.ActionType.Command ) {
            rec.setActionResult(ActionLogRecord.Result.OK);
        }
        em.persist(rec);
    }
}

package edu.harvard.iq.dataverse.actionlogging;

import java.util.Date;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * A service bean that persists {@link ActionLogRecord}s to the DB.
 * @author michael
 */
@Stateless
public class ActionLogServiceBean {

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    /**
     * Log the record. Set default values.
     * @param rec
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void log( ActionLogRecord rec ) {
        if ( rec.getEndTime() == null ) {
            rec.setEndTime( new Date() );
        }
        if ( rec.getActionResult() == null
                && rec.getActionType() != ActionLogRecord.ActionType.Command ) {
            rec.setActionResult(ActionLogRecord.Result.OK);
        }
        em.persist(rec);
    }
}

Add Transaction Requires New to Action Log service


package org.robolectric.shadows;

import android.opengl.GLSurfaceView;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

/** Fake implementation of GLSurfaceView */
@Implements(GLSurfaceView.class)
public class ShadowGLSurfaceView extends ShadowSurfaceView {
  @Implementation
  protected void onPause() {}

  @Implementation
  protected void onResume() {}

  @Implementation
  protected void queueEvent(Runnable r) {
    r.run();
  }
}

package org.robolectric.shadows;

import android.opengl.GLSurfaceView;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

/** Fake implementation of GLSurfaceView */
@Implements(GLSurfaceView.class)
public class ShadowGLSurfaceView extends ShadowSurfaceView {
  @Implementation
  protected void onPause() {}

  @Implementation
  protected void onResume() {}
}

Call queued events on GLSurfaceView shadow.

PiperOrigin-RevId: 200648230


package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Lists;

public final class ListElementParser extends StringElementParser {

    @Override
    Pattern createPattern() {
        return new PatternBuilder()
                .openNamedParantheses("list")
                    .appendNonCapturingPart("[")
                    .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                    .openAnonymousParantheses()
                    .appendNonCapturingPart("\\s*,\\s*")
                        .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                    .closeParantheses()
                    .zeroOrMore()
                    .appendNonCapturingPart("]")
                .closeParantheses()
                .or()
                .build();
    }

    @Override
    void parse(Matcher matcher, StringElementContext context) {
        createList(matcher, context);
    }

    private void createList(Matcher matcher, StringElementContext context) {
        List<StringElement> elements = Lists.newArrayList();
        Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group());
        while (elementMatcher.find()) {
            StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end());
            context.removeElement(element);
            elements.add(element);
        }
        context.addElement(new ListElement(matcher.start(), matcher.end(), elements));;
    }
}

package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Lists;

public final class ListElementParser extends StringElementParser {

    @Override
    Pattern createPattern() {
        return new PatternBuilder()
                .appendNonCapturingPart("\\[")
                .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                .openAnonymousParantheses()
                    .appendNonCapturingPart("\\s*,\\s*")
                    .appendNonCapturingPart(StringElementParser.REPLACE_PATTERN)
                .closeParantheses()
                .zeroOrMore()
                .appendNonCapturingPart("\\]")
                .build();
    }

    @Override
    void parse(Matcher matcher, StringElementContext context) {
        createList(matcher, context);
    }

    private void createList(Matcher matcher, StringElementContext context) {
        List<StringElement> elements = Lists.newArrayList();
        Matcher elementMatcher = StringElementParser.REPLACE_PATTERN.matcher(matcher.group());
        while (elementMatcher.find()) {
            StringElement element = context.getElementAt(elementMatcher.start(), elementMatcher.end());
            context.removeElement(element);
            elements.add(element);
        }
        context.addElement(new ListElement(matcher.start(), matcher.end(), elements));;
    }
}

Fix some bugs in the list parser regex

Fix some bugs in the list parser regex


package jp.glassmoon.app;

import java.io.File;

import jp.glassmoon.events.GerritEvent;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gerrit.server.events.PatchSetCreatedEvent;

public class App
{
    public static void main( String[] args ) throws Exception
    {
        File f = new File("event.txt");

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        GerritEvent ev = mapper.readValue(f, GerritEvent.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ev));

        if (new PatchSetCreatedEvent().type.equals(ev.type)) {
            PatchSetCreatedEvent event = mapper.readValue(f, PatchSetCreatedEvent.class);
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
        }
    }
}

package jp.glassmoon.app;

import java.io.File;

import jp.glassmoon.events.GerritEvent;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gerrit.server.events.ChangeEvent;
import com.google.gerrit.server.events.PatchSetCreatedEvent;

public class App
{
    public static void main( String[] args ) throws Exception
    {
        File f = new File("event.txt");

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        GerritEvent ev = mapper.readValue(f, GerritEvent.class);
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(ev));

        ChangeEvent event;
        if (new PatchSetCreatedEvent().type.equals(ev.type)) {
            event = mapper.readValue(f, PatchSetCreatedEvent.class);
            System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(event));
        }
    }
}

Change type to abstract class

Change type to abstract class


/*
 *  Copyright (c) 2012 Malhar, Inc.
 *  All Rights Reserved.
 */
package com.malhartech.util;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Chetan Narsude <chetan@malhar-inc.com>
 */
public class ScheduledThreadPoolExecutor extends java.util.concurrent.ScheduledThreadPoolExecutor implements ScheduledExecutorService
{
  public static final Logger logger = LoggerFactory.getLogger(ScheduledExecutorService.class);

  /**
   * Class copy-pasted from java.util.concurrent.Executors and modified to meet our needs.
   */
  static class DefaultThreadFactory implements ThreadFactory
  {
    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadGroup group;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    DefaultThreadFactory(String groupname)
    {
      SecurityManager s = System.getSecurityManager();
      group = (s != null) ? s.getThreadGroup()
              : Thread.currentThread().getThreadGroup();
      namePrefix = groupname
              + "-"
              + poolNumber.getAndIncrement()
              + "-";
    }

    @Override
    public Thread newThread(Runnable r)
    {
      Thread t = new Thread(group, r,
                            namePrefix + threadNumber.getAndIncrement(),
                            0);
      if (t.isDaemon()) {
        t.setDaemon(false);
      }
      if (t.getPriority() != Thread.NORM_PRIORITY) {
        t.setPriority(Thread.NORM_PRIORITY);
      }
      return t;
    }
  }

  public ScheduledThreadPoolExecutor(int corePoolSize, String executorName)
  {
    super(corePoolSize, new DefaultThreadFactory(executorName));
  }

  /**
   *
   * @return long
   */
  @Override
  public final long getCurrentTimeMillis()
  {
    return System.currentTimeMillis();
  }

  @Override
  protected void afterExecute(Runnable r, Throwable t)
  {
    super.afterExecute(r, t);
    if (t != null) {
      logger.error("Scheduled task {} died with {}", r, t);
    }
  }
}

/*
 *  Copyright (c) 2012 Malhar, Inc.
 *  All Rights Reserved.
 */
package com.malhartech.util;

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

/**
 *
 * @author Chetan Narsude <chetan@malhar-inc.com>
 */
public class ScheduledThreadPoolExecutor extends java.util.concurrent.ScheduledThreadPoolExecutor implements ScheduledExecutorService
{
  public static final Logger logger = LoggerFactory.getLogger(ScheduledExecutorService.class);

  public ScheduledThreadPoolExecutor(int corePoolSize, String executorName)
  {
    super(corePoolSize, new NameableThreadFactory(executorName));
  }

  /**
   *
   * @return long
   */
  @Override
  public final long getCurrentTimeMillis()
  {
    return System.currentTimeMillis();
  }

  @Override
  protected void afterExecute(Runnable r, Throwable t)
  {
    super.afterExecute(r, t);
    if (t != null) {
      logger.error("Scheduled task {} died with {}", r, t);
    }
  }
}

Move out reusable thread factory.

Move out reusable thread factory.


/*
 * Copyright DataStax, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Internal implementation details of the driver.
 *
 * <p>The types present here (and in subpackages) should not be used from client applications. If
 * you decide to use them, do so at your own risk: binary compatibility is best-effort, and we
 * reserve the right to break things at any time. Documentation may be sparse
 */
package com.datastax.oss.driver.internal;

/*
 * Copyright DataStax, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Internal implementation details of the driver.
 *
 * <p>The types present here (and in subpackages) should not be used from client applications. If
 * you decide to use them, do so at your own risk: binary compatibility is best-effort, and we
 * reserve the right to break things at any time. Documentation may be sparse.
 */
package com.datastax.oss.driver.internal;

Fix typo in package Javadocs

Fix typo in package Javadocs


package org.openqa.selenium.testing.drivers;

import com.google.common.base.Supplier;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;

public class SauceBackedDriverSupplier implements Supplier<WebDriver> {

  private final Capabilities capabilities;

  public SauceBackedDriverSupplier(Capabilities caps) {
    this.capabilities = caps;
  }

  public WebDriver get() {
    if (!SauceDriver.shouldUseSauce()) {
      return null;
    }

    return new SauceDriver(capabilities);
  }
}

package org.openqa.selenium.testing.drivers;

import com.google.common.base.Supplier;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.LocalFileDetector;

public class SauceBackedDriverSupplier implements Supplier<WebDriver> {

  private final Capabilities capabilities;

  public SauceBackedDriverSupplier(Capabilities caps) {
    this.capabilities = caps;
  }

  public WebDriver get() {
    if (!SauceDriver.shouldUseSauce()) {
      return null;
    }

    SauceDriver driver = new SauceDriver(capabilities);
    driver.setFileDetector(new LocalFileDetector());
    return driver;
  }
}

Use a file detector for Sauce tests

DanielWagnerHall: Use a file detector for Sauce tests

git-svn-id: 4179480af2c2519a5eb5e1e9b541cbdf5cf27696@15219 07704840-8298-11de-bf8c-fd130f914ac9


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

package net.openhft.chronicle.wire;

import net.openhft.chronicle.core.annotation.NotNull;
import net.openhft.chronicle.core.io.IORuntimeException;

/*
 * Created by peter on 16/03/16.
 */
public abstract class AbstractMarshallableCfg extends AbstractMarshallable {

    @Override
    public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException {
        Wires.readMarshallable(this, wire, false);
    }

    @Override
    public void writeMarshallable(@NotNull WireOut wire) {
        Wires.writeMarshallable(this, wire, false);
    }
}

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

package net.openhft.chronicle.wire;

import net.openhft.chronicle.core.Jvm;
import net.openhft.chronicle.core.annotation.NotNull;
import net.openhft.chronicle.core.io.IORuntimeException;

/*
 * Created by peter on 16/03/16.
 */
public abstract class AbstractMarshallableCfg extends AbstractMarshallable {

    @Override
    public void readMarshallable(@NotNull WireIn wire) throws IORuntimeException {
        Wires.readMarshallable(this, wire, false);
    }

    @Override
    public void writeMarshallable(@NotNull WireOut wire) {
        Wires.writeMarshallable(this, wire, false);
    }

    @Override
    public void unexpectedField(Object event, ValueIn valueIn) {
        Jvm.warn().on(getClass(), "Field " + event + " ignored, was " + valueIn.object());
    }
}

Add support for unexpected fields and improved out of order.


package com.easternedgerobotics.rov.math;

import org.junit.Test;
import rx.observers.TestSubscriber;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;

@SuppressWarnings("checkstyle:MagicNumber")
public final class MovingAverageTest {
    @Test
    public final void averageCalculationDoesReturnTheCorrectResult() {
        final TestScheduler scheduler = new TestScheduler();
        final TestSubject<Float> numbers = TestSubject.create(scheduler);
        final TestSubscriber<Float> subscriber = new TestSubscriber<>();
        MovingAverage.from(numbers, 2).subscribe(subscriber);

        numbers.onNext(1f);
        scheduler.triggerActions();
        subscriber.assertValueCount(1);
        subscriber.assertValue(1f);

        numbers.onNext(9f);
        scheduler.triggerActions();
        subscriber.assertValueCount(2);
        subscriber.assertValues(1f, 5f);

        numbers.onNext(20f);
        scheduler.triggerActions();
        subscriber.assertValueCount(3);
        subscriber.assertValues(1f, 5f, 14.5f);

        numbers.onNext(40f);
        scheduler.triggerActions();
        subscriber.assertValueCount(4);
        subscriber.assertValues(1f, 5f, 14.5f, 30f);
    }
}

package com.easternedgerobotics.rov.math;

import org.junit.Test;
import rx.observers.TestSubscriber;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;

@SuppressWarnings("checkstyle:MagicNumber")
public final class MovingAverageTest {
    @Test
    public final void averageCalculationDoesReturnTheCorrectResult() {
        final TestScheduler scheduler = new TestScheduler();
        final TestSubject<Float> numbers = TestSubject.create(scheduler);
        final TestSubscriber<Float> subscriber = new TestSubscriber<>();
        MovingAverage.from(numbers, 2).subscribe(subscriber);

        numbers.onNext(1.5f);
        scheduler.triggerActions();
        subscriber.assertValueCount(1);
        subscriber.assertValue(1.5f);

        numbers.onNext(8.5f);
        scheduler.triggerActions();
        subscriber.assertValueCount(2);
        subscriber.assertValues(1.5f, 8.5f);

        numbers.onNext(21.5f);
        scheduler.triggerActions();
        subscriber.assertValueCount(3);
        subscriber.assertValues(1.5f, 8.5f, 15f);

        numbers.onNext(41.5f);
        scheduler.triggerActions();
        subscriber.assertValueCount(4);
        subscriber.assertValues(1f, 5f, 14.5f, 30f);
    }
}

Update moving average tests to show floating point truncation


package forager.events;

import galileo.event.EventMap;

public class ForagerEventMap extends EventMap {

    public ForagerEventMap() {
        addMapping(1, JoinEvent.class);
        addMapping(2, TaskSpec.class);
    }
}

package forager.events;

import galileo.event.EventMap;

public class ForagerEventMap extends EventMap {

    public ForagerEventMap() {
        addMapping(JoinEvent.class);
        addMapping(TaskRequest.class);
        addMapping(TaskSpec.class);
    }
}

Update for new ID-less addMapping()

Update for new ID-less addMapping()


package oe.packet;

import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;

public class PacketHandler implements IPacketHandler {

  @Override
  public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {
    System.out.println(packet.channel);
    if (packet.channel == "oe" || packet.channel == "OE") {
      InternalPacket.packet(manager, packet, playerEntity);
    }
  }

}

package oe.packet;

import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.Player;

public class PacketHandler implements IPacketHandler {

  @Override
  public void onPacketData(INetworkManager manager, Packet250CustomPayload packet, Player playerEntity) {
    if (packet.channel == "oe" || packet.channel == "OE") {
      InternalPacket.packet(manager, packet, playerEntity);
    }
  }

}

Remove Debug code in packet handler

Remove Debug code in packet handler


package referencelibrary.ui.command;

import referencelibrary.App;
import referencelibrary.io.IO;

/**
 * Created by petri on 16.4.2016.
 */
public class GenerateBibTexCommand extends Command {

    public GenerateBibTexCommand(App app, IO io) {
        super(app, io);
    }

    @Override
    public void execute() {
        io.print("\nGenerating bibTex -file");
        String filename = io.readLine("Please insert filename:");
        app.generateBixTexFile(filename);

        io.print("Generating done!\n");
    }
}

package referencelibrary.ui.command;

import referencelibrary.App;
import referencelibrary.io.IO;

/**
 * Created by petri on 16.4.2016.
 */
public class GenerateBibTexCommand extends Command {

    private static final String BIBTEX_FILE_ENDING = ".bib";

    public GenerateBibTexCommand(App app, IO io) {
        super(app, io);
    }

    @Override
    public void execute() {
        io.print("\nGenerating bibTex -file");
        String filename = io.readLine("Please insert filename:");
        app.generateBixTexFile(filename+BIBTEX_FILE_ENDING);

        io.print("Generating done!\n");
    }
}

Add .bib ending to generated files

Add .bib ending to generated files


/*
 * 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.guacamole.properties;

import java.net.URI;
import java.net.URISyntaxException;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleServerException;

/**
 * A GuacamoleProperty whose value is a URI.
 */
public abstract class URIGuacamoleProperty implements GuacamoleProperty<URI> {

    @Override
    public URI parseValue(String value) throws GuacamoleException {

        try {
            return new URI(value);
        }
        catch (URISyntaxException e) {
            throw new GuacamoleServerException("Value \"" + value
                + "\" is not a valid URI.");
        }

    }

}

/*
 * 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.guacamole.properties;

import java.net.URI;
import java.net.URISyntaxException;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.GuacamoleServerException;

/**
 * A GuacamoleProperty whose value is a URI.
 */
public abstract class URIGuacamoleProperty implements GuacamoleProperty<URI> {

    @Override
    public URI parseValue(String value) throws GuacamoleException {

        // If nothing is provided, just return null.
        if (value == null)
            return null;

        try {
            return new URI(value);
        }
        catch (URISyntaxException e) {
            throw new GuacamoleServerException("Value \"" + value
                + "\" is not a valid URI.");
        }

    }

}

Return null for null property values.

GUACAMOLE-678: Return null for null property values.


package com.conveyal.gtfs.util;

import org.junit.Test;

import static com.conveyal.gtfs.util.Util.human;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * A test suite to verify the functionality of methods in the Util class.
 */
public class UtilTest {

    /**
     * Assert that the human function returns strings that are properly formatted.
     */
    @Test
    public void canHumanize() {
        assertThat(human(123), is("123"));
        assertThat(human(1234), is("1k"));
        assertThat(human(1234567), is("1.2M"));
        assertThat(human(1234567890), is("1.2G"));
    }
}

package com.conveyal.gtfs.util;

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

import static com.conveyal.gtfs.util.Util.human;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * A test suite to verify the functionality of methods in the Util class.
 */
public class UtilTest {
    @Before // setup()
    public void before() throws Exception {
        java.util.Locale.setDefault(java.util.Locale.US);
    }

    /**
     * Assert that the human function returns strings that are properly formatted.
     */
    @Test
    public void canHumanize() {
        assertThat(human(123), is("123"));
        assertThat(human(1234), is("1k"));
        assertThat(human(1234567), is("1.2M"));
        assertThat(human(1234567890), is("1.2G"));
    }
}

Set locale to US on humanize test

Set locale to US on humanize test


package org.openlmis.core.upload;

import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {

  @Autowired
  private BudgetService service;

  @Autowired
  private FacilityService facilityService;

  @Autowired
  private ProgramService programService;

  @Autowired
  private ProcessingPeriodService processingPeriodService;

  @Override
  protected BaseModel getExisting(BaseModel record) {
    Budget budget = ((Budget) record);
    return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
  }

  @Override
  protected void save(BaseModel record) {
    fillReferenceData((Budget) record);
    validateBudget((Budget) record);
    service.save((Budget) record);
  }

  private void fillReferenceData(Budget budget){
      // set the id's of all reference data
      // this is to make sure that the save routine will be able to save this budget information
      budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
      budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
      budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
  }

  private void validateBudget(Budget budget){
     facilityService.is
  }

  @Override
  protected String getDuplicateMessageKey() {
    return "error.duplicate.Budget";
  }
}

package org.openlmis.core.upload;

import org.openlmis.core.domain.BaseModel;
import org.openlmis.core.domain.Budget;
import org.openlmis.core.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BudgetHandler extends AbstractModelPersistenceHandler {

  @Autowired
  private BudgetService service;

  @Autowired
  private FacilityService facilityService;

  @Autowired
  private ProgramService programService;

  @Autowired
  private ProcessingPeriodService processingPeriodService;

  @Override
  protected BaseModel getExisting(BaseModel record) {
    Budget budget = ((Budget) record);
    return service.getByCodes(budget.getProgram().getCode(), budget.getPeriod().getName(), budget.getFacility().getCode() );
  }

  @Override
  protected void save(BaseModel record) {
    fillReferenceData((Budget) record);
    validateBudget((Budget) record);
    service.save((Budget) record);
  }

  private void fillReferenceData(Budget budget){
      // set the id's of all reference data
      // this is to make sure that the save routine will be able to save this budget information
      budget.setFacility( facilityService.getByCode(budget.getFacility() ) );
      budget.setProgram( programService.getByCode(budget.getProgram().getCode()));
      budget.getPeriod().setId(processingPeriodService.getIdByName(budget.getPeriod().getName()));
  }

  private void validateBudget(Budget budget){

  }

  @Override
  protected String getDuplicateMessageKey() {
    return "error.duplicate.Budget";
  }
}

Fix compiler error on validate budget handler


/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

/**
 * Copyright 2005-2011 The Kuali Foundation
 *
 * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
 *
 * 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 edu.samplu.mainmenu.test;

import org.junit.Test;

import edu.samplu.common.MainMenuLookupLegacyITBase;

/**
 * tests that user 'admin' can display the Term lookup screen, search,
 * initiate an Term maintenance document via an edit action on the search results and
 * finally cancel the maintenance document
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public class TermLookUpLegacyIT extends MainMenuLookupLegacyITBase {
    @Override
    public void testLookUp() {} // no-op to avoid https://jira.kuali.org/browse/KULRICE-9047 messing up the server state

    @Override
    public String getLinkLocator() {
        return "Term Lookup";
    }

    @Test
    public void lookupAssertions() throws Exception{
        gotoMenuLinkLocator();
        super.testTermLookUp();
    }
}

KULRICE-9047: Disable term lookup smoke test to avoid any server impact till fixed.

git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@37464 7a7aa7f6-c479-11dc-97e2-85a2497f191d


package com.github.aureliano.verbum_domini.helper;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public final class UrlHelper {

	private UrlHelper() {
		super();
	}

	public static String join(Object...tokens) {
		return "/" + StringUtils.join(tokens, '/');
	}

	public static String buildWebAppUrl(ServletRequest request, String path) {
		String contextPath = ((HttpServletRequest) request).getContextPath();
		if (contextPath.startsWith("/")) {
			contextPath = contextPath.substring(1);
		}
		return join(contextPath, path);
	}

	public static String buildWebAppUrl(String path) {
		return buildWebAppUrl(WebHelper.getRequest(), path);
	}
}

package com.github.aureliano.verbum_domini.helper;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public final class UrlHelper {

	private UrlHelper() {
		super();
	}

	public static String join(Object...tokens) {
		return "/" + StringUtils.join(tokens, '/');
	}

	public static String buildWebAppUrl(ServletRequest request, String path) {
		String contextPath = ((HttpServletRequest) request).getContextPath();
		if (contextPath.startsWith("/")) {
			contextPath = contextPath.substring(1);
		}

		return (StringUtils.isEmpty(contextPath)) ? path : join(contextPath, path);
	}

	public static String buildWebAppUrl(String path) {
		return buildWebAppUrl(WebHelper.getRequest(), path);
	}
}

Build URL with server context path.

Build URL with server context path.


package net.openright.infrastructure.rest;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonGetController implements GetController {

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

	private JsonController jsonController;

	public JsonGetController(JsonController jsonController) {
		this.jsonController = jsonController;
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] parts = req.getPathInfo().split("\\/");

		try {
			JSONObject json = parts.length > 2 ? jsonController.getJSON(parts[2]) : jsonController.listJSON(req);
			log.info("JSON response: {}", json);
			sendResponse(resp, json);
		} catch (RequestException e) {
			log.warn("Invalid request {}: {}", req.getRequestURL(), e.toString());
			resp.sendError(e.getStatusCode(), e.toString());
		}
	}

	private void sendResponse(HttpServletResponse resp, JSONObject response) throws IOException {
		resp.setHeader("Expires", "-1");

		if (response == null) {
			resp.setStatus(204);
			return;
		}

		resp.setContentType("application/json");
		try (Writer writer = resp.getWriter()) {
			writer.write(response.toString());
		}
	}
}

package net.openright.infrastructure.rest;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JsonGetController implements GetController {

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

	private JsonController jsonController;

	public JsonGetController(JsonController jsonController) {
		this.jsonController = jsonController;
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] parts = req.getPathInfo().split("\\/");

		try {
			JSONObject json = parts.length > 2 ? jsonController.getJSON(parts[2]) : jsonController.listJSON(req);
			log.info("JSON response: {}", json.toString());
			sendResponse(resp, json);
		} catch (RequestException e) {
			log.warn("Invalid request {}: {}", req.getRequestURL(), e.toString());
			resp.sendError(e.getStatusCode(), e.toString());
		}
	}

	private void sendResponse(HttpServletResponse resp, JSONObject response) throws IOException {
		resp.setHeader("Expires", "-1");

		if (response == null) {
			resp.setStatus(204);
			return;
		}

		resp.setContentType("application/json");
		try (Writer writer = resp.getWriter()) {
			writer.write(response.toString());
		}
	}
}

Use json.toString instead of json when printing object.


/*
 * Copyright 2021, Yurii Serhiichuk
 *
 * 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.openweathermap.api.query;

import lombok.Data;

@Data
public abstract class AbstractQuery implements Query {
    private UnitFormat unitFormat;
    private Language language;
    private final String baseUrl = BASE_URL;

    @Override
    public String toStringRepresentation(String apiKey) {
        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        stringBuilder.append(getSearchPath());
        stringBuilder.append(QUESTION_MARK);
        if (getLanguage() != null) {
            stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND);
        }
        if (getUnitFormat() != null) {
            stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND);
        }
        stringBuilder.append(getRequestPart());
        stringBuilder.append(AND).append("appid=").append(apiKey);
        return stringBuilder.toString();
    }

    protected abstract String getSearchPath();

    protected abstract String getRequestPart();
}

/*
 * Copyright 2021, Yurii Serhiichuk
 *
 * 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.openweathermap.api.query;

import lombok.Data;

@Data
public abstract class AbstractQuery implements Query {

    @SuppressWarnings({"FieldCanBeLocal", "FieldMayBeFinal"}) /* We'd like to be able to override the base URL. */
    private String baseUrl = BASE_URL;
    private UnitFormat unitFormat;
    private Language language;

    @Override
    public String toStringRepresentation(String apiKey) {
        StringBuilder stringBuilder = new StringBuilder(baseUrl);
        stringBuilder.append(getSearchPath());
        stringBuilder.append(QUESTION_MARK);
        if (getLanguage() != null) {
            stringBuilder.append("lang=").append(getLanguage().getStringRepresentation()).append(AND);
        }
        if (getUnitFormat() != null) {
            stringBuilder.append("units=").append(getUnitFormat().getStringRepresentation()).append(AND);
        }
        stringBuilder.append(getRequestPart());
        stringBuilder.append(AND).append("appid=").append(apiKey);
        return stringBuilder.toString();
    }

    protected abstract String getSearchPath();

    protected abstract String getRequestPart();
}

Make `baseUrl` non-final as we should be able to override it.