package org.granchi.hollywood.preferences;

import org.granchi.hollywood.Action;
import org.granchi.hollywood.Model;

/**
 * Model for storing and modifying a group of preferences.
 *
 * @author serandel
 */
public abstract class PreferencesModel implements Model {
    @Override
    public Model actUpon(Action action) {
        return null;
    }
}

package org.granchi.hollywood.preferences;

import org.granchi.hollywood.Action;
import org.granchi.hollywood.Model;

/**
 * Model for storing and modifying a group of preferences.
 *
 * @author serandel
 */
// TODO do we really want a preferences model or get them integrated into the business logic?
public abstract class PreferencesModel implements Model {
    @Override
    public Model actUpon(Action action) {
        return null;
    }
}

Make remark for future consideration about if this class is a good idea or not


package org.mskcc.cbio.oncokb.api.pub.v1;

import org.mskcc.cbio.oncokb.model.Geneset;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * Created by Hongxin Zhang on 2019-08-09.
 */
@Controller
public class GenesetsApiController implements GenesetsApi {
    @Override
    public ResponseEntity<List<Geneset>> genesetsGet() {
        return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findAll(), HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Geneset> genesetsIdGet(Integer id) {
        return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findGenesetById(id), HttpStatus.OK);
    }
}

package org.mskcc.cbio.oncokb.api.pub.v1;

import io.swagger.annotations.ApiParam;
import org.mskcc.cbio.oncokb.model.Geneset;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * Created by Hongxin Zhang on 2019-08-09.
 */
@Controller
public class GenesetsApiController implements GenesetsApi {
    @Override
    public ResponseEntity<List<Geneset>> genesetsGet() {
        return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findAll(), HttpStatus.OK);
    }

    @Override
    public ResponseEntity<Geneset> genesetsIdGet(
        @ApiParam(value = "Geneset ID", required = true) @PathVariable(value = "id") Integer id
    ) {
        return new ResponseEntity<>(ApplicationContextSingleton.getGenesetBo().findGenesetById(id), HttpStatus.OK);
    }
}

Include swagger definition in the implementation


package guitests;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class ClearCommandTest extends ToDoListGuiTest {
/*
    @Test
    public void clear() {
/*
        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.meetHoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.meetHoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {
        commandBox.runCommand("clear");
        assertListSize(0);
    }*/
}

package guitests;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class ClearCommandTest extends ToDoListGuiTest {

    @Test
    public void clear() {
/*
        //verify a non-empty list can be cleared
        assertTrue(taskListPanel.isListMatching(td.getTypicalTasks()));
        assertClearCommandSuccess();

        //verify other commands can work after a clear command
        commandBox.runCommand(td.meetHoon.getAddCommand());
        assertTrue(taskListPanel.isListMatching(td.meetHoon));
        commandBox.runCommand("delete 1");
        assertListSize(0);

        //verify clear command works when the list is empty
        assertClearCommandSuccess();
    }

    private void assertClearCommandSuccess() {*/
        commandBox.runCommand("clear");
        assertListSize(0);
    }
}

Revert "commented out clear for now"

Revert "commented out clear for now"

This reverts commit 1a03b1fc61f9c32e26dd146801127306736a86c3.


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

import org.eclipse.kapua.commons.model.query.KapuaListResultImpl;

/**
 * Service configuration result list reference implementation.
 *
 * @since 1.0
 *
 */
public class ServiceConfigListResultImpl extends KapuaListResultImpl<ServiceConfig> implements ServiceConfigListResult
{
    @SuppressWarnings("unused")
    private static final long serialVersionUID = -2550359084026132096L;
}

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

import org.eclipse.kapua.commons.model.query.KapuaListResultImpl;

/**
 * Service configuration result list reference implementation.
 *
 * @since 1.0
 *
 */
public class ServiceConfigListResultImpl extends KapuaListResultImpl<ServiceConfig> implements ServiceConfigListResult
{
    private static final long serialVersionUID = -2550359084026132096L;
}

Remove "unused" annotation after interface got added


/*******************************************************************************
 * Copyright (c) 2013 University of Stuttgart.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and the Apache License 2.0 which both accompany this distribution,
 * and are available at http://www.eclipse.org/legal/epl-v10.html
 * and http://www.apache.org/licenses/LICENSE-2.0
 *
 * Contributors:
 *     Oliver Kopp - initial API and implementation
 *******************************************************************************/
package org.eclipse.winery.common.ids;

import org.eclipse.winery.common.StringEncodedAndDecoded;

public class Namespace extends StringEncodedAndDecoded {

	public Namespace(String uri, boolean URLencoded) {
		super(uri, URLencoded);
	}

}

/*******************************************************************************
 * Copyright (c) 2013,2015 University of Stuttgart.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and the Apache License 2.0 which both accompany this distribution,
 * and are available at http://www.eclipse.org/legal/epl-v10.html
 * and http://www.apache.org/licenses/LICENSE-2.0
 *
 * Contributors:
 *     Oliver Kopp - initial API and implementation
 *******************************************************************************/
package org.eclipse.winery.common.ids;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.winery.common.StringEncodedAndDecoded;

public class Namespace extends StringEncodedAndDecoded {

	public Namespace(String uri, boolean URLencoded) {
		super(uri, URLencoded);
		if (StringUtils.isEmpty(uri)) {
			throw new IllegalArgumentException("uri must not be empty or null.");
		}
	}

}

Add check for null parameter

Add check for null parameter


package org.demyo.web.controller.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import org.demyo.model.Author;
import org.demyo.service.IAuthorService;

@Controller
@RequestMapping("/api/authors")
public class AuthorAPIController extends AbstractModelAPIController<Author> {
	private final IAuthorService service;

	@Autowired
	public AuthorAPIController(IAuthorService service) {
		super(Author.class);
		this.service = service;
	}

	@Override
	protected IAuthorService getService() {
		return service;
	}

}

package org.demyo.web.controller.api;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.demyo.model.Author;
import org.demyo.service.IAuthorService;

@RestController
@RequestMapping("/api/authors")
public class AuthorAPIController extends AbstractModelAPIController<Author> {
	private final IAuthorService service;

	@Autowired
	public AuthorAPIController(IAuthorService service) {
		super(Author.class);
		this.service = service;
	}

	@Override
	protected IAuthorService getService() {
		return service;
	}

}

Use the Spring shorthand annotations for binding REST controllers

Refs #78


// $Id: RegExpMatchOnNameFilter.java 63 2006-07-12 21:50:51Z edavis $
package thredds.crawlabledataset.filter;

import thredds.crawlabledataset.CrawlableDatasetFilter;
import thredds.crawlabledataset.CrawlableDataset;

/**
 * CrawlableDatasetFilter implementation that accepts datasets whose
 * names are matched by the given regular expression.
 *
 * @author edavis
 * @since Nov 5, 2005 12:51:56 PM
 */
public class RegExpMatchOnNameFilter implements CrawlableDatasetFilter
{
//  private static org.apache.commons.logging.Log log =
//          org.apache.commons.logging.LogFactory.getLog( RegExpMatchOnNameFilter.class );

  private String regExpString;
  private java.util.regex.Pattern pattern;

  public RegExpMatchOnNameFilter( String regExpString )
  {
    this.regExpString = regExpString;
    this.pattern = java.util.regex.Pattern.compile( regExpString );
  }

  public Object getConfigObject() { return regExpString; }
  public String getRegExpString() { return regExpString; }

  public boolean accept( CrawlableDataset dataset )
  {
    java.util.regex.Matcher matcher = this.pattern.matcher( dataset.getName() );
    if ( matcher.matches() ) return true;
    return false;
  }
}

// $Id: RegExpMatchOnNameFilter.java 63 2006-07-12 21:50:51Z edavis $
package thredds.crawlabledataset.filter;

import thredds.crawlabledataset.CrawlableDatasetFilter;
import thredds.crawlabledataset.CrawlableDataset;

/**
 * CrawlableDatasetFilter implementation that accepts datasets whose
 * names are matched by the given regular expression.
 *
 * @author edavis
 * @since Nov 5, 2005 12:51:56 PM
 */
public class RegExpMatchOnNameFilter implements CrawlableDatasetFilter
{
//  private static org.apache.commons.logging.Log log =
//          org.apache.commons.logging.LogFactory.getLog( RegExpMatchOnNameFilter.class );

  private String regExpString;
  private java.util.regex.Pattern pattern;

  public RegExpMatchOnNameFilter( String regExpString )
  {
    this.regExpString = regExpString;
    this.pattern = java.util.regex.Pattern.compile( regExpString );
  }

  public Object getConfigObject() { return regExpString; }
  public String getRegExpString() { return regExpString; }

  public boolean accept( CrawlableDataset dataset )
  {
    java.util.regex.Matcher matcher = this.pattern.matcher( dataset.getName() );
    if ( matcher.find() ) return true;
    return false;
  }
}

Change to match on part of string rather than only on entire string. This allows the given regExp pattern decide if it must match at start ("^"), end ("$"), or both ("^*$).


package org.jboss.loom.migrators._ext;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.utils.ClassUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  Base class to prepare external migrators test environment (copies files etc.).
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ExternalMigratorsTestEnv {
    private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class );

    protected static File workDir;

    @BeforeClass
    public static void copyTestExtMigratorFiles() throws IOException {
        workDir = new File("target/extMigrators/");
        FileUtils.forceMkdir( workDir );
        ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestMigrator.mig.xml", workDir );
        ClassUtils.copyResourceToDir( ExternalMigratorsLoader.class, "TestJaxbBean.groovy",  workDir );
    }

    @AfterClass
    public static void deleteTestExtMigratorFiles() throws IOException {
        FileUtils.forceDelete( workDir );
    }

}// class

package org.jboss.loom.migrators._ext;

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.jboss.loom.utils.ClassUtils;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  Base class to prepare external migrators test environment (copies files etc.).
 *
 *  @author Ondrej Zizka, ozizka at redhat.com
 */
public class ExternalMigratorsTestEnv {
    private static final Logger log = LoggerFactory.getLogger( ExternalMigratorsTestEnv.class );

    protected static File workDir;

    @BeforeClass
    public static void copyTestExtMigratorFiles() throws IOException {
        workDir = new File("target/extMigrators/");
        FileUtils.forceMkdir( workDir );
        ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestMigrator.mig.xml", workDir );
        ClassUtils.copyResourceToDir( ExternalMigratorsTestEnv.class, "res/TestJaxbBean.groovy",  workDir );
    }

    @AfterClass
    public static void deleteTestExtMigratorFiles() throws IOException {
        FileUtils.forceDelete( workDir );
    }

}// class

Move test to test src

Move test to test src


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

import java.util.Properties;

public class CommandArchetypeTest extends AbstractArchetypeTest {

    public void testCommand() throws Exception {
        Properties commandArchetypeParameters = new Properties();
        commandArchetypeParameters.setProperty("scope", "testscope");
        commandArchetypeParameters.setProperty("command", "testcommand");
        commandArchetypeParameters.setProperty("description", "testdescription");
        testKarafArchetype("archetypes-command", commandArchetypeParameters);
    }

}

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

import java.util.Properties;

public class CommandArchetypeTest extends AbstractArchetypeTest {

    public void testCommand() throws Exception {
        Properties commandArchetypeParameters = new Properties();
        commandArchetypeParameters.setProperty("scope", "testscope");
        commandArchetypeParameters.setProperty("command", "testcommand");
        commandArchetypeParameters.setProperty("description", "testdescription");
        testKarafArchetype("karaf-command-archetype", commandArchetypeParameters);
    }

}

[KARAF-1109] Update the archetypes itest to reflect the new karaf-command-archetype artifactId

git-svn-id: 71d8a689455c5fbb0f077bc40adcfc391e14cb9d@1214843 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.react.bridge;

public class JSCJavaScriptExecutorFactory implements JavaScriptExecutorFactory {
  private final String mAppName;
  private final String mDeviceName;

  public JSCJavaScriptExecutorFactory(String appName, String deviceName) {
    this.mAppName = appName;
    this.mDeviceName = deviceName;
  }

  @Override
  public JavaScriptExecutor create() throws Exception {
    WritableNativeMap jscConfig = new WritableNativeMap();
    jscConfig.putString("OwnerIdentity", "ReactNative");
    jscConfig.putString("AppIdentity", mAppName);
    jscConfig.putString("OwnerIdentity", mDeviceName);
    return new JSCJavaScriptExecutor(jscConfig);
  }
}

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

package com.facebook.react.bridge;

public class JSCJavaScriptExecutorFactory implements JavaScriptExecutorFactory {
  private final String mAppName;
  private final String mDeviceName;

  public JSCJavaScriptExecutorFactory(String appName, String deviceName) {
    this.mAppName = appName;
    this.mDeviceName = deviceName;
  }

  @Override
  public JavaScriptExecutor create() throws Exception {
    WritableNativeMap jscConfig = new WritableNativeMap();
    jscConfig.putString("OwnerIdentity", "ReactNative");
    jscConfig.putString("AppIdentity", mAppName);
    jscConfig.putString("DeviceIdentity", mDeviceName);
    return new JSCJavaScriptExecutor(jscConfig);
  }
}

Fix DeviceIdentity on RN for Android

Fix DeviceIdentity on RN for Android

Reviewed By: Hypuk

Differential Revision: D5963912

fbshipit-source-id: 3959e5ab6af66512f0035efea7919572554e10b4


package org.ccci.gto.android.common.db;

import android.support.test.runner.AndroidJUnit4;
import android.test.InstrumentationTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.ccci.gto.android.common.db.TestDao.TestContract.RootTable;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(AndroidJUnit4.class)
public class ExpressionTest extends InstrumentationTestCase {

    private TestDao getDao() {
        return new TestDao(getInstrumentation().getContext());
    }

    @Test
    public void testEqualsSql() {
        final TestDao dao = getDao();

        Expression equalsExpression = RootTable.FIELD_TEST.eq("1");
        assertThat(equalsExpression.buildSql(dao).first, is("(root.test == ?)"));
    }

    @Test
    public void testNotEqualsSql() {
        final TestDao dao = getDao();

        Expression notEqualsExpression = RootTable.FIELD_TEST.not().eq("1");
        assertThat(notEqualsExpression.buildSql(dao).first, is("(NOT (root.test) == ?)"));
    }
}

package org.ccci.gto.android.common.db;

import android.support.test.runner.AndroidJUnit4;
import android.test.InstrumentationTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.ccci.gto.android.common.db.TestDao.TestContract.RootTable;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(AndroidJUnit4.class)
public class ExpressionTest extends InstrumentationTestCase {

    private TestDao getDao() {
        return new TestDao(getInstrumentation().getContext());
    }

    @Test
    public void testEqualsSql() {
        final TestDao dao = getDao();

        Expression equalsExpression = RootTable.FIELD_TEST.eq("1");
        assertThat(equalsExpression.buildSql(dao).first, is("(root.test == ?)"));
    }

    @Test
    public void testNotEqualsSql() {
        final TestDao dao = getDao();

        Expression notEqualsExpression = RootTable.FIELD_TEST.not().eq("1");
        assertThat(notEqualsExpression.buildSql(dao).first, is("(NOT (root.test) == ?)"));
    }

    @Test
    public void testCount() {
        final TestDao dao = getDao();

        Expression countExpression = RootTable.FIELD_TEST.count();
        assertThat(countExpression.buildSql(dao).first, is("COUNT (root.test)"));
    }

    @Test
    public void testCountInHaving() {
        final TestDao dao = getDao();

        Expression countExpression = RootTable.FIELD_TEST.count().eq(1);
        assertThat(countExpression.buildSql(dao).first, is("(COUNT (root.test) == 1)"));
    }
}

Add test for count method

Add test for count method


package io.github.plastix.forage.data.local.model;

import android.location.Location;

import io.realm.RealmObject;

/**
 * Realm Model "wrapper" to store location data in a Realm. This is required because Realm doesn't
 * allow third party types such as Android's location type.
 */
public class RealmLocation extends RealmObject {

    public double latitude;
    public double longitude;

    /**
     * Returns a new Android Location object with the corresponding data from the realm object.
     *
     * @return New Location object.
     */
    public Location toLocation() {
        Location location = new Location("Realm");
        location.setLatitude(latitude);
        location.setLongitude(longitude);
        return location;
    }
}

package io.github.plastix.forage.data.local.model;

import android.location.Location;

import io.github.plastix.forage.util.LocationUtils;
import io.realm.RealmObject;

/**
 * Realm Model "wrapper" to store location data in a Realm. This is required because Realm doesn't
 * allow third party types such as Android's location type.
 */
public class RealmLocation extends RealmObject {

    public double latitude;
    public double longitude;

    /**
     * Returns a new Android Location object with the corresponding data from the realm object.
     *
     * @return New Location object.
     */
    public Location toLocation() {
        return LocationUtils.buildLocation(latitude, longitude);
    }
}

Use new buildLocation helper method in LocationUtils


package com.opcoach.training.e4.rental.ui;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle This class must be
 * registered as a LifeCycleURI to fill the context
 */
public class RentalUIActivator implements BundleActivator
{

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext bcontext) throws Exception
	{

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception
	{

	}

}

package com.opcoach.training.e4.rental.ui;

import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * The activator class controls the plug-in life cycle This class must be
 * registered as a LifeCycleURI to fill the context
 */
public class RentalUIActivator implements BundleActivator
{

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext bcontext) throws Exception
	{
		IEclipseContext ct = EclipseContextFactory.getServiceContext(bcontext);
		ct.set(RentalUIConstants.PLUGIN_ID + "context", "My value");

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception
	{

	}

}

Add an E4 context on current plugin.

Add an E4 context on current plugin.


package com.insane.itsrainingfood;

import net.minecraft.entity.player.EntityPlayer;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;

public class FoodEventHandler {
	public static int ticksSinceLast = 0;
	@SubscribeEvent
	public void onPlayerTickEvent(PlayerTickEvent event)
	{
		if (event.player.worldObj.isRaining())
		{
			EntityPlayer player = event.player;
			if (ticksSinceLast == 0 && player.rotationPitch < -65f && player.getFoodStats().needFood() && player.worldObj.canBlockSeeTheSky((int) player.posX, (int) player.posY, (int) player.posZ))
			{
				event.player.getFoodStats().addStats(1, 1.0f);
				ticksSinceLast++;
				if (ItsRainingFood.proxy.shouldPlaySound())
					event.player.worldObj.playSoundAtEntity(event.player, "itsrainingfood:omnomnom", 0.8f, 1.0f);
			}
			else
			{
				ticksSinceLast++;
				ticksSinceLast = ticksSinceLast%Config.configTicks;
			}
		}
	}

}

package com.insane.itsrainingfood;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.PlayerTickEvent;

public class FoodEventHandler {
	public static int ticksSinceLast = 0;
	@SubscribeEvent
	public void onPlayerTickEvent(PlayerTickEvent event)
	{
		if (event.player.worldObj.isRaining())
		{
			EntityPlayer player = event.player;
			if (ticksSinceLast == 0 && player.rotationPitch < -65f && player.getFoodStats().needFood() && player.worldObj.canBlockSeeTheSky(MathHelper.floor_double(player.posX), MathHelper.floor_double(player.posY), MathHelper.floor_double(player.posZ)))
			{
				event.player.getFoodStats().addStats(1, 1.0f);
				ticksSinceLast++;
				if (ItsRainingFood.proxy.shouldPlaySound())
					event.player.worldObj.playSoundAtEntity(event.player, "itsrainingfood:omnomnom", 0.8f, 1.0f);
			}
			else
			{
				ticksSinceLast++;
				ticksSinceLast = ticksSinceLast%Config.configTicks;
			}
		}
	}

}

Change from cast to MathHelper

Change from cast to MathHelper


package net.openhft.chronicle.network;

import net.openhft.chronicle.core.Jvm;

/**
 * Created by peter.lawrey on 16/07/2015.
 */
public enum WanSimulator {
    ;
    private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0);
    private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000;
    private static long totalRead = 0;

    public static void dataRead(int bytes) {
        if (NET_BANDWIDTH <= 0) return;
        totalRead += bytes + 128;
        int delay = (int) (totalRead / BYTES_PER_MS);
        if (delay > 0) {
            Jvm.pause(delay);
            totalRead = 0;
        }
    }
}

package net.openhft.chronicle.network;

import net.openhft.chronicle.core.Jvm;

import java.util.Random;

/**
 * Created by peter.lawrey on 16/07/2015.
 */
public enum WanSimulator {
    ;
    private static final int NET_BANDWIDTH = Integer.getInteger("wanMB", 0);
    private static final int BYTES_PER_MS = NET_BANDWIDTH * 1000;
    private static final Random RANDOM = new Random();
    private static long totalRead = 0;

    public static void dataRead(int bytes) {
        if (NET_BANDWIDTH <= 0) return;
        totalRead += bytes + RANDOM.nextInt(BYTES_PER_MS);
        int delay = (int) (totalRead / BYTES_PER_MS);
        if (delay > 0) {
            Jvm.pause(delay);
            totalRead = 0;
        }
    }
}

Add a wan simulator to reproduce timing sensitive issues with a random 0.5 ms delay.


package org.cryptonit.cloud.timestamping;

import org.bouncycastle.util.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.security.cert.X509Certificate;
/**
 * @author Mathias Brossard
 */
public class Authority {
    private static Logger LOGGER;
    KeyPair key;
    X509Certificate crt;
    Store certs;

    public Authority(KeyPair key, X509Certificate crt, Store certs) {
        LOGGER = LoggerFactory.getLogger(Authority.class);

        this.key = key;
        this.crt = crt;
        this.certs = certs;
    }
}

package org.cryptonit.cloud.timestamping;

import org.bouncycastle.tsp.*;
import org.bouncycastle.util.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.*;
import java.security.cert.X509Certificate;
/**
 * @author Mathias Brossard
 */
public class Authority {
    private static Logger LOGGER;
    KeyPair key;
    X509Certificate crt;
    Store certs;

    public TimeStampResponse timestamp(TimeStampRequest request) {
        TimeStampResponse response = null;
        return response;
    }

    public Authority(KeyPair key, X509Certificate crt, Store certs) {
        LOGGER = LoggerFactory.getLogger(Authority.class);

        this.key = key;
        this.crt = crt;
        this.certs = certs;
    }
}

Add prototype for timestamp function

Add prototype for timestamp function


package cz.jiripinkas.jsitemapgenerator;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpClient {

    /**
     * HTTP GET to URL, return status
     *
     * @param url URL
     * @return status code (for example 200)
     * @throws Exception When error
     */
    public int get(String url) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new Exception("error sending HTTP GET to this URL: " + url);
            }
            return response.code();
        }
    }
}

package cz.jiripinkas.jsitemapgenerator;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpClient {

    /**
     * HTTP GET to URL, return status
     *
     * @param url URL
     * @return status code (for example 200)
     * @throws Exception When error
     */
    public int get(String url) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new Exception("error sending HTTP GET to this URL: " + url);
            }
            return response.code();
        } finally {
            // this will be executed after "return response.code();"
            client.connectionPool().evictAll(); // OkHttpClient starts connection pool which needs to be shut down here
        }
    }
}

Fix ping google / bing functionality so that OkHttp cleans up all resources after itself.


package org.embulk.output.sftp.utils;

import java.io.Closeable;
import java.util.concurrent.TimeUnit;

public class TimeoutCloser implements Closeable
{
    private Closeable wrapped;

    public TimeoutCloser(Closeable wrapped)
    {
        this.wrapped = wrapped;
    }

    @Override
    public void close()
    {
        new TimedCallable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                if (wrapped != null) {
                    wrapped.close();
                }
                return null;
            }
        }.callNonInterruptible(60, TimeUnit.SECONDS);
    }
}

package org.embulk.output.sftp.utils;

import java.io.Closeable;
import java.util.concurrent.TimeUnit;

public class TimeoutCloser implements Closeable
{
    private Closeable wrapped;

    public TimeoutCloser(Closeable wrapped)
    {
        this.wrapped = wrapped;
    }

    @Override
    public void close()
    {
        new TimedCallable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                if (wrapped != null) {
                    wrapped.close();
                }
                return null;
            }
        }.callNonInterruptible(120, TimeUnit.SECONDS);
    }
}

Increase time-out to 2 minutes

Increase time-out to 2 minutes


package uk.ac.ebi.quickgo.rest.controller;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Reusable REST API documentation provider. This configuration can
 * be imported by a REST application, in order for its end-points to be
 * auto-documented.
 *
 * Created 13/04/16
 * @author Edd
 */
@PropertySource("classpath:swagger.properties")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                // exclude any spring boot's default APIs e.g., /error:
                //   we only want our APIs documented
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                .paths(PathSelectors.any())
                .build();
    }
}

package uk.ac.ebi.quickgo.rest.controller;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Reusable REST API documentation provider. This configuration can
 * be imported by a REST application, in order for its end-points to be
 * auto-documented.
 *
 * Created 13/04/16
 * @author Edd
 */
@PropertySource("classpath:swagger.properties")
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .useDefaultResponseMessages(false)
                .select()
                // exclude any spring boot's default APIs e.g., /error:
                //   we only want our APIs documented
                .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                .paths(PathSelectors.any())
                .build();
    }
}

Remove default http status messages from swagger documentation.


package org.metaborg.core.plugin;

import java.util.Collection;
import java.util.ServiceLoader;

import org.metaborg.core.MetaborgException;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Module;

/**
 * Module plugin loader using Java's {@link ServiceLoader}.
 */
public class ServiceModulePluginLoader implements IModulePluginLoader {
    @Override public Iterable<Module> modules() throws MetaborgException {
        try {
            final ServiceLoader<IServiceModulePlugin> modulePlugins = ServiceLoader.load(IServiceModulePlugin.class);
            final Collection<Module> modules = Lists.newLinkedList();
            for(IServiceModulePlugin plugin : modulePlugins) {
                Iterables.addAll(modules, plugin.modules());
            }
            return modules;
        } catch(Exception e) {
            throw new MetaborgException("Unhandled exception while loading module plugins with Java's ServiceLoader", e);
        }
    }
}

package org.metaborg.core.plugin;

import java.util.Collection;
import java.util.ServiceLoader;

import org.metaborg.core.MetaborgException;

import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.inject.Module;

/**
 * Module plugin loader using Java's {@link ServiceLoader}.
 */
public class ServiceModulePluginLoader<T extends IServiceModulePlugin> implements IModulePluginLoader {
    private final Class<T> serviceClass;

    public ServiceModulePluginLoader(Class<T> serviceClass) {
        this.serviceClass = serviceClass;
    }

    @Override public Iterable<Module> modules() throws MetaborgException {
        try {
            final ServiceLoader<T> modulePlugins = ServiceLoader.load(serviceClass);
            final Collection<Module> modules = Lists.newLinkedList();
            for(T plugin : modulePlugins) {
                Iterables.addAll(modules, plugin.modules());
            }
            return modules;
        } catch(Exception e) {
            throw new MetaborgException("Unhandled exception while loading module plugins with Java's ServiceLoader", e);
        }
    }
}

Generalize service module plugin loader, in preparation for same loading mechanism for language specification Module plugins.


/*
 * CODENVY CONFIDENTIAL
 * __________________
 *
 *  [2012] - [2015] Codenvy, S.A.
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */

package com.codenvy.analytics.integration;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * @author Anatoliy Bazko
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({})
public class AllTests {
}

/*
 * CODENVY CONFIDENTIAL
 * __________________
 *
 *  [2012] - [2015] Codenvy, S.A.
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Codenvy S.A. and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Codenvy S.A.
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Codenvy S.A..
 */

package com.codenvy.analytics.integration;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/**
 * @author Anatoliy Bazko
 */
@RunWith(Suite.class)
@Suite.SuiteClasses({TestWorkspaces.class})
public class AllTests {
}

DASHB-681: Cover workspace metrics with selenium tests


package npe;

public class GuaranteedDereferenceInteractionWithAssertionMethods {

	public Object x;

	public boolean b;

	public int falsePositive() {

		if (x == null)
			System.out.println("x is null");
		if (b) {
			x = bar();
			checkForError();
		}

		return x.hashCode();
	}

	public void checkForError() {

	}
	public void reportError() {

	}
	public Object bar() {
		return new Object();
	}

	public int report(Object x, Object y, Object z) {
		if (x == null && y == null)
			reportError();

		if (z == null)
			z = new Object();
		return x.hashCode() + z.hashCode();
	}

	public int report2(Object x, Object y, Object z) {
		if (x == null && y == null)
			reportError();

		if (z == null)
			z = new Object();
		int result = x.hashCode() + z.hashCode();
		checkForError();
		return result;
	}
}

package npe;

public class GuaranteedDereferenceInteractionWithAssertionMethods {

	public Object x;

	public boolean b;

	public int falsePositive() {

		if (x == null)
			System.out.println("x is null");
		if (b) {
			x = bar();
			checkForError();
		}

		return x.hashCode();
	}

	int falsePositive2(Object x) {
		if (x == null)
			reportError();
		return x.hashCode();

	}
	public void checkForError() {

	}
	public void reportError() {

	}
	public Object bar() {
		return new Object();
	}

	public int report(Object x, Object y, Object z) {
		if (x == null && y == null)
			reportError();

		if (z == null)
			z = new Object();
		return x.hashCode() + z.hashCode();
	}

	public int report2(Object x, Object y, Object z) {
		if (x == null && y == null)
			reportError();

		if (z == null)
			z = new Object();
		int result = x.hashCode() + z.hashCode();
		checkForError();
		return result;
	}
}

Add another false positive test case

Add another false positive test case

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@6399 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


/*
 * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.hawkular.metrics.api.jaxrs.util;

import org.hawkular.metrics.core.api.MetricType;

/**
 * Returns the longer path format used by the REST-interface from the given MetricType
 *
 * @author Michael Burman
 */
public class MetricTypeTextConverter {

    private MetricTypeTextConverter() { }

    public static String getLongForm(MetricType<?> mt) {

        if(mt == MetricType.GAUGE) {
            return "gauges";
        } else if(mt == MetricType.COUNTER) {
            return "counters";
        } else {
            return mt.getText();
        }
    }
}

/*
 * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
 * and other contributors as indicated by the @author tags.
 *
 * 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.hawkular.metrics.api.jaxrs.util;

import org.hawkular.metrics.core.api.MetricType;

/**
 * Returns the longer path format used by the REST-interface from the given MetricType
 *
 * @author Michael Burman
 */
public class MetricTypeTextConverter {

    private MetricTypeTextConverter() { }

    public static String getLongForm(MetricType<?> mt) {

        if(mt == MetricType.GAUGE) {
            return "gauges";
        } else if(mt == MetricType.COUNTER) {
            return "counters";
        } else if(mt == MetricType.AVAILABILITY) {
            return mt.getText();
        } else {
            throw new RuntimeException("Unsupported type " + mt.getText());
        }
    }
}

Throw RuntimeException if new type is not added here also


/*
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.imagepipeline.postprocessors;

import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;

/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {

  private @Nullable CacheKey mCacheKey;

  @Override
  public void process(Bitmap bitmap) {
    NativeRoundingFilter.toCircle(bitmap);
  }

  @Nullable
  @Override
  public CacheKey getPostprocessorCacheKey() {
    if (mCacheKey == null) {
      mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
    }
    return mCacheKey;
  }
}

/*
 * Copyright (c) 2017-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
package com.facebook.imagepipeline.postprocessors;

import android.graphics.Bitmap;
import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.nativecode.NativeRoundingFilter;
import com.facebook.imagepipeline.request.BasePostprocessor;
import javax.annotation.Nullable;

/** Postprocessor that rounds a given image as a circle. */
public class RoundAsCirclePostprocessor extends BasePostprocessor {
  private static final boolean ENABLE_ANTI_ALIASING = true;

  private @Nullable CacheKey mCacheKey;
  private final boolean mEnableAntiAliasing;

  public RoundAsCirclePostprocessor() {
    this(ENABLE_ANTI_ALIASING);
  }

  public RoundAsCirclePostprocessor(boolean enableAntiAliasing) {
    mEnableAntiAliasing = enableAntiAliasing;
  }

  @Override
  public void process(Bitmap bitmap) {
    NativeRoundingFilter.toCircle(bitmap, mEnableAntiAliasing);
  }

  @Nullable
  @Override
  public CacheKey getPostprocessorCacheKey() {
    if (mCacheKey == null) {
      if (mEnableAntiAliasing) {
        mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor#AntiAliased");
      } else {
        mCacheKey = new SimpleCacheKey("RoundAsCirclePostprocessor");
      }
    }
    return mCacheKey;
  }
}

Update existing native rounding post processor

Reviewed By: oprisnik

Differential Revision: D9607950

fbshipit-source-id: 080aa9cd339761a48e534c2fd4d3677005063e78


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Metrics used for autoscaling
 *
 * @author bratseth
 */
public class AutoscalingMetrics {

    public static final MetricSet autoscalingMetricSet = create();

    private static MetricSet create() {
        return new MetricSet("autoscaling",
                             metrics("cpu.util",
                                     "mem.util",
                                     "disk.util",
                                     "application_generation",
                                     "in_service",
                                     "queries.rate"));
    }

    private static Set<Metric> metrics(String ... metrics) {
        return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet());
    }

}

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin.monitoring;

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Metrics used for autoscaling
 *
 * @author bratseth
 */
public class AutoscalingMetrics {

    public static final MetricSet autoscalingMetricSet = create();

    private static MetricSet create() {
        return new MetricSet("autoscaling",
                             metrics("cpu.util",
                                     "mem.util",
                                     "disk.util",
                                     "application_generation",
                                     "in_service"));
    }

    private static Set<Metric> metrics(String ... metrics) {
        return Arrays.stream(metrics).map(Metric::new).collect(Collectors.toSet());
    }

}

Revert "Add queries.rate to the 'autoscaling' consumer."


package uni.projects.javafxcrud;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(Thread.currentThread().getContextClassLoader().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

package uni.projects.javafxcrud;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Change to class loader instead of contexclassloader, cause the latter is slower.


package com.icosillion.podengine.utils;

import com.icosillion.podengine.exceptions.DateFormatException;

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

public class DateUtils {

    private static SimpleDateFormat[] dateFormats = {
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"),
            new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"),
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z"),
            new SimpleDateFormat("dd MMM yyyy HH:mm Z")
    };

    public static Date stringToDate(String dt) throws DateFormatException {

        Date date = null;

        for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
            try {
                date = dateFormat.parse(dt);
                break;
            } catch (ParseException e) {
                //This format didn't work, keep going
            }
        }

        return date;
    }
}

package com.icosillion.podengine.utils;

import com.icosillion.podengine.exceptions.DateFormatException;

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

public class DateUtils {

    private static SimpleDateFormat[] dateFormats = {
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US),
            new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US),
            new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z", Locale.US),
            new SimpleDateFormat("dd MMM yyyy HH:mm Z", Locale.US)
    };

    public static Date stringToDate(String dt) throws DateFormatException {

        Date date = null;

        for (SimpleDateFormat dateFormat : DateUtils.dateFormats) {
            try {
                date = dateFormat.parse(dt);
                break;
            } catch (ParseException e) {
                //This format didn't work, keep going
            }
        }

        return date;
    }
}

Use US Locale for date parser

Use US Locale for date parser


package som.interpreter.nodes.dispatch;

import som.vm.Universe;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SInvokable;
import som.vmobjects.SSymbol;

import com.oracle.truffle.api.frame.VirtualFrame;

public final class GenericDispatchNode extends AbstractDispatchWithLookupNode {

  public GenericDispatchNode(final SSymbol selector, final Universe universe) {
    super(selector, universe);
  }

  @Override
  public Object executeDispatch(
      final VirtualFrame frame, final Object[] arguments) {
    SInvokable method = lookupMethod(arguments[0]);
    if (method != null) {
      return method.getCallTarget().call(arguments);
    } else {
      // TODO: perhaps, I should mark this branch with a branch profile as
      //       being unlikely
      return sendDoesNotUnderstand(arguments);
    }
  }

  private Object sendDoesNotUnderstand(final Object[] arguments) {
    // TODO: this is all extremely expensive, and could be optimized by
    //       further specialization for #dnu
    return SAbstractObject.sendDoesNotUnderstand(selector, arguments, universe);
  }

  @Override
  public int lengthOfDispatchChain() {
    return 1000;
  }
}

package som.interpreter.nodes.dispatch;

import som.vm.Universe;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SInvokable;
import som.vmobjects.SSymbol;

import com.oracle.truffle.api.frame.VirtualFrame;

public final class GenericDispatchNode extends AbstractDispatchWithLookupNode {

  public GenericDispatchNode(final SSymbol selector, final Universe universe) {
    super(selector, universe);
  }

  @Override
  public Object executeDispatch(
      final VirtualFrame frame, final Object[] arguments) {
    SInvokable method = lookupMethod(arguments[0]);
    if (method != null) {
      return method.invoke(arguments);
    } else {
      // TODO: perhaps, I should mark this branch with a branch profile as
      //       being unlikely
      return sendDoesNotUnderstand(arguments);
    }
  }

  private Object sendDoesNotUnderstand(final Object[] arguments) {
    // TODO: this is all extremely expensive, and could be optimized by
    //       further specialization for #dnu
    return SAbstractObject.sendDoesNotUnderstand(selector, arguments, universe);
  }

  @Override
  public int lengthOfDispatchChain() {
    return 1000;
  }
}

Use invoke method like in all other places.

Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>


package info.novatec.tr;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TokenRunApplication.class)
@IntegrationTest
@WebAppConfiguration
public class TokenRunApplicationTests {

	@Test
	@Ignore
	public void contextLoads() {
	}

}

package info.novatec.tr;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TokenRunApplication.class)
@IntegrationTest
@WebAppConfiguration
public class TokenRunApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Remove @Ignore annotation which is not needed. The test runs successfully.


package ch.zuehlke.campplanner;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {

	@Test
	public void contextLoads() {
	}

}

package ch.zuehlke.campplanner;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("dev")
@SpringApplicationConfiguration(classes = CampplannerApplication.class)
@WebAppConfiguration
public class CampplannerApplicationTests {

	@Test
	public void contextLoads() {
	}

}

Use dev profile for integration tests.

Use dev profile for integration tests.


package me.normanmaurer.niosmtp.impl.internal;

import java.util.Collection;
import java.util.Iterator;

import me.normanmaurer.niosmtp.DeliveryRecipientStatus;
import me.normanmaurer.niosmtp.DeliveryResult;

public class DeliveryResultImpl implements DeliveryResult{

    private final Collection<DeliveryRecipientStatus> status;
    private final Throwable cause;

    public DeliveryResultImpl(Collection<DeliveryRecipientStatus> status) {
        this.status = status;
        this.cause = null;
    }

    public DeliveryResultImpl(Throwable cause) {
        this.cause = cause;
        this.status = null;
    }

    @Override
    public boolean isSuccess() {
        return cause == null;
    }

    @Override
    public Throwable getCause() {
        return null;
    }

    @Override
    public Iterator<DeliveryRecipientStatus> getRecipientStatus() {
        if (status == null) {
            return null;
        }
        return status.iterator();
    }

}

package me.normanmaurer.niosmtp.impl.internal;

import java.util.Collection;
import java.util.Iterator;

import me.normanmaurer.niosmtp.DeliveryRecipientStatus;
import me.normanmaurer.niosmtp.DeliveryResult;

public class DeliveryResultImpl implements DeliveryResult{

    private final Collection<DeliveryRecipientStatus> status;
    private final Throwable cause;

    public DeliveryResultImpl(Collection<DeliveryRecipientStatus> status) {
        this.status = status;
        this.cause = null;
    }

    public DeliveryResultImpl(Throwable cause) {
        this.cause = cause;
        this.status = null;
    }

    @Override
    public boolean isSuccess() {
        return cause == null;
    }

    @Override
    public Throwable getCause() {
        return cause;
    }

    @Override
    public Iterator<DeliveryRecipientStatus> getRecipientStatus() {
        if (status == null) {
            return null;
        }
        return status.iterator();
    }

}

Return the Throwable on error

Return the Throwable on error


package com.github.sparkcaller.variantdiscovery;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import scala.Tuple2;

import java.io.File;

public class VQSRRecalibrationApplier extends BaseGATKProgram {
    public VQSRRecalibrationApplier(String pathToReference, String extraArgs, String coresPerNode) {
        super("ApplyRecalibration", extraArgs);
        setReference(pathToReference);
        addArgument("-nt", coresPerNode);
    }

    public static String constructRecalFilename(String vcfToRecalibrate, String mode) {
        return Utils.removeExtenstion(vcfToRecalibrate, "vcf") + "-recalib-" + mode + ".vcf";
    }

    public File applyRecalibration(File vcfToRecalibrate, Tuple2<File, File> recalibrationFiles, String mode) {
        File recalibrationFile = recalibrationFiles._1;
        File tranchesFile = recalibrationFiles._2;

        changeArgument("-mode", mode);
        changeArgument("-input", vcfToRecalibrate.getPath());

        changeArgument("-tranchesFile", tranchesFile.getPath());
        changeArgument("-recalFile", recalibrationFile.getPath());

        File recalibratedOutput = new File(constructRecalFilename(vcfToRecalibrate.getPath(), mode));
        setOutputFile(recalibratedOutput.getPath());
        return recalibratedOutput;
    }
}

package com.github.sparkcaller.variantdiscovery;

import com.github.sparkcaller.BaseGATKProgram;
import com.github.sparkcaller.Utils;
import scala.Tuple2;

import java.io.File;

/*
 * Applies the recalibration targets generated by VQSRTarget generator.
 *
 * See:
 * https://software.broadinstitute.org/gatk/gatkdocs/org_broadinstitute_gatk_tools_walkers_variantrecalibration_ApplyRecalibration.php
 *
 * For more documentation.
 */

public class VQSRRecalibrationApplier extends BaseGATKProgram {
    public VQSRRecalibrationApplier(String pathToReference, String extraArgs, String coresPerNode) {
        super("ApplyRecalibration", extraArgs);
        setReference(pathToReference);
        addArgument("-nt", coresPerNode);
    }

    public static String constructRecalFilename(String vcfToRecalibrate, String mode) {
        return Utils.removeExtenstion(vcfToRecalibrate, "vcf") + "-recalib-" + mode + ".vcf";
    }

    public File applyRecalibration(File vcfToRecalibrate, Tuple2<File, File> recalibrationFiles, String mode) {
        File recalibrationFile = recalibrationFiles._1;
        File tranchesFile = recalibrationFiles._2;

        changeArgument("-mode", mode);
        changeArgument("-input", vcfToRecalibrate.getPath());

        changeArgument("-tranchesFile", tranchesFile.getPath());
        changeArgument("-recalFile", recalibrationFile.getPath());

        File recalibratedOutput = new File(constructRecalFilename(vcfToRecalibrate.getPath(), mode));
        setOutputFile(recalibratedOutput.getPath());
        return recalibratedOutput;
    }
}

[Genomics]: Add a breif explaination of what the class does.


package com.saintsrobotics.frc;

import edu.wpi.first.wpilibj.Relay;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {
    // Motors
    public static final int LEFT_MOTOR_1 = 1;
    public static final int LEFT_MOTOR_2 = 2;

    public static final int RIGHT_MOTOR_1 = 3;
    public static final int RIGHT_MOTOR_2 = 4;

    // Relays
    public static final int PICKUP_RELAY = 1;
    public static final Relay.Direction PICKUP_RELAY_DIRECTION =
            Relay.Direction.kBoth;

    public static final int SHOOTER_RELAY = 2;
    public static final Relay.Direction SHOOTER_RELAY_DIRECTION =
            Relay.Direction.kForward;

    public static final int GEAR_SHIFTER_RELAY = 3;
    public static final Relay.Direction GEAR_SHIFTER_RELAY_DIRECTION =
            Relay.Direction.kBoth;
}

package com.saintsrobotics.frc;

import edu.wpi.first.wpilibj.Relay;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {
    // Motors
    public static final int LEFT_MOTOR_1 = 1;
    public static final int LEFT_MOTOR_2 = 2;

    public static final int RIGHT_MOTOR_1 = 3;
    public static final int RIGHT_MOTOR_2 = 4;

    // Relays
    public static final int PICKUP_RELAY = 2;
    public static final Relay.Direction PICKUP_RELAY_DIRECTION =
            Relay.Direction.kBoth;

    public static final int SHOOTER_RELAY = 1;
    public static final Relay.Direction SHOOTER_RELAY_DIRECTION =
            Relay.Direction.kForward;

    public static final int GEAR_SHIFTER_RELAY = 3;
    public static final Relay.Direction GEAR_SHIFTER_RELAY_DIRECTION =
            Relay.Direction.kBoth;
}

Fix shooter and pickup relay numbers

Fix shooter and pickup relay numbers


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

package co.phoenixlab.discord.api.request.channel;

import co.phoenixlab.discord.api.entities.guild.DiscordPermissionSet;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class EditChannelPermissionsRequest {

    private DiscordPermissionSet allow;
    private DiscordPermissionSet deny;

}

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

package co.phoenixlab.discord.api.request.channel;

import co.phoenixlab.discord.api.entities.guild.DiscordPermissionSet;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Builder
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class EditChannelPermissionsRequest {

    public enum Type {
        MEMBER,
        ROLE
    }

    private DiscordPermissionSet allow;
    private DiscordPermissionSet deny;
    private Type type;

}

Add type field to edit channel perms request


package com.example.android.sunshine.app;

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

/**
 * Created by pmatushkin on 8/26/2015.
 */
public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

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

package com.example.android.sunshine.app;

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

/**
 * Created by pmatushkin on 8/26/2015.
 */
public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

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

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

        EditText editText = this.getEditText();
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                Dialog d = getDialog();

                if (d instanceof AlertDialog) {
                    AlertDialog dialog = (AlertDialog) d;
                    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    // Check if the EditText is empty
                    if (editable.length() < mMinLength) {
                        // Disable OK button
                        positiveButton.setEnabled(false);
                    } else {
                        // Enable OK button
                        positiveButton.setEnabled(true);
                    }
                }
            }
        });
    }
}

Use custom length attribute to enable or disable OK button in location preference dialog


package org.oxtrust.qa.runner;

import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;

@RunWith(Cucumber.class)
@CucumberOptions(features = { "src/test/java/org/oxtrust/qa/features" }, plugin = { "pretty",
		"json:target/cucumber/json/cucumber.json" }, glue = "", monochrome = true, tags = { "@gluuQAPending" })
public class AllFeatureBeingImplementedTest {

}

package org.oxtrust.qa.runner;

import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;
import cucumber.api.CucumberOptions;

//@RunWith(Cucumber.class)
//@CucumberOptions(features = { "src/test/java/org/oxtrust/qa/features" }, plugin = { "pretty",
//		"json:target/cucumber/json/cucumber.json" }, glue = "", monochrome = true, tags = { "@gluuQAPending" })
public class AllFeatureBeingImplementedTest {

}

Fix typo in Qa test

Fix typo in Qa test


/*
 * Copyright 2008-2011 Red Hat, Inc, and individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.torquebox.messaging.metadata;

public class QueueMetaData extends AbstractDestinationMetaData {

    private boolean durable;

    public QueueMetaData() {

    }

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

    public String toString() {
        return "[QueueMetaData: name=" + getName() + "]";
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isDurable() {
        return this.durable;
    }

}

/*
 * Copyright 2008-2011 Red Hat, Inc, and individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.torquebox.messaging.metadata;

public class QueueMetaData extends AbstractDestinationMetaData {

    private boolean durable = true;

    public QueueMetaData() {

    }

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

    public String toString() {
        return "[QueueMetaData: name=" + getName() + "]";
    }

    public void setDurable(boolean durable) {
        this.durable = durable;
    }

    public boolean isDurable() {
        return this.durable;
    }

}

Make queues durable by default in the MetaData so tasks & backgroundable get it for free.


package ru.aserdyuchenko.servlet;

import static org.junit.Assert.*;

public class ServletDeleteUserTest {

}

package ru.aserdyuchenko.servlet;

import org.junit.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class ServletDeleteUserTest {
    @Test
    public void addUser() throws ServletException, IOException, SQLException {
        ServletDeleteUser servlet = new ServletDeleteUser();
        HttpServletRequest request = mock(HttpServletRequest.class);
        HttpServletResponse response = mock(HttpServletResponse.class);
        List<User> users = DataSource.getInstance().getList();

        User user = users.get(users.size() - 1);

        when(request.getParameter("login")).thenReturn(user.getLogin());

        servlet.doPost(request, response);

        assertFalse(DataSource.getInstance().getList().contains(user));
    }
}

Test for add and delete user.

Test for add and delete user.


package syntax;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.extendj.JavaChecker;
import org.extendj.parser.JavaParser;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;

public abstract class SyntaxTestBase {
  private static final String DIR = "src/test/resources/syntax/";

  private static class Checker extends JavaChecker {
    private String runChecker(String file) throws IOException {
      run(new String[]{file});
      return program.structuredPrettyPrint();
    }
  }

  private static String slurp(String file) throws IOException {
    return new String(Files.readAllBytes(Paths.get(file)), UTF_8);
  }

  protected void checkSyntax(String name) {
    String actual, expected;
    try {
      actual   = new Checker().runChecker(DIR + name + ".java");
      expected = slurp(DIR + name + ".expected");
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
    assertEquals(expected.trim(), actual.trim());
  }
}

package syntax;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.extendj.JavaChecker;
import org.extendj.parser.JavaParser;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.*;

public abstract class SyntaxTestBase {
  private static final String DIR = "src/test/resources/syntax/";

  private static class Checker extends JavaChecker {
    private String runChecker(String file) throws IOException {
      run(new String[]{"-classpath", "build/classes/main", file});
      return program.structuredPrettyPrint();
    }
  }

  private static String slurp(String file) throws IOException {
    return new String(Files.readAllBytes(Paths.get(file)), UTF_8);
  }

  protected void checkSyntax(String name) {
    String actual, expected;
    try {
      actual   = new Checker().runChecker(DIR + name + ".java");
      expected = slurp(DIR + name + ".expected");
    }
    catch (IOException e) {
      throw new RuntimeException(e);
    }
    assertEquals(expected.trim(), actual.trim());
  }
}

Add proper classpath to syntax tests

Add proper classpath to syntax tests

To prevent unknown type errors being spewed on stderr.


package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Lists;

public final class ListElementParser extends StringElementParser {

    ListElementParser() {}

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

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

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

package org.monospark.spongematchers.parser.element;

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

import org.monospark.spongematchers.util.PatternBuilder;

import com.google.common.collect.Lists;

public final class ListElementParser extends StringElementParser {

    ListElementParser() {}

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

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

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

Fix a bug where spaces in a list element would cause an exception


package org.metaborg.runtime.task.primitives;

import static org.metaborg.runtime.task.util.ListBuilder.makeList;

import org.metaborg.runtime.task.Task;
import org.metaborg.runtime.task.TaskEngine;
import org.metaborg.runtime.task.TaskManager;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;

public class task_api_get_results_0_1 extends AbstractPrimitive {
	public static task_api_get_results_0_1 instance = new task_api_get_results_0_1();

	public task_api_get_results_0_1() {
		super("task_api_get_results", 0, 1);
	}

	@Override
	public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException {
		final TaskEngine taskEngine = TaskManager.getInstance().getCurrent();
		final IStrategoTerm taskID = tvars[0];
		final Task task = taskEngine.getTask(taskID);
		if(!task.hasResults())
			return false;
		env.setCurrent(makeList(env.getFactory(), task.results()));
		return true;
	}
}

package org.metaborg.runtime.task.primitives;

import static org.metaborg.runtime.task.util.ListBuilder.makeList;

import org.metaborg.runtime.task.Task;
import org.metaborg.runtime.task.TaskEngine;
import org.metaborg.runtime.task.TaskManager;
import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;

public class task_api_get_results_0_1 extends AbstractPrimitive {
	public static task_api_get_results_0_1 instance = new task_api_get_results_0_1();

	public task_api_get_results_0_1() {
		super("task_api_get_results", 0, 1);
	}

	@Override
	public boolean call(IContext env, Strategy[] svars, IStrategoTerm[] tvars) throws InterpreterException {
		final TaskEngine taskEngine = TaskManager.getInstance().getCurrent();
		final IStrategoTerm taskID = tvars[0];
		final Task task = taskEngine.getTask(taskID);
		if(!task.solved())
			return false;
		env.setCurrent(makeList(env.getFactory(), task.results()));
		return true;
	}
}

Fix task_api_get_results failing if task had no results, while this is actually fine.


package devopsdistilled.operp.client.items;

import javax.inject.Inject;

import org.springframework.context.ApplicationContext;

import devopsdistilled.operp.client.items.controllers.CreateItemPaneController;
import devopsdistilled.operp.server.data.entity.items.Item;
import devopsdistilled.operp.server.data.service.items.ItemService;

public class ItemControllerImpl implements ItemController {

	@Inject
	private ApplicationContext context;

	@Inject
	private ItemService itemService;

	@Override
	public void createItem() {
		CreateItemPaneController createItemPaneController = context
				.getBean(CreateItemPaneController.class);
		createItemPaneController.init();
	}

	@Override
	public void editItem(Item item) {

	}

	@Override
	public void listItems() {
		ListItemPane listItemPane = context.getBean(ListItemPane.class);
		listItemPane.init();
		listItemPane.getDialog();
	}

	@Override
	public void deleteItem(Item item) {
		itemService.delete(item);
	}

}

package devopsdistilled.operp.client.items;

import javax.inject.Inject;

import org.springframework.context.ApplicationContext;

import devopsdistilled.operp.client.items.controllers.CreateItemPaneController;
import devopsdistilled.operp.client.items.controllers.ListItemPaneController;
import devopsdistilled.operp.server.data.entity.items.Item;
import devopsdistilled.operp.server.data.service.items.ItemService;

public class ItemControllerImpl implements ItemController {

	@Inject
	private ApplicationContext context;

	@Inject
	private ItemService itemService;

	@Override
	public void createItem() {
		CreateItemPaneController createItemPaneController = context
				.getBean(CreateItemPaneController.class);
		createItemPaneController.init();
	}

	@Override
	public void listItems() {
		ListItemPaneController listItemPaneController = context
				.getBean(ListItemPaneController.class);
		listItemPaneController.init();
	}

	@Override
	public void editItem(Item item) {

	}

	@Override
	public void deleteItem(Item item) {
		itemService.delete(item);
	}

}

Define listItems() with new MVC model

Define listItems() with new MVC model

OPEN - task 41: Design "ListItemPane" as per new MVC model
http://github.com/DevOpsDistilled/OpERP/issues/issue/41


package devopsdistilled.operp.server.data.entity.account;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import devopsdistilled.operp.server.data.entity.Entiti;

@MappedSuperclass
public abstract class Account extends Entiti<Long> {

	private static final long serialVersionUID = -8130237994739975187L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long accountId;

	private Double balance;

	public Long getAccountId() {
		return accountId;
	}

	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}

	public Double getBalance() {
		return balance;
	}

	public void setBalance(Double balance) {
		this.balance = balance;
	}

	@Override
	public Long id() {
		return getAccountId();
	}

	@Override
	public String toString() {
		return new String(getAccountId() + ": " + getBalance().toString());
	}
}

package devopsdistilled.operp.server.data.entity.account;

import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

import devopsdistilled.operp.server.data.entity.Entiti;

@MappedSuperclass
public abstract class Account extends Entiti<Long> {

	private static final long serialVersionUID = -8130237994739975187L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long accountId;

	private Double balance = 0.0;

	public Long getAccountId() {
		return accountId;
	}

	public void setAccountId(Long accountId) {
		this.accountId = accountId;
	}

	public Double getBalance() {
		return balance;
	}

	public void setBalance(Double balance) {
		this.balance = balance;
	}

	@Override
	public Long id() {
		return getAccountId();
	}

	@Override
	public String toString() {
		return new String(getAccountId() + ": " + getBalance().toString());
	}
}

Set default balance to be 0.0

Set default balance to be 0.0

OPEN - task 79: Create Party Module
http://github.com/DevOpsDistilled/OpERP/issues/issue/79


/*
 *  Copyright 2019 Google LLC. All rights reserved.
 *
 * 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.
 *
 * Any software provided by Google hereunder is distributed “AS IS”,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and is not intended for production use.
 *
 */

package com.google.gcs.sdrs.dao;

import java.io.Serializable;

/**
 * Interface for Data Access Object pattern
 *
 * @author salguerod
 *
 * @param <T>
 * @param <Id>
 */
public interface Dao<T, Id extends Serializable> {

  Id save(T entity);

  void update(T object);

  T findById(Id id);

  void delete(T object);

}

/*
 *  Copyright 2019 Google LLC. All rights reserved.
 *
 * 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.
 *
 * Any software provided by Google hereunder is distributed “AS IS”,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, and is not intended for production use.
 *
 */

package com.google.gcs.sdrs.dao;

import java.io.Serializable;

/**
 * Interface for Data Access Object pattern
 *
 * @author salguerod
 *
 * @param <T>
 * @param <Id>
 */
public interface Dao<T, Id extends Serializable> {

  Id save(T entity);

  void update(T entity);

  T findById(Id id);

  void delete(T entity);

}

Rename object to entity in interface.

Rename object to entity in interface.


package net.sourceforge.javydreamercsw.client.ui.nodes.actions;

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;

/**
 *
 * @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
 */
public class CreateTestAction extends AbstractAction {

    public CreateTestAction() {
        super("Create Test",
                new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                final CreateTestDialog dialog =
                        new CreateTestDialog(new javax.swing.JFrame(), true);
                dialog.setLocationRelativeTo(null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        dialog.dispose();
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
}

package net.sourceforge.javydreamercsw.client.ui.nodes.actions;

import com.validation.manager.core.db.TestPlan;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.ImageIcon;
import org.openide.util.Utilities;

/**
 *
 * @author Javier A. Ortiz Bultron <javier.ortiz.78@gmail.com>
 */
public class CreateTestAction extends AbstractAction {

    public CreateTestAction() {
        super("Create Test",
                new ImageIcon("com/validation/manager/resources/icons/Signage/Add Square.png"));
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                final CreateTestDialog dialog =
                        new CreateTestDialog(new javax.swing.JFrame(), true);
                dialog.setTestPlan(Utilities.actionsGlobalContext().lookup(TestPlan.class));
                dialog.setLocationRelativeTo(null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        dialog.dispose();
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
}

Fix NPE while creating tests.

Fix NPE while creating tests.


package com.alexstyl.specialdates.events.namedays;

import android.support.annotation.RawRes;

import com.alexstyl.specialdates.R;
import com.novoda.notils.exception.DeveloperError;

public enum NamedayLocale {
    GREEK("gr", true, R.raw.gr_namedays),
    ROMANIAN("ro", false, R.raw.ro_namedays),
    RUSSIAN("ru", false, R.raw.ru_namedays),
    LATVIAN("lv", false, R.raw.lv_namedays),
    SLOVAK("sk", false, R.raw.sk_namedays),
    CZECH("cs", false, R.raw.cs_namedays);

    private final String shortCode;
    private final boolean soundCompared;
    private final int rawResId;

    NamedayLocale(String shortCode, boolean soundCompared, @RawRes int rawResId) {
        this.shortCode = shortCode;
        this.soundCompared = soundCompared;
        this.rawResId = rawResId;
    }

    public static NamedayLocale from(String displayLanguage) {
        for (NamedayLocale locale : values()) {
            if (locale.name().equalsIgnoreCase(displayLanguage)) {
                return locale;
            }
        }
        throw new DeveloperError("No NamedayLocale found for [%s]", displayLanguage);
    }

    public int getRawResId() {
        return rawResId;
    }

    public boolean isComparedBySound() {
        return soundCompared;
    }

    public String getShortCode() {
        return shortCode;
    }
}

package com.alexstyl.specialdates.events.namedays;

import android.support.annotation.RawRes;

import com.alexstyl.specialdates.R;
import com.novoda.notils.exception.DeveloperError;

public enum NamedayLocale {
    GREEK("gr", true, R.raw.gr_namedays),
    ROMANIAN("ro", false, R.raw.ro_namedays),
    RUSSIAN("ru", false, R.raw.ru_namedays),
    LATVIAN("lv", false, R.raw.lv_namedays),
    SLOVAK("sk", false, R.raw.sk_namedays),
    CZECH("cs", false, R.raw.cs_namedays);

    private final String shortCode;
    private final boolean soundCompared;
    private final int rawResId;

    NamedayLocale(String shortCode, boolean soundCompared, @RawRes int rawResId) {
        this.shortCode = shortCode;
        this.soundCompared = soundCompared;
        this.rawResId = rawResId;
    }

    public static NamedayLocale from(String displayLanguage) {
        for (NamedayLocale locale : values()) {
            if (locale.getShortCode().equalsIgnoreCase(displayLanguage)) {
                return locale;
            }
        }
        throw new DeveloperError("No NamedayLocale found for [%s]", displayLanguage);
    }

    public int getRawResId() {
        return rawResId;
    }

    public boolean isComparedBySound() {
        return soundCompared;
    }

    public String getShortCode() {
        return shortCode;
    }
}

Use getShortCode() instead of enum name()


package com.uwetrottmann.trakt.v2.entities;

public class Username {

    /**
     * Special user name for the current user (determined by auth data).
     */
    public static final Username ME = new Username("me");

    private String encodedUsername;

    /**
     * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-").
     *
     * @param username A username as returned by the trakt API.
     * @see #ME
     */
    public Username(String username) {
        if (username == null || username.length() == 0) {
            throw new IllegalArgumentException("trakt username can not be empty.");
        }
        this.encodedUsername = username.replace(".", "-");
    }

    @Override
    public String toString() {
        return encodedUsername;
    }
}

package com.uwetrottmann.trakt.v2.entities;

public class Username {

    /**
     * Special user name for the current user (determined by auth data).
     */
    public static final Username ME = new Username("me");

    private String encodedUsername;

    /**
     * Encodes the username returned from trakt so it is API compatible (currently replaces "." with "-").
     *
     * @param username A username as returned by the trakt API.
     * @see #ME
     */
    public Username(String username) {
        if (username == null || username.length() == 0) {
            throw new IllegalArgumentException("trakt username can not be empty.");
        }
        // trakt encodes some special chars in usernames
        // - points "." as a dash "-"
        // - spaces " " as a dash "-"
        // - multiple dashes are reduced to one
        this.encodedUsername = username.replace(".", "-").replace(" ", "-").replaceAll("(-)+", "-");
    }

    @Override
    public String toString() {
        return encodedUsername;
    }
}

Remove spaces in user names.

Remove spaces in user names.

- Also ensure multiple consecutive dashes are replaced by just one.