package org.apache.helix.integration.task;

/*
 * 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.
 */
import org.apache.helix.HelixManagerFactory;
import org.apache.helix.InstanceType;
import org.apache.helix.TestHelper;
import org.apache.helix.manager.zk.ZkClient;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.JobContext;
import org.apache.helix.task.TaskDriver;
import org.apache.helix.task.Workflow;
import org.apache.helix.task.WorkflowConfig;
import org.apache.helix.task.WorkflowContext;
import org.testng.Assert;
import org.testng.annotations.Test;

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

public class TestRetrieveWorkflows extends TaskTestBase {
  @Test
  public void testGetAllWorkflows() throws Exception {
    List<Workflow> workflowList = new ArrayList<Workflow>();
    for (int i = 0; i < 4; i++) {
      Workflow workflow = WorkflowGenerator.generateDefaultRepeatedJobWorkflowBuilder(TestHelper.getTestMethodName() + i).build();
      _driver.start(workflow);
      workflowList.add(workflow);
    }

    for (Workflow workflow : workflowList) {
      //TaskTestUtil.pollForWorkflowState(_driver, workflow.getName(), TaskState.COMPLETED);
    }

    _manager = HelixManagerFactory
        .getZKHelixManager("ESPRESSO_TEST_NUAGE", "Admin", InstanceType.ADMINISTRATOR, "zk-ei1-espresso.stg.linkedin.com:12913");
    _manager.connect();
    TaskDriver taskDriver = new TaskDriver(_manager);

    Map<String, WorkflowConfig> workflowConfigMap = taskDriver.getWorkflows();
    Assert.assertEquals(workflowConfigMap.size(), workflowList.size());

    for(Map.Entry<String, WorkflowConfig> workflow :  workflowConfigMap.entrySet()) {
      WorkflowConfig workflowConfig = workflow.getValue();
      WorkflowContext workflowContext = _driver.getWorkflowContext(workflow.getKey());
      Assert.assertNotNull(workflowContext);

      for(String job : workflowConfig.getJobDag().getAllNodes()) {
        JobConfig jobConfig = _driver.getJobConfig(job);
        JobContext jobContext = _driver.getJobContext(job);

        Assert.assertNotNull(jobConfig);
        Assert.assertNotNull(jobContext);
      }
    }
  }
}

Add unit test to retrieve workflow and job configurations.


package com.github.conradoqg.studydsa.hackerrank.challenges.ctci;

import java.util.Scanner;

public class FibonacciNumbers {
    public static int fibonacci(int n) {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else {
            return fibonacci(n - 1) + fibonacci(n - 2);
        }

    }

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            int n = scanner.nextInt();
            scanner.close();
            System.out.println(fibonacci(n));
        }
    }
}

Add fibonacci numbers CTCI challenge


package com.merchantwarehouse.qa.cukes;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;

/**
 * This class tests the integration with various junit features (@BeforeClass and @AfterClass). It also has the side
 * effect of testing that the same Gherkin rules and the same Cucumber Step Definitions may appear in more than one
 * file without them conflicting.
 *
 * @author dominicl
 */
@RunWith(Cucumber.class)
@Cucumber.Options(features = "DifferentlyNamedFeature.feature")
public class JunitIntegrationTest {

    // counters of how many times junit's beforeclass/afterclass were called. these should be 1x each.
    private static int countOfTimesBeforeClassWasCalled = 0;
    private static int countOfTimesAfterClassWasCalled = 0;

    // counters of how many times given/when/then were called. given the above feature file, these should be 2x each.
    // this is important, because there are 2 Gherkin feature files with the same rules, so the stock version of cucumber
    // would run these rules 4x each. actually, it would fail to run at all because both this class and the InheritanceTest
    // and GlueClassTest define identical step definitions. we'll validate the counters in @AfterClass
    private static int countOfTimesGivenWasCalled = 0;
    private static int countOfTimesWhenWasCalled = 0;
    private static int countOfTimesThenWasCalled = 0;

    @BeforeClass
    public static void beforeClass() {
        countOfTimesBeforeClassWasCalled++;
        System.out.format("Called beforeClass() %d times", countOfTimesBeforeClassWasCalled).println();
    }

    @AfterClass
    public static void afterClass() {
        countOfTimesAfterClassWasCalled++;
        System.out.format("Called afterClass() %d times", countOfTimesAfterClassWasCalled).println();

        assertEquals("countOfTimesBeforeClassWasCalled", 1, countOfTimesBeforeClassWasCalled);
        assertEquals("countOfTimesAfterClassWasCalled", 1, countOfTimesAfterClassWasCalled);

        assertEquals("countOfTimesGivenWasCalled", 2, countOfTimesGivenWasCalled);
        assertEquals("countOfTimesWhenWasCalled", 2, countOfTimesWhenWasCalled);
        assertEquals("countOfTimesThenWasCalled", 2, countOfTimesThenWasCalled);
    }

    @Then("^the total should be (\\d+)$")
    public void then_the_total_should_be(Integer total) {
        countOfTimesThenWasCalled++;
    }

    @Given("^two integers (\\d+) and (\\d+)$")
    public final void given_two_integers(final Integer a, final Integer b) {
        countOfTimesGivenWasCalled++;
    }

    @When("^you add them together$")
    public final void when_you_add_them_together() {
        countOfTimesWhenWasCalled++;
    }
}

Test the Cucumber + JUnit integration


package org.commcare.engine.extensions;

import android.content.Context;

import org.commcare.dalvik.R;
import org.commcare.utils.EthiopianDateHelper;
import org.commcare.utils.NepaliDateUtilities;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.xpath.XPathUnsupportedException;
import org.javarosa.xpath.expr.XPathFuncExpr;

import java.util.Date;
import java.util.Vector;

/**
 * @author ctsims
 */
public class CalendaredDateFormatHandler implements IFunctionHandler {

    private final Context context;

    public CalendaredDateFormatHandler(Context context) {
        this.context = context;
    }

    @Override
    public String getName() {
        return "format-date-for-calendar";
    }

    @Override
    public Vector getPrototypes() {
        Vector v = new Vector();
        v.add(new Class[]{Date.class, String.class});
        return v;
    }

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

    @Override
    public Object eval(Object[] args, EvaluationContext ec) {
        if ("".equals(args[0])) {
            return "";
        }
        Date d = (Date)XPathFuncExpr.toDate(args[0]);
        String calendar = (String)args[1];
        if ("ethiopian".equals(calendar)) {
            return EthiopianDateHelper.ConvertToEthiopian(context, d);
        } else if ("nepali".equals(calendar)) {
            return NepaliDateUtilities.convertToNepaliString(
                    context.getResources().getStringArray(R.array.nepali_months), d);
        } else {
            throw new XPathUnsupportedException("Unsupported calendar type: " + calendar);
        }
    }
}

Revert "remove now uneeded calendar format handler"


/*
 * #%L
 * A framework for reusable algorithms.
 * %%
 * Copyright (C) 2014 Board of Regents of the University of
 * Wisconsin-Madison and University of Konstanz.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package imagej.ops;

/**
 * A contingency that may hold, or not, depending on the circumstances.
 *
 * @author Curtis Rueden
 */
public interface Contingent {

	/**
	 * True if the contingency holds; i.e., the current circumstances conform to
	 * the contingency's requirements.
	 */
	boolean conforms();

}

Add interface for testing contingencies


/*
 * 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.tika.parser.fork;

import java.io.InputStream;

import junit.framework.TestCase;

import org.apache.tika.fork.ForkParser;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;

/**
 * Test that the ForkParser correctly behaves when
 *  wired in to the regular Parsers and their test data
 */
public class ForkParserIntegrationTest extends TestCase {
    /**
     * Simple text parsing
     * TODO Fix this test so it passes
     */
    public void DISABLEDtestForkedTextParsing() throws Exception {
       final ForkParser parser = new ForkParser(
             ForkParserIntegrationTest.class.getClassLoader(),
             new ForkParser());

       try {
          ContentHandler output = new BodyContentHandler();
          InputStream stream = ForkParserIntegrationTest.class.getResourceAsStream("testTXT.txt");
          ParseContext context = new ParseContext();
          parser.parse(stream, output, new Metadata(), context);

          String content = output.toString();
          assertTrue(content.contains("Test d'indexation"));
          assertTrue(content.contains("http://www.apache.org/"));
       } finally {
          parser.close();
       }
    }

    /**
     * TIKA-808 - Ensure that parsing of our test PDFs work under
     *  the Fork Parser, to ensure that complex parsing behaves
     * TODO Fix this test so it passes
     */
    public void DISABLEDtestForkedPDFParsing() throws Exception {
       final ForkParser parser = new ForkParser(
             ForkParserIntegrationTest.class.getClassLoader(),
             new ForkParser());

       try {
          ContentHandler output = new BodyContentHandler();
          InputStream stream = ForkParserIntegrationTest.class.getResourceAsStream("testPDF.pdf");
          ParseContext context = new ParseContext();
          parser.parse(stream, output, new Metadata(), context);

          String content = output.toString();
          assertTrue(content.contains("Apache Tika"));
          assertTrue(content.contains("Tika - Content Analysis Toolkit"));
          assertTrue(content.contains("incubator"));
          assertTrue(content.contains("Apache Software Foundation"));
      } finally {
          parser.close();
      }
    }

    public void testDUMMY() {
       // To avoid warnings about no tests while others are disabled
    }
}

Add disabled tests for TIKA-808 (parser needs fixing so that tests can pass)


package jsystem.runner.agent.publisher;

/**
 * Exception to throw in case something went wrong while publishing.
 *
 * @author itai_a
 *
 */
public class PublisherException extends Exception {

	private static final long serialVersionUID = 1L;

	public PublisherException(String message) {
		super(message);
	}

	public PublisherException(String message, Throwable t) {
		super(message, t);
	}

}

Support for adding the HTML link to the mail and better exception handling in the publish test


/*
 * Copyright 2016, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.spine3.server.storage.datastore;

import org.junit.Test;
import org.spine3.test.Tests;

import static org.junit.Assert.assertTrue;

/**
 * @author Alex Tymchenko
 */
public class DatastorePropertiesShould {
    @Test
    public void have_private_constructor() {
        assertTrue(Tests.hasPrivateUtilityConstructor(DatastoreProperties.class));
    }
}

Improve the code coverage for a utility class.


package org.jboss.weld.test;

import org.jboss.testharness.impl.runner.servlet.ServletTestRunner;
import org.jboss.weld.BeanManagerImpl;
import org.jboss.weld.Container;
import org.jboss.weld.bootstrap.spi.BeanDeploymentArchive;
import org.jboss.weld.servlet.ServletHelper;

public class BeanManagerLocator
{

   public static BeanManagerLocator INSTANCE = new BeanManagerLocator();

   private BeanManagerLocator()
   {
      // TODO Auto-generated constructor stub
   }

   private BeanDeploymentArchive testArchive;

   public BeanManagerImpl locate()
   {
      if (ServletTestRunner.getCurrentServletContext() != null)
      {
         return ServletHelper.getModuleBeanManager(ServletTestRunner.getCurrentServletContext());
      }
      else if (getTestArchive() != null)
      {
         return Container.instance().beanDeploymentArchives().get(getTestArchive());
      }
      else
      {
         throw new IllegalStateException();
      }
   }

   private BeanDeploymentArchive getTestArchive()
   {
      if (testArchive == null)
      {
         try
         {
            testArchive = (BeanDeploymentArchive) Class.forName("org.jboss.weld.mock.MockBeanDeploymentArchive").newInstance();
         }
         catch (InstantiationException e)
         {
            throw new IllegalStateException(e);
         }
         catch (IllegalAccessException e)
         {
            throw new IllegalStateException(e);
         }
         catch (ClassNotFoundException e)
         {
            throw new IllegalStateException(e);
         }
      }
      return testArchive;
   }

}

Split out how we locate the bean manager for the test


/*
 * The contents of this file are subject to the OpenMRS Public License
 * Version 1.1 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://license.openmrs.org
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * Copyright (C) OpenMRS, LLC.  All Rights Reserved.
 */
package org.openmrs.module.openhmis.backboneforms.web.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.openmrs.web.taglib.fieldgen.FieldGenHandlerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/fieldgenhandlers.json")
public class FieldGenHandlerController {
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Set<String>> fieldgenhandlers() {
		Map<String, Set<String>> container = new HashMap<String, Set<String>>();
		container.put("results", new TreeSet<String>(FieldGenHandlerFactory.getSingletonInstance().getHandlers().keySet()));
		return container;
	}
}

Move this out of Cashier


package com.alexrnl.subtitlecorrector.io.subrip;

import java.io.BufferedReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.alexrnl.subtitlecorrector.common.Subtitle;
import com.alexrnl.subtitlecorrector.common.SubtitleFile;
import com.alexrnl.subtitlecorrector.io.SubtitleReader;

/**
 * TODO
 * @author Alex
 */
public class SubRipReader extends SubtitleReader {
	/** Logger */
	private static Logger			lg	= Logger.getLogger(SubRipReader.class.getName());

	/** The date formatter */
	private final SimpleDateFormat	dateFormatter;

	/**
	 * Constructor #1.<br />
	 */
	private SubRipReader () {
		super();
		dateFormatter = new SimpleDateFormat(SubRip.SUBRIP_DATE_FORMAT);
	}

	@Override
	protected Subtitle readSubtitle (final SubtitleFile subtitleFile, final BufferedReader reader)
			throws IOException {
		final long begin;
		final long end;
		final StringBuilder content = new StringBuilder();
		String currentLine;

		// Removing empty lines
		do {
			currentLine = reader.readLine().trim();
		} while (!currentLine.isEmpty());
		// Get the subtitle number
		final int subtitleIndex = Integer.parseInt(currentLine);
		if (lg.isLoggable(Level.INFO)) {
			lg.info("Reading subtitle#" + subtitleIndex);
		}

		// Get the begin and end dates of the subtitle
		currentLine = reader.readLine().trim();
		final String[] dates = currentLine.split(SubRip.SUBRIP_DATE_SEPARATOR);
		if (dates.length < 2) {
			throw new IOException("Could not parse " + currentLine + " as a valid line in the subrip format");
		}
		try {
			begin = dateFormatter.parse(dates[0]).getTime();
			end = dateFormatter.parse(dates[1]).getTime();
		} catch (final ParseException e) {
			lg.warning("Could not parse either " + dates[0] + " or " + dates[1] + " as a date");
			throw new IOException("Problem while parsing a date", e);
		}
		// Get the content of the subtitle
		do {
			currentLine = reader.readLine().trim();
			content.append(currentLine);
		} while (!currentLine.isEmpty());

		return new Subtitle(begin, end, content.toString());
	}
}

Add the Reader implementation for the SubRip format


/*
 * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package org.jeeventstore.jeecqrs.sagas.impl;

import org.jeeventstore.jeecqrs.sagas.SagaTimeoutRequest;

/**
 * Default implementation of {@link SagaTimeoutRequest}.
 *
 * @param <E>   the type of events to handle
 */
public class DefaultSagaTimeoutRequest<E> implements SagaTimeoutRequest<E> {

    private String bucketId;
    private String sagaId;
    private long timeout;
    private String description;
    private E event;

    public DefaultSagaTimeoutRequest(
            String bucketId,
            String sagaId,
            long timeout,
            String description,
            E event) {

        if (bucketId == null)
            throw new NullPointerException("bucketId must not be null");
        if (sagaId == null)
            throw new NullPointerException("sagaId must not be null");
        if (sagaId.trim().isEmpty())
            throw new IllegalArgumentException("sagaId must not be empty");
        if (event == null)
            throw new NullPointerException("event must not be null");

        this.bucketId = bucketId;
        this.sagaId = sagaId;
        this.timeout = timeout;
        this.description = description;
        this.event = event;
    }

    @Override
    public String bucketId() {
        return bucketId;
    }

    @Override
    public String sagaId() {
        return sagaId;
    }

    @Override
    public long timeout() {
	return timeout;
    }

    @Override
    public String description() {
        return description;
    }

    @Override
    public E event() {
	return event;
    }

}

Add default implementation for SagaTimeoutRequest


package org.smartdeveloperhub.harvesters.it.backend.exhibitor;

import com.sun.jersey.core.provider.AbstractMessageReaderWriterProvider;

import org.apache.commons.codec.Charsets;
import org.apache.commons.io.IOUtils;
import org.smartdeveloperhub.harvesters.it.backend.Entities;
import org.smartdeveloperhub.harvesters.it.backend.Entity;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;

@Produces("application/psr.sdh.itcollector.entity+json")
public class ITHarvesterEntityProvider<T> extends AbstractMessageReaderWriterProvider<T> {

	private static final String MEDIA_TYPE = "application/psr.sdh.itcollector.entity+json";

	@Override
	public boolean isReadable(Class<?> type	, Type genericType,
								Annotation[] annotations, MediaType mediaType) {

		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public T readFrom(Class<T> type, Type genericType, Annotation[] annotations,
						MediaType mediaType, MultivaluedMap<String,
						String> httpHeaders, InputStream entityStream)
								throws IOException, WebApplicationException {

			String serialized = IOUtils.toString(entityStream, Charsets.UTF_8);
			return (T) Entities.unmarshallEntity(serialized, (Class<Entity>) type);
	}

	@Override
	public boolean isWriteable(Class<?> type, Type genericType,
								Annotation[] annotations, MediaType mediaType) {

		return true;
	}

	@Override
	public void writeTo(T object, Class<?> type, Type genericType,
						Annotation[] annotations, MediaType mediaType,
						MultivaluedMap<String, Object> httpHeaders,
						OutputStream entityStream)
								throws IOException, WebApplicationException {

		if (Entity.class.isAssignableFrom(object.getClass())) {

			String serialized = Entities.marshallEntity((Entity) object);
			IOUtils.write(serialized, entityStream, Charsets.UTF_8);

		} else {

			throw new IOException(object.getClass().getName() + " cannot be deserialized as " + MEDIA_TYPE);
		}
	}

}

Add entity provider for IT harvester


package org.springframework.security.web.authentication.logout;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;

/**
 *
 * @author Luke Taylor
 */
public class SimpleUrlLogoutSuccessHandlerTests {

    @Test
    public void doesntRedirectIfResponseIsCommitted() throws Exception {
        SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
        lsh.setDefaultTargetUrl("/target");
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        response.setCommitted(true);
        lsh.onLogoutSuccess(request, response, mock(Authentication.class));
        assertNull(request.getSession(false));
        assertNull(response.getRedirectedUrl());
        assertNull(response.getForwardedUrl());
    }
}

package org.springframework.security.web.authentication.logout;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;

/**
 *
 * @author Luke Taylor
 */
public class SimpleUrlLogoutSuccessHandlerTests {

    @Test
    public void doesntRedirectIfResponseIsCommitted() throws Exception {
        SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
        lsh.setDefaultTargetUrl("/target");
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        response.setCommitted(true);
        lsh.onLogoutSuccess(request, response, mock(Authentication.class));
        assertNull(request.getSession(false));
        assertNull(response.getRedirectedUrl());
        assertNull(response.getForwardedUrl());
    }

    @Test
    public void absoluteUrlIsSupported() throws Exception {
        SimpleUrlLogoutSuccessHandler lsh = new SimpleUrlLogoutSuccessHandler();
        lsh.setDefaultTargetUrl("http://someurl.com/");
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        lsh.onLogoutSuccess(request, response, mock(Authentication.class));
        assertEquals("http://someurl.com/", response.getRedirectedUrl());
    }

}

Test to check that absolute URLs work in SimpleUrlLogoutSuccessHandler.


package flyway.asdi;

import java.sql.Connection;
import java.util.List;

import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

import fi.nls.oskari.util.FlywayHelper;

/**
 * Adds printout bundle to all user/default views
 */
public class V1_17_0__add_printout_bundle_to_views implements JdbcMigration {

	private static final String BUNDLE_ID = "printout";

	@Override
	public void migrate(Connection connection) throws Exception {
		  final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection);
	        for (Long viewId : views) {
	            if (FlywayHelper.viewContainsBundle(connection, BUNDLE_ID, viewId)) {
	                continue;
	            }
	            FlywayHelper.addBundleWithDefaults(connection, viewId, BUNDLE_ID);
	        }
	}

}

Add Flyway migration to add printout- bundle to user and default views


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

import java.net.URI;
import java.net.URISyntaxException;

import javax.security.auth.login.Configuration;

import junit.framework.TestCase;

public class URIParameterTest extends TestCase {

	private URIParameter uriParameter;
	private URI			 uri;

	/**
	 * @tests {@link java.security.URIParamter#constructor(java.net.URI)}
	 */
	public void test_Constructor() throws URISyntaxException {
		try {
			new URIParameter(null);
			fail("Should throw NPE");
		} catch (NullPointerException e) {
			// expected
		}

		assertTrue(uriParameter instanceof Policy.Parameters);
		assertTrue(uriParameter instanceof Configuration.Parameters);
	}

	/**
	 * @tests {@link java.security.URIParameter#getURI()}
	 */
	public void testGetURI() {
		URI u = uriParameter.getURI();
		assertEquals(uri, u);
		assertSame(uri, u);
	}

	/*
     * @see TestCase#setUp()
     */
	protected void setUp() throws Exception {
        super.setUp();
        uri = new URI("http://www.test.com");
        uriParameter = new URIParameter(uri);
	}

	/*
     * @see TestCase#tearDown()
     */
	protected void tearDown() throws Exception {
        super.tearDown();
        uriParameter = null;
        uri 		 = null;
    }
}

Add test for Java 6 new classes URIParameter


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

package griffon.core.i18n;

import griffon.util.ConfigReader;
import griffon.util.Environment;
import griffon.util.GriffonApplicationUtils;
import griffon.util.Metadata;
import groovy.lang.Script;
import groovy.util.ConfigObject;

import java.net.URL;
import java.util.*;

import static griffon.util.ConfigUtils.getConfigValue;

/**
 * @author Andres Almiray
 * @since 1.1.0
 */
public class GroovyScriptResourceBundle extends ResourceBundle {
    private final ConfigObject config;
    private final List<String> keys = new ArrayList<String>();

    public GroovyScriptResourceBundle(URL location) {
        this(null, location);
    }

    public GroovyScriptResourceBundle(Script script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(String script) {
        this(null, script);
    }

    public GroovyScriptResourceBundle(Class scriptClass) {
        this(null, scriptClass);
    }

    public GroovyScriptResourceBundle(ConfigReader reader, URL location) {
        this(resolveConfigReader(reader).parse(location));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Script script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, String script) {
        this(resolveConfigReader(reader).parse(script));
    }

    public GroovyScriptResourceBundle(ConfigReader reader, Class scriptClass) {
        this(resolveConfigReader(reader).parse(scriptClass));
    }

    private static ConfigReader resolveConfigReader(ConfigReader reader) {
        if (null != reader) return reader;
        reader = new ConfigReader();
        reader.registerConditionalBlock("environments", Environment.getCurrent().getName());
        reader.registerConditionalBlock("projects", Metadata.getCurrent().getApplicationName());
        reader.registerConditionalBlock("platforms", GriffonApplicationUtils.getFullPlatform());
        return reader;
    }

    private GroovyScriptResourceBundle(ConfigObject config) {
        this.config = config;
        keys.addAll(this.config.flatten(new LinkedHashMap()).keySet());
    }

    protected Object handleGetObject(String key) {
        Object value = getConfigValue(config, key, null);
        return null == value ? null : String.valueOf(value);
    }

    public Enumeration<String> getKeys() {
        final Iterator<String> keysIterator = keys.iterator();
        return new Enumeration<String>() {
            public boolean hasMoreElements() {
                return keysIterator.hasNext();
            }

            public String nextElement() {
                return keysIterator.next();
            }
        };
    }
}

Add a ConfigObject backed ResourceBundle implementation


package uk.gov.register.core;

import org.flywaydb.core.Flyway;
import org.junit.Before;
import org.junit.Test;
import org.skife.jdbi.v2.DBI;
import uk.gov.register.configuration.ConfigManager;
import uk.gov.register.exceptions.NoSuchConfigException;

import java.io.IOException;
import java.util.Optional;

import static org.mockito.Mockito.*;

public class RegisterContextTest {
    private RegisterName registerName;
    private ConfigManager configManager;
    private DBI dbi;
    private Flyway flyway;

    @Before
    public void setup() {
        registerName = new RegisterName("register");
        configManager = mock(ConfigManager.class, RETURNS_DEEP_STUBS);
        dbi = mock(DBI.class);
        flyway = mock(Flyway.class);
    }

    @Test
    public void resetRegister_shouldNotResetRegister_whenEnableRegisterDataDeleteIsDisabled() throws IOException, NoSuchConfigException {
        RegisterContext context = new RegisterContext(registerName, configManager, dbi, flyway, Optional.empty(), false, false);
        context.resetRegister();

        verify(flyway, never()).clean();
        verify(configManager, never()).refreshConfig();
        verify(flyway, never()).migrate();
    }

    @Test
    public void resetRegister_shouldResetRegister_whenEnableRegisterDataDeleteIsEnabled() throws IOException, NoSuchConfigException {
        RegisterContext context = new RegisterContext(registerName, configManager, dbi, flyway, Optional.empty(), true, false);
        context.resetRegister();

        verify(flyway, times(1)).clean();
        verify(configManager, times(1)).refreshConfig();
        verify(flyway, times(1)).migrate();
    }
}

Add tests for resetRegister method in RegisterContext


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

import android.net.Uri;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.testutil.DataSourceContractTest;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import com.google.android.exoplayer2.upstream.cache.NoOpCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import com.google.common.collect.ImmutableList;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;

/** {@link DataSource} contract tests for {@link CacheDataSource}. */
@RunWith(AndroidJUnit4.class)
public class CacheDataSourceContractTest extends DataSourceContractTest {
  private static final byte[] DATA = TestUtil.buildTestData(20);

  @Rule public final TemporaryFolder tempFolder = new TemporaryFolder();

  private Uri simpleUri;

  @Before
  public void setUp() throws IOException {
    File file = tempFolder.newFile();
    Files.write(Paths.get(file.getAbsolutePath()), DATA);
    simpleUri = Uri.fromFile(file);
  }

  @Override
  protected ImmutableList<TestResource> getTestResources() {
    return ImmutableList.of(
        new TestResource.Builder()
            .setName("simple")
            .setUri(simpleUri)
            .setExpectedBytes(DATA)
            .build());
  }

  @Override
  protected Uri getNotFoundUri() {
    return Uri.fromFile(tempFolder.getRoot().toPath().resolve("nonexistent").toFile());
  }

  @Override
  protected DataSource createDataSource() throws IOException {
    File tempFolder =
        Util.createTempDirectory(ApplicationProvider.getApplicationContext(), "ExoPlayerTest");
    SimpleCache cache =
        new SimpleCache(tempFolder, new NoOpCacheEvictor(), TestUtil.getInMemoryDatabaseProvider());
    return new CacheDataSource(cache, new FileDataSource());
  }
}

Add contract test for CacheDataSource


package org.cifasis.mc1;

/**
 * An action represents the visible actions of the processes in the shared state.
 * Created by Cristian on 22/06/15.
 */
public class Action {

    private final String name;
    private final MCProcess process;

    public Action(String name, MCProcess process) {
        this.name = name;
        this.process = process;
    }

    public String getName() {
        return name;
    }

    public MCProcess getProcess() {
        return process;
    }
}

Add new class to represent actions (mazurkiewicz).


package com.orientechnologies.orient.distributed.impl.coordinator.network;

import com.orientechnologies.orient.distributed.impl.coordinator.OSubmitRequest;
import com.orientechnologies.orient.distributed.impl.coordinator.ddl.ODDLQuerySubmitRequest;
import com.orientechnologies.orient.distributed.impl.coordinator.transaction.OSessionOperationId;
import org.junit.Assert;
import org.junit.Test;

import java.io.*;

public class ONetworkSubmitRequestTest {

  @Test
  public void testSerialize() throws IOException {

    String db = "testDb";
    OSessionOperationId opId = new OSessionOperationId("foo");
    ODDLQuerySubmitRequest req = new ODDLQuerySubmitRequest("create class FooBar");
    ONetworkSubmitRequest request = new ONetworkSubmitRequest(db, opId, req);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(baos);
    request.write(out);
    byte[] serialized = baos.toByteArray();
    out.close();
    baos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(serialized);
    DataInputStream in = new DataInputStream(bais);

    ONetworkSubmitRequest request2 = new ONetworkSubmitRequest();
    request2.read(in);
    in.close();
    bais.close();

    Assert.assertEquals(request.getCommand(), request2.getCommand());
    Assert.assertEquals(request.getDatabase(), request2.getDatabase());
    Assert.assertEquals(request.getOperationId(), request2.getOperationId());
    OSubmitRequest req2 = request2.getRequest();
    Assert.assertEquals(req.getRequestType(), req2.getRequestType());
    Assert.assertEquals(req.getClass(), req2.getClass());
    Assert.assertEquals(req.getQuery(), ((ODDLQuerySubmitRequest)req2).getQuery());

  }
}

Add serialization tests for ONetworkSubmitRequest


package roart.evolution.marketfilter.common.gene.impl;

import java.util.Random;

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

import roart.common.constants.Constants;
import roart.common.util.RandomUtil;
import roart.iclij.config.MarketFilter;

public class MarketFilterMutateCommon {
    protected Logger log = LoggerFactory.getLogger(this.getClass());

    protected static final int RANDOMS = 7;

    Random random = new Random();

    /*
     * private String inccategory;

    private Integer incdays;

    private Double incthreshold;

    private String deccategory;

    private Integer decdays;

    private Double decthreshold;

    private Double confidence;

     */
    public int generateDays() {
        return RandomUtil.random(random, 5, 50);
    }

    public double generateConfidence() {
        return RandomUtil.random(random, 0.01, 0.01, 100);
    }

    public double generateThreshold() {
        return RandomUtil.random(random, 0.9, 0.01, 20);
    }

    public String generateCategory(MarketFilter myconfig) {
        //String[] categories = { "1w", "1m", "3m", "1y", "3y", "5y", "10y", "cy" };
        if (myconfig.categories.isEmpty()) {
            return null;
        }
        int index = random.nextInt(myconfig.categories.size());
        return myconfig.categories.get(index);
    }

    public void mutateCommon(MarketFilter myconfig) {
        int task = random.nextInt(this.RANDOMS);
        switch (task) {
        case 0:
            myconfig.setDeccategory(this.generateCategory(myconfig));
            break;
        case 1:
            myconfig.setDecdays(this.generateDays());
            break;
        case 2:
            myconfig.setDecthreshold(this.generateThreshold());
            break;
        case 3:
            myconfig.setInccategory(this.generateCategory(myconfig));
            break;
        case 4:
            myconfig.setIncdays(this.generateDays());
            break;
        case 5:
            myconfig.setIncthreshold(this.generateThreshold());
            break;
        case 6:
            myconfig.setConfidence(this.generateConfidence());
            break;
        default:
            log.error(Constants.NOTFOUND, task);
        }
    }

}

Choose evolution genetic algorithm (I225).


package ch.bisi.jicon.examples;

import ch.bisi.jicon.Jicon;
import ch.bisi.jicon.common.JiconIcon;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * A simple example showing howto retrieve favicons from github.
 */
@SuppressFBWarnings("DMI_HARDCODED_ABSOLUTE_FILENAME")
public class GetGithubFavicons {

  public static void main(final String[] args) throws IOException {
    final List<JiconIcon> githubFavicons = Jicon.retrieveAll(new URL("https://www.github.com"));
    Jicon.saveInDir(githubFavicons, "/home/osboxes/github_favicons/");
  }

}

Create a simple example program


package alien4cloud.paas.exception;

import alien4cloud.paas.IPaaSProvider;

/**
 * Exception to be thrown in case the {@link IPaaSProvider} fail to find a resource for one of the elments in the topology.
 */
public class ResourceMatchingFailedException extends PaaSDeploymentException {
    private static final long serialVersionUID = 1L;

    /**
     *
     * @param message
     */
    public ResourceMatchingFailedException(String message) {
        super(message);
    }

    public ResourceMatchingFailedException(String message, Throwable cause) {
        super(message, cause);
    }
}

Fix Compilation failure for cloudify 2


/*******************************************************************************
 * Copyright (c) 2018 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.app.api.core.exception;

import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.app.api.core.exception.model.KapuaExceptionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class KapuaExceptionMapper implements ExceptionMapper<KapuaException> {

    private static final Logger LOG = LoggerFactory.getLogger(KapuaExceptionMapper.class);

    @Override
    public Response toResponse(KapuaException kapuaException) {
        LOG.error("Generic Kapua exception!", kapuaException);
        return Response
                .status(Status.UNAUTHORIZED)
                .entity(new KapuaExceptionInfo(Status.INTERNAL_SERVER_ERROR, kapuaException.getCode(), kapuaException))
                .build();
    }

}

/*******************************************************************************
 * Copyright (c) 2018 Eurotech and/or its affiliates and others
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Eurotech - initial API and implementation
 *******************************************************************************/
package org.eclipse.kapua.app.api.core.exception;

import org.eclipse.kapua.KapuaException;
import org.eclipse.kapua.app.api.core.exception.model.KapuaExceptionInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class KapuaExceptionMapper implements ExceptionMapper<KapuaException> {

    private static final Logger LOG = LoggerFactory.getLogger(KapuaExceptionMapper.class);

    @Override
    public Response toResponse(KapuaException kapuaException) {
        LOG.error("Generic Kapua exception!", kapuaException);
        return Response
                .serverError()
                .entity(new KapuaExceptionInfo(Status.INTERNAL_SERVER_ERROR, kapuaException.getCode(), kapuaException))
                .build();
    }

}

Write correct HTTP error code in REST Internal Error


package com.ushahidi.android.presentation.model.mapper;

import com.ushahidi.android.domain.entity.Form;
import com.ushahidi.android.presentation.model.FormModel;

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

import javax.inject.Inject;

/**
 * Transforms data between domain layer and presentation layer
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class FormModelDataMapper {

    /**
     * Default constructor
     */
    @Inject
    public FormModelDataMapper() {
        // Do nothing
    }

    /**
     * Maps {@link Form} to {@link FormModel}
     *
     * @param form The form  to be mapped
     * @return The mapped form model
     */
    public FormModel map(Form form) {
        FormModel formModel = null;
        if (form != null) {
            formModel = new FormModel();
            formModel._id = form._id;
            formModel.setCreated(form.getCreated());
            formModel.setUpdated(form.getUpdated());
            formModel.setDescription(form.getDescription());
            formModel.setName(form.getName());
            formModel.setDeploymentId(form.getDeploymentId());
            formModel.setDisabled(form.isDisabled());
        }
        return formModel;
    }

    /**
     * Maps {@link FormModel} to {@link Form}
     *
     * @param formModel The form to be mapped
     * @return The mapped form
     */
    public Form map(FormModel formModel) {
        Form form = null;
        if (formModel != null) {
            form = new Form();
            form._id = formModel._id;
            form.setCreated(formModel.getCreated());
            form.setUpdated(formModel.getUpdated());
            form.setDeploymentId(formModel.getDeploymentId());
            form.setName(formModel.getName());
            form.setDescription(formModel.getDescription());
            form.setDisabled(formModel.isDisabled());
        }
        return form;
    }

    /**
     * Maps a list of {@link Form} to a list of {@link FormModel}
     *
     * @param formList The form entity list
     * @return The mapped form entity list
     */
    public List<FormModel> map(List<Form> formList) {
        List<FormModel> formModelList = null;
        if (formList != null) {
            formModelList = new ArrayList<>();
            for (Form form : formList) {
                FormModel formModel = map(form);
                formModelList.add(formModel);
            }
        }
        return formModelList;
    }
}

Add form model data mapper


package alexandria.israelferrer.com.libraryofalexandria;

import android.content.SharedPreferences;

import junit.framework.TestCase;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import static alexandria.israelferrer.com.libraryofalexandria.ArtWorkListActivityTests.ARTWORKS;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class ArtWorkModelTests extends TestCase {
    private ArtWorkModel model;
    private SharedPreferences preferences;
    private ArtWorkService service;
    private Callback callback;
    private Exception exception;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        preferences = mock(SharedPreferences.class);
        service = mock(ArtWorkService.class);
        callback = mock(Callback.class);
        model = new ArtWorkModel(service, preferences);
        exception = new Exception();
    }

    public void testGetArtWorks_success() throws Exception {
        serviceSuccessAnswer();
        model.getArtWorks(callback);
        verify(service, only()).getArtWorks(any(Callback.class));
        verify(callback, only()).success(ARTWORKS);
        verify(preferences, times(ARTWORKS.size())).getFloat(any(String.class), eq(0F));
    }

    private void serviceSuccessAnswer() {
        doAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                ((Callback) args[0]).success(ARTWORKS);
                return null;
            }
        }).when(service).getArtWorks(any(Callback.class));
    }

    public void testGetArtWorks_failure() throws Exception {
        serviceFailureAnswer();
        model.getArtWorks(callback);
        verify(service, only()).getArtWorks(any(Callback.class));
        verify(callback, only()).failure(exception);
    }

    private void serviceFailureAnswer() {
        doAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                ((Callback) args[0]).failure(exception);
                return null;
            }
        }).when(service).getArtWorks(any(Callback.class));
    }
}

Add test to the model


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This 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.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.xwiki.test;

import javax.inject.Named;
import javax.inject.Singleton;

import org.xwiki.component.annotation.Component;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.configuration.internal.MemoryConfigurationSource;

/**
 * Make easier to inject a usable {@link ConfigurationSource} component associated to role hint "xwikiproperties".
 *
 * @version $Id$
 */
@Component
@Singleton
@Named("xwikiproperties")
public class XWikiPropertiesMemoryConfigurationSource extends MemoryConfigurationSource
{

}

Add a test tools to easily inject a usable ConfigurationSource associated to "xwikiproperties"


/*
 * 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.oodt.cas.pge;

import org.apache.oodt.cas.workflow.util.CygwinScriptFile;
import org.apache.oodt.cas.workflow.util.ScriptFile;

/**
 * Runs a CAS-style Product Generation Executive based on the PCS Wrapper
 * Architecture from mattmann et al. on OCO specifically on a Windows Cygwin-running
 * machine
 *
 * @author riverma (Rishi Verma)
 */
public class WinPGETaskInstance extends PGETaskInstance {

	  /**
	   * Override buildPgeRunScript method to call a windows specific script file
	   */
	  @Override
	  protected ScriptFile buildPgeRunScript() {
		  CygwinScriptFile sf = new CygwinScriptFile(this.pgeConfig.getShellType());
	      sf.setCommands(this.pgeConfig.getExeCmds());

	      return sf;
	  }

}

Support the ability to run PGE Task Instances on Windows (Cygwin) executable environments


package com.github.arteam.dropwizard.http2.client;

import com.codahale.metrics.MetricRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.jersey.validation.Validators;
import io.dropwizard.logging.BootstrapLogging;
import io.dropwizard.setup.Environment;
import org.assertj.core.api.Assertions;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.util.component.LifeCycle;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Date: 1/6/16
 * Time: 8:50 PM
 *
 * @author Artem Prigoda
 */
public class Http2ClientExternalServiceTest {

    static {
        BootstrapLogging.bootstrap();
    }

    private Environment environment = new Environment("default", new ObjectMapper(),
            Validators.newValidator(), new MetricRegistry(), ClassLoader.getSystemClassLoader());

    private HttpClient httpClient;

    @Before
    public void setUp() throws Exception {
        httpClient = new JettyHttpClientBuilder(environment).build();
        for (LifeCycle managedObject : environment.lifecycle().getManagedObjects()) {
            managedObject.start();
        }
    }

    @After
    public void tearDown() throws Exception {
        for (LifeCycle managedObject : environment.lifecycle().getManagedObjects()) {
            managedObject.stop();
        }
    }

    @Test
    public void testExternalService() throws Exception {
        String content = httpClient.GET("https://http2.golang.org/reqinfo")
                .getContentAsString();
        assertThat(content).contains("Method: GET");
        assertThat(content).contains("Protocol: HTTP/2.0");
        assertThat(content).contains("Host: http2.golang.org:443");
        assertThat(content).contains("RequestURI: \"/reqinfo\"");
    }
}

Add a test for connecting to a Go Lang test server


package boq.utils.render;

import net.minecraftforge.common.ForgeDirection;

import org.lwjgl.opengl.GL11;

import boq.utils.log.Log;
import boq.utils.misc.Rotation;

public class RotationHelper {

    public static void setupSide(ForgeDirection side) {
        switch (side) {
            case DOWN:
                GL11.glRotatef(90, 1, 0, 0);
                GL11.glTranslatef(0, 0, -1);
                break;
            case UP:
                GL11.glRotatef(-90, 1, 0, 0);
                GL11.glTranslatef(0, -1, 0);
                break;
            case NORTH:
                GL11.glRotatef(180, 0, 1, 0);
                GL11.glTranslatef(-1, 0, -1);
                break;
            case SOUTH:
                break;
            case EAST:
                GL11.glRotatef(90, 0, 1, 0);
                GL11.glTranslatef(-1, 0, 0);
                break;
            case WEST:
                GL11.glRotatef(-90, 0, 1, 0);
                GL11.glTranslatef(0, 0, -1);
                break;
            default:
                Log.warning("Invalid side while rendering @ RenderHelper.setupSide");
                break;
        }
    }

    public static void setupRotation(Rotation rotation) {
        switch (rotation) {
            case R0:
                break;
            case R90:
                GL11.glRotatef(-90, 0, 0, 1);
                GL11.glTranslatef(-1, 0, 0);
                break;
            case R180:
                GL11.glRotatef(180, 0, 0, 1);
                GL11.glTranslatef(-1, -1, 0);
                break;
            case R270:
                GL11.glRotatef(90, 0, 0, 1);
                GL11.glTranslatef(0, -1, 0);
                break;
        }
    }

}

Move rotation helper to utils


package edu.northwestern.bioinformatics.studycalendar.web.schedule;

import edu.northwestern.bioinformatics.studycalendar.service.StudyService;
import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import gov.nih.nci.cabig.ctms.lang.DateTools;
import gov.nih.nci.cabig.ctms.lang.NowFactory;
import static org.easymock.EasyMock.expect;

import java.util.Calendar;

public class ScheduleReconsentCommandTest extends StudyCalendarTestCase {
    private ScheduleReconsentCommand command;
    private StudyService studyService;
    private NowFactory nowFactory;

    protected void setUp() throws Exception {
        super.setUp();
        studyService = registerMockFor(StudyService.class);
        nowFactory = registerMockFor(NowFactory.class);
        command = new ScheduleReconsentCommand(studyService, nowFactory);
    }

    public void testValidate() throws Exception {
        command.setStartDate(DateTools.createTimestamp(2005, Calendar.AUGUST, 3));

        expect(nowFactory.getNow()).andReturn(DateTools.createDate(2007, Calendar.AUGUST, 3)).times(2);
        replayMocks();
        command.validate(null);
        verifyMocks();
        assertSameDay("Expected Date different than actual", DateTools.createDate(2007, Calendar.AUGUST, 3), command.getStartDate());
    }
}

Test for the Schedule Reconsent Command


/*
 * Copyright 2015 Michael Rozumyanskiy
 *
 * 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 io.michaelrocks.lightsaber.processor.annotations;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.objectweb.asm.Type;

import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Map;

@ParametersAreNonnullByDefault
public class AnnotationDescriptor {
    private final Type type;
    private final Map<String, Type> fields;

    AnnotationDescriptor(final Type type, final Map<String, Type> fields) {
        this.type = type;
        this.fields = fields;
    }

    public Type getType() {
        return type;
    }

    public Map<String, Type> getFields() {
        return fields;
    }

    @Override
    public boolean equals(@Nullable final Object object) {
        if (this == object) {
            return true;
        }

        if (object == null || getClass() != object.getClass()) {
            return false;
        }

        final AnnotationDescriptor that = (AnnotationDescriptor) object;

        return new EqualsBuilder()
                .append(type, that.type)
                .append(fields, that.fields)
                .isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37)
                .append(type)
                .append(fields)
                .toHashCode();
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("type", type)
                .append("fields", fields)
                .toString();
    }
}

Add an annotation descriptor class which describes annotation fields


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

/**
 * Given a binary tree, can you write a method to get a List<BinaryNode> using a in order
 * traversal?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BinaryTreeInOrder {
}

Add statement to problem 15


package com.microsoft.windowsazure.services.queue.models;

public class CreateMessageOptions extends QueueServiceOptions {
    private Integer visibilityTimeoutInSeconds;
    private Integer timeToLiveInSeconds;

    public Integer getVisibilityTimeoutInSeconds() {
        return visibilityTimeoutInSeconds;
    }

    public void setVisibilityTimeoutInSeconds(Integer visibilityTimeoutInSeconds) {
        this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds;
    }

    public Integer getTimeToLiveInSeconds() {
        return timeToLiveInSeconds;
    }

    public void setTimeToLiveInSeconds(Integer timeToLiveInSeconds) {
        this.timeToLiveInSeconds = timeToLiveInSeconds;
    }
}

package com.microsoft.windowsazure.services.queue.models;

public class CreateMessageOptions extends QueueServiceOptions {
    private Integer visibilityTimeoutInSeconds;
    private Integer timeToLiveInSeconds;

    public Integer getVisibilityTimeoutInSeconds() {
        return visibilityTimeoutInSeconds;
    }

    public CreateMessageOptions setVisibilityTimeoutInSeconds(Integer visibilityTimeoutInSeconds) {
        this.visibilityTimeoutInSeconds = visibilityTimeoutInSeconds;
        return this;
    }

    public Integer getTimeToLiveInSeconds() {
        return timeToLiveInSeconds;
    }

    public CreateMessageOptions setTimeToLiveInSeconds(Integer timeToLiveInSeconds) {
        this.timeToLiveInSeconds = timeToLiveInSeconds;
        return this;
    }
}

Add missing "return this;" to options class


package org.realityforge.gwt.appcache.server.propertyprovider;

import javax.servlet.http.HttpServletRequest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;

public class UserAgentPropertyProviderTest
{
  @DataProvider( name = "AgentMapping" )
  public Object[][] getAgentMapping()
  {
    return new Object[][] {
      { "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36",
        "safari" },
      { "opera", "opera" },
      { "Gecko and some other text?", "gecko1_8" },
    };
  }

  @Test( dataProvider = "AgentMapping" )
  public void userAgentExtraction( final String userAgent, final String value )
  {
    final UserAgentPropertyProvider provider = new UserAgentPropertyProvider();

    assertEquals( provider.getPropertyName(), "user.agent" );
    final HttpServletRequest request = mock( HttpServletRequest.class );
    when( request.getHeader( "User-Agent" ) ).thenReturn( userAgent );
    assertEquals( provider.getPropertyValue( request ), value );
  }

  @Test( expectedExceptions = IllegalStateException.class )
  public void badUserAgent()
  {
    final UserAgentPropertyProvider provider = new UserAgentPropertyProvider();

    assertEquals( provider.getPropertyName(), "user.agent" );
    final HttpServletRequest request = mock( HttpServletRequest.class );
    when( request.getHeader( "User-Agent" ) ).thenReturn( "SomethingElse" );
    provider.getPropertyValue( request );
  }
}

Add some basic testing around proeprty provider


/****************************************************************************
*                                                                           *
*  OpenNI 1.x Alpha                                                         *
*  Copyright (C) 2011 PrimeSense Ltd.                                       *
*                                                                           *
*  This file is part of OpenNI.                                             *
*                                                                           *
*  OpenNI 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 3 of the License, or     *
*  (at your option) any later version.                                      *
*                                                                           *
*  OpenNI 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 OpenNI. If not, see <http://www.gnu.org/licenses/>.           *
*                                                                           *
****************************************************************************/
package org.OpenNI;

public class AlternativeViewpointCapability extends CapabilityBase
{
	public AlternativeViewpointCapability(ProductionNode node) throws StatusException
	{
		super(node);

		this.viewPointChanged = new StateChangedObservable()
		{
			@Override
			protected int registerNative(String cb, OutArg<Long> phCallback)
			{
				return NativeMethods.xnRegisterToViewPointChange(toNative(), this, cb, phCallback);
			}

			@Override
			protected void unregisterNative(long hCallback)
			{
				NativeMethods.xnUnregisterFromViewPointChange(toNative(), hCallback);
			}
		};
	}

	boolean isViewpointSupported(ProductionNode other)
	{
		return NativeMethods.xnIsViewPointSupported(toNative(), other.toNative());
	}

	void setViewpoint(ProductionNode other) throws StatusException
	{
		int status = NativeMethods.xnSetViewPoint(toNative(), other.toNative());
		WrapperUtils.throwOnError(status);
	}

	void resetViewpoint() throws StatusException
	{
		int status = NativeMethods.xnResetViewPoint(toNative());
		WrapperUtils.throwOnError(status);
	}

	boolean isViewpointAs(ProductionNode other)
	{
		return NativeMethods.xnIsViewPointAs(toNative(), other.toNative());
	}

	public IStateChangedObservable getViewPointChangedEvent() { return this.viewPointChanged; }

	private StateChangedObservable viewPointChanged;
}

Deal with a bad file rename - phase II


package org.apache.aries.subsystem.obr.internal;

import static org.junit.Assert.assertEquals;

import org.apache.felix.bundlerepository.Requirement;
import org.easymock.EasyMock;
import org.junit.Test;
import org.osgi.resource.Namespace;
import org.osgi.resource.Resource;

public class FelixRequirementAdapterTest {
	@Test
	public void testCardinalityDirectiveMultiple() {
		Requirement req = EasyMock.createNiceMock(Requirement.class);
		EasyMock.expect(req.getFilter()).andReturn("");
		EasyMock.expect(req.isMultiple()).andReturn(true);
		EasyMock.replay(req);
		FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class));
		assertEquals(adapter.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE), Namespace.CARDINALITY_MULTIPLE);
	}

	@Test
	public void testCardinalityDirectiveSingle() {
		Requirement req = EasyMock.createNiceMock(Requirement.class);
		EasyMock.expect(req.getFilter()).andReturn("");
		EasyMock.expect(req.isMultiple()).andReturn(false);
		EasyMock.replay(req);
		FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class));
		assertEquals(adapter.getDirectives().get(Namespace.REQUIREMENT_CARDINALITY_DIRECTIVE), Namespace.CARDINALITY_SINGLE);
	}

	@Test
	public void testResolutionDirectiveMandatory() {
		Requirement req = EasyMock.createNiceMock(Requirement.class);
		EasyMock.expect(req.getFilter()).andReturn("");
		EasyMock.expect(req.isOptional()).andReturn(false);
		EasyMock.replay(req);
		FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class));
		assertEquals(adapter.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE), Namespace.RESOLUTION_MANDATORY);
	}

	@Test
	public void testResolutionDirectiveOptional() {
		Requirement req = EasyMock.createNiceMock(Requirement.class);
		EasyMock.expect(req.getFilter()).andReturn("");
		EasyMock.expect(req.isOptional()).andReturn(true);
		EasyMock.replay(req);
		FelixRequirementAdapter adapter = new FelixRequirementAdapter(req, EasyMock.createNiceMock(Resource.class));
		assertEquals(adapter.getDirectives().get(Namespace.REQUIREMENT_RESOLUTION_DIRECTIVE), Namespace.RESOLUTION_OPTIONAL);
	}
}

Add tests to verify optional requirements are not treated as mandatory.


/*
 * 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 io.prestosql.tests.product.launcher.env.configs;

import com.google.common.base.Splitter;

import java.util.List;
import java.util.Optional;

import static java.lang.System.getenv;

public class ConfigEnvBased
        extends ConfigDefault
{
    @Override
    public String getHadoopBaseImage()
    {
        return getEnvOrDefault("HADOOP_BASE_IMAGE", super.getHadoopBaseImage());
    }

    @Override
    public String getImagesVersion()
    {
        return getEnvOrDefault("DOCKER_IMAGES_VERSION", super.getImagesVersion());
    }

    @Override
    public String getHadoopImagesVersion()
    {
        return getEnvOrDefault("HADOOP_IMAGES_VERSION", super.getHadoopImagesVersion());
    }

    @Override
    public String getTemptoEnvironmentConfigFile()
    {
        return getEnvOrDefault("TEMPTO_ENVIRONMENT_CONFIG_FILE", super.getTemptoEnvironmentConfigFile());
    }

    @Override
    public List<String> getExcludedGroups()
    {
        return Optional
                .ofNullable(getenv("DISTRO_SKIP_GROUP"))
                .map(value -> Splitter.on(',')
                        .omitEmptyStrings()
                        .trimResults()
                        .splitToList(value))
                .orElse(super.getExcludedGroups());
    }

    @Override
    public List<String> getExcludedTests()
    {
        return Optional
                .ofNullable(getenv("DISTRO_SKIP_TEST"))
                .map(value -> Splitter.on(',')
                        .omitEmptyStrings()
                        .trimResults()
                        .splitToList(value))
                .orElse(super.getExcludedTests());
    }

    private static String getEnvOrDefault(String envKey, String defaultValue)
    {
        return Optional
                .ofNullable(getenv(envKey))
                .orElse(defaultValue);
    }
}

Add ENV based environment config


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

package org.jboss.as.controller.client.impl;

import java.io.File;

import org.jboss.as.controller.client.ModelControllerClient;

/**
 * This is for internal use only.
 *
 * @author Kabir Khan
 */
public interface AdditionalBootCliScriptInvoker {
    String CLI_SCRIPT_PROPERTY = "org.wildfly.internal.cli.boot.hook.script";
    String MARKER_DIRECTORY_PROPERTY = "org.wildfly.internal.cli.boot.hook.marker.dir";
    String SKIP_RELOAD_PROPERTY = "org.wildfly.internal.cli.boot.hook.reload.skip";

    void runCliScript(ModelControllerClient client, File file);
}

Add interface to invoke additional boot operations from CLI


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.underfs.s3a;

import alluxio.util.io.PathUtils;
import com.amazonaws.services.s3.transfer.TransferManager;
import java.io.IOException;

/**
 * A stream for writing a file into S3. Unlike {@link S3AOutputStream}, this class directly
 * uploads the file to the final S3 path instead of a temporary Alluxio generated S3 path.
 */
public class S3ADirectOutputStream extends S3AOutputStream {
  /**
   * Constructs a new stream for writing a file.
   *
   * @param bucketName the name of the bucket
   * @param key the key of the file
   * @param manager the transfer manager to upload the file with
   * @throws IOException when a non-Alluxio related error occurs
   */
  public S3ADirectOutputStream(String bucketName, String key, TransferManager manager)
      throws IOException {
    super(bucketName, key, manager);
  }

  @Override
  public String getUploadPath() {
    return PathUtils.getPermanentFileName(super.getUploadPath());
  }
}

Implement direct s3a output stream.


package com.reactnativenavigation.params.parsers;

import android.os.Bundle;

import com.balysv.materialmenu.MaterialMenuDrawable;
import com.reactnativenavigation.params.TitleBarLeftButtonParams;

public class TitleBarLeftButtonParamsParser extends TitleBarButtonParamsParser {

    public TitleBarLeftButtonParams parseSingleButton(Bundle params) {
        TitleBarLeftButtonParams leftButtonParams = new TitleBarLeftButtonParams(super.parseSingleButton(params));
        leftButtonParams.iconState = getIconStateFromId(leftButtonParams.eventId);
        return leftButtonParams;
    }

    private MaterialMenuDrawable.IconState getIconStateFromId(String id) {
        switch (id) {
            case "back":
                return MaterialMenuDrawable.IconState.ARROW;
            case "cancel":
                return MaterialMenuDrawable.IconState.X;
            case "accept":
                return MaterialMenuDrawable.IconState.CHECK;
            case "sideMenu":
                return MaterialMenuDrawable.IconState.BURGER;
            default:
                throw new RuntimeException("Unsupported button type " + id);
        }
    }
}

package com.reactnativenavigation.params.parsers;

import android.os.Bundle;

import com.balysv.materialmenu.MaterialMenuDrawable;
import com.reactnativenavigation.params.TitleBarLeftButtonParams;

public class TitleBarLeftButtonParamsParser extends TitleBarButtonParamsParser {

    public TitleBarLeftButtonParams parseSingleButton(Bundle params) {
        TitleBarLeftButtonParams leftButtonParams = new TitleBarLeftButtonParams(super.parseSingleButton(params));
        leftButtonParams.iconState = getIconStateFromId(leftButtonParams.eventId);
        return leftButtonParams;
    }

    private MaterialMenuDrawable.IconState getIconStateFromId(String id) {
        switch (id) {
            case "back":
                return MaterialMenuDrawable.IconState.ARROW;
            case "cancel":
                return MaterialMenuDrawable.IconState.X;
            case "accept":
                return MaterialMenuDrawable.IconState.CHECK;
            case "sideMenu":
                return MaterialMenuDrawable.IconState.BURGER;
            default:
                throw new RuntimeException("Unsupported button id: " + id + ". Supported ids are: back, cancel, accept and sideMenu");
        }
    }
}

Clarify unsupported left button exception message


/*
 * Copyright 2018-present Open Networking Foundation
 *
 * 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.onosproject.openstacktelemetry.impl;

import org.junit.Test;
import org.onlab.junit.TestUtils;

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

/**
 * Unit tests for prometheus telemetry manager.
 */
public final class PrometheusTelemetryManagerTest {

    private PrometheusTelemetryManager manager;
    private OpenstackTelemetryServiceAdapter telemetryService =
            new OpenstackTelemetryServiceAdapter();

    /**
     * Tests app activation and deactivation.
     */
    @Test
    public void testActivateDeactivate() {
        manager = new PrometheusTelemetryManager();

        TestUtils.setField(manager, "openstackTelemetryService", telemetryService);

        manager.activate();

        assertTrue(telemetryService.services.contains(manager));

        manager.deactivate();

        assertFalse(telemetryService.services.contains(manager));
    }
}

Add prometheus telemetry manager unit test


package com.rizki.mufrizal.belajar.oauth2.service;

import com.rizki.mufrizal.belajar.oauth2.domain.UserRole;
import com.rizki.mufrizal.belajar.oauth2.repository.UserRepository;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailLoginService implements UserDetailsService{

    @Resource
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.rizki.mufrizal.belajar.oauth2.domain.User user = userRepository.getUserByUsername(username);

        if (user == null) {
            return null;
        }

        List<GrantedAuthority> userGrantedAuthorities = buildUserAuthority(user.getUserRoles());
        return buildUserForAuthentication(user, userGrantedAuthorities);
    }

    private User buildUserForAuthentication(com.rizki.mufrizal.belajar.oauth2.domain.User user, List<GrantedAuthority> authorities) {
        return new User(user.getUsername(), user.getPassword(), user.isEnable(), true, true, true, authorities);
    }

    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoleSet) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<GrantedAuthority>();

        for (UserRole userRole : userRoleSet) {
            grantedAuthorities.add(new SimpleGrantedAuthority(userRole.getRole()));
        }

        return new ArrayList<GrantedAuthority>(grantedAuthorities);
    }
}

Add Domain User Detail Login


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

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Converts values of an enum to and from integers.
 */
final class EnumAdapter<E extends ProtoEnum> {
  private final Map<Integer, E> fromInt = new LinkedHashMap<Integer, E>();

  EnumAdapter(Class<E> type) {
    for (E value : type.getEnumConstants()) {
      fromInt.put(value.getValue(), value);
    }
  }

  public int toInt(E e) {
    return e.getValue();
  }

  public E fromInt(int value) {
    return fromInt.get(value);
  }
}

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

import java.util.Arrays;
import java.util.Comparator;

/**
 * Converts values of an enum to and from integers.
 */
final class EnumAdapter<E extends ProtoEnum> {
  private static final Comparator<ProtoEnum> COMPARATOR = new Comparator<ProtoEnum>() {
    @Override public int compare(ProtoEnum o1, ProtoEnum o2) {
      return o1.getValue() - o2.getValue();
    }
  };

  private final Class<E> type;

  private final int[] values;
  private final E[] constants;

  EnumAdapter(Class<E> type) {
    this.type = type;

    constants = type.getEnumConstants();
    Arrays.sort(constants, COMPARATOR);

    values = new int[constants.length];
    for (int i = 0; i < constants.length; i++) {
      values[i] = constants[i].getValue();
    }
  }

  public int toInt(E e) {
    return e.getValue();
  }

  public E fromInt(int value) {
    int index = Arrays.binarySearch(values, value);
    if (index < 0) {
      throw new IllegalArgumentException(
          "Unknown enum tag " + value + " for " + type.getCanonicalName());
    }
    return constants[index];
  }
}

Replace the enum adapter tag map with an integer BST.


/*
 * Copyright 2017, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.server.storage.jdbc.entity.query;

import com.google.protobuf.Message;
import org.junit.Test;

import java.sql.ResultSet;
import java.sql.SQLException;

import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.mock;

/**
 * @author Dmytro Dashenkov.
 */
public class SelectEntityByIdQueryShould {

    @Test
    public void return_null_if_serialized_message_column_is_empty() throws SQLException {
        final ResultSet resultSet = mock(ResultSet.class);

        final SelectEntityByIdQuery<String> query =
                SelectEntityByIdQuery.<String>newBuilder("dummy-table")
                                     .build();

        final Message deserialized = query.readMessage(resultSet);
        assertNull(deserialized);
    }
}

Add a test for the select entity by ID query.


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

/**
 * @hide
 */
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
package androidx.work.impl.background.firebase;

import android.support.annotation.RestrictTo;

Remove work-firebase package-level docs from being generated.


/*
 * 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.rocketmq.connect.jdbc.connector;

import io.openmessaging.connector.api.source.SourceTask;

public abstract class JdbcSourceTask extends SourceTask {
/*
 * To Be Continued
 */
}

Add Jdbc Source Task (To be continued)


package fr.alecharp.picshare.service;

import com.google.inject.Singleton;
import fr.alecharp.picshare.domain.Picture;
import net.codestory.http.Part;

import javax.inject.Inject;
import javax.inject.Named;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

/**
 * @author Adrien Lecharpentier
 */
@Singleton
public class PictureService {
    private final String storageLocation;

    @Inject
    public PictureService(@Named("storageLocation") String storageLocation) {
        this.storageLocation = storageLocation;
    }

    public Optional<Picture> upload(String eventID, Part part) {
        try {
            Path target = Paths.get(storageLocation, eventID, part.fileName());
            Files.copy(part.inputStream(), target);
            return Optional.of(new Picture(part.fileName(), "/" + target.toString()));
        } catch (IOException e) {
            // TODO: log
            return Optional.empty();
        }
    }
}

Create service to upload pictures


/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.language.view;

import static org.testng.Assert.assertEquals;

import org.testng.annotations.Test;

import com.opengamma.engine.value.ValueProperties;
import com.opengamma.util.tuple.Triple;

@Test
public class ValueRequirementUtilsTest {

  public void testParseRequirements() {
    assertEquals(Triple.of("Default", "FairValue", ValueProperties.none()), ValueRequirementUtils.parseRequirement("FairValue"));
    assertEquals(Triple.of("Default", "Present Value", ValueProperties.none()), ValueRequirementUtils.parseRequirement("Present Value"));
    assertEquals(Triple.of("Default", "FairValue", ValueProperties.none()), ValueRequirementUtils.parseRequirement("Default/FairValue"));
    assertEquals(Triple.of("Default", "Present Value", ValueProperties.none()), ValueRequirementUtils.parseRequirement("Default/Present Value"));
    assertEquals(Triple.of("Foo", "FairValue", ValueProperties.none()), ValueRequirementUtils.parseRequirement("Foo/FairValue"));
    assertEquals(Triple.of("SHIFT 10BPS", "Present Value", ValueProperties.none()), ValueRequirementUtils.parseRequirement("SHIFT 10BPS/Present Value"));
    assertEquals(Triple.of("Default", "FairValue", ValueProperties.with("x", "A").with("y", "B").get()), ValueRequirementUtils.parseRequirement("FairValue[x=A,y=B]"));
    assertEquals(Triple.of("Default", "Present Value", ValueProperties.with("x", "A").with("y", "B").get()), ValueRequirementUtils.parseRequirement("Present Value{x=A,y=B}"));
    assertEquals(Triple.of("Foo Bar", "Present Value", ValueProperties.with("x", "=[\\,{}]").get()), ValueRequirementUtils.parseRequirement("Foo Bar/Present Value[x=\\=\\[\\\\\\,{}\\]]"));
    assertEquals(Triple.of("Foo Bar", "Present Value", ValueProperties.with("x", "=[\\,{}] ").get()), ValueRequirementUtils.parseRequirement("Foo Bar/Present Value[x=\\=\\[\\\\\\,{}\\]\\ ]"));
  }

}

Test correct/expected parsing of value requirement strings.


/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.test.integration;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.testng.Arquillian;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import static org.testng.Assert.assertTrue;
import org.testng.annotations.Test;

public class DeploymentDeployTest extends Arquillian {
	public static final String ARTIFACT = "de.dfki.asr.compass:compass-deployment:ear:2.1.0-SNAPSHOT";

	@Deployment
	public static EnterpriseArchive getCoreCompassDeployment() {
		return Maven.resolver()
				.loadPomFromFile("pom.xml")
				.resolve(ARTIFACT)
				.withoutTransitivity()
				.asSingle(EnterpriseArchive.class);
	}

	@Test
	public void itWorked() {
		assertTrue(true);
	}
}

Add test case to trigger deployment of entire compass-deployment artifact.


package uk.ac.ebi.quickgo.annotation.service.search;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationFields;
import uk.ac.ebi.quickgo.common.SearchableDocumentFields;
import uk.ac.ebi.quickgo.rest.search.SearchableField;

import java.util.stream.Stream;
import org.springframework.stereotype.Component;

/**
 * Checks if a given field is searchable searchable.
 *
 * @author Ricardo Antunes
 */
@Component
public class AnnotationSearchableField implements SearchableField, SearchableDocumentFields {
    @Override public boolean isDocumentSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }

    @Override public Stream<String> searchableDocumentFields() {
        return AnnotationFields.Searchable.searchableFields().stream();
    }

    @Override public boolean isSearchable(String field) {
        return AnnotationFields.Searchable.isSearchable(field);
    }
}

Create a class that is responsible for indicating when a field is searchable or not.


package com.rchab.menshykov.increasingsequence.advancedcase;

import org.junit.Test;

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

public class AppAdvancedTest {

    @Test
    public void testLogSet() {
        List<Integer> inputList = new ArrayList<>();
        int size = 10000;
        for (int i = 0; i < size; i++) {
            Random random = new Random();
            inputList.add(random.nextInt(size));
//            inputList.add(i+1);
        }
//        System.out.println(inputList);
        long startTime = System.currentTimeMillis();
        Sequence sequence = new Sequence(inputList);

        final List<Integer> result = sequence.getLastSequenceElement().getIntegerSequent();
        long endTime = System.currentTimeMillis();
        long totalTime = endTime - startTime;
        System.out.println("totalTime: " + totalTime + "; size=" + result.size());
        System.out.println(result);
    }
}

Add test for performance check


package io.dongyue.at15.tree.server.controllers;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by at15 on 16-1-2.
 */
@RestController
//@RequestMapping("/meta")
public class MetaController {
    //    @RequestMapping("/")
    @RequestMapping("/meta")
    public String index() {
        // TODO: should list all meta
        return "please specify which meta you need";
    }

    @RequestMapping("/{table}/meta")
    public String meta(@PathVariable String table) {
        return table;
    }
}

Add route param for meta