package de.sormuras.bach.util;

import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ServiceLoader;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.spi.ToolProvider;

/** Tool registry. */
public class Tools {

  final Map<String, ToolProvider> map;

  public Tools() {
    this.map = new TreeMap<>();
    ServiceLoader.load(ToolProvider.class).stream()
        .map(ServiceLoader.Provider::get)
        .forEach(provider -> map.putIfAbsent(provider.name(), provider));
  }

  public ToolProvider get(String name) {
    var tool = map.get(name);
    if (tool == null) {
      throw new NoSuchElementException("No such tool: " + name);
    }
    return tool;
  }

  public void forEach(Consumer<ToolProvider> action) {
    map.values().forEach(action);
  }
}

package de.sormuras.bach.util;

import java.util.Map;
import java.util.NoSuchElementException;
import java.util.ServiceLoader;
import java.util.TreeMap;
import java.util.function.Consumer;
import java.util.spi.ToolProvider;

/** Tool registry. */
public class Tools {

  final Map<String, ToolProvider> map;

  public Tools() {
    this.map = new TreeMap<>();
    ServiceLoader.load(ToolProvider.class, ClassLoader.getSystemClassLoader()).stream()
        .map(ServiceLoader.Provider::get)
        .forEach(provider -> map.putIfAbsent(provider.name(), provider));
  }

  public ToolProvider get(String name) {
    var tool = map.get(name);
    if (tool == null) {
      throw new NoSuchElementException("No such tool: " + name);
    }
    return tool;
  }

  public void forEach(Consumer<ToolProvider> action) {
    map.values().forEach(action);
  }
}

Use system (application) class loader to load tool providers


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

package org.cloudfoundry.operations;

import org.junit.Test;

import static org.cloudfoundry.operations.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;

public final class ListRoutesRequestTest {

    @Test
    public void isValid() {
        ValidationResult result = ListRoutesRequest.builder()
                .level(ListRoutesRequest.Level.Organization)
                .build()
                .isValid();

        assertEquals(VALID, result.getStatus());
    }

}

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

package org.cloudfoundry.operations;

import org.junit.Test;

import static org.cloudfoundry.operations.ValidationResult.Status.VALID;
import static org.junit.Assert.assertEquals;

public final class ListRoutesRequestTest {

    @Test
    public void isValid() {
        ValidationResult result = ListRoutesRequest.builder()
                .level(ListRoutesRequest.Level.Organization)
                .build()
                .isValid();

        assertEquals(VALID, result.getStatus());
    }

    @Test
    public void isValidNoLevel() {
        ValidationResult result = ListRoutesRequest.builder()
                .build()
                .isValid();

        assertEquals(VALID, result.getStatus());
    }

}

Add test for level being omitted on Routes operation.

Added testing for the default case.


/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
 *
 * 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 java.util.jar;

import java.util.zip.ZipException;

/**
 * This runtime exception is thrown when a problem occurrs while reading a JAR
 * file.
 *
 */
public class JarException extends ZipException {

	/**
	 * Constructs a new instance of this class with its walkback filled in.
	 */
	public JarException() {
		super();
	}

	/**
	 * Constructs a new instance of this class with its walkback and message
	 * filled in.
	 *
	 * @param detailMessage
	 *            String The detail message for the exception.
	 */
	public JarException(String detailMessage) {
		super(detailMessage);
	}
}

/* Copyright 1998, 2005 The Apache Software Foundation or its licensors, as applicable
 *
 * 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 java.util.jar;

import java.util.zip.ZipException;

/**
 * This runtime exception is thrown when a problem occurrs while reading a JAR
 * file.
 */
public class JarException extends ZipException {

    private static final long serialVersionUID = 7159778400963954473L;

    /**
     * Constructs a new instance of this class with its walkback filled in.
     */
    public JarException() {
        super();
    }

    /**
     * Constructs a new instance of this class with its walkback and message
     * filled in.
     *
     * @param detailMessage
     *            String The detail message for the exception.
     */
    public JarException(String detailMessage) {
        super(detailMessage);
    }
}

Add constant SUID and minor reformatting

svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=410556


package org.multibit.hd.core.dto;

/**
 *
Enum to provide the following to various UI models:

 *

 *
High level wallet type selection (standard, Trezor, KeepKey etc)

 *

 *
 *
This reduces code complexity in factory methods when deciding how to build supporting objects

 *
 * @since 0.0.1
 *
 */
public enum WalletMode {

  /**
   * Target a standard soft wallet (BIP 32 or BIP 44)
   */
  STANDARD,

  /**
   * Target a Trezor wallet (BIP 44 only)
   */
  TREZOR,

  /**
   * Target a KeepKey wallet (BIP 44 only)
   */
  KEEP_KEY,

  // End of enum
  ;

}

package org.multibit.hd.core.dto;

/**
 *
Enum to provide the following to various UI models:

 *

 *
High level wallet type selection (standard, Trezor, KeepKey etc)

 *

 *
 *
This reduces code complexity in factory methods when deciding how to build supporting objects

 *
 * @since 0.0.1
 */
public enum WalletMode {

  /**
   * Target a standard soft wallet (BIP 32 or BIP 44)
   */
  STANDARD("MultiBit"),

  /**
   * Target a Trezor wallet (BIP 44 only)
   */
  TREZOR("Trezor"),

  /**
   * Target a KeepKey wallet (BIP 44 only)
   */
  KEEP_KEY("KeepKey"),

  // End of enum
  ;

  private final String brand;

  WalletMode(String brand) {
    this.brand = brand;
  }

  /**
   * @return The brand name for use with localisation
   */
  public String brand() {
    return brand;
  }
}

Add support for brand names in message keys to reduce translation burden


/**
 * Copyright 2015 Smart Community Lab
 *
 * 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 it.smartcommunitylab.carpooling.mongo.repos;

import it.smartcommunitylab.carpooling.model.Travel;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;

public interface TravelRepository extends MongoRepository<Travel, String>, TravelRepositoryCustom {

	@Query("{'userId':?0}")
	List<Travel> findTravelByDriverId(String userId);

	@Query("{'id':?0, 'userId':?1}")
	Travel findTravelByIdAndDriverId(String id, String userId);

}

/**
 * Copyright 2015 Smart Community Lab
 *
 * 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 it.smartcommunitylab.carpooling.mongo.repos;

import it.smartcommunitylab.carpooling.model.Travel;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;

public interface TravelRepository extends PagingAndSortingRepository<Travel, String>, TravelRepositoryCustom {

	@Query("{'userId':?0}")
	List<Travel> findTravelByDriverId(String userId);

	@Query("{'userId':?0}")
	Page<Travel> findTravelByDriverId(String userId, Pageable pageable);

	@Query("{'id':?0, 'userId':?1}")
	Travel findTravelByIdAndDriverId(String id, String userId);

}

Fix for usage of PagingAndSortingRepository


package name.matco.simcity.api;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@Provider
public class ObjectMapperResolver implements ContextResolver<ObjectMapper> {

	private final ObjectMapper mapper;

	public ObjectMapperResolver() {
		mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);
	}

	@Override
	public ObjectMapper getContext(final Class<?> type) {
		return mapper;
	}
}

package name.matco.simcity.api;

import java.io.IOException;

import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.jaxrs.cfg.EndpointConfigBase;
import com.fasterxml.jackson.jaxrs.cfg.ObjectWriterInjector;
import com.fasterxml.jackson.jaxrs.cfg.ObjectWriterModifier;

@Provider
public class ObjectMapperResolver implements ContextResolver<ObjectMapper> {

	private final ObjectMapper mapper;

	public ObjectMapperResolver() {
		mapper = new ObjectMapper();
		ObjectWriterInjector.set(new ObjectWriterModifier() {
			@Override
			public ObjectWriter modify(final EndpointConfigBase<?> endpoint, final MultivaluedMap<String, Object> responseHeaders, final Object valueToWrite, final ObjectWriter w, final JsonGenerator g) throws IOException {
				final DefaultPrettyPrinter pp = new DefaultPrettyPrinter();
				pp.indentObjectsWith(new DefaultIndenter("\t", "\n"));
				g.setPrettyPrinter(pp);
				return w;
			}
		});
	}

	@Override
	public ObjectMapper getContext(final Class<?> type) {
		return mapper;
	}
}

Improve indentation of JSON content from REST API


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

package org.apache.jmeter.threads;

import junit.framework.TestCase;

public class TestJMeterContextService extends TestCase {

    public TestJMeterContextService(String name) {
        super(name);
    }

    // Give access to the method for test code
    public static void incrNumberOfThreads(){
        JMeterContextService.incrNumberOfThreads();
    }
    // Give access to the method for test code
    public static void decrNumberOfThreads(){
        JMeterContextService.decrNumberOfThreads();
    }
}

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

package org.apache.jmeter.threads;

import junit.framework.TestCase;

public class TestJMeterContextService extends TestCase {

    public TestJMeterContextService(String name) {
        super(name);
    }

    public void testCounts(){
        assertEquals(0,JMeterContextService.getNumberOfThreads());
        assertEquals(0,JMeterContextService.getTotalThreads());
        incrNumberOfThreads();
        assertEquals(1,JMeterContextService.getNumberOfThreads());
        assertEquals(0,JMeterContextService.getTotalThreads());
        decrNumberOfThreads();
        assertEquals(0,JMeterContextService.getTotalThreads());
        assertEquals(0,JMeterContextService.getNumberOfThreads());
        JMeterContextService.addTotalThreads(27);
        JMeterContextService.addTotalThreads(27);
        assertEquals(54,JMeterContextService.getTotalThreads());
        assertEquals(0,JMeterContextService.getNumberOfThreads());
    }

    // Give access to the method for test code
    public static void incrNumberOfThreads(){
        JMeterContextService.incrNumberOfThreads();
    }
    // Give access to the method for test code
    public static void decrNumberOfThreads(){
        JMeterContextService.decrNumberOfThreads();
    }
}

Create some tests for JMeterContextService

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

Former-commit-id: b15f11b6a02e16103f434a4a2a64a0bdd7f863e9


package eu.europa.esig.dss.validation.process.qmatrix;

import java.util.Date;

import javax.xml.bind.DatatypeConverter;

public final class EIDASUtils {

	private EIDASUtils() {
	}

	/**
	 * Start date of the eIDAS regularisation
	 */
	private final static Date EIDAS_DATE = DatatypeConverter.parseDateTime("2016-07-01T00:00:00.000Z").getTime();

	/**
	 * End of the grace period for eIDAS regularisation
	 */
	private final static Date EIDAS_GRACE_DATE = DatatypeConverter.parseDateTime("2017-07-01T00:00:00.000Z").getTime();

	public static boolean isPostEIDAS(Date date) {
		return date != null && date.compareTo(EIDAS_DATE) >= 0;
	}

	public static boolean isPreEIDAS(Date date) {
		return date != null && date.compareTo(EIDAS_DATE) < 0;
	}

	public static boolean isPostGracePeriod(Date date) {
		return date != null && date.compareTo(EIDAS_GRACE_DATE) >= 0;
	}

}

package eu.europa.esig.dss.validation.process.qmatrix;

import java.util.Date;

import javax.xml.bind.DatatypeConverter;

public final class EIDASUtils {

	private EIDASUtils() {
	}

	/**
	 * Start date of the eIDAS regulation
	 *
	 * Regulation was signed in Brussels : 1st of July 00:00 Brussels = 30th of June 22:00 UTC
	 */
	private final static Date EIDAS_DATE = DatatypeConverter.parseDateTime("2016-06-30T22:00:00.000Z").getTime();

	/**
	 * End of the grace period for eIDAS regulation
	 */
	private final static Date EIDAS_GRACE_DATE = DatatypeConverter.parseDateTime("2017-06-30T22:00:00.000Z").getTime();

	public static boolean isPostEIDAS(Date date) {
		return date != null && date.compareTo(EIDAS_DATE) >= 0;
	}

	public static boolean isPreEIDAS(Date date) {
		return date != null && date.compareTo(EIDAS_DATE) < 0;
	}

	public static boolean isPostGracePeriod(Date date) {
		return date != null && date.compareTo(EIDAS_GRACE_DATE) >= 0;
	}

}

Fix eIDAS date (Brussels date is used)

Fix eIDAS date (Brussels date is used)


package info.u_team.u_team_test.init;

import info.u_team.u_team_test.TestMod;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;
import net.minecraftforge.fml.common.gameevent.PlayerEvent.PlayerChangedDimensionEvent;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE)
public class TestDimensions {

	@SubscribeEvent
	public static void on(RegisterDimensionsEvent event) {
		// Dimension are broken currently
		// if (!DimensionManager.getRegistry().containsKey(TestModDimensions.BASIC.getRegistryName())) { // How do we know when
		// the dimension needs to be registered??
		// DimensionManager.registerDimension(TestModDimensions.BASIC.getRegistryName(), TestModDimensions.BASIC, null, true);
		// }
	}

	@SubscribeEvent
	public static void on(EntityTravelToDimensionEvent event) {
		System.out.println("START TRAVELING TO " + event.getDimension() + " AS " + event.getEntity());
	}

	@SubscribeEvent
	public static void on(PlayerChangedDimensionEvent event) {
		System.out.println("FINISHED TRAVELING TO: " + event.getTo() + " FROM " + event.getFrom() + " AS " + event.getPlayer());
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_test.TestMod;
import net.minecraftforge.event.entity.EntityTravelToDimensionEvent;
import net.minecraftforge.event.entity.player.PlayerEvent.PlayerChangedDimensionEvent;
import net.minecraftforge.event.world.RegisterDimensionsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber;
import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus;

@EventBusSubscriber(modid = TestMod.MODID, bus = Bus.FORGE)
public class TestDimensions {

	@SubscribeEvent
	public static void on(RegisterDimensionsEvent event) {
		// Dimension are broken currently
		// if (!DimensionManager.getRegistry().containsKey(TestModDimensions.BASIC.getRegistryName())) { // How do we know when
		// the dimension needs to be registered??
		// DimensionManager.registerDimension(TestModDimensions.BASIC.getRegistryName(), TestModDimensions.BASIC, null, true);
		// }
	}

	@SubscribeEvent
	public static void on(EntityTravelToDimensionEvent event) {
		System.out.println("START TRAVELING TO " + event.getDimension() + " AS " + event.getEntity());
	}

	@SubscribeEvent
	public static void on(PlayerChangedDimensionEvent event) {
		System.out.println("FINISHED TRAVELING TO: " + event.getTo() + " FROM " + event.getFrom() + " AS " + event.getPlayer());
	}

}

Fix compile error due to new forge version


package cpw.mods.fml.relauncher;

import java.security.Permission;

/**
 * A custom security manager stopping certain events from happening
 * unexpectedly.
 *
 * @author cpw
 *
 */
public class FMLSecurityManager extends SecurityManager {
    @Override
    public void checkPermission(Permission perm)
    {
        String permName = perm.getName() != null ? perm.getName() : "missing";
        if (permName.startsWith("exitVM"))
        {
            String callingClass = getClassContext()[4].getName();
            // FML is allowed to call system exit
            if (!callingClass.startsWith("cpw.mods.fml."))
            {
                throw new ExitTrappedException();
            }
        }
        else if ("setSecurityManager".equals(permName))
        {
            throw new SecurityException("Cannot replace the FML security manager");
        }
        return;
    }

    public static class ExitTrappedException extends SecurityException {
        private static final long serialVersionUID = 1L;
    }
}

package cpw.mods.fml.relauncher;

import java.security.Permission;

/**
 * A custom security manager stopping certain events from happening
 * unexpectedly.
 *
 * @author cpw
 *
 */
public class FMLSecurityManager extends SecurityManager {
    @Override
    public void checkPermission(Permission perm)
    {
        String permName = perm.getName() != null ? perm.getName() : "missing";
        if (permName.startsWith("exitVM"))
        {
            Class<?>[] classContexts = getClassContext();
            String callingClass = classContexts.length > 3 ? classContexts[4].getName() : "none";
            String callingParent = classContexts.length > 4 ? classContexts[5].getName() : "none";
            // FML is allowed to call system exit and the Minecraft applet (from the quit button)
            if (!(callingClass.startsWith("cpw.mods.fml.") || ( "net.minecraft.client.Minecraft".equals(callingClass) && "net.minecraft.client.Minecraft".equals(callingParent)) || ("net.minecraft.server.dedicated.DedicatedServer".equals(callingClass) && "net.minecraft.server.MinecraftServer".equals(callingParent))))
            {
                throw new ExitTrappedException();
            }
        }
        else if ("setSecurityManager".equals(permName))
        {
            throw new SecurityException("Cannot replace the FML security manager");
        }
        return;
    }

    public static class ExitTrappedException extends SecurityException {
        private static final long serialVersionUID = 1L;
    }
}

Fix up other exit points. Should stop process hangs for clean exits.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.technobots.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 * @author miguel
 */
public class NormalAutonomous extends CommandGroup {

    public NormalAutonomous() {

        //addSequential(new StopBall());
        addParallel(new ShooterOn(-.8));
        addSequential(new ReleaseBall());
        addSequential(new StopBall());

    }
}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.technobots.commands;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 * @author miguel
 */
public class NormalAutonomous extends CommandGroup {

    public NormalAutonomous() {

        //addSequential(new StopBall());
        addParallel(new ShooterOn(-.6));
        addSequential(new ReleaseBall());
        addSequential(new StopBall());

    }
}

Change speed for shooter in autonomous.

Change speed for shooter in autonomous.


package org.opencds.cqf.config;

import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;

import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Library;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created by Christopher on 1/12/2017.
 */
public class STU3LibrarySourceProvider implements LibrarySourceProvider {

    private LibraryResourceProvider provider;
    private FhirLibrarySourceProvider innerProvider;

    public STU3LibrarySourceProvider(LibraryResourceProvider provider) {
        this.provider = provider;
        this.innerProvider = new FhirLibrarySourceProvider();
    }

    @Override
    public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
        Library lib = provider.getDao().read(new IdType(versionedIdentifier.getId()));

        if (lib != null) {
            for (Attachment content : lib.getContent()) {
                if (content.getContentType().equals("text/cql")) {
                    return new ByteArrayInputStream(content.getData());
                }
            }
        }

        return this.innerProvider.getLibrarySource(versionedIdentifier);
    }
}

package org.opencds.cqf.config;

import ca.uhn.fhir.jpa.rp.dstu3.LibraryResourceProvider;

import org.cqframework.cql.cql2elm.FhirLibrarySourceProvider;
import org.cqframework.cql.cql2elm.LibrarySourceProvider;
import org.hl7.elm.r1.VersionedIdentifier;
import org.hl7.fhir.dstu3.model.Attachment;
import org.hl7.fhir.dstu3.model.IdType;
import org.hl7.fhir.dstu3.model.Library;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Created by Christopher on 1/12/2017.
 */
public class STU3LibrarySourceProvider implements LibrarySourceProvider {

    private LibraryResourceProvider provider;
    private FhirLibrarySourceProvider innerProvider;

    public STU3LibrarySourceProvider(LibraryResourceProvider provider) {
        this.provider = provider;
        this.innerProvider = new FhirLibrarySourceProvider();
    }

    @Override
    public InputStream getLibrarySource(VersionedIdentifier versionedIdentifier) {
        try {
            Library lib = provider.getDao().read(new IdType(versionedIdentifier.getId()));
            for (Attachment content : lib.getContent()) {
                if (content.getContentType().equals("text/cql")) {
                    return new ByteArrayInputStream(content.getData());
                }
            }
        }
        catch(Exception e){}

        return this.innerProvider.getLibrarySource(versionedIdentifier);
    }
}

Put exception eating back in

Put exception eating back in


package com.insightfullogic.lambdabehave.expectations;

import org.hamcrest.Matcher;
import org.hamcrest.Matchers;

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

/**
 * .
 */
public final class StringExpectation extends BoundExpectation<String> {
    public StringExpectation(final String str, final boolean positive) {
        super(str, positive);
    }

    public StringExpectation isEmptyString() {
        return matches(Matchers.isEmptyString());
    }

    public StringExpectation isEmptyOrNullString() {
        return matches(Matchers.isEmptyOrNullString());
    }

    public StringExpectation equalToIgnoringCase(final String expectedString) {
        return matches(Matchers.equalToIgnoringCase(expectedString));
    }

    public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
        return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
    }

    public StringExpectation containsString(final String substring) {
        return matches(Matchers.containsString(substring));
    }

    public StringExpectation endsWith(final String suffix) {
        return matches(Matchers.endsWith(suffix));
    }

    public StringExpectation startsWith(final String prefix) {
        return matches(Matchers.startsWith(prefix));
    }

    private StringExpectation matches(final Matcher<String> matcher) {
        assertThat(objectUnderTest, matcher);
        return this;
    }

    public StringExpectation matches(String regex) {
        assertTrue(objectUnderTest.matches(regex));
        return this;
    }

}

package com.insightfullogic.lambdabehave.expectations;

import org.hamcrest.Matcher;
import org.hamcrest.Matchers;

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

/**
 * .
 */
public final class StringExpectation extends BoundExpectation<String> {
    public StringExpectation(final String str, final boolean positive) {
        super(str, positive);
    }

    public StringExpectation isEmptyString() {
        return matches(Matchers.isEmptyString());
    }

    public StringExpectation isEmptyOrNullString() {
        return matches(Matchers.isEmptyOrNullString());
    }

    public StringExpectation equalToIgnoringCase(final String expectedString) {
        return matches(Matchers.equalToIgnoringCase(expectedString));
    }

    public StringExpectation equalToIgnoringWhiteSpace(final String expectedString) {
        return matches(Matchers.equalToIgnoringWhiteSpace(expectedString));
    }

    public StringExpectation containsString(final String substring) {
        return matches(Matchers.containsString(substring));
    }

    public StringExpectation endsWith(final String suffix) {
        return matches(Matchers.endsWith(suffix));
    }

    public StringExpectation startsWith(final String prefix) {
        return matches(Matchers.startsWith(prefix));
    }

    private StringExpectation matches(final Matcher<String> matcher) {
        assertThat(objectUnderTest, matcher);
        return this;
    }

    public StringExpectation matches(String regex) {
        assertTrue("String " + objectUnderTest + " does not match regex " + regex, objectUnderTest.matches(regex));
        return this;
    }

}

Add failure message when testing whether a string matches a regex


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

package com.facebook.buck.util.zip.collect;

import com.facebook.buck.core.util.immutables.BuckStyleValue;
import java.nio.file.Path;
import org.immutables.value.Value;

/** A source for a zip file entry that represents an entry for another zip file. */
@BuckStyleValue
@Value.Immutable(builder = false, copy = false, prehash = true)
public interface ZipEntrySourceFromZip extends ZipEntrySource {

  /** Path to the source zip file. */
  @Override
  Path getSourceFilePath();

  /** The name of the entry */
  @Override
  String getEntryName();

  /** Position of the entry in the list of entries. */
  int getEntryPosition();
}

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

package com.facebook.buck.util.zip.collect;

import com.facebook.buck.core.util.immutables.BuckStylePrehashedValue;
import java.nio.file.Path;

/** A source for a zip file entry that represents an entry for another zip file. */
@BuckStylePrehashedValue
public interface ZipEntrySourceFromZip extends ZipEntrySource {

  /** Path to the source zip file. */
  @Override
  Path getSourceFilePath();

  /** The name of the entry */
  @Override
  String getEntryName();

  /** Position of the entry in the list of entries. */
  int getEntryPosition();
}

Use BuckStylePrehashedValue instead of overriding BuckStyleValue

Reviewed By: cjhopman

shipit-source-id: e8fa582b5625172ed362e697e82e07477e3c1ebf


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

import elemental2.dom.HTMLElement;

/**
 * Convenience class to support lazy element creation. The bulk of a LazyElement is not instantiated until {@link
 * #element()} is called.
 */
public abstract class LazyElement implements IsElement {

    private HTMLElement element;

    /**
     * Creates and returns the element on demand by calling {@link #createElement()} or just returns the previously
     * created element.
     */
    @Override
    public HTMLElement element() {
        if (element == null) {
            element = createElement();
        }
        return element;
    }

    /**
     * Create the element contained within the {@link LazyElement}.
     *
     * @return the lazy element
     */
    protected abstract HTMLElement createElement();

    /** @return whether the element was already created */
    protected boolean initialized() {
        return element != null;
    }
}

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

import elemental2.dom.HTMLElement;

/**
 * Convenience class to support lazy element creation. The bulk of a LazyElement is not instantiated until {@link
 * #element()} is called.
 */
public abstract class LazyElement implements IsElement {

    private HTMLElement element;

    /**
     * Creates and returns the element on demand by calling {@link #createElement()} or just returns the previously
     * created element.
     */
    @Override
    public HTMLElement element() {
        if (element == null) {
            element = createElement();
        }
        return element;
    }

    /** @deprecated use {@link #element()} instead. */
    @Override
    @Deprecated
    public HTMLElement asElement() {
        return element();
    }

    /**
     * Create the element contained within the {@link LazyElement}.
     *
     * @return the lazy element
     */
    protected abstract HTMLElement createElement();

    /** @return whether the element was already created */
    protected boolean initialized() {
        return element != null;
    }
}

Make API changes backward compatible

Make API changes backward compatible


package src;

/**
 * Created by roxane on 03/10/2016.
 */
public class test {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}

Create Java package inside src/ folder

Create Java package inside src/ folder

The package will allow the project to respect standard Java
architecture.


package jetbrains.buildServer.clouds.azure;

import jetbrains.buildServer.serverSide.BuildAgentEx;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildAgent;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

/**
 * Changes name of authorized agents by cloud integration.
 */
public class AzureAgentNameChanger extends BuildServerAdapter {

    private static final String AUTHORIZATION_MESSAGE = "Virtual agent is authorized automatically";

    @Override
    public void agentStatusChanged(@NotNull SBuildAgent agent, boolean wasEnabled, boolean wasAuthorized) {
        if (!(agent instanceof BuildAgentEx)) {
            return;
        }

        // Check that it's an authorized virtual agent
        final String comment = agent.getAuthorizeComment().getComment();
        if (!agent.isAuthorized() || comment == null || !comment.contains(AUTHORIZATION_MESSAGE)) {
            return;
        }

        // Check that it's an azure agent
        final Map<String, String> config = agent.getConfigurationParameters();
        final String agentName = config.get(AzurePropertiesNames.INSTANCE_NAME);
        if (StringUtil.isEmpty(agentName)) {
            return;
        }

        // Set name
        final BuildAgentEx buildAgent = (BuildAgentEx) agent;
        buildAgent.setName(agentName);
    }
}

package jetbrains.buildServer.clouds.azure;

import jetbrains.buildServer.serverSide.BuildAgentEx;
import jetbrains.buildServer.serverSide.BuildServerAdapter;
import jetbrains.buildServer.serverSide.SBuildAgent;
import jetbrains.buildServer.util.StringUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

/**
 * Changes name of authorized agents by cloud integration.
 */
public class AzureAgentNameChanger extends BuildServerAdapter {

    private static final String AUTHORIZATION_MESSAGE = "Virtual agent is authorized automatically";

    @Override
    public void agentStatusChanged(@NotNull SBuildAgent agent, boolean wasEnabled, boolean wasAuthorized) {
        if (!(agent instanceof BuildAgentEx)) {
            return;
        }

        // Check that it's an authorized virtual agent
        final String comment = agent.getAuthorizeComment().getComment();
        if (!agent.isAuthorized() || comment == null || !comment.contains(AUTHORIZATION_MESSAGE)) {
            return;
        }

        // Check that it's an azure agent
        final Map<String, String> config = agent.getConfigurationParameters();
        final String agentName = config.get(AzurePropertiesNames.INSTANCE_NAME);
        if (StringUtil.isEmpty(agentName) || agentName.equals(agent.getName())) {
            return;
        }

        // Set name
        final BuildAgentEx buildAgent = (BuildAgentEx) agent;
        buildAgent.setName(agentName);
    }
}

Change build agent name only if it differs


package ee.ellytr.autoclick.tps;

import ee.ellytr.autoclick.EllyCheat;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

public class TPSRunnable implements Runnable {

    @Override
    public void run() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            double tps = Math.round(TPSTracker.getTPS() * 100.0) / 100.0;
            if (tps <= EllyCheat.getInstance().getConfig().getInt("tps-warning")) {
                for (Player player2 : Bukkit.getOnlinePlayers()) {
                    if (player2.hasPermission("ellycheat.cps.warning")) {
                        player2.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!");
                    }
                }
                if (EllyCheat.getInstance().getConfig().getBoolean("log-warnings")) {
                    Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!");
                }
            }
        }
        Bukkit.getScheduler().runTaskLaterAsynchronously(EllyCheat.getInstance(), this, 20);
    }
}

package ee.ellytr.autoclick.tps;

import ee.ellytr.autoclick.EllyCheat;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;

public class TPSRunnable implements Runnable {

    @Override
    public void run() {
        for (Player player : Bukkit.getOnlinePlayers()) {
            double tps = Math.round(TPSTracker.getTPS() * 100.0) / 100.0;
            if (tps <= EllyCheat.getInstance().getConfig().getInt("tps-warning")) {
                if (player.hasPermission("ellycheat.cps.warning")) {
                    player.sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!");
                }
                if (EllyCheat.getInstance().getConfig().getBoolean("log-warnings")) {
                    Bukkit.getConsoleSender().sendMessage(ChatColor.GRAY + "[" + ChatColor.RED + "!" + ChatColor.GRAY + "] The server is currently running at " + ChatColor.GOLD + tps + ChatColor.GRAY + " TPS!");
                }
            }
        }
        Bukkit.getScheduler().runTaskLaterAsynchronously(EllyCheat.getInstance(), this, 20);
    }
}

Fix TPS warning messages being sent too many times


package de.rheinfabrik.heimdalldroid.network.oauth2;

import de.rheinfabrik.heimdall2.OAuth2AccessToken;
import de.rheinfabrik.heimdall2.grants.OAuth2RefreshAccessTokenGrant;
import de.rheinfabrik.heimdalldroid.network.TraktTvApiFactory;
import de.rheinfabrik.heimdalldroid.network.models.RefreshTokenRequestBody;
import io.reactivex.Single;

/**
 * TraktTv refresh token grant as described in http://docs.trakt.apiary.io/#reference/authentication-oauth/token/exchange-refresh_token-for-access_token.
 */
public class TraktTvRefreshAccessTokenGrant extends OAuth2RefreshAccessTokenGrant<OAuth2AccessToken> {

    // Properties

    public String clientSecret;
    public String clientId;
    public String redirectUri;

    // OAuth2RefreshAccessTokenGrant

    @Override
    public Single<OAuth2AccessToken> grantNewAccessToken() {
        RefreshTokenRequestBody body = new RefreshTokenRequestBody(refreshToken, clientId, clientSecret, redirectUri, GRANT_TYPE);
        return TraktTvApiFactory.newApiService().refreshAccessToken(body).singleOrError();
    }
}

package de.rheinfabrik.heimdalldroid.network.oauth2;

import de.rheinfabrik.heimdall2.OAuth2AccessToken;
import de.rheinfabrik.heimdall2.grants.OAuth2RefreshAccessTokenGrant;
import de.rheinfabrik.heimdalldroid.network.TraktTvApiFactory;
import de.rheinfabrik.heimdalldroid.network.models.RefreshTokenRequestBody;
import io.reactivex.Single;

/**
 * TraktTv refresh token grant as described in http://docs.trakt.apiary.io/#reference/authentication-oauth/token/exchange-refresh_token-for-access_token.
 */
public class TraktTvRefreshAccessTokenGrant extends OAuth2RefreshAccessTokenGrant<OAuth2AccessToken> {

    // Properties

    public String clientSecret;
    public String clientId;
    public String redirectUri;

    // OAuth2RefreshAccessTokenGrant

    @Override
    public Single<OAuth2AccessToken> grantNewAccessToken() {
        RefreshTokenRequestBody body = new RefreshTokenRequestBody(getRefreshToken(), clientId, clientSecret, redirectUri, getGRANT_TYPE());
        return TraktTvApiFactory.newApiService().refreshAccessToken(body).singleOrError();
    }
}

Migrate usage of the TokenGrant in the sample


package org.xcolab.client.admin.enums;

public enum ServerEnvironment {
    PRODUCTION, STAGING, DEV, LOCAL, UNKNOWN;

    public boolean isProduction() {
        return PRODUCTION == this;
    }
}

package org.xcolab.client.admin.enums;

public enum ServerEnvironment {
    PRODUCTION, STAGING, DEV, LOCAL, UNKNOWN;

    public boolean getIsProduction() {
        return PRODUCTION == this;
    }
}

Fix method name to work with jsp

Fix method name to work with jsp


package com.github.havarunner.scenarios.duplicated;

import com.github.havarunner.annotation.AfterAll;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertTrue;

abstract class VerifyThatTestAreRunOnlyOnceTestSuperClass {
    protected final AtomicInteger suiteObject;
    protected final List<String> scenarios;
    VerifyThatTestAreRunOnlyOnceTestSuperClass(AtomicInteger suiteObject, List<String> scenarios) {
        this.suiteObject = suiteObject;
        this.scenarios = scenarios;
    }
    @Test
    public void verifyTestIsRanOnlyOncePerScenario() {
        final int runNumber = suiteObject.addAndGet(1);
        System.out.println("Run: "+runNumber+ " for scenario: "+scenarios);
        synchronized (VerifyThatTestAreRunOnlyOnceTestOneImpl.class) {
            assertTrue(runNumber+" / "+VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size()+ " currentScenario: "+scenarios, VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size() >= runNumber);
        }
    }

    @AfterAll
    public void afterAll() {

    }

}

package com.github.havarunner.scenarios.duplicated;

import org.junit.Test;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.Assert.assertTrue;

abstract class VerifyThatTestAreRunOnlyOnceTestSuperClass {
    protected final AtomicInteger suiteObject;
    protected final List<String> scenarios;
    VerifyThatTestAreRunOnlyOnceTestSuperClass(AtomicInteger suiteObject, List<String> scenarios) {
        this.suiteObject = suiteObject;
        this.scenarios = scenarios;
    }
    @Test
    public void verifyTestIsRanOnlyOncePerScenario() {
        final int runNumber = suiteObject.addAndGet(1);
        System.out.println("Run: "+runNumber+ " for scenario: "+scenarios);
        synchronized (VerifyThatTestAreRunOnlyOnceTestOneImpl.class) {
            assertTrue(runNumber+" / "+VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size()+ " currentScenario: "+scenarios, VerifyThatTestAreRunOnlyOnceTestOneImpl.scenarios().size() >= runNumber);
        }
    }
}

Remove @AfterAll, did not cause problem after all


package com.stubbornjava.examples.undertow.routing;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

// {{start:handler}}
public class ConstantStringHandler implements HttpHandler {
    private final String value;
    public ConstantStringHandler(String value) {
        this.value = value;
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseSender().send(value);
    }
}
// {{end:handler}}

package com.stubbornjava.examples.undertow.routing;

import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

// {{start:handler}}
public class ConstantStringHandler implements HttpHandler {
    private final String value;
    public ConstantStringHandler(String value) {
        this.value = value;
    }

    @Override
    public void handleRequest(HttpServerExchange exchange) throws Exception {
        exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/plain");
        exchange.getResponseSender().send(value + "\n");
    }
}
// {{end:handler}}

Add newline at the end of constant string handler


/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.model.properties;

/** Information about an action that writes a PV
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class WritePVActionInfo extends ActionInfo
{
    private final String pv;
    private final String value;

    /** @param description Action description
     *  @param pv PV name
     *  @param value Value to write
     */
    public WritePVActionInfo(final String description, final String pv, final String value)
    {
        super(description);
        this.pv = pv;
        this.value = value;
    }

    @Override
    public ActionType getType()
    {
        return ActionType.WRITE_PV;
    }

    /** @return PV name */
    public String getPV()
    {
        return pv;
    }

    /** @return Value to write */
    public String getValue()
    {
        return value;
    }

    @Override
    public String toString()
    {
        if (getDescription().isEmpty())
            return "Write " + pv + " = " + value;
        else
            return getDescription();
    }
}

/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.model.properties;

/** Information about an action that writes a PV
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class WritePVActionInfo extends ActionInfo
{
    private final String pv;
    private final String value;

    /** @param description Action description
     *  @param pv PV name
     *  @param value Value to write
     */
    public WritePVActionInfo(final String description, final String pv, final String value)
    {
        super(description);
        this.pv = pv;
        this.value = value;
    }

    @Override
    public ActionType getType()
    {
        return ActionType.WRITE_PV;
    }

    /** @return PV name */
    public String getPV()
    {
        return pv;
    }

    /** @return Value to write */
    public String getValue()
    {
        return value;
    }

    @Override
    public String toString()
    {
        if (getDescription().isEmpty())
            return "Write " + value + " to " + pv;
        else
            return getDescription();
    }
}

Use same string representation as BOY

WritePVAction: Use same string representation as BOY

"Write 1 to some_pv" was used in BOY, and this this shows on buttons
that use $(actions) as their label, a different text impacts existing
screens


package org.pentaho.ui.xul.swt.tags;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.ToolBar;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swt.AbstractSwtXulContainer;

public class SwtToolbar extends AbstractSwtXulContainer implements XulToolbar{

  ToolBar toolbar;
  public SwtToolbar(Element self, XulComponent parent, XulDomContainer domContainer, String tagName) {
    super("toolbar");

    toolbar = new ToolBar((Composite) parent.getManagedObject(), SWT.HORIZONTAL);
    setManagedObject(toolbar);
  }

  public ToolbarMode getMode() {
    // TODO Auto-generated method stub
    return null;
  }

  public String getToolbarName() {
    // TODO Auto-generated method stub
    return null;
  }

  public void setMode(ToolbarMode mode) {
    // TODO Auto-generated method stub

  }

  public void setToolbarName(String name) {
    // TODO Auto-generated method stub

  }

}

package org.pentaho.ui.xul.swt.tags;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.containers.XulToolbar;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swt.AbstractSwtXulContainer;

public class SwtToolbar extends AbstractSwtXulContainer implements XulToolbar{

  ToolBar toolbar;
  public SwtToolbar(Element self, XulComponent parent, XulDomContainer domContainer, String tagName) {
    super("toolbar");

    String attr = self.getAttributeValue("parenttoouter");
    Object shell = (attr != null && attr.equals("true") && domContainer.getOuterContext() != null)
      ? domContainer.getOuterContext()
      : null;
    if(shell != null && shell instanceof Shell){
      toolbar = new ToolBar((Shell) shell, SWT.HORIZONTAL);
    } else if(shell != null && shell instanceof Composite){
      toolbar = new ToolBar((Composite) shell, SWT.HORIZONTAL);
    } else {
      toolbar = new ToolBar((Composite) parent.getManagedObject(), SWT.HORIZONTAL);
    }
    setManagedObject(toolbar);
  }

  public ToolbarMode getMode() {
    // TODO Auto-generated method stub
    return null;
  }

  public String getToolbarName() {
    // TODO Auto-generated method stub
    return null;
  }

  public void setMode(ToolbarMode mode) {
    // TODO Auto-generated method stub

  }

  public void setToolbarName(String name) {
    // TODO Auto-generated method stub

  }

}

[AGILEBI-71] Support for parenting toolbar to outercontext


/*
 * This file is part of the DITA Open Toolkit project.
 * See the accompanying license.txt file for applicable licenses.
 */

/*
 * (c) Copyright IBM Corp. 2008 All Rights Reserved.
 */
package org.dita.dost.platform;

import org.dita.dost.util.StringUtils;
/**
 * CheckTranstypeAction class.
 *
 */
final class CheckTranstypeAction extends ImportAction {

    /**
     * Get result.
     * @return result
     */
    @Override
    public String getResult() {
        final StringBuilder retBuf = new StringBuilder();
        final String property = paramTable.get("property");
        for (final String value: valueSet) {
            retBuf.append("<not><equals arg1=\"${")
                .append(StringUtils.escapeXML(property))
                .append("}\" arg2=\"")
                .append(StringUtils.escapeXML(value))
                .append("\" casesensitive=\"false\"/></not>");
        }
        return retBuf.toString();
    }

}

/*
 * This file is part of the DITA Open Toolkit project.
 * See the accompanying license.txt file for applicable licenses.
 */

/*
 * (c) Copyright IBM Corp. 2008 All Rights Reserved.
 */
package org.dita.dost.platform;

import org.dita.dost.util.StringUtils;
/**
 * CheckTranstypeAction class.
 *
 */
final class CheckTranstypeAction extends ImportAction {

    /**
     * Get result.
     * @return result
     */
    @Override
    public String getResult() {
        final StringBuilder retBuf = new StringBuilder();
        final String property = paramTable.containsKey("property") ? paramTable.get("property") : "transtype";
        for (final String value: valueSet) {
            retBuf.append("<not><equals arg1=\"${")
                .append(StringUtils.escapeXML(property))
                .append("}\" arg2=\"")
                .append(StringUtils.escapeXML(value))
                .append("\" casesensitive=\"false\"/></not>");
        }
        return retBuf.toString();
    }

}

Add default check type in integration

Add default check type in integration

Fixes broken unit tests from commit bfdda34.


package org.springframework.cloud.servicebroker.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;

/**
 * Details of a request that supports arbitrary parameters and asynchronous behavior.
 *
 * @author Scott Frederick
 */
@Getter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public abstract class AsyncParameterizedServiceInstanceRequest extends AsyncServiceInstanceRequest {
	/**
	 * Parameters passed by the user in the form of a JSON structure. The service broker is responsible
	 * for validating the contents of the parameters for correctness or applicability.
	 */
	@JsonSerialize
	@JsonProperty("parameters")
	protected final Map<String, Object> parameters;

	public AsyncParameterizedServiceInstanceRequest(Map<String, Object> parameters) {
		this.parameters = parameters;
	}

	public <T> T getParameters(Class<T> cls) {
		try {
			T bean = cls.newInstance();
			BeanUtils.populate(bean, parameters);
			return bean;
		} catch (Exception e) {
			throw new IllegalArgumentException("Error mapping parameters to class of type " + cls.getName());
		}
	}
}

package org.springframework.cloud.servicebroker.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Map;

/**
 * Details of a request that supports arbitrary parameters and asynchronous behavior.
 *
 * @author Scott Frederick
 */
@Getter
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public abstract class AsyncParameterizedServiceInstanceRequest extends AsyncServiceInstanceRequest {
	/**
	 * Parameters passed by the user in the form of a JSON structure. The service broker is responsible
	 * for validating the contents of the parameters for correctness or applicability.
	 */
	@JsonSerialize
	@JsonProperty("parameters")
	protected final Map<String, Object> parameters;

	public AsyncParameterizedServiceInstanceRequest(Map<String, Object> parameters) {
		this.parameters = parameters;
	}

	public <T> T getParameters(Class<T> cls) {
		try {
			T bean = cls.newInstance();
			BeanUtils.populate(bean, parameters);
			return bean;
		} catch (Exception e) {
			throw new IllegalArgumentException("Error mapping parameters to class of type " + cls.getName(), e);
		}
	}
}

Add the cause when mapping parameters fails


package com.atlassian.sal.refimpl;

import com.atlassian.sal.api.ApplicationProperties;

import java.util.Date;
import java.io.File;

/**
 * Implementation of ApplicationProperties for http://localhost
 */
public class RefimplApplicationProperties implements ApplicationProperties
{
    private static final Date THEN = new Date();

    public String getBaseUrl()
    {
        return System.getProperty("baseurl", "http://localhost:8080/atlassian-plugins-refimpl");
    }

    public String getDisplayName()
    {
        return "RefImpl";
    }

    public String getVersion()
    {
        return "1.0";
    }

    public Date getBuildDate()
    {
        return THEN;
    }

    public String getBuildNumber()
    {
        return "123";
    }

    public File getHomeDirectory()
    {
        return new File(System.getProperty("java.tmp.dir"));
    }
}

package com.atlassian.sal.refimpl;

import com.atlassian.sal.api.ApplicationProperties;

import java.util.Date;
import java.io.File;

/**
 * Implementation of ApplicationProperties for http://localhost
 */
public class RefimplApplicationProperties implements ApplicationProperties
{
    private static final Date THEN = new Date();

    public String getBaseUrl()
    {
        return System.getProperty("baseurl", "http://localhost:8080/atlassian-plugins-refimpl");
    }

    public String getDisplayName()
    {
        return "RefImpl";
    }

    public String getVersion()
    {
        return "1.0";
    }

    public Date getBuildDate()
    {
        return THEN;
    }

    public String getBuildNumber()
    {
        return "123";
    }

    public File getHomeDirectory()
    {
        return new File(System.getProperty("java.io.tmpdir"));
    }
}

Fix wrong java tmp dir sys property

Fix wrong java tmp dir sys property

git-svn-id: 2433085265c0232ec46d186f8a8240da49417e22@32162 2c54a935-e501-0410-bc05-97a93f6bca70


package arez;

import javax.annotation.Nonnull;
import jsinterop.annotations.JsFunction;

/**
 * Interface that accepts an {@link Observer} that has been scheduled and
 * performs the actions required to run observer.
 *
 *
The interface is marked with the {@link JsFunction} annotation to communicate
 * to the GWT2 compiler that it is not necessary to generate class information
 * for the implementing methods which reduces code size somewhat.

 */
@JsFunction
@FunctionalInterface
interface Reaction
{
  /**
   * React to changes, or throw an exception if unable to do so.
   *
   * @param observer the observer of changes.
   * @throws Throwable if there is an error reacting to changes.
   */
  void react( @Nonnull Observer observer )
    throws Throwable;
}

package arez;

import javax.annotation.Nonnull;

/**
 * Interface that accepts an {@link Observer} that has been scheduled and
 * performs the actions required to run observer.
 */
@FunctionalInterface
interface Reaction
{
  /**
   * React to changes, or throw an exception if unable to do so.
   *
   * @param observer the observer of changes.
   * @throws Throwable if there is an error reacting to changes.
   */
  void react( @Nonnull Observer observer )
    throws Throwable;
}

Remove JsFunction as in some cases it increases the code size


package com.Acrobot.Breeze.Configuration;

import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;

import java.lang.reflect.Field;

/**
 * @author Acrobot
 */
public class FieldParser {
    /**
     * Parses a field into a YAML-compatible string
     *
     * @param field Field to parse
     * @return Parsed field
     */
    public static String parse(Field field) {
        StringBuilder builder = new StringBuilder(50);

        try {
            builder.append(field.getName()).append(": ").append(ValueParser.parseToYAML(field.get(null)));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return "";
        }

        if (field.isAnnotationPresent(ConfigurationComment.class)) {
            builder.append('\n').append('#').append(field.getAnnotation(ConfigurationComment.class).value());
        }

        return builder.toString();
    }
}

package com.Acrobot.Breeze.Configuration;

import com.Acrobot.Breeze.Configuration.Annotations.ConfigurationComment;

import java.lang.reflect.Field;

/**
 * @author Acrobot
 */
public class FieldParser {
    /**
     * Parses a field into a YAML-compatible string
     *
     * @param field Field to parse
     * @return Parsed field
     */
    public static String parse(Field field) {
        StringBuilder builder = new StringBuilder(50);

        if (field.isAnnotationPresent(ConfigurationComment.class)) {
            builder.append('#').append(field.getAnnotation(ConfigurationComment.class).value()).append('\n');
        }

        try {
            builder.append(field.getName()).append(": ").append(ValueParser.parseToYAML(field.get(null)));
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return "";
        }

        return builder.toString();
    }
}

Move comments in above config fields. This should help avoid confusions as it matches the class' annotation layout and almost every other plugin does it like this.


package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;

@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {

    @DefaultMessage("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultMessage("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultMessage("Select datasource")
    String selectDatasourceLabel();

    @DefaultMessage("Result limit")
    String resultLimitLabel();

    @DefaultMessage("Execute")
    String executeButtonLabel();

    @DefaultMessage("{0} rows.")
    @AlternateMessage({"one", "{0} row."})
    String updateCountMessage(@PluralCount int count);

    @DefaultMessage("Export as CSV file")
    String exportCsvLabel();
}

package com.codenvy.ide.ext.datasource.client.sqllauncher;

import com.google.gwt.i18n.client.LocalizableResource.DefaultLocale;
import com.google.gwt.i18n.client.Messages;

@DefaultLocale("en")
public interface SqlRequestLauncherConstants extends Messages {

    @DefaultMessage("Open SQL editor")
    String menuEntryOpenSqlEditor();

    @DefaultMessage("SQL editor")
    String sqlEditorWindowTitle();

    @DefaultMessage("Select datasource")
    String selectDatasourceLabel();

    @DefaultMessage("Result limit")
    String resultLimitLabel();

    @DefaultMessage("Execute")
    String executeButtonLabel();

    @DefaultMessage("{0} rows.")
    @AlternateMessage({"one", "{0} row."})
    String updateCountMessage(@PluralCount int count);

    @DefaultMessage("Export as CSV file")
    String exportCsvLabel();

    @DefaultMessage("Execution mode")
    String executionModeLabel();

    @DefaultMessage("Execute all - ignore and report errors")
    String executeAllModeItem();

    @DefaultMessage("First error - stop on first error")
    String stopOnErrorModeitem();

    @DefaultMessage("Transaction - rollback on first error")
    String transactionModeItem();
}

Add string for execution mode

Add string for execution mode


package com.braintreepayments.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;

import com.braintreepayments.demo.fragments.SettingsFragment;

public class SettingsActivity extends Activity {

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

        getActionBar().setDisplayHomeAsUpEnabled(true);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return false;
    }
}

package com.braintreepayments.demo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.braintreepayments.demo.fragments.SettingsFragment;

public class SettingsActivity extends AppCompatActivity {

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

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment())
                .commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return false;
    }
}

Fix crash in demo app settings

Fix crash in demo app settings


package org.appcelerator.titanium;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ContextSpecific {

}

Remove crlf - oops, changed settings on my Win7 dev machine


// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.

package org.xbill.DNS;

import java.util.*;
import java.io.*;
import java.net.*;

/**
 * A special-purpose thread used by Resolvers (both SimpleResolver and
 * ExtendedResolver) to perform asynchronous queries.
 *
 * @author Brian Wellington
 */

class ResolveThread implements Runnable {

private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;

/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
	      ResolverListener listener)
{
	this.res = res;
	this.query = query;
	this.id = id;
	this.listener = listener;
}

/**
 * Performs the query, and executes the callback.
 */
public void
run() {
	try {
		Message response = res.send(query);
		listener.receiveMessage(id, response);
	}
	catch (Exception e) {
		listener.handleException(id, e);
	}
}

}

// Copyright (c) 1999 Brian Wellington (bwelling@xbill.org)
// Portions Copyright (c) 1999 Network Associates, Inc.

package org.xbill.DNS;

import java.util.*;
import java.io.*;
import java.net.*;

/**
 * A special-purpose thread used by Resolvers (both SimpleResolver and
 * ExtendedResolver) to perform asynchronous queries.
 *
 * @author Brian Wellington
 */

class ResolveThread extends Thread {

private Message query;
private Object id;
private ResolverListener listener;
private Resolver res;

/** Creates a new ResolveThread */
public
ResolveThread(Resolver res, Message query, Object id,
	      ResolverListener listener)
{
	this.res = res;
	this.query = query;
	this.id = id;
	this.listener = listener;
}

/**
 * Performs the query, and executes the callback.
 */
public void
run() {
	try {
		Message response = res.send(query);
		listener.receiveMessage(id, response);
	}
	catch (Exception e) {
		listener.handleException(id, e);
	}
}

}

Make this a subclass of Thread.

Make this a subclass of Thread.

git-svn-id: becfadaebdf67c7884f0d18099f2460615305e2e@969 c76caeb1-94fd-44dd-870f-0c9d92034fc1


package io.smartlogic.smartchat;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;

public class GcmIntentService extends IntentService {
    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("New SmartChat")
                .setContentText("SmartChat from " + extras.getString("creator_email"));
        Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
        resultIntent.putExtras(extras);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }
}

package io.smartlogic.smartchat;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

import io.smartlogic.smartchat.activities.DisplaySmartChatActivity;
import io.smartlogic.smartchat.activities.MainActivity;

public class GcmIntentService extends IntentService {
    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("New SmartChat")
                .setContentText("SmartChat from " + extras.getString("creator_email"));
        Intent resultIntent = new Intent(this, DisplaySmartChatActivity.class);
        resultIntent.putExtras(extras);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(extras.getInt("id", 1), mBuilder.build());
    }
}

Use the media id as notification id

Use the media id as notification id


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

import java.util.logging.Logger;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;

/**
 * CDI Resource aliases
 *
 * @author Rafael Benevides
 *
 */
public class Resources {

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }
}

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

import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;

/**
 * CDI Resource aliases
 *
 * @author Rafael Benevides
 *
 */
public class Resources {

    @Produces
    public Logger produceLog(InjectionPoint injectionPoint) {
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }

    @Produces
    @RequestScoped
    public FacesContext produceFacesContext() {
        return FacesContext.getCurrentInstance();
    }
}

Fix compilation error in deltaspike quickstart


package ch.rasc.eds.starter.schedule;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

import ch.rasc.eds.starter.config.MongoDb;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.User;

@Component
public class DisableInactiveUser {

	private final MongoDb mongoDb;

	@Autowired
	public DisableInactiveUser(MongoDb mongoDb) {
		this.mongoDb = mongoDb;
	}

	@Scheduled(cron = "0 0 5 * * *")
	public void doCleanup() {
		// Inactivate users that have a lastAccess timestamp that is older than one year
		ZonedDateTime oneYearAgo = ZonedDateTime.now(ZoneOffset.UTC).minusYears(1);
		this.mongoDb.getCollection(User.class).updateMany(
				Filters.lte(CUser.lastAccess, oneYearAgo),
				Updates.set(CUser.enabled, false));
	}

}

package ch.rasc.eds.starter.schedule;

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;

import ch.rasc.eds.starter.config.MongoDb;
import ch.rasc.eds.starter.entity.CUser;
import ch.rasc.eds.starter.entity.User;

@Component
public class DisableInactiveUser {

	private final MongoDb mongoDb;

	@Autowired
	public DisableInactiveUser(MongoDb mongoDb) {
		this.mongoDb = mongoDb;
	}

	@Scheduled(cron = "0 0 5 * * *")
	public void doCleanup() {
		// Inactivate users that have a lastAccess timestamp that is older than one year
		ZonedDateTime oneYearAgo = ZonedDateTime.now(ZoneOffset.UTC).minusYears(1);
		this.mongoDb.getCollection(User.class).updateMany(
				Filters.lte(CUser.lastAccess, Date.from(oneYearAgo.toInstant())),
				Updates.set(CUser.enabled, false));
	}

}

Fix query. Has to use java.util.Date

Fix query. Has to use java.util.Date


/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

package bisq.desktop.common.view;

import javax.inject.Inject;
import javax.inject.Singleton;

import java.util.HashMap;

@Singleton
public class CachingViewLoader implements ViewLoader {

    private final HashMap<Object, View> cache = new HashMap<>();
    private final ViewLoader viewLoader;

    @Inject
    public CachingViewLoader(ViewLoader viewLoader) {
        this.viewLoader = viewLoader;
    }

    @Override
    public View load(Class<? extends View> viewClass) {
        if (cache.containsKey(viewClass))
            return cache.get(viewClass);

        View view = viewLoader.load(viewClass);
        cache.put(viewClass, view);
        return view;
    }
}

/*
 * This file is part of Bisq.
 *
 * Bisq is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or (at
 * your option) any later version.
 *
 * Bisq is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Bisq. If not, see <http://www.gnu.org/licenses/>.
 */

package bisq.desktop.common.view;

import javax.inject.Inject;
import javax.inject.Singleton;

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

@Singleton
public class CachingViewLoader implements ViewLoader {

    private final Map<Class<? extends View>, View> cache = new HashMap<>();
    private final ViewLoader viewLoader;

    @Inject
    public CachingViewLoader(ViewLoader viewLoader) {
        this.viewLoader = viewLoader;
    }

    @Override
    public View load(Class<? extends View> viewClass) {
        if (cache.containsKey(viewClass))
            return cache.get(viewClass);

        View view = viewLoader.load(viewClass);
        cache.put(viewClass, view);
        return view;
    }
}

Set correct type of cache map

Set correct type of cache map


package org.commonmark.ext.heading.anchor.internal;

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

import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.node.Text;

import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider;

public class HeadingIdAttributeProvider implements AttributeProvider {

    private final UniqueIdentifierProvider idProvider;

    private HeadingIdAttributeProvider() {
        idProvider = new UniqueIdentifierProvider("heading");
    }

    public static HeadingIdAttributeProvider create() {
        return new HeadingIdAttributeProvider();
    }

    @Override
    public void setAttributes(Node node, final Map<String, String> attributes) {

        if (node instanceof Heading) {

            final List<String> wordList = new ArrayList<>();

            node.accept(new AbstractVisitor() {
                @Override
                public void visit(Text text) {
                    wordList.add(text.getLiteral());
                }

                @Override
                public void visit(Code code) {
                    wordList.add(code.getLiteral());
                }
            });

            attributes.put("id", idProvider.getUniqueIdentifier(String.join("", wordList)).toLowerCase());
        }
    }

}

package org.commonmark.ext.heading.anchor.internal;

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

import org.commonmark.html.AttributeProvider;
import org.commonmark.node.AbstractVisitor;
import org.commonmark.node.Code;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.node.Text;

import org.commonmark.ext.heading.anchor.UniqueIdentifierProvider;

public class HeadingIdAttributeProvider implements AttributeProvider {

    private final UniqueIdentifierProvider idProvider;

    private HeadingIdAttributeProvider() {
        idProvider = new UniqueIdentifierProvider("heading");
    }

    public static HeadingIdAttributeProvider create() {
        return new HeadingIdAttributeProvider();
    }

    @Override
    public void setAttributes(Node node, final Map<String, String> attributes) {

        if (node instanceof Heading) {

            final List<String> wordList = new ArrayList<>();

            node.accept(new AbstractVisitor() {
                @Override
                public void visit(Text text) {
                    wordList.add(text.getLiteral());
                }

                @Override
                public void visit(Code code) {
                    wordList.add(code.getLiteral());
                }
            });

            String finalString = "";
            for (String word : wordList) {
                finalString += word + " ";
            }
            finalString = finalString.trim().toLowerCase();

            attributes.put("id", idProvider.getUniqueIdentifier(finalString));
        }
    }

}

Remove Java 8 string join method

Remove Java 8 string join method


package com.splicemachine.kafka;

import java.io.IOException;
import java.util.Properties;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServerStartable;
import kafka.utils.TestUtils;

public class TestKafkaCluster {
    KafkaServerStartable kafkaServer;

    public TestKafkaCluster(String connectString) throws Exception {
        KafkaConfig config = getKafkaConfig(connectString);
        kafkaServer = new KafkaServerStartable(config);
        kafkaServer.startup();
    }

    public static void main(String [] args) throws Exception {
        TestKafkaCluster cluster;
        if (args.length==1)
            cluster = new TestKafkaCluster(args[0]);
        else
            throw new RuntimeException("No zookeper local");
    }

    private static KafkaConfig getKafkaConfig(final String zkConnectString) {
        scala.collection.Iterator<Properties> propsI =
                TestUtils.createBrokerConfigs(1,true).iterator();
        assert propsI.hasNext();
        Properties props = propsI.next();
        assert props.containsKey("zookeeper.connect");
        props.put("zookeeper.connect", zkConnectString);
        return new KafkaConfig(props);
    }

    public String getKafkaBrokerString() {
        return String.format("localhost:%d",
                kafkaServer.serverConfig().port());
    }

    public int getKafkaPort() {
        return kafkaServer.serverConfig().port();
    }

    public void stop() throws IOException {
        kafkaServer.shutdown();
    }
}

package com.splicemachine.kafka;

import java.io.IOException;
import java.util.Properties;
import kafka.server.KafkaConfig;
import kafka.server.KafkaServerStartable;
import kafka.utils.TestUtils;

public class TestKafkaCluster {
    KafkaServerStartable kafkaServer;

    public TestKafkaCluster(String connectString) throws Exception {
        KafkaConfig config = getKafkaConfig(connectString);
        kafkaServer = new KafkaServerStartable(config);
        kafkaServer.startup();
    }

    public static void main(String [] args) throws Exception {
        TestKafkaCluster cluster;
        if (args.length==1)
            cluster = new TestKafkaCluster(args[0]);
        else
            throw new RuntimeException("No zookeper local");
    }

    private static KafkaConfig getKafkaConfig(final String zkConnectString) {
        scala.collection.Iterator<Properties> propsI =
                TestUtils.createBrokerConfigs(1,true).iterator();
        assert propsI.hasNext();
        Properties props = propsI.next();
        assert props.containsKey("zookeeper.connect");
        props.put("zookeeper.connect", zkConnectString);
        props.put("port","9092");
        return new KafkaConfig(props);
    }

    public String getKafkaBrokerString() {
        return String.format("localhost:%d",
                kafkaServer.serverConfig().port());
    }

    public int getKafkaPort() {
        return kafkaServer.serverConfig().port();
    }

    public void stop() throws IOException {
        kafkaServer.shutdown();
    }
}

Fix the port to 9092

Fix the port to 9092


package com.genymobile.scrcpy;

import junit.framework.Assert;

import org.junit.Test;

import java.nio.charset.StandardCharsets;

public class StringUtilsTest {

    @Test
    @SuppressWarnings("checkstyle:MagicNumber")
    public void testUtf8Trucate() {
        String s = "aÉbÔc";
        byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
        Assert.assertEquals(7, utf8.length);

        int count;

        count = StringUtils.getUtf8TruncationIndex(utf8, 1);
        Assert.assertEquals(1, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 2);
        Assert.assertEquals(1, count); // É is 2 bytes-wide

        count = StringUtils.getUtf8TruncationIndex(utf8, 3);
        Assert.assertEquals(3, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 4);
        Assert.assertEquals(4, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 5);
        Assert.assertEquals(4, count); // Ô is 2 bytes-wide

        count = StringUtils.getUtf8TruncationIndex(utf8, 6);
        Assert.assertEquals(6, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 7);
        Assert.assertEquals(7, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 8);
        Assert.assertEquals(7, count); // no more chars
    }
}

package com.genymobile.scrcpy;

import junit.framework.Assert;

import org.junit.Test;

import java.nio.charset.StandardCharsets;

public class StringUtilsTest {

    @Test
    @SuppressWarnings("checkstyle:MagicNumber")
    public void testUtf8Truncate() {
        String s = "aÉbÔc";
        byte[] utf8 = s.getBytes(StandardCharsets.UTF_8);
        Assert.assertEquals(7, utf8.length);

        int count;

        count = StringUtils.getUtf8TruncationIndex(utf8, 1);
        Assert.assertEquals(1, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 2);
        Assert.assertEquals(1, count); // É is 2 bytes-wide

        count = StringUtils.getUtf8TruncationIndex(utf8, 3);
        Assert.assertEquals(3, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 4);
        Assert.assertEquals(4, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 5);
        Assert.assertEquals(4, count); // Ô is 2 bytes-wide

        count = StringUtils.getUtf8TruncationIndex(utf8, 6);
        Assert.assertEquals(6, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 7);
        Assert.assertEquals(7, count);

        count = StringUtils.getUtf8TruncationIndex(utf8, 8);
        Assert.assertEquals(7, count); // no more chars
    }
}

Fix typo in test name

Fix typo in test name


/** EstimotoServiceUtil.java ---
 *
 * Copyright (C) 2014 Dmitry Mozgin
 *
 * Author: Dmitry Mozgin <m0391n@gmail.com>
 *
 *
 */

package com.m039.estimoto.util;

import android.content.Context;
import android.content.Intent;

import com.m039.estimoto.service.EstimotoService;

/**
 *
 *
 * Created: 03/22/14
 *
 * @author Dmitry Mozgin
 * @version
 * @since
 */
public class EstimotoServiceUtil {

    public static void turnOn(Context ctx) {
        Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
        intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
        ctx.startService(intent);
    }

    public static void turnOff(Context ctx) {
        Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
        intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
        ctx.startService(intent);
    }

    private static Intent newEstimotoIntent(Context ctx, String action) {
        Intent intent = new Intent(ctx, EstimotoService.class);
        intent.setAction(action);
        return intent;
    }

} // EstimotoServiceUtil

/** EstimotoServiceUtil.java ---
 *
 * Copyright (C) 2014 Dmitry Mozgin
 *
 * Author: Dmitry Mozgin <m0391n@gmail.com>
 *
 *
 */

package com.m039.estimoto.util;

import android.content.Context;
import android.content.Intent;

import com.m039.estimoto.service.EstimotoService;

/**
 *
 *
 * Created: 03/22/14
 *
 * @author Dmitry Mozgin
 * @version
 * @since
 */
public class EstimotoServiceUtil {

    public static void turnOn(Context ctx) {
        Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
        intent.putExtra(EstimotoService.EXTRA_TURN_ON, true);
        ctx.startService(intent);
    }

    public static void turnOff(Context ctx) {
        Intent intent = newEstimotoIntent(ctx, EstimotoService.ACTION_CONTROL);
        intent.putExtra(EstimotoService.EXTRA_TURN_OFF, true);
        ctx.startService(intent);
        ctx.stopService(intent); // hack
    }

    private static Intent newEstimotoIntent(Context ctx, String action) {
        Intent intent = new Intent(ctx, EstimotoService.class);
        intent.setAction(action);
        return intent;
    }

} // EstimotoServiceUtil

Add hack to stop service

Add hack to stop service


package de.retest.recheck.ui.descriptors;

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

public class ElementUtil {

	private ElementUtil() {}

	public static List<Element> flattenAllElements( final List<Element> elements ) {
		final List<Element> flattened = new ArrayList<>();

		for ( final Element element : elements ) {
			flattened.add( element );
			flattened.addAll( flattenChildElements( element ) );
		}

		return flattened;
	}

	public static List<Element> flattenChildElements( final Element element ) {
		final List<Element> flattened = new ArrayList<>();

		for ( final Element childElement : element.getContainedElements() ) {
			flattened.add( childElement );
			flattened.addAll( flattenChildElements( childElement ) );
		}

		return flattened;
	}

	public static boolean pathEquals( final Element element0, final Element element1 ) {
		return element0.getIdentifyingAttributes().getPathTyped()
				.equals( element1.getIdentifyingAttributes().getPathTyped() );
	}
}

package de.retest.recheck.ui.descriptors;

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

public class ElementUtil {

	private ElementUtil() {}

	public static List<Element> flattenAllElements( final List<? extends Element> elements ) {
		final List<Element> flattened = new ArrayList<>();

		for ( final Element element : elements ) {
			flattened.add( element );
			flattened.addAll( flattenChildElements( element ) );
		}

		return flattened;
	}

	public static List<Element> flattenChildElements( final Element element ) {
		final List<Element> flattened = new ArrayList<>();

		for ( final Element childElement : element.getContainedElements() ) {
			flattened.add( childElement );
			flattened.addAll( flattenChildElements( childElement ) );
		}

		return flattened;
	}

	public static boolean pathEquals( final Element element0, final Element element1 ) {
		return element0.getIdentifyingAttributes().getPathTyped()
				.equals( element1.getIdentifyingAttributes().getPathTyped() );
	}
}

Use wildcard to also accept e.g. list of `RootElement`s


package com.avairebot.orion.commands.utility;

import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InviteCommand extends AbstractCommand {
    public InviteCommand(Orion orion) {
        super(orion);
    }

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

    @Override
    public String getDescription() {
        return "Returns a link that can be used to invite to bot to other servers.";
    }

    @Override
    public List<String> getUsageInstructions() {
        return Collections.singletonList("`!invite` - Gives you an invite link that can be used to invite Orion to servers.");
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("invite", "join");
    }

    @Override
    public boolean onCommand(Message message, String[] args) {
        MessageFactory.makeInfo(message,
                "You can invite me to your server by [clicking here](%s) or use the link below:\n\n%s",
                orion.config.botAuth().getOAuth(), orion.config.botAuth().getOAuth())
                .queue();

        return true;
    }
}

package com.avairebot.orion.commands.utility;

import com.avairebot.orion.Orion;
import com.avairebot.orion.contracts.commands.AbstractCommand;
import com.avairebot.orion.factories.MessageFactory;
import net.dv8tion.jda.core.entities.Message;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InviteCommand extends AbstractCommand {
    public InviteCommand(Orion orion) {
        super(orion);
    }

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

    @Override
    public String getDescription() {
        return "Returns a link that can be used to invite the bot to other servers.";
    }

    @Override
    public List<String> getUsageInstructions() {
        return Collections.singletonList("`!invite` - Gives you an invite link that can be used to invite Orion to servers.");
    }

    @Override
    public List<String> getTriggers() {
        return Arrays.asList("invite", "join");
    }

    @Override
    public boolean onCommand(Message message, String[] args) {
        MessageFactory.makeInfo(message,
                "You can invite me to your server by [clicking here](%s) or use the link below:\n\n%s",
                orion.config.botAuth().getOAuth(), orion.config.botAuth().getOAuth())
                .queue();

        return true;
    }
}

Fix spelling mistake in invite command description