/*
 * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
 *
 * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
 */

package org.openlmis.web.controller.vaccine;

import org.openlmis.vaccine.dto.FacilityDemographicEstimateForm;
import org.openlmis.vaccine.service.demographics.FacilityDemographicEstimateService;
import org.openlmis.web.controller.BaseController;
import org.openlmis.web.response.OpenLmisResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/vaccine/demographic/estimate/facility/")
public class FacilityDemographicEstimateController extends BaseController {

  @Autowired
  FacilityDemographicEstimateService service;

  @RequestMapping("get")
  public ResponseEntity<OpenLmisResponse> get( @RequestParam("year") Integer year, @RequestParam("programId") Long programId,  HttpServletRequest request){
    return OpenLmisResponse.response("estimates", service.getEstimateFor(loggedInUserId(request), programId, year));
  }

  @RequestMapping("save")
  public ResponseEntity<OpenLmisResponse> save(@RequestBody FacilityDemographicEstimateForm form,  HttpServletRequest request){
    service.save(form);
    return OpenLmisResponse.response("estimates", form);
  }

}

Create facility demographic estimate controller


package org.apache.commons.vfs2.provider;

import junit.framework.Assert;

import org.junit.Test;

public class UriParserTestCase
{

    @Test
    public void testColonInFileName()
    {
        Assert.assertEquals(null, UriParser.extractScheme("some/path/some:file"));
    }

    @Test
    public void testNormalScheme()
    {
        Assert.assertEquals("ftp", UriParser.extractScheme("ftp://user:pass@host/some/path/some:file"));
    }

}

Add some simple tests to make sure extract scheme behaves as expected.

git-svn-id: c455d203a03ec41bf444183aad31e7cce55db786@1237945 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Copyright (c) 2017, Rockwell Collins.
 *
 * Developed with the sponsorship of Defense Advanced Research Projects Agency
 * (DARPA).
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this data, including any software or models in source or binary form, as
 * well as any drawings, specifications, and documentation (collectively
 * "the Data"), to deal in the Data without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute,
 * sublicense, and/or sell copies of the Data, and to permit persons to whom the
 * Data 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 Data.
 *
 * THE DATA 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, SPONSORS, DEVELOPERS, CONTRIBUTORS, 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 DATA OR THE
 * USE OR OTHER DEALINGS IN THE DATA.
 */

package com.rockwellcollins.atc.agree.unparsing;

import org.eclipse.xtext.serializer.ISerializer;
import org.osate.aadl2.AnnexLibrary;
import org.osate.aadl2.AnnexSubclause;
import org.osate.annexsupport.AnnexUnparser;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.rockwellcollins.atc.agree.agree.AgreeContract;
import com.rockwellcollins.atc.agree.serializer.AgreeSerializer;
import com.rockwellcollins.atc.agree.ui.internal.AgreeActivator;

public class AgreeAnnexUnparser implements AnnexUnparser {
    @Inject private ISerializer serializer;

    protected ISerializer getSerializer() {
        if (serializer == null) {
            Injector injector = AgreeActivator.getInstance().getInjector(
                    AgreeActivator.COM_ROCKWELLCOLLINS_ATC_AGREE_AGREE);
            serializer = injector.getInstance(AgreeSerializer.class);
        }
        return serializer;
    }

	@Override
	public String unparseAnnexLibrary(AnnexLibrary library, String indent) {
		return indent + getSerializer().serialize(library);
	}

	@Override
	public String unparseAnnexSubclause(AnnexSubclause subclause, String indent) {
		return indent + getSerializer().serialize(subclause);
	}

	public String unparseContract(AgreeContract agreeContract, String indent) {
		return indent + getSerializer().serialize(agreeContract);
	}

}

Add unparser for serializing out with OSATE


package org.mutabilitydetector.runtime;

import org.mutabilitydetector.AnalysisResult;
import org.mutabilitydetector.AnalysisSession;
import org.mutabilitydetector.IsImmutable;
import org.mutabilitydetector.ThreadUnsafeAnalysisSession;
import org.mutabilitydetector.AnalysisSession.RequestedAnalysis;
import org.mutabilitydetector.locations.Dotted;

public final class RuntimeAnalysisExample {
    private final AnalysisSession analysisSession = ThreadUnsafeAnalysisSession.createWithCurrentClassPath();

    private void run(Object requiredToBeImmutable) {
        RequestedAnalysis requestedAnalysis = analysisSession.resultFor(Dotted.fromClass(requiredToBeImmutable.getClass()));
        AnalysisResult result = requestedAnalysis.result;
        if(result.isImmutable.equals(IsImmutable.IMMUTABLE)) {
            // rest safe in the knowledge the class is immutable, share across threads with joyful abandon
        } else if(result.isImmutable.equals(IsImmutable.NOT_IMMUTABLE)) {
            // be careful here: make defensive copies, don't publish the reference, read Java Concurrency In Practice right away!
        }
    }

    public static void main(String[] args) {
        new RuntimeAnalysisExample().run(makeParam());
    }

    private static Object makeParam() {
        return new java.util.Date();
    }

}

Add an example of using mutability detector at runtime.

git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@618 c7a0535c-eda6-11de-83d8-6d5adf01d787


package org.robockets.stronghold.robot.highgoalshooter;

import org.robockets.stronghold.robot.Robot;

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

/**
 * Enable the PIDController for the hood part of the high goal shooter subsystem.
 */
public class EnableTurnTablePID extends Command {

    public EnableTurnTablePID() {
        requires(Robot.shooter);
    }

    protected void initialize() {
    }

    protected void execute() {
    	Robot.shooter.turnTablePidController.enable();
    }

    protected boolean isFinished() {
        return false;
    }

    protected void end() {
    	Robot.shooter.turnTablePidController.disable();
    }

    protected void interrupted() {
    }
}

Add turn table enable PID.

Add turn table enable PID.


/*
 * Copyright (c) 2015 Cisco Systems, Inc. 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
 */
package org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.schemas.Schema.Location;

/**
 * The purpose of generated class in src/main/java for Union types is to create new instances of unions from a string representation.
 * In some cases it is very difficult to automate it since there can be unions such as (uint32 - uint16), or (string - uint32).
 *
 * The reason behind putting it under src/main/java is:
 * This class is generated in form of a stub and needs to be finished by the user. This class is generated only once to prevent
 * loss of user code.
 */
public class SchemaLocationBuilder {

    public static Location getDefaultInstance(final String defaultValue) {
        throw new java.lang.UnsupportedOperationException("Not yet implemented");
    }

}

Add missing union type builder

Add missing union type builder

This type was missing and should not be generated over and over again.

Change-Id: Ife3e97c2c639e29ca2115429b53e6dec62440db7
Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>


/*
 * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.api.rest.validation;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 * @since 6.13
 */
@JsonPropertyOrder({"ruleId", "ruleDescription","affectedComponentId", "label"})
public class ValidationIssueReport {

	private String ruleId;
	private String ruleDescription;
	private String affectedComponentId;

	@JsonProperty(value="label")
	private String affectedComponentLabel;

	public ValidationIssueReport(String ruleId, String ruleDescription, String affectedComponentId, String affectedComponentLabel) {
		this.ruleId = ruleId;
		this.ruleDescription = ruleDescription;
		this.affectedComponentId = affectedComponentId;
		this.affectedComponentLabel = affectedComponentLabel;
	}

	public String getRuleId() {
		return ruleId;
	}

	public void setRuleId(String ruleId) {
		this.ruleId = ruleId;
	}

	public String getRuleDescription() {
		return ruleDescription;
	}

	public void setRuleDescription(String ruleDescription) {
		this.ruleDescription = ruleDescription;
	}

	public String getAffectedComponentId() {
		return affectedComponentId;
	}

	public void setAffectedComponentId(String affectedComponentId) {
		this.affectedComponentId = affectedComponentId;
	}

	public String getAffectedComponentLabel() {
		return affectedComponentLabel;
	}

	public void setAffectedComponentLabel(String affectedComponentLabel) {
		this.affectedComponentLabel = affectedComponentLabel;
	}

}

SO-3379: Add POJO class for easier CSV conversion


package uk.ac.ed.inf.Metabolic.ndomAPI;

import java.util.List;

public interface IModel extends IModelObject {
	public List<ICompartment> getCompartmentList();

	public List<IReaction> getReactionList();
}

package uk.ac.ed.inf.Metabolic.ndomAPI;

import java.util.List;

public interface IModel extends IModelObject {
	public List<ICompartment> getCompartmentList();

	public List<IReaction> getReactionList();

	//Defined properties dictionaries
	public List<String> getECnumberList();

	public List<String> getSmilesList();

	public List<String> getRoleList();

	public List<String> getCIDList();

	public List<String> getChEBIList();

	public List<String> getPubChemList();

	public List<String> getInChIList();

	public List<String> getGOTermList();

/*
//getters for object from property
 	public List<String> get();

	public List<String> get();

	public List<String> get();

	public List<String> get();

*/
}

Add getters, based upon properties values


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

import com.intellij.CommonBundle;
import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Ref;
import com.intellij.ui.GuiUtils;
import com.intellij.util.ObjectUtil;
import consulo.logging.Logger;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.lang.reflect.InvocationTargetException;

public class IOExceptionDialog extends DialogWrapper {
  private static final Logger LOG = Logger.getInstance(IOExceptionDialog.class);
  private final JTextArea myErrorLabel;

  public IOExceptionDialog(String title, String errorText)  {
    super((Project)null, true);
    setTitle(title);
    setOKButtonText(CommonBundle.message("dialog.ioexception.tryagain"));

    myErrorLabel = new JTextArea();
    myErrorLabel.setText(errorText);
    myErrorLabel.setFont(UIManager.getFont("Label.font"));
    myErrorLabel.setBackground(UIManager.getColor("Label.background"));
    myErrorLabel.setForeground(UIManager.getColor("Label.foreground"));

    init();
  }

  @Nullable
  @Override
  protected JComponent createCenterPanel() {
    return myErrorLabel;
  }

  @Nonnull
  @Override
  protected Action[] createLeftSideActions() {
    return new Action[] {
      new AbstractAction(CommonBundle.message("dialog.ioexception.proxy")) {
        @Override
        public void actionPerformed(@Nonnull ActionEvent e) {
          ShowSettingsUtil.getInstance().editConfigurable(ObjectUtil.tryCast(e.getSource(), JComponent.class), new HttpProxyConfigurable());
        }
      }
    };
  }

  /**
   * Show the dialog
   * @return true if "Try Again" button pressed and false if "Cancel" button pressed
   */
  public static boolean showErrorDialog(final String title, final String text) {
    final Ref<Boolean> ok = Ref.create(false);
    try {
      GuiUtils.runOrInvokeAndWait(new Runnable() {
        @Override
        public void run() {
          IOExceptionDialog dialog = new IOExceptionDialog(title, text);
          dialog.show();
          ok.set(dialog.isOK());
        }
      });
    }
    catch (InterruptedException e) {
      LOG.info(e);
    }
    catch (InvocationTargetException e) {
      LOG.info(e);
    }

    return ok.get();
  }
}

Revert "drop old io exception dialog"

Revert "drop old io exception dialog"

This reverts commit 48d33bf0fee6f5b304fa73ac783d942ecda932ec.


package org.roklib.urifragmentrouting.parameter;

import org.junit.Test;
import org.roklib.urifragmentrouting.exception.ParameterValueConversionException;
import org.roklib.urifragmentrouting.parameter.converter.AbstractParameterValueConverterTest;
import org.roklib.urifragmentrouting.parameter.converter.ParameterValueConverter;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;

public class IdWithTextParameterValueConverterTest extends AbstractParameterValueConverterTest<SingleLongWithIgnoredTextUriParameter.IdWithText> {
    @Override
    protected ParameterValueConverter<SingleLongWithIgnoredTextUriParameter.IdWithText> getConverter() {
        return SingleLongWithIgnoredTextUriParameter.IdWithTextParameterValueConverter.INSTANCE;
    }

    @Override
    protected SingleLongWithIgnoredTextUriParameter.IdWithText getExpectedValue() {
        return new SingleLongWithIgnoredTextUriParameter.IdWithTextImpl(123L, "_text");
    }

    @Override
    protected String getStringForExpectedValue() {
        return "123_text";
    }

    @Override
    protected String getInvalidStringValue() {
        return "string";
    }

    @Test
    public void testConvertToString_id_is_null() throws Exception {
        final SingleLongWithIgnoredTextUriParameter.IdWithText idWithText = new SingleLongWithIgnoredTextUriParameter.IdWithTextImpl();
        final String convertedToString = getConverter().convertToString(idWithText);
        assertThat(convertedToString, is(""));
    }

    @Test(expected = ParameterValueConversionException.class)
    public void testConvertToValue_with_invalid_number() throws Exception {
        getConverter().convertToValue("99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999_text");
    }
}

Add unit tests for IdWithTextParameterValueConverter


package com.yahoo.config.model.api.container;

import org.junit.Test;

import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.LOGSERVER_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static com.yahoo.config.model.api.container.ContainerServiceType.QRSERVER;
import static org.junit.Assert.assertEquals;

/**
 * @author gjoranv
 */
public class ContainerServiceTypeTest {

    @Test
    public void new_values_are_not_added_without_updating_tests() {
        assertEquals(5, ContainerServiceType.values().length);
    }

    @Test
    public void service_names_do_not_change() {
        assertEquals("container", CONTAINER.serviceName);
        assertEquals("qrserver", QRSERVER.serviceName);
        assertEquals("container-clustercontroller", CLUSTERCONTROLLER_CONTAINER.serviceName);
        assertEquals("logserver-container", LOGSERVER_CONTAINER.serviceName);
        assertEquals("metrics-proxy-container", METRICS_PROXY_CONTAINER.serviceName);
    }

}

Add unit test to ensure names don't change.


package com.jmb.springfactory.controller.api;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jmb.springfactory.exceptions.NotFoundException;
import com.jmb.springfactory.exceptions.ServiceLayerException;
import com.jmb.springfactory.model.bo.QueryTaskObject;
import com.jmb.springfactory.model.dto.TaskDto;
import com.jmb.springfactory.service.task.TaskService;

@RestController
@RequestMapping("/group/{groupId}/task")
public class GroupTaskController {

    @Autowired
    private TaskService taskService;

    @PostMapping
    public TaskDto create(@Valid @RequestBody TaskDto task, @PathVariable("groupId") Integer groupId)
            throws NotFoundException, ServiceLayerException {
        return taskService.saveByGroup(task, groupId);
    }

    @DeleteMapping("/{taskId}")
    public void delete(@PathVariable("taskId") Integer taskId) {
        taskService.delete(taskId);
    }

    @GetMapping
    public List<TaskDto> findAll(@PathVariable("groupId") Integer groupId) {
        final QueryTaskObject queryTask = QueryTaskObject.builder().groupId(groupId).build();
        return taskService.findAll(queryTask);
    }
}

Create controller to manage group tasks

Create controller to manage group tasks


// Copyright (C) 2016 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.gerrit.acceptance.rest.change;

import static com.google.common.truth.Truth.assertThat;

import com.google.gerrit.acceptance.AbstractDaemonTest;
import com.google.gerrit.acceptance.RestResponse;
import com.google.gerrit.acceptance.PushOneCommit.Result;

import org.apache.http.HttpStatus;
import org.junit.Test;

public class TopicIT extends AbstractDaemonTest {
  @Test
  public void topic() throws Exception {
    Result result = createChange();
    String endpoint = "/changes/" + result.getChangeId() + "/topic";
    RestResponse response = adminSession.put(endpoint, "topic");
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    response = adminSession.delete(endpoint);
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_NO_CONTENT);

    response = adminSession.put(endpoint, "topic");
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_OK);

    response = adminSession.put(endpoint, "");
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.SC_NO_CONTENT);
  }
}

Test that deleting topic returns HTTP status 204

Bug: Issue 4237
Change-Id: Ie345dfc1b1161d9892cc58a18a76bbb6e2a39220


package io.jean_eudes.maven;

import static org.apache.maven.plugins.annotations.LifecyclePhase.POST_INTEGRATION_TEST;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import kafka.admin.AdminUtils;
import kafka.utils.ZkUtils;
import scala.collection.*;
import scala.collection.Iterable;

@Mojo(name = "deleteAllTopics",
      defaultPhase = POST_INTEGRATION_TEST,
      threadSafe = true)
public class KafkaDeleteAllTopicsExecuteMojo extends AbstractMojo {

    @Parameter(property = "zookeeper.host", defaultValue = "localhost")
    private String zookeeperHost;

    @Parameter(property = "zookeeper.port", defaultValue = "2181")
    private int zookeeperPort;

    public void execute() throws MojoExecutionException, MojoFailureException {
        ZkUtils zkUtils = ZkUtils.apply(String.format("%s:%d", zookeeperHost, zookeeperPort), 10000, 10000, false);

        Iterator<String> stringPropertiesMap = AdminUtils.fetchAllTopicConfigs(zkUtils).keysIterator();

        while (stringPropertiesMap.hasNext()) {
            String topic = stringPropertiesMap.next();

            AdminUtils.deleteTopic(zkUtils, topic);

            long start = System.currentTimeMillis();
            long timeout = 10000;

            while (AdminUtils.topicExists(zkUtils, topic) && (System.currentTimeMillis() - start) < timeout) {

                try {
                    TimeUnit.SECONDS.sleep(100);
                } catch (InterruptedException e) {
                    getLog().warn(e);
                }
            }

            if ((System.currentTimeMillis() - start) > timeout) {
                getLog().warn(String.format("Topic '%s' deletion failed", topic));
            }

        }

    }

}

Add maven goal to delete all topics.

Add maven goal to delete all topics.


package com.github.havarunner.beforeafter;

import com.github.havarunner.HavaRunner;
import com.github.havarunner.annotation.AfterAll;
import org.junit.Test;
import org.junit.runner.notification.RunNotifier;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class AfterAllFails {

    @Test
    public void HavaRunner_will_propagate_AfterAll_exceptions() {
        try {
            new HavaRunner(WithAfterAll.class).run(new RunNotifier());
            fail("Should have thrown an exception");
        } catch (Exception e) {
            assertEquals(IllegalArgumentException.class, e.getCause().getClass());
        }
    }

    static class WithAfterAll {
        @Test
        void test() {}

        @AfterAll
        void afterAll() {
            throw new IllegalArgumentException("Expected");
        }
    }
}

Add spec for @AfterAll failures

Add spec for @AfterAll failures


package seedu.address.commons.events.ui;

import seedu.address.commons.events.BaseEvent;

public class LeftPanelTodaySelectionChangedEvent extends BaseEvent {

    public LeftPanelTodaySelectionChangedEvent() {}

    @Override
    public String toString() {
        return this.getClass().getSimpleName();
    }
}

Add event for today selection at left panel


package mir.responses.responsesAllElementTypesToAllElementTypes.simpleChangesTests;

import allElementTypes.Root;
import org.eclipse.emf.ecore.EObject;
import tools.vitruv.extensions.dslsruntime.response.AbstractResponseRealization;
import tools.vitruv.framework.change.echange.EChange;
import tools.vitruv.framework.change.echange.feature.attribute.ReplaceSingleValuedEAttribute;
import tools.vitruv.framework.userinteraction.UserInteracting;

@SuppressWarnings("all")
class SetSingleValuedEAttributeResponse extends AbstractResponseRealization {
  public SetSingleValuedEAttributeResponse(final UserInteracting userInteracting) {
    super(userInteracting);
  }

  public static Class<? extends EChange> getExpectedChangeType() {
    return ReplaceSingleValuedEAttribute.class;
  }

  private boolean checkChangeProperties(final ReplaceSingleValuedEAttribute<Root, Integer> change) {
    EObject changedElement = change.getAffectedEObject();
    // Check model element type
    if (!(changedElement instanceof Root)) {
    	return false;
    }

    // Check feature
    if (!change.getAffectedFeature().getName().equals("singleValuedEAttribute")) {
    	return false;
    }
    return true;
  }

  public boolean checkPrecondition(final EChange change) {
    if (!(change instanceof ReplaceSingleValuedEAttribute<?, ?>)) {
    	return false;
    }
    ReplaceSingleValuedEAttribute typedChange = (ReplaceSingleValuedEAttribute)change;
    if (!checkChangeProperties(typedChange)) {
    	return false;
    }
    getLogger().debug("Passed precondition check of response " + this.getClass().getName());
    return true;
  }

  public void executeResponse(final EChange change) {
    ReplaceSingleValuedEAttribute<Root, Integer> typedChange = (ReplaceSingleValuedEAttribute<Root, Integer>)change;
    mir.routines.simpleChangesTests.SetSingleValuedEAttributeEffect effect = new mir.routines.simpleChangesTests.SetSingleValuedEAttributeEffect(this.executionState, this, typedChange);
    effect.applyRoutine();
  }
}

Add missing generated response test class.


package org.codingmatters.poom.services.domain.repositories.inmemory;

import org.codingmatters.poom.services.domain.property.query.PropertyQuery;
import org.codingmatters.poom.services.domain.repositories.Repository;
import org.codingmatters.poom.servives.domain.entities.PagedEntityList;
import org.codingmatters.test.Ref;
import org.codingmatters.test.Simple;
import org.codingmatters.test.simple.E;
import org.junit.Before;
import org.junit.Test;

public class InMemoryRepositoryWithPropertyQuerySortTest {

    private Repository<Simple, PropertyQuery> repository = InMemoryRepositoryWithPropertyQuery.validating(Simple.class);

    @Before
    public void setUp() throws Exception {
        System.out.println("***INSERTION***");
        for (long i = 0; i < 50; i++) {
            Simple build = Simple.builder()
                    .a( i )
                    .e( E.builder()
                            .f( i % 4 > 1 ? "wb" : "wa" )
                            .g( i % 2 == 0 ? "fa" : "fb" )
                            .build() )
                    .ref( Ref.builder().a( i ).build() )
                    .build();
            System.out.println( "f=" + build.e().f() + "\tg=" + build.e().g() );
            this.repository.create( build );
        }
    }

    @Test
    public void test() throws Exception {
        String sort = "e.f asc , e.g asc";
        System.out.println("***TRI => " + sort + " \t***");
        PagedEntityList<Simple> search = this.repository.search( PropertyQuery.builder().sort( sort ).build(), 0, 1005 );
        search.stream().forEach( s -> System.out.println( "f=" + s.value().e().f() + "\tg=" + s.value().e().g() ) );

    }
}

Add test case with multiple sort

Add test case with multiple sort


package org.apereo.cas.configuration.model.core.authentication;

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

/**
 * This is {@link AuthenticationExceptionsProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */

public class AuthenticationExceptionsProperties {
    private List exceptions = new ArrayList<>();

    public List getExceptions() {
        return exceptions;
    }

    public void setExceptions(final List exceptions) {
        this.exceptions = exceptions;
    }
}

package org.apereo.cas.configuration.model.core.authentication;

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

/**
 * This is {@link AuthenticationExceptionsProperties}.
 *
 * @author Misagh Moayyed
 * @since 5.0.0
 */

public class AuthenticationExceptionsProperties {
    private List<Class<? extends Exception>> exceptions = new ArrayList<>();

    public List<Class<? extends Exception>> getExceptions() {
        return exceptions;
    }

    public void setExceptions(final List<Class<? extends Exception>> exceptions) {
        this.exceptions = exceptions;
    }
}

Fix generic type enforcement for exceptions


package com.example.todocloud.listener;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerViewOnItemTouchListener implements RecyclerView.OnItemTouchListener {

  private ClickListener clickListener;
  private GestureDetector gestureDetector;

  public RecyclerViewOnItemTouchListener(
      Context context,
      final RecyclerView recyclerView,
      final ClickListener clickListener
  ) {
    this.clickListener = clickListener;
    gestureDetector = new GestureDetector(
        context,
        new GestureDetector.SimpleOnGestureListener() {

          @Override
          public boolean onSingleTapUp(MotionEvent e) {
            return true;
          }

          @Override
          public void onLongPress(MotionEvent e) {
            View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
            int childViewAdapterPosition = recyclerView.getChildAdapterPosition(childView);
            if (childView != null && clickListener != null) {
              clickListener.onLongClick(childView, childViewAdapterPosition);
            }
          }

        }
    );
  }

  @Override
  public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
    View childView = rv.findChildViewUnder(e.getX(), e.getY());
    int childViewAdapterPosition = rv.getChildAdapterPosition(childView);
    if (childView != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
      clickListener.onClick(childView, childViewAdapterPosition);
    }
    return false;
  }

  @Override
  public void onTouchEvent(RecyclerView rv, MotionEvent e) {

  }

  @Override
  public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

  }

  public interface ClickListener {
    void onClick(View childView, int childViewAdapterPosition);
    void onLongClick(View childView, int childViewAdapterPosition);
  }

}

Implement RecyclerView touch event handling


// BSD License (http://lemurproject.org/galago-license)
package org.lemurproject.galago.core.parse.stem;

import org.tartarus.snowball.ext.arabicStemmer;

public class SnowballArabicStemmer extends Stemmer {

  arabicStemmer stemmer = new arabicStemmer();

  @Override
  protected String stemTerm(String term) {
    String stem = term;
    stemmer.setCurrent(term);
    if (stemmer.stem()) {
      stem = stemmer.getCurrent();
    }
    return stem;
  }
}

Update snowball and add arabic and tamil stemmers


import junit.framework.TestCase;

import traildb.*;

import java.util.UUID;
import java.io.FileNotFoundException;

public class TestUUIDs extends TestCase {
	UUID cookie1;
	UUID cookie2;
	protected void setUp() throws FileNotFoundException {
		TrailDBConstructor cons = new TrailDBConstructor("test", new String[] {"user", "action"});

		cookie1 = UUID.randomUUID();
		cookie2 = UUID.randomUUID();

		cons.add(cookie1, 1, new String[] {"bob", "run"});
		cons.add(cookie2, 2, new String[] {"fred", "walk"});
		cons.add(cookie1, 4, new String[] {"jerry", "speak"});
		cons.add(cookie1, 5, new String[] {"ted", "fly"});
		cons.add(cookie2, 6, new String[] {"doug", "dab"});

		cons.finalize();
		cons.close();
	}

	public void testBasic() throws FileNotFoundException {
		TrailDB tdb = new TrailDB("test.tdb");
		long numCookies = tdb.numTrails();

		for (long i=0; i < numCookies; i++) {
			UUID uuid = tdb.getUUID(i);

			long tid = tdb.getTrailId(uuid);
			assertEquals(i, tid);

			assertTrue(uuid.equals(cookie1) || uuid.equals(cookie2));
		}
	}
}

Add unit test for uuid stuff

Add unit test for uuid stuff


package ca.uhn.fhir.rest.param;

import static org.junit.Assert.assertTrue;

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

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.api.QualifiedParamList;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;

@RunWith(JUnit4.class)
public class DateRangeParamTest {
	private FhirContext fhirContext;

	@Before
	public void initMockContext() {
		fhirContext = Mockito.mock(FhirContext.class);
	}

	/** Can happen e.g. when the query parameter for {@code _lastUpdated} is left empty. */
	@Test
	public void testParamWithoutPrefixAndWithoutValue() {
		QualifiedParamList qualifiedParamList = new QualifiedParamList(1);
		qualifiedParamList.add("");

		List<QualifiedParamList> params = new ArrayList<>(1);
		params.add(qualifiedParamList);
		DateRangeParam dateRangeParam = new DateRangeParam();
		dateRangeParam.setValuesAsQueryTokens(fhirContext, "_lastUpdated", params);

		assertTrue(dateRangeParam.isEmpty());
	}

	/** Can happen e.g. when the query parameter for {@code _lastUpdated} is given as {@code lt} without any value. */
	@Test
	public void testUpperBoundWithPrefixWithoutValue() {
		QualifiedParamList qualifiedParamList = new QualifiedParamList(1);
		qualifiedParamList.add("lt");

		List<QualifiedParamList> params = new ArrayList<>(1);
		params.add(qualifiedParamList);
		DateRangeParam dateRangeParam = new DateRangeParam();
		dateRangeParam.setValuesAsQueryTokens(fhirContext, "_lastUpdated", params);

		assertTrue(dateRangeParam.isEmpty());
	}

	/** Can happen e.g. when the query parameter for {@code _lastUpdated} is given as {@code gt} without any value. */
	@Test
	public void testLowerBoundWithPrefixWithoutValue() {
		QualifiedParamList qualifiedParamList = new QualifiedParamList(1);
		qualifiedParamList.add("gt");

		List<QualifiedParamList> params = new ArrayList<>(1);
		params.add(qualifiedParamList);
		DateRangeParam dateRangeParam = new DateRangeParam();
		dateRangeParam.setValuesAsQueryTokens(fhirContext, "_lastUpdated", params);

		assertTrue(dateRangeParam.isEmpty());
	}
}

Add some test demonstrating null pointer problems in the DateRangeParam class


package com.uet.beman;

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

/**
 * Created by thanhpd on 3/12/2015.
 */
public class GroupNode extends Node {

    private List<Node> childNode = new ArrayList<Node>();

    public GroupNode() {
    }

    public GroupNode(int id, String message, int parentId, List<Node> childNode) {
        super(id, message, parentId);
        setChildNodeList(childNode);
    }

    public GroupNode(int id) { super(id, null, 0); }

    public List<Node> getChildNodeList() { return childNode; }

    public void setChildNodeList(List<Node> childNode) { this.childNode = childNode; }

    public boolean isSentenceNode() { return false; }

    public List<GroupNode> getGroupGroupNode() {
        List<GroupNode> result = new ArrayList<>();
        for (Node i:childNode) {
            if (!i.isSentenceNode()) result.add((GroupNode) i);
        }
        return result;
    }

    public List<SentenceNode> getGroupSentenceNode() {
        List<SentenceNode> result = new ArrayList<SentenceNode>();
        for (Node i:childNode) {
            if (i.isSentenceNode()) result.add((SentenceNode) i);
        }
        return result;
    }
}

Add data structure for storing schedule message


package com.joliciel.talismane.tokeniser.filters;

import java.util.Set;
import java.util.regex.Pattern;

import com.joliciel.talismane.TalismaneSession;
import com.joliciel.talismane.tokeniser.Token;
import com.joliciel.talismane.tokeniser.TokenSequence;

/**
 * Systematically lowercase the first alphabetic word of a sentence, unless it
 * is in all caps.
 */
public class LowercaseFirstWordFilter implements TokenFilter {
  private final TalismaneSession session;

  private static final Pattern alphaPattern = Pattern.compile("\\p{L}.*", Pattern.UNICODE_CHARACTER_CLASS);
  private static final Pattern punctuation = Pattern.compile("[:;]", Pattern.UNICODE_CHARACTER_CLASS);

  public LowercaseFirstWordFilter(TalismaneSession session) {
    this.session = session;
  }

  @Override
  public void apply(TokenSequence tokenSequence) {
    boolean lowerNextWord = true;
    for (Token token : tokenSequence) {
      String word = token.getText();
      if (lowerNextWord && alphaPattern.matcher(word).matches()) {
        if (Character.isUpperCase(word.charAt(0)) && (word.length() == 1 || !word.equals(word.toUpperCase()))) {
          Set<String> possibleWords = session.getDiacriticizer().diacriticize(word);
          if (possibleWords.size() > 0)
            token.setText(possibleWords.iterator().next());
          else
            token.setText(word.toLowerCase());
        }
        lowerNextWord = false;
      } else if (punctuation.matcher(word).matches()) {
        lowerNextWord = true;
      }
    } // next token
  }
}

Add lowercase first word filter

Add lowercase first word filter


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

import com.facebook.presto.hive.metastore.ExtendedHiveMetastore;
import com.facebook.presto.hive.metastore.thrift.BridgingHiveMetastore;
import com.facebook.presto.hive.metastore.thrift.InMemoryHiveMetastore;

import java.io.File;

public class TestHiveClientInMemoryMetastore
        extends AbstractTestHiveClientLocal
{
    @Override
    protected ExtendedHiveMetastore createMetastore(File tempDir)
    {
        File baseDir = new File(tempDir, "metastore");
        InMemoryHiveMetastore hiveMetastore = new InMemoryHiveMetastore(baseDir);
        return new BridgingHiveMetastore(hiveMetastore);
    }

    @Override
    public void testMetadataDelete()
    {
        // InMemoryHiveMetastore ignores "removeData" flag in dropPartition
    }

    @Override
    public void testTransactionDeleteInsert()
    {
        // InMemoryHiveMetastore does not check whether partition exist in createPartition and dropPartition
    }
}

Add unit test for InMemoryMetastore

Add unit test for InMemoryMetastore

InMemoryMetastore is a mock implementation of HiveMetastore which is used
to test BridgingHiveMetastore without a real Metastore.


package org.skywalking.apm.agent.core.context;

import java.util.Map;
import org.junit.Assert;
import org.junit.Test;

/**
 * @author wusheng
 */
public class LeafSpanTestCase {
    @Test
    public void testLeaf() {
        LeafSpan span = new LeafSpan(0, "serviceA", System.currentTimeMillis());
        span.push();
        span.setOperationName("serviceA2");
        span.setTag("key", "value-text");
        span.setTag("key2", false);
        span.setTag("key3", 1);

        //start 2nd span
        span.push();

        Assert.assertFalse(span.isFinished());
        Assert.assertTrue(span.isLeaf());
        span.setOperationName("service123");
        span.setTag("key", "value-text2");
        span.setTag("key2", true);
        span.setTag("key3", 2);
        Assert.assertEquals("serviceA2", span.getOperationName());
        Assert.assertEquals("value-text", span.getStrTag("key"));
        Assert.assertFalse(span.getBoolTag("key2"));
        Assert.assertEquals(1, span.getIntTag("key3").intValue());

        //end 2nd span
        span.pop();

        span.pop();
        Assert.assertTrue(span.isFinished());
    }
}

Add test case for leaf span.

Add test case for leaf span.


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

import java.util.Set;

import javax.time.calendar.OffsetTime;

import com.opengamma.engine.view.calc.DependencyGraphExecutorFactory;

/**
 * A master for storing batch job runs.
 *

 * This extends {@code BatchMaster} to provide tools to store batches.
 */
public interface BatchRunMaster extends BatchMaster {

  /**
   * Starts the storage of a batch job run.
   *

   * This creates all static data structures, such as compute host, OpenGamma
   * version and risk run. This method must be called before any risk can be
   * written for the batch in question.
   *
   * @param batch  the batch job which is starting, not null
   */
  void startBatch(BatchJobRun batch);

  /**
   * Ends the storage of a batch job run.
   *

   * This marks the batch as complete.
   *
   * @param batch  the batch job which has finished, not null
   */
  void endBatch(BatchJobRun batch);

  //-------------------------------------------------------------------------
  /**
   * Creates a LiveData snapshot in the database.
   * If the snapshot already exists, does nothing.
   *
   * @param snapshotId The date and time of the snapshot, not null
   */
  void createLiveDataSnapshot(SnapshotId snapshotId);

  /**
   * Fixes the time of a LiveData snapshot in the database.
   * For example, the head trader may set the time of LDN_CLOSE every day.
   * One day he may set it at 17:31, the next at 17:44.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @param fix The time to which the observation time was fixed, not null
   */
  void fixLiveDataSnapshotTime(SnapshotId snapshotId, OffsetTime fix);

  /**
   * Adds market data fixings to an existing LiveData snapshot. The
   * snapshot must already exist.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @param values The fixings, not null
   */
  void addValuesToSnapshot(SnapshotId snapshotId, Set<LiveDataValue> values);

  /**
   * Gets all market data fixings associated with an existing snapshot.
   *
   * @param snapshotId The date and time of the snapshot, not null
   * @return The fixings associated with this snapshot, not null
   * @throws IllegalArgumentException If a snapshot with the given
   * ID does not exist
   */
  Set<LiveDataValue> getSnapshotValues(SnapshotId snapshotId);

  /**
   * Gets a factory for executing dependency graphs and
   * writing risk values into the database.
   *

   * The risk is written into the database incrementally,
   * as the dependency graph is being executed. This
   * is useful if you do not already have the results in
   * memory.
   *
   * @param batch The batch job for which results will be written
   * @return A factory used to execute the batch dependency graph
   * and write results into the database.
   */
  DependencyGraphExecutorFactory<?> createDependencyGraphExecutorFactory(BatchJobRun batch);

}

Make batch master more standard

[PLAT-1279] Make batch master more standard

Split BatchMaster and BatchRunMaster


package com.microsoft.azure.services.blob;

import org.junit.Before;
import org.junit.BeforeClass;

import com.microsoft.azure.configuration.Configuration;

public abstract class IntegrationTestBase {
    protected Configuration createConfiguration() {
        Configuration config = new Configuration();
        config.setProperty(BlobConfiguration.ACCOUNT_NAME, "xxx");
        config.setProperty(BlobConfiguration.ACCOUNT_KEY, "xxx");
        config.setProperty(BlobConfiguration.URL, "http://xxx.blob.core.windows.net");

        // when mock running
        // config.setProperty("serviceBus.uri", "http://localhost:8086");
        // config.setProperty("wrapClient.uri",
        // "http://localhost:8081/WRAPv0.9");

        return config;
    }

    @BeforeClass
    public static void initializeSystem() {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }

    @Before
    public void initialize() throws Exception {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }
}

package com.microsoft.azure.services.blob;

import java.util.Map;

import org.junit.Before;
import org.junit.BeforeClass;

import com.microsoft.azure.configuration.Configuration;

public abstract class IntegrationTestBase {
    protected Configuration createConfiguration() {
        Configuration config = new Configuration();
        Map<String, String> env = System.getenv();
        setConfigValue(config, env, BlobConfiguration.ACCOUNT_NAME, "xxx");
        setConfigValue(config, env, BlobConfiguration.ACCOUNT_KEY, "xxx");
        setConfigValue(config, env, BlobConfiguration.URL, "http://xxx.blob.core.windows.net");

        // when mock running
        // config.setProperty("serviceBus.uri", "http://localhost:8086");
        // config.setProperty("wrapClient.uri",
        // "http://localhost:8081/WRAPv0.9");

        return config;
    }

    private void setConfigValue(Configuration config, Map<String, String> props, String key, String defaultValue) {
        String value = props.get(key);
        if (value == null)
            value = defaultValue;

        config.setProperty(key, value);
    }

    @BeforeClass
    public static void initializeSystem() {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }

    @Before
    public void initialize() throws Exception {
        System.out.println("initialize");
        // System.setProperty("http.proxyHost", "itgproxy");
        // System.setProperty("http.proxyPort", "80");
        // System.setProperty("http.keepAlive", "false");
    }
}

Support configuring integration tests with env. variables


package com.custardsource.parfait.benchmark;

import java.util.List;

public class BlockedMetricHelper {
    private BlockedMetricHelper() {
    }

    static long computeTotalBlockedCount(List<BlockedMetricCollector> blockedMetricCollectors) {
        long totalBlockedCount = 0;
        for (BlockedMetricCollector collector : blockedMetricCollectors) {
            totalBlockedCount += collector.getTotalBlockedCount();
        }
        return totalBlockedCount;
    }

    static long computeTotalBlockedTime(List<BlockedMetricCollector> blockedMetricCollectors) {
        long totalBlockedTime = 0;
        for (BlockedMetricCollector collector : blockedMetricCollectors) {
            totalBlockedTime += collector.getTotalBlockedTime();
        }
        return totalBlockedTime;
    }
}

Introduce helper methods for calculating standard metrics across tests.


package won.node.service.linkeddata.generate;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;
import org.apache.jena.vocabulary.RDFS;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.util.StopWatch;

import won.protocol.util.CheapInsecureRandomString;

@Ignore
public class RdfManipulationSpeedTest {
    CheapInsecureRandomString rnd = new CheapInsecureRandomString();

    /**
     * Shows: adding to model is relatively stable, performance degrades somewhat.
     */
    @Test
    public void testAddToModel() {
        StopWatch sw = new StopWatch();
        for (int i = 0; i < 1000; i += 10) {
            Model m = ModelFactory.createDefaultModel();
            Resource main = m.getResource("uri:/main");
            int count = i * 1000;
            List<URI> uris = generateURIs(count);
            sw.start();
            addToModel(m, main, uris);
            sw.stop();
            long millis = sw.getLastTaskTimeMillis();
            System.out.println("Adding " + count + " uris takes " + millis + " millis, that's "
                            + (double) millis / ((double) count / 1000) + " per 1000 uris");
        }
    }

    @Test
    public void testUriCreate() {
        StopWatch sw = new StopWatch();
        sw.start();
        int count = 1000000;
        for (int i = 0; i < count; i++) {
            generateURI();
        }
        sw.stop();
        long millis = sw.getLastTaskTimeMillis();
        System.out.println("Creating " + count + " uris takes " + millis + " millis, that's "
                        + (double) millis / ((double) count / 1000) + " per 1000 uris");
        sw.start();
        for (int i = 0; i < count; i++) {
            generateURIString();
        }
        sw.stop();
        millis = sw.getLastTaskTimeMillis();
        System.out.println("Creating " + count + " uri strings takes " + millis + " millis, that's "
                        + (double) millis / ((double) count / 1000) + " per 1000 uris");
    }

    private Model addToModel(Model m, Resource main, List<URI> uris) {
        uris.forEach(uri -> m.add(main, RDFS.member, m.getResource(uri.toString())));
        return m;
    }

    private List<URI> generateURIs(int num) {
        return Stream.generate(() -> generateURI()).limit(num).collect(Collectors.toList());
    }

    private URI generateURI() {
        return URI.create("uri:/new-uri/" + rnd.nextString(30));
    }

    private String generateURIString() {
        return "uri:/new-uri/" + rnd.nextString(30);
    }
}

Add small test for checking speed of RDF manipulation


package com.github.aureliano.edocs.app.cmd;

import com.github.aureliano.edocs.app.EdocsApp;
import com.github.aureliano.edocs.app.gui.HelpDialog;

public class OpenAboutDialogCommand implements ICommand {

	@Override
	public void execute() {
		if (!this.canExecute()) {
			return;
		}

		new HelpDialog(EdocsApp.instance().getFrame()).setVisible(true);
	}

	@Override
	public boolean canExecute() {
		return true;
	}
}

Create open about dialog command.

Create open about dialog command.


package org.fedorahosted.flies.core.action;

import java.util.List;

import javax.persistence.EntityManager;

import org.fedorahosted.flies.core.model.Community;
import org.fedorahosted.flies.core.model.Project;
import org.hibernate.search.jpa.Search;
import org.hibernate.search.jpa.FullTextEntityManager;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;

@Name("searchadmin")
@Scope(ScopeType.EVENT)
public class SearchAdmin {
    @In
	EntityManager entityManager;

    public void resetProjectIndex() throws Exception {
    	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    	List<Project> projects = entityManager.createQuery("select project from Project as project").getResultList();
	 	            for (Project project : projects) {
	                fullTextEntityManager.index(project);
	 	            }

    }

    public void resetCommunityIndex() throws Exception {
    	FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(entityManager);

    	List<Community> communities = entityManager.createQuery("select community from Community as community").getResultList();
	 	            for (Community community : communities) {
	                fullTextEntityManager.index(community);
	 	            }

    }
}

Add re-index component for Project, Community.


package edu.brown.cs.systems.pivottracing.tools;

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

import edu.brown.cs.systems.pivottracing.PTAgentProtos.AgentStatus;
import edu.brown.cs.systems.pivottracing.PTAgentProtos.PivotTracingCommand;
import edu.brown.cs.systems.pivottracing.PivotTracingConfig;
import edu.brown.cs.systems.pubsub.PubSub;
import edu.brown.cs.systems.pubsub.PubSubClient.Subscriber;

/** Just subscribes and prints all query results to stdout */
public class GetAgentStatus extends Subscriber<AgentStatus> {

    @Override
    protected void OnMessage(AgentStatus message) {
        System.out.println(message);
    }

    public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException {
        PubSub.subscribe(PivotTracingConfig.STATUS_TOPIC, new GetAgentStatus());
        while (!Thread.currentThread().isInterrupted()) {
            PubSub.publish(PivotTracingConfig.COMMANDS_TOPIC, PivotTracingCommand.newBuilder().setSendStatus(true).build());
            Thread.sleep(10000);
        }
    }

}

Add tool to print agent status

Add tool to print agent status


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

package com.solsticesquared.schelling.dynamics;

import com.solsticesquared.schelling.move.MovementMethod;

/**
 * Represents a mechanism for defining the types of dynamics (both allowed
 * and to use) for an arbitrary simulation.
 */
public interface SimulationDynamics {

    /**
     * Returns whether or not the dynamics of a simulation allow empty cells
     * in the simulation space.
     *
     * @return Whether or not empty cells are allowed.
     */
    boolean allowsEmptyCells();

    /**
     * Returns whether or not the dynamics of a simulation allow a "happy"
     * agent to search for a new location whose utility is the same as her
     * current neighborhood.
     *
     * @return Whether or not "happy" agents may relocate.
     */
    boolean allowsHappyAgentRelocation();

    /**
     * Returns the {@link MovementMethod} that represents how agents may move
     * around a simulation.
     *
     * @return How agents may move in a simulation space.
     */
    MovementMethod getMovementMethod();
}

Add mechanism for defining simulation dynamics.


/*
 * Copyright 2017 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.
 */
@org.gradle.api.NonNullApi
package org.gradle.util;

Cover `org.gradle.util` with nullability annotations


/**
 * Copyright (C) 2016 Red Hat, 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.redhat.ipaas.rest.v1.handler.integration;

import com.redhat.ipaas.model.integration.Integration;
import com.redhat.ipaas.project.converter.ProjectGenerator;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Component;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/integration-support")
@Api(value = "integration-support")
@Component
public class IntegrationSupportHandler {

    private final ProjectGenerator projectConverter;

    public IntegrationSupportHandler( ProjectGenerator projectConverter) {
        this.projectConverter = projectConverter;
    }

    @POST
    @Path("/generate/pom.xml")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public byte[] projectPom(Integration integration) {
        projectConverter.generatePom(integration);
    }

}

Add a POST /integration-support/generate/pom.xml api endpoint so that the UI can get a pom.xml for the integration currently being edited so it can pass it to the data mapper.


package org.beanmaker.util;

import org.apache.commons.io.FileUtils;

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

public class DbBeanFileFilenameFixes {

    public static void replaceExtraDotsInInternalFilename(DbBeanFile dbBeanFile) throws IOException {
        replaceExtraDotsInInternalFilename(dbBeanFile, "_");
    }

    public static void replaceExtraDotsInInternalFilename(DbBeanFile dbBeanFile, String replacement) throws IOException {
        String[] parts = dbBeanFile.getOrigFilename().split("\\.");
        int length = parts.length;
        if (length <= 2)
            return;

        StringBuilder newFilename = new StringBuilder();
        newFilename.append(parts[0]);
        for (int i = 1; i < length - 1; ++i)
            newFilename.append(replacement).append(parts[i]);
        newFilename.append(".").append(parts[length - 1]);

        safeInternalRename(dbBeanFile, newFilename.toString());
    }

    private static void safeInternalRename(DbBeanFile dbBeanFile, String newFilename) throws IOException {
        File oldFile = dbBeanFile.getFile();
        File newFile = new File(oldFile.getParentFile(), newFilename);
        FileUtils.copyFile(oldFile, newFile);

        dbBeanFile.setOrigFilename(newFilename);
        dbBeanFile.updateDB();

        FileUtils.deleteQuietly(oldFile);
    }

    public static void replaceCharactersInInternalFilename(DbBeanFile dbBeanFile, String regex, String replacement) throws IOException {
        String[] parts = dbBeanFile.getOrigFilename().split(regex);
        int length = parts.length;
        if (length == 1)
            return;

        StringBuilder newFilename = new StringBuilder();
        newFilename.append(parts[0]);
        for (int i = 1; i < length; ++i)
            newFilename.append(replacement).append(parts[i]);

        safeInternalRename(dbBeanFile, newFilename.toString());
    }
}

Create helper class to manage DbBeanFile filenames


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with
 * this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
 * Suite 330, Boston, MA 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.Priority;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check for newlines & tabs in gene descriptions - causes problems for TSV dumping.
 */
public class DescriptionNewlines extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of DescriptionNewlines.
	 */
	public DescriptionNewlines() {

		addToGroup("post_genebuild");
		addToGroup("release");

		setDescription("Check for newlines and tabs in gene descriptions.");

		setPriority(Priority.AMBER);
		setEffect("Will cause problems for TSV file dumping and importing");
		setFix("Remove newlines and tabs; useful SQL for identifying affected genes:\nSELECT g.gene_id, gsi.stable_id, g.description FROM gene g, gene_stable_id gsi WHERE g.gene_id=gsi.gene_id AND (LOCATE('\\n', g.description) > 0 or LOCATE('\\t', g.description) > 0);");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g, gene_stable_id gsi WHERE g.gene_id=gsi.gene_id AND (LOCATE('\n', g.description) > 0 OR LOCATE('\t', g.description) > 0)");

		if (rows > 0) {

			result = false;
			ReportManager.problem(this, con, rows + " genes have newlines and/or tabs in their descriptions");

		} else {

			ReportManager.correct(this, con, "No genes have newlines or tabs in their descriptions");

		}
		return result;

	} // run

	// -------------------------------------------------------------------------

} // DescriptionNewlines


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.test.docker;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Map;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import io.github.bonigarcia.SelenoidConfig;
import io.github.bonigarcia.test.mockito.MockitoExtension;

@ExtendWith(MockitoExtension.class)
public class SelenoidConfigFromHubTest {

    @InjectMocks
    SelenoidConfig selenoidConfig;

    @Test
    @SuppressWarnings("serial")
    void testBrowserConfig() throws IOException {
        String browsersJsonFromProperties = selenoidConfig
                .getBrowsersJsonAsString();

        Gson gson = new Gson();
        Type mapType = new TypeToken<Map<String, Object>>() {
        }.getType();
        Map<String, Object> browserMap = gson
                .fromJson(browsersJsonFromProperties, mapType);

        assertTrue(browserMap.containsKey("chrome"));
        assertTrue(browserMap.containsKey("firefox"));
        assertTrue(browserMap.containsKey("operablink"));
    }

}

Add test to check browser config form Docker Hub


package prope.executables;

import java.nio.file.Paths;

import org.junit.Test;

public class AnalysisWorkflowTests {

	@Test(expected = IllegalArgumentException.class)
	public void testNonExistingDirectory() {
		@SuppressWarnings("unused")
		AnalysisWorkflow sut = new AnalysisWorkflow(Paths.get("foobar"),
				AnalysisType.DEPLOYABILITY);
	}

}

package prope.executables;

import static org.junit.Assert.assertEquals;

import java.nio.file.Paths;
import java.util.List;

import org.junit.Test;

import prope.reporting.ReportEntry;

public class AnalysisWorkflowTests {

	private AnalysisWorkflow sut;

	private final String deployabilityResourcesPath = "src/test/resources/installability/deployment/";

	@Test(expected = IllegalArgumentException.class)
	public void testNonExistingDirectory() {
		sut = new AnalysisWorkflow(Paths.get("foobar"),
				AnalysisType.DEPLOYABILITY);
	}

	@Test
	public void deployabilityAnalysis(){
		sut = new AnalysisWorkflow(Paths.get(deployabilityResourcesPath + "xmlDescriptorWithText.zip"),
				AnalysisType.DEPLOYABILITY);

		List<ReportEntry> results = sut.start().getEntries();
		assertEquals(results.size(),1);

		ReportEntry entry = results.get(0);
		assertEquals(14, getDeploymentEffort(entry));
		assertEquals(2, getEffortOfPackageConstruction(entry));
		assertEquals(12, getDescriptorComplexity(entry));
	}

	private int getDeploymentEffort(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("DE"));
		} else {
			return 0;
		}
	}

	private int getEffortOfPackageConstruction(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("EPC"));
		} else {
			return 0;
		}
	}

	private int getDescriptorComplexity(ReportEntry entry) {
		if (entry != null) {
			return Integer.parseInt(entry.getVariableValue("DDS"));
		} else {
			return 0;
		}
	}
}

Add integration test for deployability analysis


package sorting;

import common.ArrayUtils;

/**
 * Sort an array containing only 0s and/or 1s and/or 2s.
 */
public class Sort012 {

	public static void sort012(int[] array) {
		if (array == null) {
			throw new NullPointerException("You passed a null array.");
		}

		if (array.length == 1) {
			return;
		}

		int twoIndex = array.length;
		while (twoIndex >= 1 && array[twoIndex - 1] == 2) {
			twoIndex--;
		}

		int zeroIndex = -1;
		for (int index = 0; index < twoIndex; index++) {
			if (array[index] == 2) {
				twoIndex--;
				ArrayUtils.swap(array, index, twoIndex);
			}

			if (array[index] == 0) {
				zeroIndex++;
				ArrayUtils.swap(array, index, zeroIndex);
			}
		}

		return;
	}
}

[Java] Sort array with only 0s and/or 1s and/or 2s.


/*
 * Copyright 2015 Ryan Gilera.
 *
 * 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.daytron.revworks.ui.constants;

/**
 *
 * @author Ryan Gilera
 */
public enum ExceptionMsg {
    INVALID_USER_CREDENTIAL("No such user found. Invalid credentials."),
    NO_CURRENT_USER_EXCEPTION("No user is login."),
    WRONG_CURRENT_USER_TYPE_EXCEPTION("Wrong user type access.")
    ;
        private final String msg;

    private ExceptionMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

}

Add custom exception messages to the new exceptions created


/*
 * Copyright (C) 2015 Pedro Vicente Gomez Sanchez.
 *
 * 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.sample;

import android.test.ActivityInstrumentationTestCase2;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static org.hamcrest.core.Is.is;

/**
 * @author Pedro Vicente Gomez Sanchez.
 */
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

  public MainActivityTest() {
    super(MainActivity.class);
  }

  @Override protected void setUp() throws Exception {
    super.setUp();
    getActivity();
  }

  public void shouldShowsLynxViewAsGoneByDefault() {
    onView(withId(R.id.lynx_view)).check(matches(is(isDisplayed())));
  }

  public void shouldShowsLynxViewOnShowLynxButtonClicked() {
    onView(withId(R.id.bt_show_lynx_view)).perform(click());

    onView(withId(R.id.lynx_view)).check(matches(isDisplayed()));
  }
}

Add two tests to MainActivity checking LynxView visibility inside MainActivity


package com.cwainner.chris.recipecentral;

import android.os.Build;
import android.widget.TextView;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.*;

@Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP)
@RunWith(RobolectricGradleTestRunner.class)

public class AboutActivityTest {
    private AboutActivity activity;

    @Before
    public void setup() {
        activity = Robolectric.setupActivity(AboutActivity.class);
    }

    @Test
    public void validateAboutHeader(){
        TextView aboutHeaderView = (TextView) activity.findViewById(R.id.aboutHeader);
        assertTrue("About".equals(aboutHeaderView.getText().toString()));
    }
}

Add about activity test file with header test


import org.dalton.DaltonStock;

/**
 *
 */

/**
 * @author student
 *
 */
public class Stock {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DaltonStock stock = new DaltonStock("AMZN");
		stock.
		System.out.println(stock.name);
	}

}

Add original code (note: to run copy into eclipse)


//$Header$
/*
 * Copyright 2001-2004 The Apache Software 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.apache.jmeter.protocol.http.sampler;

import java.net.URL;

/**
 * Dummy HTTPSampler class for use by classes that need an HTTPSampler,
 * but that don't need an actual sampler, e.g. for Parsing testing.
 */
public final class HTTPNullSampler extends HTTPSamplerBase {

	/* (non-Javadoc)
	 * @see org.apache.jmeter.protocol.http.sampler.HTTPSamplerBase#sample(java.net.URL, java.lang.String, boolean, int)
	 */
	protected HTTPSampleResult sample(URL u, String s, boolean b, int i) {
		throw new UnsupportedOperationException("For test purposes only");
	}

}

Add dummy HTTP sampler for use in generic HTTP tests

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

Former-commit-id: 1a2c9a26225308f6f0fa93c4a3551122f1f5b1da


package info.u_team.u_team_test.integration;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.integration.*;

@Integration("xyz")
public class TestIntegrationNotCall implements IModIntegration {

	public static final Logger LOGGER = LogManager.getLogger("IntegrationNotCall");

	@Override
	public void construct() {
		LOGGER.error("Integration not call is constructed! THIS SHOULD NEVER HAPPEN!!");
		throw new RuntimeException("Integration should not be constructed");
	}

}

Add not call integration to test if it is called only the right times


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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 net.imagej.ops.map.neighborhood;

import net.imagej.ops.AbstractComputerOp;
import net.imglib2.util.Pair;

/**
 * Abstract superclass for {@link CenterAwareComputerOp} implementations.
 *
 * @author Jonathan Hale (University of Konstanz)
 */
public abstract class AbstractCenterAwareComputerOp<I, O> extends
	AbstractComputerOp<Pair<I, Iterable<I>>, O> implements
	CenterAwareComputerOp<I, O>
{
	// NB: Empty.
}

Add abstract superclass for CenterAwareComputerOps

Signed-off-by: squareys <b4e1335d2c774058f7a95112f52894dcc752fd3f@googlemail.com>


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

import junit.framework.Test;
import junit.framework.TestSuite;
import org.apache.jackrabbit.test.api.observation.EventIteratorTest;
import org.apache.jackrabbit.test.api.observation.EventTest;
import org.apache.jackrabbit.test.api.observation.GetRegisteredEventListenersTest;
import org.apache.jackrabbit.test.api.observation.LockingTest;
import org.apache.jackrabbit.test.api.observation.NodeAddedTest;
import org.apache.jackrabbit.test.api.observation.NodeRemovedTest;
import org.apache.jackrabbit.test.api.observation.NodeMovedTest;
import org.apache.jackrabbit.test.api.observation.NodeReorderTest;
import org.apache.jackrabbit.test.api.observation.PropertyAddedTest;
import org.apache.jackrabbit.test.api.observation.PropertyChangedTest;
import org.apache.jackrabbit.test.api.observation.PropertyRemovedTest;
import org.apache.jackrabbit.test.api.observation.AddEventListenerTest;
import org.apache.jackrabbit.test.api.observation.WorkspaceOperationTest;

/**
 * TestObservation...
 */
public class TestObservation {

    public static Test suite() {
        TestSuite suite = new TestSuite("javax.jcr.observation");
        suite.addTestSuite(EventIteratorTest.class);
        suite.addTestSuite(EventTest.class);
        suite.addTestSuite(GetRegisteredEventListenersTest.class);
        suite.addTestSuite(LockingTest.class);
        suite.addTestSuite(NodeAddedTest.class);
        suite.addTestSuite(NodeRemovedTest.class);
        suite.addTestSuite(NodeMovedTest.class);
        suite.addTestSuite(NodeReorderTest.class);
        suite.addTestSuite(PropertyAddedTest.class);
        suite.addTestSuite(PropertyChangedTest.class);
        suite.addTestSuite(PropertyRemovedTest.class);
        suite.addTestSuite(AddEventListenerTest.class);
        suite.addTestSuite(WorkspaceOperationTest.class);
        return suite;
    }
}

Test suite for observation tests.

Test suite for observation tests.

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


package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime(DateTimeZone.UTC);
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

package org.motechproject.server.pillreminder.util;

import org.joda.time.DateTime;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Util {

    public static DateTime currentDateTime() {
        return new DateTime();
    }

    public static Date newDate(int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        cal.set(year, month, day);
        return cal.getTime();
    }

    public static boolean areDatesSame(Date date1, Date date2) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
        return dateFormat.format(date1).equals(dateFormat.format(date2));
    }

    public static Date getDateAfter(Date date, int numOfMonth) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, numOfMonth);
        return cal.getTime();
    }
}

Remove UTC from time util<Manohar/Shruthi>


/*
 *
 * 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.messaginghub.amqperative.example;

import java.util.UUID;

import org.messaginghub.amqperative.Client;
import org.messaginghub.amqperative.ClientOptions;
import org.messaginghub.amqperative.Connection;
import org.messaginghub.amqperative.Delivery;
import org.messaginghub.amqperative.Message;
import org.messaginghub.amqperative.Receiver;
import org.messaginghub.amqperative.Session;

public class TransactedReceiver {

    public static void main(String[] args) throws Exception {

        try {
            String brokerHost = "localhost";
            int brokerPort = 5672;
            String address = "examples";

            ClientOptions options = new ClientOptions();
            options.id(UUID.randomUUID().toString());
            Client client = Client.create(options);

            Connection connection = client.connect(brokerHost, brokerPort);
            Session session = connection.openSession();

            session.begin();

            Receiver receiver = session.openReceiver(address);
            Delivery del = receiver.receive();
            Message<String> message = del.message();

            System.out.println("Received: " + message.body());

            session.commit();

            connection.close().get();
        } catch (Exception exp) {
            System.out.println("Caught exception, exiting.");
            exp.printStackTrace(System.out);
            System.exit(1);
        } finally {
        }
    }
}

Create a simple transacted receive example


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.athenz.filter;

import com.google.inject.Inject;
import com.yahoo.jdisc.http.ssl.SslTrustStoreConfigurator;
import com.yahoo.jdisc.http.ssl.SslTrustStoreContext;
import com.yahoo.vespa.hosted.controller.athenz.config.AthenzConfig;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

/**
 * Load trust store with Athenz CA certificates
 *
 * @author bjorncs
 */
public class AthenzTrustStoreConfigurator implements SslTrustStoreConfigurator {

    private final KeyStore trustStore;

    @Inject
    public AthenzTrustStoreConfigurator(AthenzConfig config) {
        this.trustStore = createTrustStore(new File(config.athenzCaTrustStore()));
    }

    private static KeyStore createTrustStore(File trustStoreFile) {
        try (FileInputStream in = new FileInputStream(trustStoreFile)) {
            KeyStore trustStore = KeyStore.getInstance("JKS");
            trustStore.load(in, "changeit".toCharArray());
            return trustStore;
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void configure(SslTrustStoreContext context) {
        context.updateTrustStore(trustStore);
    }
}

Add trust store configurator with Athenz CA certificates


/*
 * Copyright (c) 2015 Inocybe 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
 */
package org.opendaylight.ovsdb.openstack.netvirt.impl;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.Random;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;
import org.opendaylight.ovsdb.openstack.netvirt.api.NetworkingProvider;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
import org.osgi.framework.ServiceReference;

/**
 * Unit test for class ProviderNetworkManagerImpl
 *
 * TODO In order to have deeper tests, private inner class
 *  ProviderEntry of ProviderNetworkManager should be public.
 */
@RunWith(MockitoJUnitRunner.class)
public class ProviderNetworkManagerImplTest {

    @InjectMocks private ProviderNetworkManagerImpl providerNetworkManagerImpl;
    @Spy private HashMap<Node, NetworkingProvider> nodeToProviderMapping;

    private Random r = new Random();

    /**
     * Test method {@link ProviderNetworkManagerImpl#getProvider(Node)}
     */
    @Test
    public void testGetProvider(){
        Node node = mock(Node.class);
        NetworkingProvider networkingProvider = mock(NetworkingProvider.class);

        // populate nodeToProviderMapping
        nodeToProviderMapping.put(node, networkingProvider);

        // test when nodeToProviderMapping is populate
        assertEquals("Error, did not return the networkingProvider of the specified node", networkingProvider, providerNetworkManagerImpl.getProvider(node));
    }

    /**
     * Test method {@link ProviderNetworkManagerImpl#providerAdded(ServiceReference, NetworkingProvider)}
     */
    @Test
    public void testProviderAdded(){
        ServiceReference ref = mock(ServiceReference.class);

        // configure ref
        when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());
        when(ref.getProperty(Constants.SOUTHBOUND_PROTOCOL_PROPERTY)).thenReturn("proto");
        when(ref.getProperty(Constants.OPENFLOW_VERSION_PROPERTY)).thenReturn("of");
        when(ref.getProperty(Constants.PROVIDER_TYPE_PROPERTY)).thenReturn("provider");

        // nothing much to test
        providerNetworkManagerImpl.providerAdded(ref, mock(NetworkingProvider.class));
    }

    /**
     * Test method {@link ProviderNetworkManagerImpl#providerRemoved(ServiceReference)}
     */
    @Test
    public void testProviderRemoved(){
        ServiceReference ref = mock(ServiceReference.class);

        // configure ref
        when(ref.getProperty(org.osgi.framework.Constants.SERVICE_ID)).thenReturn(r.nextLong());

        // nothing much to test
        providerNetworkManagerImpl.providerRemoved(ref);
    }
}

Add JUnit testing for ProviderNetworkManagerImpl.

Change-Id: Ie195e64d2e6f80fea11dee7ea6bfc1d3635567da
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


package org.wildfly.security.auth.util;

import org.junit.Test;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;

public class RegexNameRewriterTest {

    private static final String BEFORE_REPLACE_USER_NAME = ".user.";
    private static final String AFTER_REPLACE_ALL_USER_NAME = "dotuserdot";
    private static final String AFTER_REPLACE_USER_NAME = "dotuser.";

    @Test
    public void testRegexNameRewriter() {
        Pattern pattern = Pattern.compile("\\.");

        RegexNameRewriter regexNameRewriter = new RegexNameRewriter(pattern, "dot", true);
        String regexName = regexNameRewriter.rewriteName(BEFORE_REPLACE_USER_NAME);
        assertEquals(AFTER_REPLACE_ALL_USER_NAME, regexName);

        regexNameRewriter = new RegexNameRewriter(pattern, "dot", false);
        regexName = regexNameRewriter.rewriteName(BEFORE_REPLACE_USER_NAME);
        assertEquals(AFTER_REPLACE_USER_NAME, regexName);
    }

}

Add a test class for RegexNameRewriter

[ELY-2446] Add a test class for RegexNameRewriter


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.updater.core;

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;
import org.scijava.util.FileUtils;

/**
 * A conditional JUnit test for uploading via file: protocol.
 *
 * This verifies that the file: protocol (required for Dropbox, or for scripts running
 * on the same machine as the webserver) works alright.
 *
 * @author Johannes Schindelin
 */
public class LocalhostUploaderTest extends AbstractUploaderTestBase {
	public LocalhostUploaderTest() {
		super("localhost");
	}

	@Test
	public void testLocalhostUpload() throws Exception {
		final File tmp = FileUtils.createTemporaryDirectory("localhost-upload", "");
		url = tmp.toURI().toURL().toString();

		test(new FileDeleter(), "file:localhost", tmp.getAbsolutePath());

		assertTrue(FileUtils.deleteRecursively(tmp));
	}

	private class FileDeleter implements AbstractUploaderTestBase.Deleter {
		@Override
		public void delete(final String path) throws IOException {
			final File file = files.prefix(path);
			if (!file.delete()) throw new IOException("Could not delete " + file);
		}
	}
}

Add a test for uploading using the file: protocol

We now advertise Dropbox as a method to provide an update site,
so we better make sure that the localhost side of it actually works.

Signed-off-by: Johannes Schindelin <53fb8db7833fca1e1746dd8592f61048d350f64c@gmx.de>


package apostov;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import jline.console.ConsoleReader;
import jline.console.completer.FileNameCompleter;
import jline.console.completer.StringsCompleter;

public class JLineMain {

	public static void main(final String[] args) throws IOException {

		final ConsoleReader reader = new ConsoleReader();

		reader.setPrompt("> ");
		reader.addCompleter(new StringsCompleter("exit", CommandLineInterpreter.BOARD_ARG_NAME));

		final CommandLineInterpreter clInterpreter = new CommandLineInterpreter();
		String line;

		while ((line = reader.readLine()) != null) {
			final String trimmedLine = line.trim();
			if (trimmedLine.isEmpty()) {
				continue;
			} else if (trimmedLine.equalsIgnoreCase("exit")) {
				break;
			}  else if (trimmedLine.equalsIgnoreCase("gc")) {
				System.gc();
			} else {
				final String[] splitLine = line.split("\\s+");
				try {
					clInterpreter.interpretArguments(splitLine);
				} catch (final InvalidArgumentsException e) {
					e.printStackTrace();
				}
			}
		}

		reader.flush();

	}

}

Add a first version of a JLine interpreter


package com.cloudera.disttest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Random;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class TestFailSometimes {

  @Test
  public void failSometimes() throws Exception {
    Random r = new Random();
    if (r.nextFloat() > 0.5) {
      throw new Exception();
    }
  }
}

Add a test which fails probabilistically, to test retry-on-failure


/*
 * 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.felix.gogo.runtime;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map.Entry;

/*
 * Test features of the new parser/tokenizer, many of which are not supported
 * by the original parser.
 */
public class TestParser4 extends AbstractParserTest
{
    public void testPipeErr() throws Exception
    {
        Context c = new Context();
        c.addCommand("echo", this);
        c.addCommand("echoerr", this);
        c.addCommand("tac", this);

        assertEquals("hello", c.execute("echo | tac"));
        assertEquals("hello", c.execute("echoerr |& tac"));
    }

    public void testRedir() throws Exception {
        Context c = new Context();
        c.addCommand("echo", this);
        c.addCommand("tac", this);

        Path path = Paths.get("target/tmp");
        Files.createDirectories(path);
        c.currentDir(path);

        Files.deleteIfExists(path.resolve("foo"));
        assertEquals("hello", c.execute("echo >foo | tac"));
        assertEquals("hello\n", new String(Files.readAllBytes(path.resolve("foo"))));
    }

    public void echo()
    {
        System.out.println("hello");
    }

    public void echoerr()
    {
        System.err.println("hello");
    }

    public String tac() throws IOException {
        StringWriter sw = new StringWriter();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
        boolean first = true;
        String s;
        while ((s = rdr.readLine()) != null) {
            if (!first) {
                sw.write(' ');
            }
            first = false;
            sw.write(s);
        }
        return sw.toString();
    }

}

Add a small test for redirections

Add a small test for redirections

git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@1735999 13f79535-47bb-0310-9956-ffa450edef68


/******************************************************************************
 *  Compilation:  javac HelloWorld.java
 *  Execution:    java HelloWorld
 *
 *  Prints "Hello, World". By tradition, this is everyone's first program.
 *
 *  % java HelloWorld
 *  Hello, World
 *
 *  These 17 lines of text are comments. They are not part of the program;
 *  they serve to remind us about its properties. The first two lines tell
 *  us what to type to compile and test the program. The next line describes
 *  the purpose of the program. The next few lines give a sample execution
 *  of the program and the resulting output. We will always include such
 *  lines in our programs and encourage you to do the same.
 *
 ******************************************************************************/

public class HelloWorld {

    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        System.out.println("Hello, World");
    }

}

Print hello world to terminal

Print hello world to terminal


package de.passau.uni.sec.compose.reputation;

public class Source
{
	private String soid;

	private String streamid;

	public String getSoid() {
		return soid;
	}

	public void setSoid(String soid) {
		this.soid = soid;
	}

	public String getStreamid() {
		return streamid;
	}

	public void setStreamid(String streamid) {
		this.streamid = streamid;
	}

}

Add source object for reputation

Add source object for reputation