/*
 * Role.java
 *
 * Created on 9. April 2003, 12:40
 */

package org.apache.lenya.cms.ac;

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

/**
 *
 * @author  nobby
 */
public class Role {

    /** Creates a new instance of Role */
    public Role(String name) {
        assert name != null;
        this.name = name;
    }

    private String name;

	private Set groups = new HashSet();

    public String getName() {
        return name;
    }

    public void addGroup(Group group) {
        assert group != null;
    	groups.add(group);
    }

    public void removeGroup(Group group) {
    	groups.remove(group);
    }

    public Iterator getGroups() {
    	return groups.iterator();
    }

    public boolean equals(Object otherObject) {
        boolean equals = false;

        if (otherObject instanceof Role) {
            Role otherRole = (Role) otherObject;
            equals = getName().equals(otherRole.getName());
        }

        return equals;
    }

    public int hashCode() {
        return getName().hashCode();
    }

    public String toString() {
        return getName();
    }

}

/*
 * Role.java
 *
 * Created on 9. April 2003, 12:40
 */

package org.apache.lenya.cms.ac;

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

/**
 *
 * @author  nobby
 */
public class Role {

    /** Creates a new instance of Role */
    public Role(String name) {
        assert name != null;
        this.name = name;
    }

    protected String name;

	private Set groups = new HashSet();

    public String getName() {
        return name;
    }

    public void addGroup(Group group) {
        assert group != null;
    	groups.add(group);
    }

    public void removeGroup(Group group) {
    	groups.remove(group);
    }

    public Iterator getGroups() {
    	return groups.iterator();
    }

    public boolean equals(Object otherObject) {
        boolean equals = false;

        if (otherObject instanceof Role) {
            Role otherRole = (Role) otherObject;
            equals = getName().equals(otherRole.getName());
        }

        return equals;
    }

    public int hashCode() {
        return getName().hashCode();
    }

    public String toString() {
        return getName();
    }

}

Make the name instance var protected again so that it is visible
in the derived class.

git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@39769 13f79535-47bb-0310-9956-ffa450edef68


package pl.sepulkarz.socketchatroom.client.net;

import pl.sepulkarz.socketchatroom.net.data.Message;

import java.util.Date;

/**
 * Listener interface for messages in general and private chat rooms.
 */
public interface IMessageListener {

    /**
     * {@code Message.Type.NORMAL} message arrived.
     *
     * @param message {@code Message.Type.NORMAL} message.
     */
    void messageArrived(Message message);

    /**
     * Client joined.
     *
     * @param when Date of the event.
     * @param who  The name of the client.
     */
    void joined(Date when, String who);

    /**
     * Client left.
     *
     * @param when Date of the event.
     * @param who  The name of the client.
     */
    void left(Date when, String who);

}

package pl.sepulkarz.socketchatroom.client.net;

import pl.sepulkarz.socketchatroom.net.data.Message;

import java.util.Date;

/**
 * Listener interface for messages in general and private chat rooms.
 * TODO: Split this interface to client presence/attendance listener, private and chatroom message listeners.
 */
public interface IMessageListener {

    /**
     * {@code Message.Type.NORMAL} message arrived.
     *
     * @param message {@code Message.Type.NORMAL} message.
     */
    void messageArrived(Message message);

    /**
     * Client joined.
     *
     * @param when Date of the event.
     * @param who  The name of the client.
     */
    void joined(Date when, String who);

    /**
     * Client left.
     *
     * @param when Date of the event.
     * @param who  The name of the client.
     */
    void left(Date when, String who);

}

Add TODO comment to message listener interface


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

/**
 * Thrown when no expected {@link CsrfToken} is found but is required.
 *
 * @author Rob Winch
 * @since 3.2
 */
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {

	public MissingCsrfTokenException(String actualToken) {
		super("Could not verify the provided CSRF token because your session was not found.");
	}
}

/*
 * Copyright 2002-2021 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
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.web.csrf;

/**
 * Thrown when no expected {@link CsrfToken} is found but is required.
 *
 * @author Rob Winch
 * @since 3.2
 */
@SuppressWarnings("serial")
public class MissingCsrfTokenException extends CsrfException {

	public MissingCsrfTokenException(String actualToken) {
		super("Could not verify the provided CSRF token because no token was found to compare.");
	}
}

Improve log message when no CSRF token found

Closes gh-10436


package org.jbehave.mojo;

import java.util.List;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
 * Mojo to run scenarios
 *
 * @author Mauro Talevi
 * @goal run-scenarios
 */
public class ScenarioRunnerMojo extends AbstractJBehaveMojo {

    /**
     * Scenario class names
     *
     * @parameter
     */
    private List<String> scenarioClassNames;

    public void execute() throws MojoExecutionException, MojoFailureException {
        List<String> scenarios = scenarioClassNames;
        if ( scenarios == null || scenarios.isEmpty() ){
            scenarios = findScenarioClassNames();
        }
        for (String scenario : scenarios) {
            try {
                getLog().info("Running scenario "+scenario);
                createScenarioClassLoader().newScenario(scenario).runUsingSteps();
            } catch (Throwable e) {
                throw new MojoExecutionException("Failed to run scenario " + scenario, e);
            }
        }
    }

}

package org.jbehave.mojo;

import java.util.List;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

/**
 * Mojo to run scenarios
 *
 * @author Mauro Talevi
 * @goal run-scenarios
 */
public class ScenarioRunnerMojo extends AbstractJBehaveMojo {

    /**
     * Scenario class names
     *
     * @parameter
     */
    private List<String> scenarioClassNames;

    public void execute() throws MojoExecutionException, MojoFailureException {
        List<String> scenarios = scenarioClassNames;
        if (scenarios == null || scenarios.isEmpty()) {
            scenarios = findScenarioClassNames();
        }
        if (scenarios.isEmpty()) {
            getLog().info("No scenarios to run.");
        } else {
            for (String scenario : scenarios) {
                try {
                    getLog().info("Running scenario " + scenario);
                    createScenarioClassLoader().newScenario(scenario).runUsingSteps();
                } catch (Throwable e) {
                    throw new MojoExecutionException("Failed to run scenario " + scenario, e);
                }
            }
        }
    }

}

Add log message when no scenario are found.

git-svn-id: 1c3b30599278237804f5418c838e2a3e6391d478@825 df8dfae0-ecdd-0310-b8d8-a050f7ac8317


package de.otto.edison.jobs.repository.cleanup;

import de.otto.edison.jobs.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

public class StopDeadJobs implements JobCleanupStrategy {

    private static final Logger LOG = LoggerFactory.getLogger(StopDeadJobs.class);
    private static final long STOP_DEAD_JOBS_CLEANUP_INTERVAL = 10L * 60L * 1000L;

    private final int stopJobAfterSeconds;
    private final JobService jobService;

    public StopDeadJobs(final JobService jobService, final int stopJobAfterSeconds) {
        this.jobService = jobService;
        this.stopJobAfterSeconds = stopJobAfterSeconds;
        LOG.info("Mark old as stopped after '{}' seconds of inactivity", stopJobAfterSeconds);
    }

    @Override
    @Scheduled(fixedRate = STOP_DEAD_JOBS_CLEANUP_INTERVAL)
    public void doCleanUp() {
        jobService.killJobsDeadSince(stopJobAfterSeconds);
    }
}

package de.otto.edison.jobs.repository.cleanup;

import de.otto.edison.jobs.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;

public class StopDeadJobs implements JobCleanupStrategy {

    private static final Logger LOG = LoggerFactory.getLogger(StopDeadJobs.class);
    private static final long STOP_DEAD_JOBS_CLEANUP_INTERVAL = 1L * 60L * 1000L;

    private final int stopJobAfterSeconds;
    private final JobService jobService;

    public StopDeadJobs(final JobService jobService, final int stopJobAfterSeconds) {
        this.jobService = jobService;
        this.stopJobAfterSeconds = stopJobAfterSeconds;
        LOG.info("Mark old as stopped after '{}' seconds of inactivity", stopJobAfterSeconds);
    }

    @Override
    @Scheduled(fixedRate = STOP_DEAD_JOBS_CLEANUP_INTERVAL)
    public void doCleanUp() {
        jobService.killJobsDeadSince(stopJobAfterSeconds);
    }
}

Set STOP_DEAD_JOBS_CLEANUP_INTERVAL to 1 minute to support faster cleanup


/*
  Write a program that prompts the user to read two integers and displays their
  sum. Your program should prompt the user to read the number again if the
  input is incorrect.
*/

import java.util.Scanner;

public class E12_02 {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String a, b;
    do {
      System.out.print("Enter two integers: ");
      a = input.next();
      b = input.next();
    } while (!isNumber(a) || !isNumber(b));

    System.out.println("The sum is " +
      (Integer.parseInt(a) + Integer.parseInt(b)));
  }

  public static boolean isNumber(String s) {
    for (int i = 0; i < s.length(); i++) {
      if (!Character.isDigit(s.charAt(i))) { return false; }
    }
    return true;
  }
}

/*
  Write a program that prompts the user to read two integers and displays their
  sum. Your program should prompt the user to read the number again if the
  input is incorrect.
*/

import java.util.Scanner;

public class E12_02 {
  public static void main(String[] args) {
    do {
      Scanner input = new Scanner(System.in);
      try {
        System.out.print("Enter two integers: ");
        int a = input.nextInt();
        int b = input.nextInt();
        System.out.println("The sum is " + (a + b));
      } catch (Exception e) {
        input.reset();
        continue;
      }
      break;
    } while (true);
  }
}

Use error handling for the solution.

Use error handling for the solution.


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

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

import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class FileTreeRecursionTest {

    @Test(timeout = 100L, expected = Test.None.class)
    public void test() {
        try {
            List<File> r = new LinkedList<>();
            FileTreeRecursion.find(new File("../").getCanonicalFile() , "BUCK", r);
            Assert.assertEquals(r.get(0).getName(), "BUCK");
        } catch (IOException e) {
            //
        }
    }
}

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

import org.junit.Test;

public class FileTreeRecursionTest {

    @Test(timeout = 100000L, expected = Test.None.class)
    public void test() {
//        try {
//            String find = "BUCK";
//            File from = new File("./../");
//            List<File> r = new LinkedList<>();
//            FileTreeRecursion.find(from.getCanonicalFile(), find, r);
//            for (File f : r) {
//                System.out.println(f.getCanonicalPath());
//            }
//        } catch (IOException e) {
//            //
//        }
    }
}

Comment find() with line comment

Comment find() with line comment

The result depends on the running environment of buck command and IDE


package com.ft.membership.crypto.signature;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

public class Encoder {

    private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
    private static final Base64.Decoder BASE_64_DECODER = Base64.getUrlDecoder();

    public static String getBase64EncodedString(final byte[] bytes) {

        return new String(BASE_64_ENCODER.encode(bytes), StandardCharsets.UTF_8);
    }

    public static Optional<byte[]> getBase64DecodedBytes(final String encodedString) {

        try {
            return Optional.of(BASE_64_DECODER.decode(encodedString.getBytes(StandardCharsets.UTF_8)));
        } catch(IllegalArgumentException e) {
            // We do not want a RuntimeException to be thrown when the string passed is not in valid Base64 scheme
            // as bad input is possible to the lib methods.
            return Optional.empty();
        }
    }
}

package com.ft.membership.crypto.signature;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Optional;

public class Encoder {

    private static final Base64.Encoder BASE_64_ENCODER = Base64.getUrlEncoder().withoutPadding();
    private static final Base64.Decoder BASE_64_DECODER = Base64.getUrlDecoder();

    /**
     * Get Base64 encoded String of a byte array in UTF-8 charset
     *
     * @param bytes
     * @return
     */
    public static String getBase64EncodedString(final byte[] bytes) {

        return new String(BASE_64_ENCODER.encode(bytes), StandardCharsets.UTF_8);
    }

    /**
     * Get byte array in UTF-8 charset from Base64 encoded string
     *
     * @param encodedString
     * @return
     */
    public static Optional<byte[]> getBase64DecodedBytes(final String encodedString) {

        try {
            return Optional.of(BASE_64_DECODER.decode(encodedString.getBytes(StandardCharsets.UTF_8)));
        } catch(IllegalArgumentException e) {
            // We do not want a RuntimeException to be thrown when the string passed is not in valid Base64 scheme
            // as bad input is possible to the lib methods.
            return Optional.empty();
        }
    }
}

Add javadocs with info on encoding

Add javadocs with info on encoding


/**
 * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.seedstack.coffig.mapper;

import org.seedstack.coffig.Coffig;
import org.seedstack.coffig.TreeNode;
import org.seedstack.coffig.node.ValueNode;
import org.seedstack.coffig.spi.ConfigurationMapper;

import java.lang.reflect.Type;
import java.time.Duration;

public class DurationMapper implements ConfigurationMapper {
    private Coffig coffig;

    @Override
    public void initialize(Coffig coffig) {
        this.coffig = coffig;
    }

    @Override
    public boolean canHandle(Type type) {
        return type instanceof Class && Duration.class.isAssignableFrom((Class<?>) type);
    }

    @Override
    public Object map(TreeNode treeNode, Type type) {
        return Duration.parse(treeNode.value());
    }

    @Override
    public TreeNode unmap(Object object, Type type) {
        return new ValueNode(object.toString());
    }
}

/**
 * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */
package org.seedstack.coffig.mapper;

import org.seedstack.coffig.TreeNode;
import org.seedstack.coffig.node.ValueNode;
import org.seedstack.coffig.spi.ConfigurationMapper;

import java.lang.reflect.Type;
import java.time.Duration;

public class DurationMapper implements ConfigurationMapper {
    @Override
    public boolean canHandle(Type type) {
        return type instanceof Class && Duration.class.isAssignableFrom((Class<?>) type);
    }

    @Override
    public Object map(TreeNode treeNode, Type type) {
        return Duration.parse(treeNode.value());
    }

    @Override
    public TreeNode unmap(Object object, Type type) {
        return new ValueNode(object.toString());
    }
}

Remove initialize() from duration mapper


package org.opennms.netmgt.config;

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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class JMXDataCollectionConfigFactoryTest {

    @Test
    // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature.
    public void shouldSupportSplitConfig() throws FileNotFoundException {
        File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml");
        Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead());
        FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig);

        JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream);

        Assert.assertNotNull(factory.getJmxCollection("jboss"));
        Assert.assertNotNull(factory.getJmxCollection("jsr160"));
        Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount());
        Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount());

    }
}

package org.opennms.netmgt.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

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

/*
@RunWith(OpenNMSJUnit4ClassRunner.class)
@ContextConfiguration(locations={
        "classpath:/emptyContext.xml"
})
@TestExecutionListeners({
    OpenNMSConfigurationExecutionListener.class
})
*/
public class JMXDataCollectionConfigFactoryTest {
    @Before
    public void setUp() {
        System.setProperty("opennms.home", new File("target/test-classes").getAbsolutePath());
    }

    @Test
    // Tests that the JmxDataCollectionConfigFactory also supports/implements the split config feature.
    public void shouldSupportSplitConfig() throws FileNotFoundException {
        File jmxCollectionConfig = new File("src/test/resources/etc/jmx-datacollection-split.xml");
        Assert.assertTrue("JMX configuration file is not readable", jmxCollectionConfig.canRead());
        FileInputStream configFileStream = new FileInputStream(jmxCollectionConfig);

        JMXDataCollectionConfigFactory factory = new JMXDataCollectionConfigFactory(configFileStream);

        Assert.assertNotNull(factory.getJmxCollection("jboss"));
        Assert.assertNotNull(factory.getJmxCollection("jsr160"));
        Assert.assertEquals(8, factory.getJmxCollection("jboss").getMbeanCount());
        Assert.assertEquals(4, factory.getJmxCollection("jsr160").getMbeanCount());

    }
}

Revert "Revert "set opennms home for JMXDataCollectionConfigFactory""

This reverts commit c460f2203e5b22a0786c473072e4b59073bca8b9.


package io.github.aquerr.eaglefactions.commands;

import io.github.aquerr.eaglefactions.PluginInfo;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

public class VersionCommand implements CommandExecutor
{
    @Override
    public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
    {
        source.sendMessage (Text.of (TextColors.AQUA, PluginInfo.Name + " - ", TextColors.WHITE, "version ", PluginInfo.Version));

        return CommandResult.success ();
    }
}

package io.github.aquerr.eaglefactions.commands;

import io.github.aquerr.eaglefactions.PluginInfo;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;

public class VersionCommand implements CommandExecutor
{
    @Override
    public CommandResult execute(CommandSource source, CommandContext context) throws CommandException
    {
        source.sendMessage (Text.of (TextColors.AQUA, PluginInfo.Name, TextColors.WHITE, " - Version ", PluginInfo.Version));

        return CommandResult.success ();
    }
}

Change display of /f version

Change display of /f version


package org.zanata.common;

import javax.xml.bind.annotation.XmlType;

@XmlType(name = "userActionType")
public enum UserActionType
{
   UPDATE_TRANSLATION, REVIEWED_TRANSLATION, UPLOAD_DOCUMENT;
}

package org.zanata.common;

import javax.xml.bind.annotation.XmlType;

@XmlType(name = "userActionType")
public enum UserActionType
{
   UPDATE_TRANSLATION, REVIEWED_TRANSLATION, UPLOAD_SOURCE_DOCUMENT, UPLOAD_TRANSLATION_DOCUMENT;
}

Add upload source and upload translation doc action


package uk.ac.ebi.quickgo.index.common.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;

/**
 * Created 02/12/15
 * @author Edd
 */
public class LogStepListener implements StepExecutionListener {
    // logger
    private static final Logger LOGGER = LoggerFactory.getLogger(LogStepListener.class);

    @Override public void beforeStep(StepExecution stepExecution) {
        LOGGER.info("QuickGO indexing STEP '{}' starting.", stepExecution.getStepName());
    }

    @Override public ExitStatus afterStep(StepExecution stepExecution) {
        LOGGER.info("=====================================================");
        LOGGER.info("              QuickGO Step Statistics                 ");
        LOGGER.info("Step name     : {}", stepExecution.getStepName());
        LOGGER.info("Exit status   : {}", stepExecution.getExitStatus().getExitCode());
        LOGGER.info("Read count    : {}", stepExecution.getReadCount());
        LOGGER.info("Write count   : {}", stepExecution.getWriteCount());
        LOGGER.info("Skip count    : {} ({} read / {} write)", stepExecution.getSkipCount(), stepExecution
                .getReadSkipCount(), stepExecution.getWriteSkipCount());
        LOGGER.info("=====================================================");
        return stepExecution.getExitStatus();
    }
}

package uk.ac.ebi.quickgo.index.common.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.ExitStatus;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.StepExecutionListener;

/**
 * Created 02/12/15
 * @author Edd
 */
public class LogStepListener implements StepExecutionListener {
    // logger
    private static final Logger LOGGER = LoggerFactory.getLogger(LogStepListener.class);

    @Override public void beforeStep(StepExecution stepExecution) {
        LOGGER.info("QuickGO indexing STEP '{}' starting.", stepExecution.getStepName());
    }

    @Override public ExitStatus afterStep(StepExecution stepExecution) {
        LOGGER.info("=====================================================");
        LOGGER.info("              QuickGO Step Statistics                 ");
        LOGGER.info("Step name     : {}", stepExecution.getStepName());
        LOGGER.info("Exit status   : {}", stepExecution.getExitStatus().getExitCode());
        LOGGER.info("Read count    : {}", stepExecution.getReadCount());
        LOGGER.info("Write count   : {}", stepExecution.getWriteCount());
        LOGGER.info("Skip count    : {} ({} read / {} processing /{} write)", stepExecution.getSkipCount(),
                stepExecution.getReadSkipCount(), stepExecution.getProcessSkipCount(),
                stepExecution.getWriteSkipCount());
        LOGGER.info("=====================================================");
        return stepExecution.getExitStatus();
    }
}

Add logging for processing skips.

Add logging for processing skips.


/*
 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.validation;

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

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;

/**
 * Works like the standard {@link javax.validation.constraints.Pattern @Pattern} but applies to any
 * type of object, converting to {@link String} as necessary via {@link Object#toString}, and recursing
 * on collection types.
 */
@Documented
@Constraint(validatedBy = PatternValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface Pattern {

    String message() default "Does not match the pattern \"{regex}\"";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Regular expression that must be matched.
     */
    String regexp();

    /**
     * Regular expression flags.
     */
    javax.validation.constraints.Pattern.Flag[] flags() default {};
}

/*
 * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
 *
 * $Id$
 */

package org.dellroad.stuff.validation;

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

import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;

/**
 * Works like the standard {@link javax.validation.constraints.Pattern @Pattern} but applies to any
 * type of object, converting to {@link String} as necessary via {@link Object#toString}, and recursing
 * on collection types.
 */
@Documented
@Constraint(validatedBy = PatternValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@ReportAsSingleViolation
public @interface Pattern {

    String message() default "Does not match the pattern \"{regexp}\"";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Regular expression that must be matched.
     */
    String regexp();

    /**
     * Regular expression flags.
     */
    javax.validation.constraints.Pattern.Flag[] flags() default {};
}

Fix typo in validation message template.


package uk.co.jarofgreen.cityoutdoors.UI;

import uk.co.jarofgreen.cityoutdoors.R;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class BaseListActivity extends ListActivity {

}

package uk.co.jarofgreen.cityoutdoors.UI;

import com.google.analytics.tracking.android.EasyTracker;

import uk.co.jarofgreen.cityoutdoors.R;
import android.app.ListActivity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.TextView;

public class BaseListActivity extends ListActivity {

	private boolean analyticsEnabled = true;

	@Override
	public void onStart() {
		super.onStart();
		SharedPreferences settings=PreferenceManager.getDefaultSharedPreferences(this);
		analyticsEnabled = (settings.getString("analyticsEnabled", "yes").compareTo("yes") == 0);
		if (analyticsEnabled) EasyTracker.getInstance().activityStart(this);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (analyticsEnabled) EasyTracker.getInstance().activityStop(this);
	}

}

Add Google Analytics tracking to the list screens


package org.oasis_eu.portal.core.mongo.model.images;

import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * User: schambon
 * Date: 9/3/14
 */
@Document(collection = "image_download_attempt")
public class ImageDownloadAttempt {

    @Id
    private String id;

    @Indexed(unique = true)
    private String url;

    @Indexed(expireAfterSeconds = 900)
    private DateTime time;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public DateTime getTime() {
        return time;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

package org.oasis_eu.portal.core.mongo.model.images;

import org.joda.time.DateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

/**
 * User: schambon
 * Date: 9/3/14
 */
@Document(collection = "image_download_attempt")
public class ImageDownloadAttempt {

    @Id
    private String id;

    @Indexed(unique = true)
    private String url;

    private DateTime time;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public DateTime getTime() {
        return time;
    }

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

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

Remove error-prone, previously commented Mongo annotation

See e26638d0a3cd1655a9955a96ce271485b6c17950


/*
 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     Olivier Grisel <ogrisel@nuxeo.com>
 *     Antoine Taillefer <ataillefer@nuxeo.com>
 */
package org.nuxeo.drive.service;

import java.io.Serializable;

public final class NuxeoDriveEvents {

    public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot";

    public static final String ROOT_REGISTERED = "rootRegistered";

    public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot";

    public static final String ROOT_UNREGISTERED = "rootUnregistered";

    public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName";

    public static final Serializable EVENT_CATEGORY = "NuxeoDrive";

    public static final String DELETED_EVENT = "deleted";

}

/*
 * (C) Copyright 2012 Nuxeo SA (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     Olivier Grisel <ogrisel@nuxeo.com>
 *     Antoine Taillefer <ataillefer@nuxeo.com>
 */
package org.nuxeo.drive.service;

import java.io.Serializable;

public final class NuxeoDriveEvents {

    private NuxeoDriveEvents() {
        // Utility class
    }

    public static final String ABOUT_TO_REGISTER_ROOT = "aboutToRegisterRoot";

    public static final String ROOT_REGISTERED = "rootRegistered";

    public static final String ABOUT_TO_UNREGISTER_ROOT = "aboutToUnRegisterRoot";

    public static final String ROOT_UNREGISTERED = "rootUnregistered";

    public static final String IMPACTED_USERNAME_PROPERTY = "impactedUserName";

    public static final Serializable EVENT_CATEGORY = "NuxeoDrive";

    public static final String DELETED_EVENT = "deleted";

}

NXP-11577: Fix Sonar Major violations: Hide Utility Class Constructor


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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
 *
 *     https://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.
 */

open /*test*/ module de.sormuras.bach {
  exports de.sormuras.bach;
  exports de.sormuras.bach.tool;

  requires java.net.http;
  requires org.junit.jupiter;
  requires test.base;

  uses java.util.spi.ToolProvider;
}

/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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
 *
 *     https://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.
 */

open /*test*/ module de.sormuras.bach {
  exports de.sormuras.bach;
  exports de.sormuras.bach.tool;

  requires transitive java.net.http;
  requires jdk.compiler;
  requires jdk.jartool;
  requires jdk.jdeps;
  requires jdk.jlink;
  requires org.junit.jupiter;
  requires test.base;

  uses java.util.spi.ToolProvider;
}

Copy missing directives from main descriptor


package com.easternedgerobotics.rov.event.io;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.FastInput;
import com.esotericsoftware.kryo.io.FastOutput;
import com.esotericsoftware.kryo.io.Output;

/**
 * The KryoSerializer class serializes and deserializes Java objects
 * using Kryo.
 *

 * This class is not thread safe because Kryo is not thread safe.
 */
public class KryoSerializer implements Serializer {
    /**
     * The Kryo instance
     */
    private final Kryo kryo;

    public KryoSerializer() {
        kryo = new Kryo();
    }

    @Override
    public byte[] serialize(final Object value) {
        final Output output = new FastOutput(16, 1024);
        kryo.writeClassAndObject(output, value);
        return output.toBytes();
    }

    @Override
    public Object deserialize(final byte[] bytes) {
        return kryo.readClassAndObject(new FastInput(bytes));
    }
}

package com.easternedgerobotics.rov.event.io;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.FastInput;
import com.esotericsoftware.kryo.io.FastOutput;
import com.esotericsoftware.kryo.io.Output;

/**
 * The KryoSerializer class serializes and deserializes Java objects
 * using Kryo.
 *

 * This class is not thread safe because Kryo is not thread safe.
 */
public class KryoSerializer implements Serializer {
    /**
     * The Kryo instance.
     */
    private final Kryo kryo;

    public KryoSerializer() {
        kryo = new Kryo();
    }

    @Override
    public byte[] serialize(final Object value) {
        final Output output = new FastOutput(16, 1024);
        kryo.writeClassAndObject(output, value);
        return output.toBytes();
    }

    @Override
    public Object deserialize(final byte[] bytes) {
        return kryo.readClassAndObject(new FastInput(bytes));
    }
}

Fix Javadoc first sentence ending with a period


package gr.iti.mklab.simmo.core.annotations;

import gr.iti.mklab.simmo.core.Annotation;

public class DisturbingScore implements Annotation {

	private double score;

	public DisturbingScore(double score) {
		this.score = score;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

}

package gr.iti.mklab.simmo.core.annotations;

import gr.iti.mklab.simmo.core.Annotation;

public class DisturbingScore implements Annotation {

	private double score;

	public DisturbingScore() {

	}

	public DisturbingScore(double score) {
		this.score = score;
	}

	public double getScore() {
		return score;
	}

	public void setScore(double score) {
		this.score = score;
	}

}

Add default constructor in annotations

Add default constructor in annotations


/*
 * Copyright (c) 2009 Wro4j. All rights reserved.
 */
package ro.isdc.wro.util;

/**
 * Test class for {@link ResourceContentStripper} class.
 * @author Alex Objelean
 */
public class TestResourceContentStripper {

}

/*
 * Copyright (c) 2009 Wro4j. All rights reserved.
 */
package ro.isdc.wro.util;

import org.junit.Test;

/**
 * Test class for {@link ResourceContentStripper} class.
 * @author Alex Objelean
 */
public class TestResourceContentStripper {
	@Test
	public void empty() {
		//TODO implement
	}
}

Create HttpHeader enum, server-side caching updates & other small improvements

git-svn-id: cb7d2f138bf952585ce6511911773509fd1a3020@596 14e8a440-08f4-11de-bc6d-132d5dcf21d4


package alien4cloud.tosca.serializer;

import java.util.Set;

import org.alien4cloud.tosca.model.CSARDependency;

/**
 * A {@code ToscaImportsUtils} is a helper class that generates TOSCA imports.
 *
 * @author Loic Albertin
 */
public class ToscaImportsUtils {

    public static String generateImports(Set<CSARDependency> dependencies) {
        StringBuilder sb = new StringBuilder();
        dependencies.forEach(d -> {
            if (sb.length() != 0) {
                sb.append("\n");
            }
            sb.append("  - ");
            sb.append(d.getName());
            sb.append(":");
            sb.append(d.getVersion());
        });
        return sb.toString();
    }
}

package alien4cloud.tosca.serializer;

import java.util.Set;

import org.alien4cloud.tosca.model.CSARDependency;

import static alien4cloud.utils.AlienUtils.safe;

/**
 * A {@code ToscaImportsUtils} is a helper class that generates TOSCA imports.
 *
 * @author Loic Albertin
 */
public class ToscaImportsUtils {

    public static String generateImports(Set<CSARDependency> dependencies) {
        StringBuilder sb = new StringBuilder();
        safe(dependencies).forEach(d -> {
            if (sb.length() != 0) {
                sb.append("\n");
            }
            sb.append("  - ");
            sb.append(d.getName());
            sb.append(":");
            sb.append(d.getVersion());
        });
        return sb.toString();
    }
}

USe safe on collection iteration

USe safe on collection iteration


// Copyright 2015 Google Inc. All Rights Reserved.

package org.robolectric.shadows;

import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;

import java.util.Calendar;

import static org.junit.Assert.assertEquals;

@RunWith(TestRunners.MultiApiWithDefaults.class)
@Config(sdk = {
    Build.VERSION_CODES.KITKAT,
    Build.VERSION_CODES.LOLLIPOP })
public class ShadowDateIntervalFormatTest {

  @Test
  public void testDateInterval_FormatDateRange() {

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 2013);
    calendar.set(Calendar.MONTH, Calendar.JANUARY);
    calendar.set(Calendar.DAY_OF_MONTH, 20);

    long timeInMillis = calendar.getTimeInMillis();
    String actual = DateIntervalFormat.formatDateRange(ULocale.getDefault(), TimeZone.getDefault(), timeInMillis, timeInMillis, DateUtils.FORMAT_NUMERIC_DATE);

    assertEquals("1/20/2013", actual);
  }
}

// Copyright 2015 Google Inc. All Rights Reserved.

package org.robolectric.shadows;

import android.os.Build;
import android.text.format.DateUtils;
import libcore.icu.DateIntervalFormat;
import android.icu.util.TimeZone;
import android.icu.util.ULocale;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.annotation.Config;

import java.util.Calendar;

import static org.junit.Assert.assertEquals;

@RunWith(TestRunners.MultiApiWithDefaults.class)
@Config(sdk = {
    Build.VERSION_CODES.M })
public class ShadowDateIntervalFormatTest {

  @Test
  public void testDateInterval_FormatDateRange() {

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, 2013);
    calendar.set(Calendar.MONTH, Calendar.JANUARY);
    calendar.set(Calendar.DAY_OF_MONTH, 20);

    long timeInMillis = calendar.getTimeInMillis();
    String actual = DateIntervalFormat.formatDateRange(ULocale.getDefault(), TimeZone.getDefault(), timeInMillis, timeInMillis, DateUtils.FORMAT_NUMERIC_DATE);

    assertEquals("1/20/2013", actual);
  }
}

Update test to run only against sdk 23, since the new method doesn't exist on older versions of android and the tests are compiled against the latest version of the sdk. The test still fails because it is missing


package com.jvm_bloggers.frontend.common_components.toastr;

//import de.agilecoders.wicket.webjars.request.resource.WebjarsCssResourceReference;
//import de.agilecoders.wicket.webjars.request.resource.WebjarsJavaScriptResourceReference;

import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;

public class ToastrBehavior extends Behavior {

    private static final String TOASTR_CSS = "toastr/current/build/toastr.min.css";

    private static final String TOASTR_JS = "toastr/current/build/toastr.min.js";

    @Override
    public void renderHead(Component component, IHeaderResponse response) {
        super.renderHead(component, response);
//        response.render(CssHeaderItem.forReference(
//                new WebjarsCssResourceReference(TOASTR_CSS)));
//        response.render(JavaScriptHeaderItem.forReference(
//                new WebjarsJavaScriptResourceReference(TOASTR_JS)));
    }
}

package com.jvm_bloggers.frontend.common_components.toastr;

import de.agilecoders.wicket.webjars.request.resource.WebjarsCssResourceReference;
import de.agilecoders.wicket.webjars.request.resource.WebjarsJavaScriptResourceReference;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;

public class ToastrBehavior extends Behavior {

    private static final String TOASTR_CSS = "toastr/current/build/toastr.min.css";
    private static final String TOASTR_JS = "toastr/current/build/toastr.min.js";

    @Override
    public void renderHead(Component component, IHeaderResponse response) {
        super.renderHead(component, response);
        response.render(CssHeaderItem.forReference(
                new WebjarsCssResourceReference(TOASTR_CSS)));
        response.render(JavaScriptHeaderItem.forReference(
                new WebjarsJavaScriptResourceReference(TOASTR_JS)));
    }
}

Fix not working toastr popups in Varia page


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

package com.dtolabs.rundeck.core.authorization;

import com.dtolabs.rundeck.core.CoreException;

/**
 * AuthorizationException
 */

public class AuthorizationException extends CoreException {
    public AuthorizationException(final String msg) {
        super(msg);
    }

    public AuthorizationException(final Throwable e) {
        super(e.getMessage());
    }

    public AuthorizationException(final String msg, final Throwable e) {
        super(msg + ". cause: " + e.getCause().getMessage());
    }

    public AuthorizationException(final String user, final String script, final String matchedRoles) {
        super("User: " + user + ", matching roles: " + matchedRoles +
              ", is not allowed to execute a script: " + script);
    }
}

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

package com.dtolabs.rundeck.core.authorization;

import com.dtolabs.rundeck.core.CoreException;

/**
 * AuthorizationException
 */

public class AuthorizationException extends CoreException {
    public AuthorizationException(final String msg) {
        super(msg);
    }

    public AuthorizationException(final Throwable e) {
        super(e.getMessage());
    }

    public AuthorizationException(final String msg, final Throwable e) {
        super(msg + (null != e.getCause() ? ". cause: "+ e.getCause().getMessage() : ""));
    }

    public AuthorizationException(final String user, final String script, final String matchedRoles) {
        super("User: " + user + ", matching roles: " + matchedRoles +
              ", is not allowed to execute a script: " + script);
    }
}

Fix potential NPE in constructor

Fix potential NPE in constructor


package protocolsupport.protocol.transformer.v_1_7.utils;

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

import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;

import net.minecraft.server.v1_8_R3.Item;
import net.minecraft.server.v1_8_R3.MinecraftKey;
import net.minecraft.server.v1_8_R3.MinecraftServer;
import net.minecraft.server.v1_8_R3.MojangsonParser;
import net.minecraft.server.v1_8_R3.NBTTagCompound;

public class ChatJsonConverter {

	public static String convert(String message) {
		BaseComponent[] components = ComponentSerializer.parse(message);
		BaseComponent[] newcomponents = new BaseComponent[components.length];
		for (int i = 0; i < components.length; i++) {
			BaseComponent component = components[i];
			List<BaseComponent> extra = component.getExtra();
			BaseComponent newcomponent = fixComponent(component);
			List<BaseComponent> newextra = new ArrayList<BaseComponent>();
			if (extra != null) {
				for (BaseComponent child : extra) {
					newextra.add(fixComponent(child));
				}
				newcomponent.setExtra(newextra);
			}
			newcomponents[i] = newcomponent;
		}
		return ComponentSerializer.toString(newcomponents);
	}

	private static BaseComponent fixComponent(BaseComponent component) {
		HoverEvent event = component.getHoverEvent();
		if (event != null) {
			if (event.getAction() == HoverEvent.Action.SHOW_ITEM) {
				try {
					String itemstackjson = event.getValue()[0].toPlainText();
					NBTTagCompound compound = MojangsonParser.parse(itemstackjson);
					String itemid = compound.getString("id");
					Item item = Item.REGISTRY.get(new MinecraftKey(itemid));
					if (item != null) {
						compound.setInt("id", Item.getId(item));
					}
					component.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_ITEM, new BaseComponent[] { new TextComponent(compound.toString()) } ));
				} catch (Throwable t) {
					if (MinecraftServer.getServer().isDebugging()) {
						t.printStackTrace();
					}
				}
			}
		}
		return component;
	}

}

package protocolsupport.protocol.transformer.v_1_7.utils;

public class ChatJsonConverter {

	//TODO: actually transform json
	public static String convert(String message) {
		return message;
	}

}

Remove chat json converting, spigot base components don't work.


package de.flux.playground.deckcompare.importer;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Test;

import de.flux.playground.deckcompare.dto.Deck;

public class DeckImporterTest {

    @Test
    public void importDeck() throws Exception {
        DeckImporter importer = new DeckImporter();

        File deckFile = obtainDeckFile("the-fun-ends-here-shl-jinteki-edition-1st-.o8d");
        Deck deck = importer.importDeck(deckFile);

        assertThat(deck.getGame(), is(not("")));
        assertThat(deck.getSection(), is(not(empty())));
        assertThat(deck.getNotes(), is(not("")));
    }

    private File obtainDeckFile(String fileName) throws URISyntaxException {
        URL url = DeckImporterTest.class.getResource(fileName);
        File deckFile = new File(url.toURI());
        return deckFile;
    }

}

package de.flux.playground.deckcompare.importer;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import org.junit.Test;

import de.flux.playground.deckcompare.dto.Deck;

public class DeckImporterTest {

    private static final int FIRST_SECTION = 0;
    private static final int SECOND_SECTION = 1;

    @Test
    public void importDeck() throws Exception {
        DeckImporter importer = new DeckImporter();

        File deckFile = obtainDeckFile("the-fun-ends-here-shl-jinteki-edition-1st-.o8d");
        Deck deck = importer.importDeck(deckFile);

        assertThat(deck.getGame(), is("0f38e453-26df-4c04-9d67-6d43de939c77"));
        assertSections(deck);
        assertThat(deck.getNotes(), is(not("")));
    }

    private void assertSections(Deck deck) {
        assertThat(deck.getSection().size(), is(2));
        assertIdentity(deck);
        assertCardsOfDeck(deck);
    }

    private void assertIdentity(Deck deck) {
        assertThat(deck.getSection().get(FIRST_SECTION).getCard().size(), is(1));
        // TODO: add more asserts for the identity
    }

    private void assertCardsOfDeck(Deck deck) {
        assertThat(deck.getSection().get(SECOND_SECTION).getCard().size(), is(24));
        // TODO: add more asserts for the cards of the deck
    }

    private File obtainDeckFile(String fileName) throws URISyntaxException {
        URL url = DeckImporterTest.class.getResource(fileName);
        File deckFile = new File(url.toURI());
        return deckFile;
    }

}

Add more specific asserts for the imported deck


package org.squiddev.plethora.gameplay.modules.glasses.objects;

import net.minecraft.item.Item;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.method.wrapper.FromTarget;
import org.squiddev.plethora.api.method.wrapper.Optional;
import org.squiddev.plethora.api.method.wrapper.PlethoraMethod;
import org.squiddev.plethora.gameplay.modules.glasses.objects.object3d.Item3D;

import javax.annotation.Nonnull;

/**
 * An object which contains an item.
 */
public interface ItemObject {
	@Nonnull
	Item getItem();

	void setItem(@Nonnull Item item);

	int getDamage();

	void setDamage(int damage);

	@PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false)
	static MethodResult getItem(@FromTarget Item3D object) {
		return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage());
	}

	@PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false)
	static void setItem(@FromTarget Item3D object, Item item, @Optional(defInt = 0) int damage) {
		object.setItem(item);
		object.setDamage(damage);
	}
}

package org.squiddev.plethora.gameplay.modules.glasses.objects;

import net.minecraft.item.Item;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.method.wrapper.FromTarget;
import org.squiddev.plethora.api.method.wrapper.Optional;
import org.squiddev.plethora.api.method.wrapper.PlethoraMethod;

import javax.annotation.Nonnull;

/**
 * An object which contains an item.
 */
public interface ItemObject {
	@Nonnull
	Item getItem();

	void setItem(@Nonnull Item item);

	int getDamage();

	void setDamage(int damage);

	@PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false)
	static MethodResult getItem(@FromTarget ItemObject object) {
		return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage());
	}

	@PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false)
	static void setItem(@FromTarget ItemObject object, Item item, @Optional(defInt = 0) int damage) {
		object.setItem(item);
		object.setDamage(damage);
	}
}

Fix {get,set}Object not being available on 2D items


package com.xengar.android.weather;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.LocationEditTextPreference,
                0, 0);
        try {
            mMinLength = a.getInteger(R.styleable.LocationEditTextPreference_minLength,
                    DEFAULT_MINIMUM_LOCATION_LENGTH);
        } finally {
            a.recycle();
        }
    }
}

package com.xengar.android.weather;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.EditText;

public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.LocationEditTextPreference,
                0, 0);
        try {
            mMinLength = a.getInteger(R.styleable.LocationEditTextPreference_minLength,
                    DEFAULT_MINIMUM_LOCATION_LENGTH);
        } finally {
            a.recycle();
        }
    }

    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);

        EditText et = getEditText();
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Dialog d = getDialog();
                if (d instanceof AlertDialog) {
                    AlertDialog dialog = (AlertDialog) d;
                    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    // Check if the EditText is empty
                    if (s.length() < mMinLength) {
                        // Disable OK button
                        positiveButton.setEnabled(false);
                    } else {
                        // Re-enable the button.
                        positiveButton.setEnabled(true);
                    }
                }
            }
        });
    }
}

Use AlertDialog with EditTextPreference and TextWatcher to disable setting the preference if the location is too short.


/*
 * Copyright 2015 Bridje Framework.
 *
 * 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.bridje.core.ioc.test;

import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;

@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
    @Override
    public void preCreateComponent(Class<DummyComponent> clazz)
    {
        System.out.println("preCreate: " + clazz.getName());
    }

    @Override
    public void preInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("preInit: " + clazz.getName());
    }

    @Override
    public void postInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("postInit: " + clazz.getName());
    }
}

/*
 * Copyright 2015 Bridje Framework.
 *
 * 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.bridje.core.ioc.test;

import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;

@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
    @Override
    public void preCreateComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is preCreate");
    }

    @Override
    public void preInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is preInit");
    }

    @Override
    public void postInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is postInit");
    }
}

Change the text on the test

Change the text  on the test


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

import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;

/** Handler for opening files from command line
 *
 *  <p>See
 *  Opening Files from Command-Line - org.csstudio.openfile
 *  in CS-Studio docbook.
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
    @Override
    public void openDisplay(final String path, final String data) throws Exception
    {
        final Macros macros = MacroXMLUtil.readMacros(data);
        final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros);
        new OpenDisplayAction(info).run();
    }
}

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

import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;

/** Handler for opening files from command line
 *
 *  <p>See
 *  Opening Files from Command-Line - org.csstudio.openfile
 *  in CS-Studio docbook.
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
    @Override
    public void openDisplay(final String path, final String data) throws Exception
    {
        final Macros macros = MacroXMLUtil.readMacros(data);
        // 'resolve', i.e. use *.bob over *.opi if found
        final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros, true);
        new OpenDisplayAction(info).run();
    }
}

OpenFile: Use *.bob over *.opi when called from alarm UI, cmd line


package com.ksoichiro.task.repository;

import com.ksoichiro.task.domain.Account;
import com.ksoichiro.task.domain.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface TagRepository extends JpaRepository<Tag, Integer> {
    @Query("SELECT t FROM #{#entityName} t "
        + "WHERE t.account = ? ")
    Page<Tag> findByAccount(Account account, Pageable pageable);

    @Query("SELECT t from #{#entityName} t "
        + "WHERE t.id = ?1 "
        + "AND t.account = ?2")
    Tag findByIdAndAccount(Integer id, Account account);
}

package com.ksoichiro.task.repository;

import com.ksoichiro.task.domain.Account;
import com.ksoichiro.task.domain.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface TagRepository extends JpaRepository<Tag, Integer> {
    @Query("SELECT t FROM #{#entityName} t "
        + "WHERE t.account = ?1 ")
    Page<Tag> findByAccount(Account account, Pageable pageable);

    @Query("SELECT t from #{#entityName} t "
        + "WHERE t.id = ?1 "
        + "AND t.account = ?2")
    Tag findByIdAndAccount(Integer id, Account account);
}

Fix HQL parameter is not numbered

Fix HQL parameter is not numbered


package valandur.webapi.handlers;

import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ErrorHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;

public class CustomErrorHandler extends ErrorHandler {
    @Override
    protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
        if (message == null)
            message= HttpStatus.getMessage(code);

        writer.write("{ code: " + code + ", message: \"" + message + "\" }");
    }
}

package valandur.webapi.handlers;

import com.google.gson.JsonObject;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ErrorHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;

public class CustomErrorHandler extends ErrorHandler {
    @Override
    protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
        if (message == null)
            message= HttpStatus.getMessage(code);

        JsonObject obj = new JsonObject();
        obj.addProperty("code", code);
        obj.addProperty("message", message);
        writer.write(obj.toString());
    }
}

Use actual json object in error handler

style(errors): Use actual json object in error handler


package org.jboss.arquillian.moco.client;

import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

public class MocoArchiveAppender implements AuxiliaryArchiveAppender {

	@Override
	public Archive<?> createAuxiliaryArchive() {

		 return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
		            .addClass(ReflectionHelper.class)
		            .addPackage(MocoRemoteExtension.class.getPackage())
		            .addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);

	}

}

package org.jboss.arquillian.moco.client;

import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.api.Moco;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

public class MocoArchiveAppender implements AuxiliaryArchiveAppender {

	@Override
	public Archive<?> createAuxiliaryArchive() {

		 return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
		            .addClass(ReflectionHelper.class)
		            .addPackage(Moco.class.getPackage())
		            .addPackage(MocoRemoteExtension.class.getPackage())
		            .addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);

	}

}

Add Arquillian Moco API to remote deployment


package io.quarkus.mutiny.runtime;

import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

import org.jboss.logging.Logger;

import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;

@Recorder
public class MutinyInfrastructure {

    public void configureMutinyInfrastructure(ExecutorService exec) {
        Infrastructure.setDefaultExecutor(exec);
    }

    public void configureDroppedExceptionHandler() {
        Logger logger = Logger.getLogger(MutinyInfrastructure.class);
        Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                logger.error("Mutiny had to drop the following exception", throwable);
            }
        });
    }

    public void configureThreadBlockingChecker() {
        Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
            @Override
            public boolean getAsBoolean() {
                String threadName = Thread.currentThread().getName();
                return !threadName.contains("vertx-eventloop-thread-");
            }
        });
    }
}

package io.quarkus.mutiny.runtime;

import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

import org.jboss.logging.Logger;

import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;

@Recorder
public class MutinyInfrastructure {

    public void configureMutinyInfrastructure(ExecutorService exec) {
        Infrastructure.setDefaultExecutor(exec);
    }

    public void configureDroppedExceptionHandler() {
        Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable);
            }
        });
    }

    public void configureThreadBlockingChecker() {
        Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
            @Override
            public boolean getAsBoolean() {
                String threadName = Thread.currentThread().getName();
                return !threadName.contains("vertx-eventloop-thread-");
            }
        });
    }
}

Remove the logger from the heap

Remove the logger from the heap


/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.jetbrains.python.psi;

import org.jetbrains.annotations.Nullable;

/**
 * Base class for elements that have a qualified name (classes and functions).
 *
 * @author yole
 */
public interface PyQualifiedNameOwner extends PyElement {
  /**
   * Returns the qualified name of the element.
   *
   * @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
   * is contained inside an element that doesn't have a qualified name.
   */
  @Nullable
  String getQualifiedName();
}

/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * 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.jetbrains.python.psi;

import com.intellij.openapi.util.NlsSafe;
import org.jetbrains.annotations.Nullable;

/**
 * Base class for elements that have a qualified name (classes and functions).
 *
 * @author yole
 */
public interface PyQualifiedNameOwner extends PyElement {
  /**
   * Returns the qualified name of the element.
   *
   * @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
   * is contained inside an element that doesn't have a qualified name.
   */
  @Nullable
  @NlsSafe String getQualifiedName();
}

Annotate Python UML diagrams support

i18n: Annotate Python UML diagrams support

GitOrigin-RevId: 492135bbc194d71e7a869ef591be574b1225b66b


/**
 * File: SampleMetaTestCase.java
 * Created by: dstaines
 * Created on: May 1, 2009
 * CVS:  $$
 */
package org.ensembl.healthcheck.testcase.eg_core;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.testcase.AbstractTemplatedTestCase;

/**
 * Base class for EnsemblGenomes core healthchecks
 *
 * @author dstaines
 *
 */
public abstract class AbstractEgCoreTestCase extends AbstractTemplatedTestCase {

	public final static String EG_GROUP = "ensembl_genomes";

	public AbstractEgCoreTestCase() {
		super();
		this.addToGroup(EG_GROUP);
		this.appliesToType(DatabaseType.CORE);
	}
}

/**
 * File: SampleMetaTestCase.java
 * Created by: dstaines
 * Created on: May 1, 2009
 * CVS:  $$
 */
package org.ensembl.healthcheck.testcase.eg_core;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.AbstractTemplatedTestCase;

/**
 * Base class for EnsemblGenomes core healthchecks
 *
 * @author dstaines
 *
 */
public abstract class AbstractEgCoreTestCase extends AbstractTemplatedTestCase {

	public final static String EG_GROUP = "ensembl_genomes";

	public AbstractEgCoreTestCase() {
		super();
		this.addToGroup(EG_GROUP);
		this.appliesToType(DatabaseType.CORE);
		this.setTeamResponsible(Team.ENSEMBL_GENOMES);
	}
}

Set team responsible by default

Set team responsible by default


package com.hubspot.rosetta.internal;

import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;

@SuppressWarnings("serial")
public class RosettaModule extends Module {

  @Override
  public String getModuleName() {
    return "RosettaModule";
  }

  @Override
  public Version version() {
    return Version.unknownVersion();
  }

  @Override
  public void setupModule(SetupContext context) {
    context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier());

    ObjectCodec codec = context.getOwner();
    if (codec instanceof ObjectMapper) {
      ObjectMapper mapper = (ObjectMapper) codec;

      context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper));

      mapper.setSerializerProvider(new DefaultSerializerProvider.Impl());
      mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
  }
}

package com.hubspot.rosetta.internal;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;

@SuppressWarnings("serial")
public class RosettaModule extends Module {

  @Override
  public String getModuleName() {
    return "RosettaModule";
  }

  @Override
  public Version version() {
    return Version.unknownVersion();
  }

  @Override
  public void setupModule(SetupContext context) {
    context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier());

    ObjectCodec codec = context.getOwner();
    if (codec instanceof ObjectMapper) {
      ObjectMapper mapper = (ObjectMapper) codec;

      context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper));

      mapper.setSerializerProvider(new DefaultSerializerProvider.Impl());
      mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper.setSerializationInclusion(Include.ALWAYS);
    }
  }
}

Set this in addition to annotation introspector approach


package com.codenvy.ide.ext.datasource.shared;

import com.codenvy.dto.shared.DTO;

@DTO
public interface RequestParameterDTO {

    DatabaseConfigurationDTO getDatabase();

    void setDatabase(DatabaseConfigurationDTO database);

    RequestParameterDTO withDatabase(DatabaseConfigurationDTO database);

    String getSqlRequest();

    void setSqlRequest(String sqlRequest);

    RequestParameterDTO withSqlRequest(String sqlRequest);

    int getResultLimit();

    void setResultLimit(int resultLimit);

    RequestParameterDTO withResultLimit(int resultLimit);
}

package com.codenvy.ide.ext.datasource.shared;

import com.codenvy.dto.shared.DTO;

@DTO
public interface RequestParameterDTO {

    DatabaseConfigurationDTO getDatabase();

    void setDatabase(DatabaseConfigurationDTO database);

    RequestParameterDTO withDatabase(DatabaseConfigurationDTO database);

    String getSqlRequest();

    void setSqlRequest(String sqlRequest);

    RequestParameterDTO withSqlRequest(String sqlRequest);

    int getResultLimit();

    void setResultLimit(int resultLimit);

    RequestParameterDTO withResultLimit(int resultLimit);

    MultipleRequestExecutionMode getMultipleRequestExecutionMode();

    void setMultipleRequestExecutionMode(MultipleRequestExecutionMode mode);

    RequestParameterDTO withMultipleRequestExecutionMode(MultipleRequestExecutionMode mode);
}

Add the field for request execution mode in request dto


package dk.statsbiblioteket.doms.central.connectors.fedora.methods;

import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest;
import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method;
import dk.statsbiblioteket.doms.webservices.authentication.Credentials;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: abr
 * Date: 9/13/12
 * Time: 11:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class MethodsImplTest {
    @org.junit.Test
    public void testGetMethods() throws Exception {
        MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7780/fedora"),"");
        List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile");
        assertTrue("no methods!",methodList.size() > 0);
    }

}

package dk.statsbiblioteket.doms.central.connectors.fedora.methods;

import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest;
import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method;
import dk.statsbiblioteket.doms.webservices.authentication.Credentials;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: abr
 * Date: 9/13/12
 * Time: 11:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class MethodsImplTest {
    @org.junit.Test
    public void testGetMethods() throws Exception {
        MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7880/fedora"),"");
        List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile");
        assertTrue("no methods!",methodList.size() > 0);
    }

}

Use test server with methods

Use test server with methods


/*
 * 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.logging.log4j.core;

/**
 *
 *
 * @doubt Unchecked?
 *
 */
public class LoggingException extends RuntimeException {

    public LoggingException(String msg) {
        super(msg);
    }

    public LoggingException(String msg, Exception ex) {
        super(msg, ex);
    }

    public LoggingException(Exception ex) {
        super(ex);
    }
}

/*
 * 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.logging.log4j.core;

/**
 * Exception thrown when a exception occurs while logging.  In most cases exceptions will be handled
 * within Log4j but certain Appenders may be configured to allow exceptions to propagate to the
 * application. This is a RuntimeException so that the exception may be thrown in those cases without
 * requiring all Logger methods be contained with try/catch blocks.
 *
 */
public class LoggingException extends RuntimeException {

    public LoggingException(String msg) {
        super(msg);
    }

    public LoggingException(String msg, Exception ex) {
        super(msg, ex);
    }

    public LoggingException(Exception ex) {
        super(ex);
    }
}

Add javadoc description to resolve @doubt comment

git-svn-id: 1a1fa68050bcaed5349a5b70a2a7ea3fbc73e3e8@949492 13f79535-47bb-0310-9956-ffa450edef68


package de.itemis.mosig.ringbuffer;

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

public class CircularBufferTest {

	@Test
	public void constructorShouldSetProvidedSize() {
		CircularBuffer underTest = new CircularBuffer(3);
		Assert.assertEquals(3, underTest.size());
	}
}

package de.itemis.mosig.ringbuffer;

import java.util.Random;

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

public class CircularBufferTest {

	@Test
	public void whenPassingRandomNbrToTheConstructorSizeShouldBeThatNbr() {
		int expectedSize = new Random().nextInt(Integer.MAX_VALUE);
		CircularBuffer underTest = new CircularBuffer(expectedSize);
		Assert.assertEquals(expectedSize, underTest.size());
	}
}

Test now uses random nbr.

RED: Test now uses random nbr.


/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2018 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package xquery.validation;

import org.exist.test.runner.XSuite;
import org.junit.runner.RunWith;

@RunWith(XSuite.class)
@XSuite.XSuiteFiles({
        "src/test/xquery/validation"
})
public class ValidationTests {
}

/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2018 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package xquery.validation;

import org.exist.test.runner.XSuite;
import org.junit.runner.RunWith;

@RunWith(XSuite.class)
@XSuite.XSuiteFiles({
        "exist-core/src/test/xquery/validation"
})
public class ValidationTests {
}

Fix test path in Validation test

[refactor] Fix test path in Validation test


package nl.eernie.jmoribus.model;

import org.apache.commons.lang3.StringUtils;

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

public class Step  {

    private StepType stepType;
    private List<StepLine> stepLines = new ArrayList<>();

    public Step(StepType stepType) {
        this.stepType = stepType;
    }

    public StepType getStepType() {
        return stepType;
    }

    public StepLine getFirstStepLine()
    {
        return stepLines.get(0);
    }

    public List<StepLine> getStepLines()
    {
        return stepLines;
    }

    public String getCombinedStepLines(){
        String combined = "";
        for(StepLine stepLine: stepLines){
            if(StringUtils.isNotBlank(combined)){
                combined = combined + " ";
            }
            if(stepLine instanceof Table){
                int index = stepLines.indexOf(stepLine);
                combined = combined + "TABLE"+index;
            }else{
                combined = combined + stepLine.getText();
            }
        }
        return combined;
    }
}

package nl.eernie.jmoribus.model;

import org.apache.commons.lang3.StringUtils;

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

public class Step  {

    private StepType stepType;
    private List<StepLine> stepLines = new ArrayList<>();

    public Step(StepType stepType) {
        this.stepType = stepType;
    }

    public StepType getStepType() {
        return stepType;
    }

    public StepLine getFirstStepLine()
    {
        return stepLines.get(0);
    }

    public List<StepLine> getStepLines()
    {
        return stepLines;
    }

    public String getCombinedStepLines(){
        StringBuffer buffer = new StringBuffer();
        for(StepLine stepLine: stepLines){
            if(StringUtils.isNotBlank(buffer.toString())){
                buffer.append(" ");
            }
            if(stepLine instanceof Table){
                int index = stepLines.indexOf(stepLine);
                buffer.append("TABLE"+index);
            }else{
                buffer.append(stepLine.getText());
            }
        }
        return buffer.toString();
    }
}

Remove defect for building a string in a loop


package com.peterphi.std.guice.restclient.resteasy.impl;

import com.peterphi.std.util.tracing.Tracing;
import com.peterphi.std.util.tracing.TracingConstants;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class TracingClientRequestFilter implements ClientRequestFilter
{
	@Override
	public void filter(final ClientRequestContext requestContext) throws IOException
	{
		final String traceId = Tracing.log("HTTP:req", () -> "" + requestContext.getUri());

		if (traceId != null)
		{
			requestContext.getHeaders().add(TracingConstants.HTTP_HEADER_CORRELATION_ID, traceId);

			if (Tracing.isVerbose())
				requestContext.getHeaders().add(TracingConstants.HTTP_HEADER_TRACE_VERBOSE, "true");
		}
	}
}

package com.peterphi.std.guice.restclient.resteasy.impl;

import com.peterphi.std.util.tracing.Tracing;
import com.peterphi.std.util.tracing.TracingConstants;
import org.apache.log4j.Logger;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class TracingClientRequestFilter implements ClientRequestFilter
{
	private static final Logger log = Logger.getLogger(TracingClientRequestFilter.class);

	@Override
	public void filter(final ClientRequestContext requestContext) throws IOException
	{
		final String traceId = Tracing.log("HTTP:req", () -> "" + requestContext.getUri());

		if (traceId != null)
		{
			if (requestContext.getHeaders().containsKey(TracingConstants.HTTP_HEADER_CORRELATION_ID))
				log.warn("Duplicate call to tracing filter " +
				         this +
				         " for " +
				         requestContext +
				         " for " +
				         requestContext.getUri());

			requestContext.getHeaders().putSingle(TracingConstants.HTTP_HEADER_CORRELATION_ID, traceId);

			if (Tracing.isVerbose())
				requestContext.getHeaders().putSingle(TracingConstants.HTTP_HEADER_TRACE_VERBOSE, "true");
		}
	}
}

Add logic to prevent the addition of duplicate X-Correlation-ID headers if the tracing filter is called multiple times (also logs a warning if this happens)


package com.akikanellis.kata01;

import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;

public class TenPercentOffEverything extends OfferStrategy {

    private TenPercentOffEverything(long id) { super(id, "10% off everything"); }

    public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }

    @Override public Offers calculateOffers(Items items) {
        Price itemsPrice = items.stream()
                .map(QuantifiedItem::totalPrice)
                .reduce(Price::add)
                .orElse(Price.ZERO);

        Price discount = itemsPrice.multiplyBy(0.10).negate();
        Offer offer = Offer.create(description(), discount);
        QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);

        return Offers.fromSingle(quantifiedOffer);
    }
}

package com.akikanellis.kata01;

import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;

/**
 * An example offer strategy used for testing where all of our items are discounted by 10%.
 */
public class TenPercentOffEverything extends OfferStrategy {
    private static final double TEN_PERCENT = 0.10;

    private TenPercentOffEverything(long id) { super(id, "10% off everything"); }

    public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }

    @Override public Offers calculateOffers(Items items) {
        Price itemsTotalPrice = calculateItemsTotalPrice(items);
        Price discount = itemsTotalPrice.multiplyBy(TEN_PERCENT).negate();

        Offer offer = Offer.create(description(), discount);
        QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);

        return Offers.fromSingle(quantifiedOffer);
    }

    private Price calculateItemsTotalPrice(Items items) {
        return items.stream()
                .map(QuantifiedItem::totalPrice)
                .reduce(Price::add)
                .orElse(Price.ZERO);
    }
}

Refactor ten percent off everything strategy


package io.quarkus.jackson.deployment;

import java.util.Calendar;
import java.util.Date;

import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.quarkus.test.QuarkusUnitTest;

public class JacksonTimeZonePropertiesTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withConfigurationResource("application-timezone-properties.properties");

    @Inject
    ObjectMapper objectMapper;

    @Test
    public void testTimezone() throws JsonProcessingException {
        Assertions.assertThat(objectMapper.writeValueAsString(new Pojo(new Date(2021, Calendar.MARCH, 3, 11, 5))))
                .contains("+07");
    }

    public static class Pojo {

        private final Date date;

        public Pojo(Date date) {
            this.date = date;
        }

        public Date getDate() {
            return date;
        }
    }
}

package io.quarkus.jackson.deployment;

import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.quarkus.test.QuarkusUnitTest;

public class JacksonTimeZonePropertiesTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withConfigurationResource("application-timezone-properties.properties");

    @Inject
    ObjectMapper objectMapper;

    @Test
    public void testTimezone() throws JsonProcessingException {
        Assertions.assertThat(objectMapper.writeValueAsString(new Pojo(Date.from(
                ZonedDateTime.of(LocalDateTime.of(2021, Month.MARCH, 3, 11, 5), ZoneId.of("GMT")).toInstant()))))
                .contains("+07");
    }

    public static class Pojo {

        private final Date date;

        public Pojo(Date date) {
            this.date = date;
        }

        public Date getDate() {
            return date;
        }
    }
}

Replace deprecated Date constructor use in Jackson test