package org.epctagcoder.parse.SGTIN;

import org.epctagcoder.exception.EPCParseException;
import org.epctagcoder.result.SGTIN;
import org.junit.Test;

import static org.epctagcoder.parse.SGTIN.ParseSGTIN.Builder;
import static org.junit.Assert.*;

public class TestParseSGTINWithRfidTag {

    @Test
    public void whenRfidTagIsNotGS1_thenParseExceptionIsRaised() {
        assertThrows(EPCParseException.class, () -> Builder().withRFIDTag("F45349FB11DF49FA935AB6FF").build());
    }

    @Test
    public void whenPartitionIsWrong_thenParseExceptionIsRaised() {
        assertThrows(EPCParseException.class, () -> Builder().withRFIDTag("303C83F1B7DD441678901234").build());
    }

    @Test
    public void parseEpcSerialTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("96511988276", sgtin.getSerial());
    }

    @Test
    public void parseEpcEanTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("141674018641", sgtin.getCompanyPrefix() + sgtin.getItemReference());
    }

    @Test
    public void parseEpcFilterTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("3024698E2CB1005678901234").build().getSGTIN();

        assertEquals("1", sgtin.getFilterValue());
    }

    @Test
    public void parseEpcPartitionTest() throws EPCParseException {
        SGTIN sgtin = Builder().withRFIDTag("30285471BD5A0A5678901234").build().getSGTIN();

        assertEquals("2", sgtin.getPartitionValue());
    }

    @Test
    public void parseNonHexEpc() {
        assertThrows(IllegalArgumentException.class, () -> Builder().withRFIDTag("30285471BD5A0A56789G1234").build());
    }
}

Add test for SGTIN rfid tag parsing

Add test for SGTIN rfid tag parsing


package org.apollo.game.message.handler;

import org.apollo.cache.def.ItemDefinition;
import org.apollo.game.message.impl.ItemOnItemMessage;
import org.apollo.game.model.Item;
import org.apollo.game.model.World;
import org.apollo.game.model.entity.Player;
import org.apollo.game.model.inter.bank.BankConstants;
import org.apollo.game.model.inv.Inventory;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertTrue;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Player.class, ItemDefinition.class})
public class ItemOnItemVerificationHandlerTest {

	private ItemOnItemVerificationHandler verificationHandler = new ItemOnItemVerificationHandler(new World());

	@BeforeClass
	public static void setupTestItemDefinitions() {
		PowerMockito.mockStatic(ItemDefinition.class);
		Mockito.when(ItemDefinition.lookup(4151)).thenReturn(new ItemDefinition(4151));
	}

	@Test
	public void testTerminateWithNoSourceItem() throws Exception {
		Player player = PowerMockito.mock(Player.class);
		Inventory inventory = new Inventory(28);
		inventory.set(1, new Item(4151, 1));

		Mockito.when(player.getInventory()).thenReturn(inventory);

		ItemOnItemMessage itemOnItemMessage = new ItemOnItemMessage(BankConstants.SIDEBAR_INVENTORY_ID, 500, 1,
				BankConstants.SIDEBAR_INVENTORY_ID, 4151, 1);

		verificationHandler.handle(player, itemOnItemMessage);

		assertTrue("ItemOnItemVerificationHandler: failed checking source item / slot exists", itemOnItemMessage.terminated());
	}
}

Test messages with an invalid source are terminated


package com.mcac0006.services.siftscience;

import com.jayway.jsonpath.JsonPath;
import com.mcac0006.siftscience.SiftScienceHelper;
import com.mcac0006.siftscience.event.domain.CreateContent;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;

import static com.mcac0006.services.siftscience.AssertJsonKeys.assertEquals;

public class CreateContentBodyTest {

	@Test
	@SuppressWarnings("unchecked")
	public void createContentTest() throws IOException {
			final CreateContent create_order = new CreateContent();
            String expectedApiKey = "INSERT_API_KEY_HERE";
            create_order.setApiKey(expectedApiKey);
            String expectedUserId = "john_doe";
            String expectedSessionId = "abcabcabc";
            String expectedContactEmail = "test@siftscience.com";
            String expectedContactPhone = "1-800-123-1234";
            String expectedSubject = "Subject";
            String expectedContent = "Lorem ipsum dolor sit amet";
            create_order.setUserId(expectedUserId).setSessionId(expectedSessionId).setContactEmail(expectedContactEmail).setContactPhone(expectedContactPhone).setSubject(expectedSubject).setContent(expectedContent);

			final String json = SiftScienceHelper.serialize(create_order); // the json object we will be asserting

			final Object read = JsonPath.read(json, "$");
			final LinkedHashMap<String, Object> $ =(LinkedHashMap<String, Object>)read;

			// assert first level
			final List<String> $expectedKeys = Arrays.asList("$type", "$api_key", "$user_id", "$session_id", "$contact_email", "$contact_phone", "$subject", "$content");
			assertEquals($.keySet(), $expectedKeys);

			// then assert the values
			Assert.assertEquals(expectedApiKey, $.get("$api_key"));
			Assert.assertEquals("$create_content", $.get("$type"));
			Assert.assertEquals(expectedUserId, $.get("$user_id"));

			Assert.assertEquals(expectedSessionId, $.get("$session_id"));
			Assert.assertEquals(expectedContactEmail, $.get("$contact_email"));
			Assert.assertEquals(expectedContactPhone, $.get("$contact_phone"));
			Assert.assertEquals(expectedSubject, $.get("$subject"));
			Assert.assertEquals(expectedContent, $.get("$content"));
	}
}

Test on new CreateContent event

Test on new CreateContent event


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.tags.params;

public enum SortParam {
    Off,
    Alphabetical,
    Date,
    DocumentCount,
    NumberDecreasing,
    NumberIncreasing,
    ReverseAlphabetical,
    ReverseDate,
    ReverseDocumentCount;

    public static SortParam fromValue(final String value) {
        for (final SortParam param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

Add sort parameter for get query tag values. [rev: ivo.miller]


package org.realityforge.arez.api2.test;

import org.realityforge.arez.api2.AbstractArezTest;
import org.realityforge.arez.api2.ArezContext;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class TransactionApiTest
  extends AbstractArezTest
{
  @Test
  public void transactionsCanProduceValues()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    final String expectedValue = ValueUtil.randomString();

    final String v0 =
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );
        return expectedValue;
      } );

    assertFalse( context.isTransactionActive() );

    assertEquals( v0, expectedValue );
  }

  @Test
  public void transactionsCanBeNested()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    context.transaction( ValueUtil.randomString(), null, () -> {
      assertTrue( context.isTransactionActive() );

      //First nested exception
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );

        //Second nested exception
        context.transaction( ValueUtil.randomString(), null, () -> {
          assertTrue( context.isTransactionActive() );
        } );

        assertTrue( context.isTransactionActive() );
      } );

      assertTrue( context.isTransactionActive() );
    } );

    assertFalse( context.isTransactionActive() );
  }

  @Test
  public void valueProducingTransactionsCanBeNested()
    throws Exception
  {
    final ArezContext context = new ArezContext();

    assertFalse( context.isTransactionActive() );

    final String expectedValue = ValueUtil.randomString();

    final String v0 =
      context.transaction( ValueUtil.randomString(), null, () -> {
        assertTrue( context.isTransactionActive() );

        //First nested exception
        final String v1 =
          context.transaction( ValueUtil.randomString(), null, () -> {
            assertTrue( context.isTransactionActive() );

            //Second nested exception
            final String v2 =
              context.transaction( ValueUtil.randomString(), null, () -> {
                assertTrue( context.isTransactionActive() );
                return expectedValue;
              } );

            assertTrue( context.isTransactionActive() );

            return v2;
          } );

        assertTrue( context.isTransactionActive() );
        return v1;
      } );

    assertFalse( context.isTransactionActive() );

    assertEquals( v0, expectedValue );
  }
}

Add some minimal tests that exercise the API layer


package com.harmoneye.tonecircle;

import static org.junit.Assert.*;

import org.junit.Test;

public class PitchClassSetTest {

	@Test
	public void testCanonicalization() {
		PitchClassSet set = PitchClassSet.fromArray(0, 4, 7);
		PitchClassSet canonic = set.getCanonic();
		for (int i = 0; i < PitchClassSet.OCTAVE_SIZE; i++) {
			assertEquals(canonic, set.getCanonic());
			assertEquals(i, set.getRoot());
			set = set.transpose(1);
		}
	}

	@Test
	public void testEquals() {
		assertEquals(PitchClassSet.fromArray(), PitchClassSet.fromIndex(0));
		assertEquals(PitchClassSet.fromArray(1, 5, 8), PitchClassSet.fromIndex(290));
		assertNotEquals(PitchClassSet.fromArray(1, 5, 8), PitchClassSet.fromIndex(145));
	}

	@Test
	public void testGet() {
		PitchClassSet set = PitchClassSet.fromArray(0, 4, 7);
		assertTrue(set.get(0));
		assertTrue(set.get(4));
		assertTrue(set.get(7));

		assertFalse(set.get(1));
		assertFalse(set.get(2));
		assertFalse(set.get(8));
	}
}

Add an incomplete test for PitchClassSet.


/*******************************************************************************
 *
 *  Copyright FUJITSU LIMITED 2016
 *
 *  Creation Date: 2016/11/11
 *
 *******************************************************************************/

package org.oscm.app.vmware.service;

import java.util.List;

import org.oscm.app.common.intf.InstanceAccess;
import org.oscm.app.common.intf.ServerInformation;
import org.oscm.app.v2_0.exceptions.APPlatformException;

/**
 * @author tateiwamext
 *
 */
public class VMwareInstanceAccess implements InstanceAccess {

    private static final long serialVersionUID = 5685290474829749127L;

    @Override
    public List<? extends ServerInformation> getServerDetails(String instanceId)
            throws APPlatformException {
        return null;
    }

    @Override
    public String getAccessInfo(String instanceId) throws APPlatformException {
        return null;
    }

    @Override
    public String getMessage(String locale, String key, Object... arguments) {
        return null;
    }

}

Add implementation to satisfy CDI

Add implementation to satisfy CDI


/*
 * Copyright (c) 2016 Fraunhofer FOKUS
 * 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.openbaton.exceptions;

/**
 * Created by lto on 03/06/16.
 */
public class PasswordWeakException extends Exception {
    public PasswordWeakException() {
    }

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

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

    public PasswordWeakException(Throwable cause) {
        super(cause);
    }
}

Fix gui bug and add project id to vnfrecord


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

import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.spy;

import org.junit.Test;

/**
 * Unit tests for the {@link Discovery} class.
 */
public class DiscoveryTest {
    /**
     * Calling {@link Discovery#enable(DiscoveryListener)} is a shortcut for calling
     * {@link Discovery#setDisoveryListener(DiscoveryListener)} and
     * {@link Discovery#enable()}.
     */
    @Test
    public void testEnableWithListenerIsShortcut() throws Exception {
        DiscoveryListener listener = mock(DiscoveryListener.class);

        Discovery discovery = spy(new Discovery());
        doNothing().when(discovery).enable();

        discovery.enable(listener);

        verify(discovery).setDisoveryListener(listener);
        verify(discovery).enable();
    }
}

Add first unit test for Discovery class.


package com.nitorcreations.willow.utils;

import static java.nio.file.StandardWatchEventKinds.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Map.Entry;

public class FilePollingProperties {
  public interface PropertyChangeListerner {
    public void propertyValueChanged(String key, String newValue, String oldValue);
    public void propertyAdded(String key, String value);
    public void propertyRemoved(String key, String value);
  }
  private final MergeableProperties properties;

  public FilePollingProperties(final File source, final PropertyChangeListerner listener) throws IOException {
    properties = new MergeableProperties();
    properties.load(new FileInputStream(source));
    final Path sourcePath = source.getParentFile().toPath();
    try {
      final WatchService watcher = FileSystems.getDefault().newWatchService();
      sourcePath.register(watcher, ENTRY_MODIFY, ENTRY_CREATE, ENTRY_DELETE);
      new Thread(new Runnable() {
        @Override
        public void run() {
          for (;;) {
            WatchKey key = null;
            try {
              key = watcher.take();
            } catch (InterruptedException x) {
              return;
            }
            for (WatchEvent<?> event: key.pollEvents()) {
              WatchEvent.Kind<?> kind = event.kind();
              if (kind == OVERFLOW) {
                  continue;
              }
              @SuppressWarnings("unchecked")
              WatchEvent<Path> ev = (WatchEvent<Path>)event;
              if (!ev.context().equals(sourcePath)) {
                continue;
              }
              if (kind == ENTRY_DELETE) {
                for (Entry<String, String> next : properties.backingEntrySet()) {
                  listener.propertyRemoved(next.getKey(), next.getValue());
                }
                properties.clear();
              } else {
                MergeableProperties newProps = new MergeableProperties();
                try {
                  newProps.load(new FileInputStream(source));
                  MergeableProperties oldProps ;
                  synchronized (properties) {
                    oldProps = (MergeableProperties) properties.clone();
                    properties.clear();
                    properties.putAll(newProps);
                  }
                  for (Entry<String, String> next : newProps.backingEntrySet()) {
                      if (oldProps.containsKey(next.getKey())) {
                        if (!oldProps.getProperty(next.getKey()).equals(next.getValue())) {
                          listener.propertyValueChanged(next.getKey(), next.getValue(), oldProps.getProperty(next.getKey()));
                        }
                        oldProps.remove(next.getKey());
                      } else {
                        listener.propertyAdded(next.getKey(), next.getValue());
                      }
                    }
                    for (Entry<String, String> next : oldProps.backingEntrySet()) {
                      listener.propertyRemoved(next.getKey(), next.getValue());
                    }
                } catch (IOException e) {
                }
              }
            }
          }
        }
      }).start();
    } catch (Exception e) {
    }
  }
  public MergeableProperties getProperties() {
    synchronized (properties) {
      return (MergeableProperties) properties.clone();
    }
  }
}

Add file backed properties to serve as backend for simple user data


package edu.uw.apl.tupelo.model;

import java.io.File;
import java.io.InputStream;

import org.apache.commons.io.input.CountingInputStream;

/**
 * Testing aspects of reading data from a PhysicalDisk. Warning, these
 * tests can read a LOT of data, 100GB+, so can take tens of minutes.
 * We really want a Maven profile (in additon to tester) that says
 * 'Yes I really want to run these lengthy (read slow!) tests
 */
public class ReadTest extends junit.framework.TestCase {

	public void testNull() {
	}

	/**
	   Testing that we really can read as many bytes as the disk's
	   advertised size. Note that 250GB took 40+ mins to read, on
	   rejewski.

	   Running edu.uw.apl.tupelo.model.ReadTest
	   Expected: 250000000000
	   Actual: 250000000000

	   [INFO] ---------------------------------------------------------
	   [INFO] BUILD SUCCESS
	   [INFO] ---------------------------------------------------------
	   [INFO] Total time: 41:16.609s
	   [INFO] Finished at: Thu Nov 13 12:54:53 PST 2014
	   [INFO] Final Memory: 14M/170M
	   [INFO] ---------------------------------------------------------
	*/
	public void _testAdvertisedSize() throws Exception {
		File f = new File( "/dev/sda" );
		if( !f.canRead() )
			return;
		PhysicalDisk pd = new PhysicalDisk( f );
		long expected = pd.size();
		System.out.println( "Expected: " + expected );
		byte[] ba = new byte[1024*1024];
		InputStream is = pd.getInputStream();
		CountingInputStream cis = new CountingInputStream( is );
		int nin = 0;
		while( (nin = cis.read( ba )) != -1 )
			;
		cis.close();
		long actual = cis.getByteCount();
		System.out.println( "Actual: " + actual );
		assertEquals( expected, actual );
	}
}

// eof

Verify physical disk read byte count matches advertised size


package com.codingbrothers.futurimages.service.impl;

import javax.inject.Inject;
import javax.inject.Named;

import com.codingbrothers.futurimages.domain.Image;
import com.codingbrothers.futurimages.util.Utils;
import com.google.appengine.api.taskqueue.DeferredTask;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;

public class DeferredImageDataUploader implements ImageDataUploader {

	private final Queue queue;

	@Inject
	DeferredImageDataUploader(@Named("ImageDataUploader") Queue queue) {
		this.queue = queue;
	}

	@Override
	public void uploadData(Image image, com.google.appengine.api.images.Image imageData) {
		queue.add(ObjectifyService.ofy().getTransaction(),
				TaskOptions.Builder.withPayload(createUploadTask(image, imageData)));
	}

	protected DeferredTask createUploadTask(Image image, com.google.appengine.api.images.Image imageData) {
		return new ImageDataUploaderTask(Key.create(image), Utils.getImageMediaType(imageData.getFormat()),
				imageData.getImageData());
	}
}

Create deferred image data uploading strategy


package com.albroco.barebonesdigest.compatibility;

import com.albroco.barebonesdigest.DigestChallenge;
import com.albroco.barebonesdigest.DigestChallengeResponse;

import org.junit.Test;

import static com.albroco.barebonesdigest.DigestTestUtils.assertHeadersEqual;

/**
 * Tests that the digest algorithm is compatible with the module node-http-digest
 * version 0.1.0.
 *
 * @see node-http-digest
 */
public class NodeHttpDigestCompatibilityTest {

  /**
   * Tests that the library is compatible with a server implemented as:
   *
   *

   * {@code
   * var httpdigest = require('http-digest');
   *
   * // simple secured web server, unauthenticated requests are not allowed
   * httpdigest.createServer("theuser", "thepass", function(request, response) {
   * response.writeHead(200, {'Content-Type': 'text/html'});
   * response.end("
Secure zone!
");
   * }).listen(8000);
   * }

   */
  @Test
  public void testQopAuthAuthentication() throws Exception {
    // Tests an actual challenge and compares it to a correct response
    DigestChallenge challenge = DigestChallenge.parse("Digest realm=\"node-http-digest\", " +
        "qop=\"auth\", " +
        "nonce=\"f50dffb4d7abd8ef3d91bb20ff7fd3a3\", " +
        "opaque=\"666ec9a92102ba3d3add863392842bfa\"");

    String expectedResponse = "Digest username=\"theuser\"," +
        "realm=\"node-http-digest\"," +
        "nonce=\"f50dffb4d7abd8ef3d91bb20ff7fd3a3\"," +
        "uri=\"/index.html\"," +
        "response=\"cae25dac1d753c271b9e8d7e515357a8\"," +
        "cnonce=\"da90c03022411abb\"," +
        "opaque=\"666ec9a92102ba3d3add863392842bfa\"," +
        "qop=auth,nc=00000001";

    DigestChallengeResponse response = DigestChallengeResponse.responseTo(challenge)
        .clientNonce("da90c03022411abb")
        .firstRequestClientNonce("da90c03022411abb")
        .username("theuser")
        .password("thepass")
        .digestUri("/index.html")
        .requestMethod("GET");

    assertHeadersEqual(expectedResponse, response.getHeaderValue());
  }
}

Add compatibility test with node-http-digest


package com.jshoresdevelopment.conversioncalculator;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.ListView;

public class NonScrollListView extends ListView {

    public NonScrollListView(Context context) {
        super(context);
    }

    public NonScrollListView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public NonScrollListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int heightMeasureSpec_custom = MeasureSpec.makeMeasureSpec(
                Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec_custom);
        ViewGroup.LayoutParams params = getLayoutParams();
        params.height = getMeasuredHeight();
    }
}

Add customized non scrolling listview

Add customized non scrolling listview


package io.siddhi.annotation;

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

/**
 * Annotation for storing the parameters of a Siddhi Extension.
 *

 * eg:-
 *      {@literal @}Extension(
 *                      ...
 *                       parametersConstraints1 = {
 *                           {@literal @}ParameterOverload1(
 *                               parameters = {
 *                                   {@literal @}Parameter(name = "firstParameterName", type = {DataType.INT,
 *                                  DataType.LONG}),
 *                                   {@literal @}Parameter(name = "SecondParameterName", type = {DataType.STRING})
 *                               }
 *                            ),
 *                           {@literal @}ParameterOverload1(
 *                               parameters = {
 *                                   {@literal @}Parameter(name = "thirdParameterName", type = {DataType.STRING})
 *                               }
 *                           )
 *                       }
 *                      ...
 *      )
 *      public CustomExtension extends ExtensionSuperClass {
 *          ...
 *      }
 *

 */
@Retention(RetentionPolicy.RUNTIME)
@Target({})
public @interface ParameterOverload1 {
    Parameter[] parameters() default {};

}

Add new parameter overload annotation which can be used to replace current parameter list with the valid patterns specified but not used in this implementation


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

import at.ac.tuwien.inso.entity.Subject;
import at.ac.tuwien.inso.service.SubjectService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class SubjectServiceSecurityTests {

    @Autowired
    private SubjectService subjectService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void createNotAuthenticated() {
        subjectService.create(new Subject());
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "STUDENT")
    public void createNotAuthenticatedAsStudent() {
        subjectService.create(new Subject());
    }

    @Test(expected = AccessDeniedException.class)
    @WithMockUser(roles = "LECTURER")
    public void createNotAuthenticatedAsLecturer() {
        subjectService.create(new Subject());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    public void createNotAuthenticatedAsAdmin() {
        subjectService.create(new Subject("ASE", BigDecimal.ONE));
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findAllNotAuthenticated() {
        subjectService.findAll();
    }

    @Test
    @WithMockUser
    public void findAllAuthenticated() {
        subjectService.findAll();
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void findOneNotAuthenticated() {
        subjectService.findOne(Long.valueOf(1));
    }

    @Test
    @WithMockUser
    public void findOneAuthenticated() {
        subjectService.findOne(Long.valueOf(1));
    }

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void searchForSubjectsNotAuthenticated() {
        subjectService.searchForSubjects("ASE");
    }

    @Test
    @WithMockUser
    public void searchForSubjectsAuthenticated() {
        subjectService.searchForSubjects("ASE");
    }

}

Add tests for method security for SubjectService


package com.htisolutions.poolref.controllers;

import com.htisolutions.poolref.services.ResultsService;
import com.htisolutions.poolref.viewModels.ResultEntryViewModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

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

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;

@RunWith(SpringRunner.class)
@WebMvcTest(ResultsController.class)
@WithMockUser
public class ResultsControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private ResultsService resultsService;

    @Test
    public void validateFormName() throws Exception {
        List<ResultEntryViewModel> results = new ArrayList<>();
        results.add(new ResultEntryViewModel(new Date().toString(), "bm15731", "gc15xxx"));
        given(resultsService.getResults()).willReturn(results);

        mvc.perform(MockMvcRequestBuilders.get("/results/"))
                .andExpect(status().isOk())
                .andExpect(view().name("views/results"));
    }
}

Add results controller unit test

Add results controller unit test


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

import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onosproject.vtnrsc.DefaultTenantNetwork;
import org.onosproject.vtnrsc.PhysicalNetwork;
import org.onosproject.vtnrsc.SegmentationId;
import org.onosproject.vtnrsc.TenantId;
import org.onosproject.vtnrsc.TenantNetwork;
import org.onosproject.vtnrsc.TenantNetworkId;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for DefaultNeutronNetwork class.
 */
public class DefaultNeutronNetworkTest {

    private String networkIdStr1 = "123";
    private String networkIdStr2 = "234";
    private String physicalNetworkStr = "1234";
    private String tenantIdStr = "345";
    private String segmentationIdStr = "1";
    private String name = "456";

    /**
     * Checks that the DefaultNeutronNetwork class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(DefaultTenantNetwork.class);
    }

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquality() {
        TenantNetworkId networkid1 = TenantNetworkId.networkId(networkIdStr1);
        TenantNetworkId networkid2 = TenantNetworkId.networkId(networkIdStr2);
        PhysicalNetwork physicalNetwork = PhysicalNetwork
                .physicalNetwork(physicalNetworkStr);
        TenantId tenantId = TenantId.tenantId(tenantIdStr);
        SegmentationId segmentationID = SegmentationId
                .segmentationId(segmentationIdStr);
        TenantNetwork p1 = new DefaultTenantNetwork(networkid1, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        TenantNetwork p2 = new DefaultTenantNetwork(networkid1, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        TenantNetwork p3 = new DefaultTenantNetwork(networkid2, name, false,
                                                    TenantNetwork.State.ACTIVE,
                                                    false, tenantId, false,
                                                    TenantNetwork.Type.LOCAL,
                                                    physicalNetwork,
                                                    segmentationID);
        new EqualsTester().addEqualityGroup(p1, p2).addEqualityGroup(p3)
                .testEquals();
    }
}

[ONOS-3232] Add the junit test code of DefaultNeutronNetwork

Change-Id: I17bcc5410fe701cce551f59643e324d59bff1674


package org.jaexcel.framework.JAEX.annotation;

import java.lang.annotation.Annotation;

import org.jaexcel.framework.JAEX.bean.ObjectsBuilderTest;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class XlsDecoratorTest extends TestCase {

	/**
	 * Create the test case
	 *
	 * @param testName
	 *            name of the test case
	 */
	public XlsDecoratorTest(String testName) {
		super(testName);
	}

	/**
	 * @return the suite of tests being tested
	 */
	public static Test suite() {
		return new TestSuite(XlsDecoratorTest.class);
	}

	/**
	 * Test default configuration.
	 */
	public void testDefaultConfiguration() {
		Class<ObjectsBuilderTest.ObjectWithDefaultConfig> o = ObjectsBuilderTest.ObjectWithDefaultConfig.class;

		// Process @XlsDecorator
		if (o.isAnnotationPresent(XlsDecorator.class)) {

			Annotation annotation = o.getAnnotation(XlsDecorator.class);
			XlsDecorator xlsDecorator = (XlsDecorator) annotation;

			// add here the annotations attributes
			assertEquals(xlsDecorator.fontBold(), false);
			assertEquals(xlsDecorator.fontItalic(), false);
			assertEquals(xlsDecorator.alignment(), 0);
			assertEquals(xlsDecorator.verticalAlignment(), 0);
			assertEquals(xlsDecorator.border(), 0);
			assertEquals(xlsDecorator.borderLeft(), 0);
			assertEquals(xlsDecorator.borderRight(), 0);
			assertEquals(xlsDecorator.borderTop(), 0);
			assertEquals(xlsDecorator.borderBottom(), 0);
			assertEquals(xlsDecorator.backgroundColor(), 0);
			assertEquals(xlsDecorator.foregroundColor(), 0);
			assertEquals(xlsDecorator.wrapText(), false);

		}
	}
}

Add test class to XlsDecorator

Add test class to XlsDecorator


package org.monospark.spongematchers.parser.element;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;

import org.junit.Test;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.PatternElementParser.Type;

public class PatternElementParserTest {

    @Test
    public void parseElements_ListMatchAnyType_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "any:'test'";

        verifyPatternElement(input, Type.LIST_MATCH_ANY);
    }

    @Test
    public void parseElements_ListMatchAnyTypeWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " any :   'test' ";

        verifyPatternElement(input, Type.LIST_MATCH_ANY);
    }

    @Test
    public void parseElements_ListMatchAllType_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "all:'test'";

        verifyPatternElement(input, Type.LIST_MATCH_ALL);
    }

    @Test
    public void parseElements_ListMatchAllTypeWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " all  :  'test' ";

        verifyPatternElement(input, Type.LIST_MATCH_ALL);
    }

    @Test
    public void parseElements_NotType_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "!'test'";

        verifyPatternElement(input, Type.NOT);
    }

    @Test
    public void parseElements_NotTypeWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "    ! 'test' ";

        verifyPatternElement(input, Type.NOT);
    }

    @Test
    public void parseElements_ParanthesesType_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = "('test')";

        verifyPatternElement(input, Type.PARANTHESES);
    }

    @Test
    public void parseElements_ParanthesesTypeWithSpaces_ReturnsCorrectStringElement()
            throws SpongeMatcherParseException {
        String input = " (  'test' ) ";

        verifyPatternElement(input, Type.PARANTHESES);
    }

    private void verifyPatternElement(String input, Type type) throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement(input);

        PatternElement pattern = (PatternElement) element;
        assertThat(pattern.getType(), equalTo(type));
    }
}

Add unit tests for parsing pattern elements


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

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import dagger.Lazy;
import io.realm.Realm;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;

/**
 * Todo instrumentation tests for Realm
 * Realm relies heavily on native code on Android. Since we can't actually run a realm during the
 * unit tests we can only verify a few interactions with the mock. Testing the functionality of other
 * DatabaseInteractor methods must be done with instrumentation tests.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(Realm.class)
public class DatabaseInteractorTest {

    private DatabaseInteractor databaseInteractor;
    private Realm realm;
    private Lazy<Realm> realmLazy;

    @Before
    public void beforeEachTest() {
        realm = PowerMockito.mock(Realm.class);
        realmLazy = new Lazy<Realm>() {
            @Override
            public Realm get() {
                return realm;
            }
        };
        databaseInteractor = new DatabaseInteractor(realmLazy);
    }

    @Test
    public void onDestroy_shouldCallRealmClose() {
        databaseInteractor.onDestroy();
        verify(realm).close();
    }

    @Test
    public void onPause_noOp() {
        databaseInteractor.onPause();
        verifyNoMoreInteractions(realm);

    }

    @Test
    public void onStart_noOp() {
        databaseInteractor.onStart();
        verifyNoMoreInteractions(realm);
    }

    @Test
    public void onStop_noOp() {
        databaseInteractor.onStop();
        verifyNoMoreInteractions(realm);
    }

    @Test
    public void onResume_noOp() {
        databaseInteractor.onResume();
        verifyNoMoreInteractions(realm);

    }
}

Add a few DatabaseInteractor unit tests. Testing Realm is tricky since it uses native code on Android. Other DatabaseInteractor tests will need to be done as instrumentation tests.


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

/**
 * Test environment classes and utilities related to the
 * {@link io.spine.tools.gradle.compiler.ErrorProneChecksPlugin} functionality.
 */
@CheckReturnValue
@ParametersAreNonnullByDefault
package io.spine.tools.compiler.check.given;

import com.google.errorprone.annotations.CheckReturnValue;

import javax.annotation.ParametersAreNonnullByDefault;

Add package info to test env

Add package info to test env


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

package com.karumi.marvelapiclient.model;

import org.junit.Test;

public class CharactersQueryTest {
  private static final int INVALID_LIMIT = 0;
  private static final int INVALID_OFFSET = -1;
  private static final int LIMIT_BIGGET_THAN_MAX = 101;

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetInvalidOffset() throws Exception {
    CharactersQuery.Builder.create().withOffset(INVALID_OFFSET).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetLimitEqualZero() throws Exception {
    CharactersQuery.Builder.create().withLimit(INVALID_LIMIT).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenSetLimitMoreThanMaxLimit() throws Exception {
    CharactersQuery.Builder.create().withLimit(LIMIT_BIGGET_THAN_MAX).build();
  }

  @Test(expected = IllegalArgumentException.class)
     public void shouldThrowExceptionWhenAddNullComics() throws Exception {
    CharactersQuery.Builder.create().addComics(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullEvents() throws Exception {
    CharactersQuery.Builder.create().addEvents(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullSeries() throws Exception {
    CharactersQuery.Builder.create().addSeries(null).build();
  }

  @Test(expected = IllegalArgumentException.class)
  public void shouldThrowExceptionWhenAddNullStories() throws Exception {
    CharactersQuery.Builder.create().addStory(null).build();
  }
}

Add test related with query builder.

Add test related with query builder.


package org.apache.helix.integration.task;

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

import java.util.Map;

import org.apache.helix.TestHelper;
import org.apache.helix.task.JobConfig;
import org.apache.helix.task.TaskPartitionState;
import org.apache.helix.task.TaskState;
import org.apache.helix.task.TaskUtil;
import org.apache.helix.task.Workflow;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class TestUnregisteredCommand extends TaskTestBase {

  @BeforeClass
  public void beforeClass() throws Exception {
    _numNodes = 1;
    _numReplicas = 1;
    _numDbs = 1;
    _numParitions = 1;
    super.beforeClass();
  }

  @Test public void testUnregisteredCommand() throws InterruptedException {
    String workflowName = TestHelper.getTestMethodName();
    Workflow.Builder builder = new Workflow.Builder(workflowName);

    JobConfig.Builder jobBuilder =
        new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB)
            .setCommand("OtherCommand").setTimeoutPerTask(10000L).setMaxAttemptsPerTask(2)
            .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG);

    builder.addJob("JOB1", jobBuilder);

    _driver.start(builder.build());

    _driver.pollForWorkflowState(workflowName, TaskState.COMPLETED, TaskState.FAILED);
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1"))
        .getPartitionState(0), TaskPartitionState.ERROR);
    Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1"))
        .getPartitionNumAttempts(0), 1);
  }
}

Add test for unregistered command

Add test for unregistered command

Add test for unregistered command. Expected behavior:
1. Partition state is "ERROR"
2. No retry will happen.


/*
 * Copyright (c) 2015 Inocybe and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.ovsdb.openstack.netvirt;

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

import org.junit.Test;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;

/**
 * Unit test for {@link NodeConfiguration}
 */
public class NodeConfigurationTest {

    @Test
    public void testNodeConfiguration() {
        NodeConfiguration nodeConf = new NodeConfiguration();

        assertEquals("Error, did not populate the internal vlan queue correctly", Constants.MAX_VLAN - 1, nodeConf.getInternalVlans().size());
        assertNotNull("Error, tenant vlan map has not been initialized", nodeConf.getTenantVlanMap());
    }
}

Add JUnit testing for NodeConfiguration class.

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


package wcanalysis.heuristic;

import com.google.common.base.Stopwatch;

import java.util.concurrent.TimeUnit;

import gov.nasa.jpf.search.Search;

/**
 * @author Kasper Luckow
 */
public class TimeBoundedTerminationStrategy implements TerminationStrategy {

  private final Stopwatch stopwatch;
  private static final int TIME_BOUND = 15;
  private static final TimeUnit TIME_UNIT = TimeUnit.MINUTES;

  public TimeBoundedTerminationStrategy() {
    this.stopwatch = Stopwatch.createStarted();
  }

  @Override
  public boolean terminateAnalysis(Search searchState, HeuristicStatistics statistics) {
    return this.stopwatch.elapsed(TIME_UNIT) > TIME_BOUND;
  }
}

Add time bounded termination strategy

Add time bounded termination strategy


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.client.zts.utils;

import com.yahoo.security.Pkcs10Csr;
import com.yahoo.security.Pkcs10CsrBuilder;
import com.yahoo.security.SubjectAlternativeName.Type;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzRole;
import com.yahoo.vespa.athenz.client.zts.ZtsClient;

import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;

import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_RSA;

/**
 * Generates a {@link Pkcs10Csr} instance for use with {@link ZtsClient#getRoleCertificate(AthenzRole, Pkcs10Csr)}.
 *
 * @author bjorncs
 */
public class RoleCsrGenerator {

    private final String dnsSuffix;

    public RoleCsrGenerator(String dnsSuffix) {
        this.dnsSuffix = dnsSuffix;
    }

    public Pkcs10Csr generateCsr(AthenzIdentity identity, AthenzRole role, KeyPair keyPair) {
        return Pkcs10CsrBuilder.fromKeypair(new X500Principal("CN=" + role.toResourceNameString()), keyPair, SHA256_WITH_RSA)
                .addSubjectAlternativeName(
                        Type.DNS_NAME,
                        String.format("%s.%s.%s", identity.getName(), identity.getDomainName().replace(".", "-"), dnsSuffix))
                .addSubjectAlternativeName(
                        Type.RFC822_NAME,
                        String.format("%s@%s", identity.getFullName(), dnsSuffix))
                .build();
    }
}

Add CSR generator for role certificates

Add CSR generator for role certificates


// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * Main package of ChromDevTools SDK API.
 * See Tutorial at http://code.google.com/p/chromedevtools/wiki/SdkTutorial
 */
package org.chromium.sdk;

Add small fixes before release

Add small fixes before release

Review URL: http://codereview.chromium.org/7631060

git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@813 fc8a088e-31da-11de-8fef-1f5ae417a2df


/**
 *
 */
package org.biojava3.core.sequence.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import org.biojava3.core.sequence.DNASequence;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * @author mckeee1
 *
 */
public class GenbankWriterTest {

	public GenbankWriterTest() {}

	@BeforeClass
	public static void setUpClass() throws Exception {}

	@AfterClass
	public static void tearDownClass() throws Exception {}

	@Before
	public void setUp() {}

	@After
	public void tearDown() {}

	@Test
	public void testProcess() throws Exception {
		File dnaFile = new File("src/test/resources/NM_000266.gb");
		LinkedHashMap<String, DNASequence> dnaSequences = GenbankReaderHelper.readGenbankDNASequence( dnaFile );
		ByteArrayOutputStream fragwriter = new ByteArrayOutputStream();
		ArrayList<DNASequence> seqs = new ArrayList<DNASequence>();
		for(DNASequence seq : dnaSequences.values()) {
			seqs.add(seq);
		}
		GenbankWriterHelper.writeNucleotideSequence(fragwriter, seqs,
				GenbankWriterHelper.LINEAR_DNA);
		//System.out.println(fragwriter.toString());
		ByteArrayInputStream fragreader = new ByteArrayInputStream(fragwriter.toByteArray());
		dnaSequences = GenbankReaderHelper.readGenbankDNASequence( fragreader );
		fragwriter.close();
		assert(seqs.get(0).getSequenceAsString() == dnaSequences.values().iterator().next().getSequenceAsString());
	}
}

Add a test of the Genbank Functionality

Add a test of the Genbank Functionality


package com.splicemachine.mapreduce;

import java.io.IOException;
import java.sql.Types;

import org.apache.derby.iapi.error.StandardException;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.mapreduce.MapDriver;
import org.junit.Ignore;
import org.junit.Test;

import com.google.gson.Gson;
import com.splicemachine.derby.impl.load.ColumnContext;
import com.splicemachine.derby.impl.load.ImportContext;
@Ignore
public class SpliceBulkTest {
	private MapDriver<LongWritable, Text, ImmutableBytesWritable, KeyValue> mapDriver;
	private Gson gson = new Gson();

	@Test
	public void isImportContextGSONSerializable() {
		Gson gson = new Gson();
		ImportContext importContext = new ImportContext();
		String string1 = gson.toJson(importContext);
		ImportContext importContext2 = gson.fromJson(string1, ImportContext.class);
	}

	@Test
	public void testBulkImportMapper() throws IOException, StandardException {
        ColumnContext colCtx = new ColumnContext.Builder()
        .nullable(true)
        .columnType(Types.INTEGER)
        .columnNumber(0).build();
        ImportContext ctx = new ImportContext.Builder()
        .addColumn(colCtx)
        .path("/testPath")
        .destinationTable(1184l)
        .colDelimiter(",")
        .transactionId("123")
        .build();
		mapDriver = new MapDriver(new HBaseBulkLoadMapper());
		mapDriver.withInput(new LongWritable(), new Text("1234"));
		mapDriver.getConfiguration().set(HBaseBulkLoadMapper.IMPORT_CONTEXT, gson.toJson(ctx));
		mapDriver.runTest();
	}

}

Add placeholder for bulk test

Add placeholder for bulk test


/*-
 * Copyright 2015 Diamond Light Source Ltd.
 *
 * 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.eclipse.dawnsci.analysis.api.tree;

/**
 * Interface to allow UI interactions with items in a tree such as a node or attribute
 */
public interface TreeAdaptable {

	/**
	 * @return full path to file
	 */
	public abstract String getFile();

	/**
	 * @return full path to node or node attribute
	 */
	public abstract String getNode();

	/**
	 * @return node link (can be null)
	 */
	public abstract NodeLink getNodeLink();

	/**
	 * @return attribute (can be null)
	 */
	public abstract Attribute getAttribute();
}

Add interface to interact with a UI item in a tree


/*
 * #%L
 * %%
 * Copyright (C) 2020 BMW Car IT GmbH
 * %%
 * 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.
 * #L%
 */
package io.joynr.capabilities;

import io.joynr.proxy.CallbackWithModeledError;
import joynr.types.DiscoveryError;
import joynr.types.GlobalDiscoveryEntry;

public class GlobalAddRemoveQueueEntry {
    public enum MODE {
        ADD, REMOVE
    }

    public GlobalAddRemoveQueueEntry(CallbackWithModeledError<Void, DiscoveryError> callback,
                                     GlobalDiscoveryEntry globalDiscoveryEntry,
                                     String[] gbids) {
        mode = MODE.ADD;
        this.callback = callback;
        this.globalDiscoveryEntry = globalDiscoveryEntry;
        this.gbids = gbids;
        this.participantId = "";
    }

    public GlobalAddRemoveQueueEntry(CallbackWithModeledError<Void, DiscoveryError> callback, String participantId) {
        mode = MODE.REMOVE;
        this.callback = callback;
        this.participantId = participantId;
        this.globalDiscoveryEntry = null;
        this.gbids = null;
    }

    public final MODE mode;
    public final CallbackWithModeledError<Void, DiscoveryError> callback;
    public final String participantId;
    public final GlobalDiscoveryEntry globalDiscoveryEntry;
    public final String[] gbids;
}

[Java] Create class for entries in the AddRemoveQueue


package org.deidentifier.arx.examples;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.deidentifier.arx.ARXAnonymizer;
import org.deidentifier.arx.ARXConfiguration;
import org.deidentifier.arx.ARXResult;
import org.deidentifier.arx.AttributeType.Hierarchy;
import org.deidentifier.arx.Data;
import org.deidentifier.arx.DataType;
import org.deidentifier.arx.criteria.KAnonymity;
import org.deidentifier.arx.io.importdata.CSVImportAdapter;
import org.deidentifier.arx.io.importdata.Column;

/**
 * This class implements an example on how to use the API to import data from
 * a CSV file. It uses more advanced features than {@link #Example2}. Columns
 * are renamed and could be ignored altogether.
 */
public class Example2a extends Example {

    /**
     * Main entry point
     */
    public static void main(final String[] args) throws IOException {

        try {

            // Define input adapter
            CSVImportAdapter adapter = new CSVImportAdapter("data/test.csv", ';', true);

            // Define columns (index, name (optional) and datatype)
            List<Column> columns = new ArrayList<Column>();
            columns.add(new Column(0, "Alter", DataType.INTEGER));
            columns.add(new Column(1, DataType.STRING));
            columns.add(new Column(2, DataType.STRING));

            // Apply column definitions to adapter
            adapter.setColumns(columns);

            // Create data object
            final Data data = Data.create(adapter);

            // Define attribute hierarchies
            data.getDefinition()
                .setAttributeType("Alter",
                                  Hierarchy.create("data/test_hierarchy_age.csv",
                                                   ';'));
            data.getDefinition()
                .setAttributeType("gender",
                                  Hierarchy.create("data/test_hierarchy_gender.csv",
                                                   ';'));
            data.getDefinition()
                .setAttributeType("zipcode",
                                  Hierarchy.create("data/test_hierarchy_zipcode.csv",
                                                   ';'));

            // Create an instance of the anonymizer
            final ARXAnonymizer anonymizer = new ARXAnonymizer();

            // Execute the algorithm
            final ARXConfiguration config = ARXConfiguration.create();
            config.addCriterion(new KAnonymity(2));
            config.setMaxOutliers(0d);
            final ARXResult result = anonymizer.anonymize(data, config);

            // Print info
            printResult(result, data);

            // Write results
            System.out.print(" - Writing data...");
            result.getOutput(false).save("data/test_anonymized.csv", ';');
            System.out.println("Done!");

        } catch (final IllegalArgumentException e) {

            throw new RuntimeException(e);

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

    }

}

example: Add extended version of Example2 using new API


/*
 * Copyright (c) 2002-2016 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.server.security.ssl;

import org.apache.commons.lang.SystemUtils;
import org.junit.Rule;
import org.junit.Test;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;

import org.neo4j.test.TargetDirectory;

import static org.junit.Assert.*;
import static org.junit.Assume.assumeTrue;
import static org.neo4j.test.TargetDirectory.testDirForTest;

public class CertificatesIT
{
    @Rule
    public TargetDirectory.TestDirectory testDirectory = TargetDirectory.testDirForTest( getClass() );

    @Test
    public void createSelfSignedCertificate() throws Exception
    {
        assumeTrue( !SystemUtils.IS_OS_WINDOWS );

        Certificates certificates = new Certificates();
        certificates
                .createSelfSignedCertificate( testDirectory.file( "certificate" ), testDirectory.file( "privateKey" ),
                        "localhost" );

        PosixFileAttributes certificateAttributes =
                Files.getFileAttributeView( testDirectory.file( "certificate" ).toPath(), PosixFileAttributeView.class )
                        .readAttributes();

        assertTrue( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_READ ) );
        assertTrue( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OWNER_EXECUTE ) );

        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_READ ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.GROUP_EXECUTE ) );

        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_READ ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_WRITE ) );
        assertFalse( certificateAttributes.permissions().contains( PosixFilePermission.OTHERS_EXECUTE ) );
    }
}

Add the integration test; not Windows.

Add the integration test; not Windows.


package pt.passarola.utils.dagger;

/**
 * Created by ruigoncalo on 31/10/15.
 */
import android.os.Bundle;
import android.support.v4.app.Fragment;

import pt.passarola.App;

public class DaggerableFragment extends Fragment implements Daggerable {

    @Override public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        inject(this);
    }

    @Override
    public void inject(Object object) {
        App.obtain(getActivity()).inject(object);
    }

    @Override public void inject(Object object, Object... modules) {
        App.obtain(getActivity()).inject(object, modules);
    }
}

Use dagger to inject fragments

Use dagger to inject fragments


package leetcode.insertion_sort_list;

import java.util.Random;

import common.ListNode;

public class Solution {
	public ListNode insertionSortList(ListNode head) {
		if(head == null) return null;
		ListNode cur = head;
		ListNode prev = null;
        while(cur != null){
        	ListNode insertPrev = null;
        	ListNode insertNext = head;
        	ListNode next = cur.next;
        	while(insertNext != null && cur.val > insertNext.val){
        		insertPrev = insertNext;
        		insertNext = insertPrev.next;
        	}
        	if(prev != null){
        		prev.next = next;
        	}else{
        		head = next;
        	}
        	if(insertPrev == null){
        		insertNext = head;
        		head = cur;
        	}else{
        		insertNext = insertPrev.next;
        		insertPrev.next = cur;
        	}
        	cur.next = insertNext;
        	if(prev != null && prev.next != next)
        		prev = cur;
        	else if(prev == null){
        		prev = cur;
        	}
        	cur = next;
        }
        return head;
    }

	public static void dump(ListNode head){
		System.err.println("dump");
		while(head != null){
			System.err.print(head.val + " ");
			head = head.next;
		}
		System.err.println("");
	}

	public static void main(String[] args){
		final int N = 2, SIZE = 10;
		Random r = new Random();
		ListNode[] input = new ListNode[N];
		for(int i = 0; i < N; i++){
			input[i] = new ListNode(r.nextInt(SIZE));
			if(i > 0) input[i - 1].next = input[i];
		}
		dump(input[0]);
		dump(new Solution().insertionSortList(input[0]));
	}
}

Add java solution for 147. Insertion Sort List

147. Insertion Sort List: https://leetcode.com/problems/insertion-sort-list/


package org.ndexbio.rest.exceptions.mappers;

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

import org.ndexbio.model.exceptions.UnautherizedOperationException;

public class UnautherizedOperationExceptionMapper implements ExceptionMapper<UnautherizedOperationException>
{
    @Override
    public Response toResponse(UnautherizedOperationException exception)
    {
        return Response
            .status(Status.UNAUTHORIZED)
            .entity(exception.getMessage())
            .build();
    }
}

Add exception mapper for UnautherizedOperationException


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

package alluxio.client.block.options;

import alluxio.CommonTestUtils;
import alluxio.thrift.LockBlockTOptions;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Tests for the {@link LockBlockOptions} class.
 * @author gurmeetb
 *
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest({LockBlockTOptions.class})
public class LockBlockOptionsTest {

  /**
  * Test for {@link LockBlockOptions#defaults()}.
  */
  @Test
  public void testDefaults() {
    LockBlockOptions options = LockBlockOptions.defaults();
    Assert.assertNotNull(options);
  }

  /**
  * Test for {@link LockBlockOptions#equals(Object)}.
  */
  @Test
  public void testEquals() throws Exception {
    CommonTestUtils.testEquals(LockBlockOptions.class);
  }

  /**
  * Test for {@link LockBlockOptions#toThrift()}.
  */
  @Test
  public void testToThrift() throws Exception {
    String ufsPath = "ufsPath";
    long blockSize = 1000L;

    alluxio.thrift.LockBlockTOptions mockObject =
        PowerMockito.mock(alluxio.thrift.LockBlockTOptions.class);
    PowerMockito.when(mockObject.getBlockSize()).thenReturn(new Long(1000));
    PowerMockito.when(mockObject.getUfsPath()).thenReturn(ufsPath);

    LockBlockOptions options = LockBlockOptions.defaults();
    options.setUfsPath(ufsPath);
    options.setBlockSize(blockSize);

    LockBlockTOptions thriftOptions = options.toThrift();
    Assert.assertEquals(thriftOptions.getBlockSize(), mockObject.getBlockSize());
    Assert.assertEquals(thriftOptions.getUfsPath(), mockObject.getUfsPath());
  }
}

Add Unit Tests for the Block package

[ALLUXIO-873] Add Unit Tests for the Block package


package com.ibm.watson.developer_cloud.service.model;

import com.ibm.watson.developer_cloud.util.GsonSingleton;

import java.util.HashMap;

public abstract class DynamicModel extends HashMap<String, Object> implements ObjectModel {

  /*
   * (non-Javadoc)
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if ((o == null) || (getClass() != o.getClass())) {
      return false;
    }

    final DynamicModel other = (DynamicModel) o;

    return toString().equals(other.toString());
  }

  /*
   * (non-Javadoc)
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    return toString().hashCode();
  }

  /*
   * (non-Javadoc)
   * @see java.lang.Object#toString()
   */
  @Override
  public String toString() {
    return GsonSingleton.getGson().toJson(this);
  }

  /*
   * @Override
   * public void putAll(Map<? extends String, ?> m) {
   * System.out.println(m.toString());
   * }
   */
}

Revise changes to only affect core and test code


// Build a sub class of Vehicle of trucks.
class Vehicle {
	private int passengers; // number of passengers
	private int fuelcap;    // fuel capacity in gallons
	private int mpg;        // fuel consumption in miles per gallon

	// This is a constructor for Vehicle.
	Vehicle(int p, int f, int m) {
		passengers = p;
		fuelcap = f;
		mpg = m;
	}

	// Return the range.
	int range() {
		return mpg * fuelcap;
	}

	// Compute fuel needed for a given distance.
	double fuelneeded(int miles) {
		return (double) miles / mpg;
	}

	// Access methods for instance variables.
	int getPassengers() { return passengers; }
	void setPassengers(int p) { passengers = p; }
	int getFuelcap() { return fuelcap; }
	void setFuelcap(int f) { fuelcap = f; }
	int getMpg() { return mpg; }
	void setMpg(int m) { mpg = m; }
}

// Extend Vehicle to create a Truck specialization.
class Truck extends Vehicle {
  private int cargocap; // cargo capacity in pounds

  // This is a constructor for Truck.
  Truck(int p, int f, int m, int c) {
    /*
      Initialize Vehicle members using Vehicle's constructor.
    */
    super(p, f, m);

    cargocap = c;
  }

  // Accessor methods for cargocap.
  int getCargo() { return cargocap; }
  void putCargo(int c) { cargocap = c; }
}

class TruckDemo {
	public static void main(String args[]) {

		// construct some trucks
		Truck semi = new Truck(2, 200, 7, 44000);
		Truck pickup = new Truck(3, 28, 15, 2000);
		double gallons;
		int dist = 252;

		gallons = semi.fuelneeded(dist);

		System.out.println("Semi can carry " + semi.getCargo() + " pounds.");
		System.out.println("To go " + dist + " miles semi needs " + gallons + " gallons of fuel.\n");

		gallons = pickup.fuelneeded(dist);

		System.out.println("Pickup can carry " + pickup.getCargo() + " pounds.");
		System.out.println("To go " + dist + " miles pickup needs " + gallons + " gallons of fuel.\n");
	}
}

Build a sub class of Vehicle of trucks

Build a sub class of Vehicle of trucks

http://ideone.com/bDrtww


/*
 * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
 *
 * 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.search.nibrs.web;

import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerSetup {
    @Autowired
    AppProperties appProperties;

    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory() ;

        if (appProperties.getAjpEnabled()) {
            Connector ajpConnector = new Connector("AJP/1.3");
            ajpConnector.setPort(appProperties.getAjpPort());
            ajpConnector.setSecure(false);
            ajpConnector.setScheme("http");
            ajpConnector.setAllowTrace(false);
            tomcat.addAdditionalTomcatConnectors(ajpConnector);
        }

//        tomcat.addAdditionalTomcatConnectors(redirectConnector());
        return tomcat;
    }

//    private Connector redirectConnector() {
//        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
//        connector.setScheme("http");
//        connector.setPort(8080);
//        connector.setSecure(false);
//        connector.setRedirectPort(8443);
//        return connector;
//    }
}

Add the ajp port configuration.

Add the ajp port configuration.


package org.simpleframework.xml.core;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Default;
import org.simpleframework.xml.DefaultType;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.ValidationTestCase;

public class NotRequiredConstructorInjectionTest extends ValidationTestCase{

   private static final String SOURCE =
   "<exampleNotRequired value='value'/>";

   private static final String EXTRA =
   "<exampleNotRequired value='value'>"+
   "  <extra>extra string</extra>"+
   "</exampleNotRequired>";

   @Root
   private static class ExampleNotRequired {
      private final String name;
      private final String value;
      public ExampleNotRequired(@Element(name="name", required=false) String name, @Attribute(name="value") String value) {
         this.name = name;
         this.value = value;
      }
      @Attribute
      public String getValue() {
         return value;
      }
      @Element(required=false)
      public String getName() {
         return name;
      }
   }

   @Default(value=DefaultType.PROPERTY, required=false)
   public static class ExampleNotRequiredByDefault extends ExampleNotRequired {
      private final String extra;
      public ExampleNotRequiredByDefault(@Element(name="name", required=false) String name, @Attribute(name="value") String value, @Element(name="extra", required=false) String extra) {
         super(name, value);
         this.extra = extra;
      }
      public String getExtra() {
         return extra;
      }
   }

   public void s_testInjection() throws Exception {
      ExampleNotRequired example = new Persister().read(ExampleNotRequired.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
   }

   public void testInheritance() throws Exception {
      ExampleNotRequiredByDefault example = new Persister().read(ExampleNotRequiredByDefault.class, SOURCE);
      assertEquals(example.getName(), null);
      assertEquals(example.getValue(), "value");
      assertEquals(example.getExtra(), null);

      ExampleNotRequiredByDefault exampleExtra = new Persister().read(ExampleNotRequiredByDefault.class, EXTRA);
      assertEquals(exampleExtra.getName(), null);
      assertEquals(exampleExtra.getValue(), "value");
      assertEquals(exampleExtra.getExtra(), "extra string");
   }
}

Add test for non required constructor injection


package no.ntnu.capgeminitest.dbacalculator;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

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

public class DbaCalculatorLogicTest {
	private DbaCalculatorLogic logic = new DbaCalculatorLogic();

	@Before
	public void setUp() throws Exception {
	}

	@Test
	public void testInitialState() {
		assertThat(logic.text.get(), equalTo("0"));
	}

	@Test
	public void testIncrement() {
		increment(50);
		assertThat(logic.text.get(), equalTo("50"));
	}

	@Test
	public void testDecrement() {
		decrement(10);
		assertThat(logic.text.get(), equalTo("-10"));
	}

	@Test
	public void testIncrementDecrement() {
		increment(20);
		decrement(10);
		increment(9);
		decrement(9);
		assertThat(logic.text.get(), equalTo("10"));
	}

	public void increment(int number) {
		for (int i = 0; i < number; i++) {
			logic.numberIncrementer.set(new Object());
		}
	}

	public void decrement(int number) {
		for (int i = 0; i < number; i++) {
			logic.numberDecrementer.set(new Object());
		}
	}
}

Add test for Calculator logic.

Add test for Calculator logic.


package hudson.plugins.git;

import hudson.Extension;
import hudson.model.AbstractModelObject;
import hudson.model.AbstractProject;
import hudson.model.Hudson;
import hudson.model.RootAction;

import hudson.scm.SCM;
import hudson.triggers.SCMTrigger;

import org.spearce.jgit.transport.RemoteConfig;
import org.spearce.jgit.transport.URIish;

import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import javax.servlet.ServletException;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import java.io.IOException;

import java.util.logging.Logger;
import static java.util.logging.Level.INFO;

/**
 * Information screen for the use of Git in Hudson.
 */
@Extension
public class GitStatus extends AbstractModelObject implements RootAction {
    public String getDisplayName() {
        return "Git";
    }

    public String getSearchUrl() {
        return getUrlName();
    }

    public String getIconFileName() {
        // TODO
        return null;
    }

    public String getUrlName() {
        return "git";
    }

    public void doNotifyCommit(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
        String urlString = req.getParameter("url");
	URIish url = null;
        try {
            url = new URIish(urlString);
        } catch (java.net.URISyntaxException e) { }

        boolean scmFound = false,
                triggerFound = false,
                urlFound = false;
        for (AbstractProject<?,?> project : Hudson.getInstance().getItems(AbstractProject.class)) {
            SCM scm = project.getScm();
            if (scm instanceof GitSCM) scmFound = true; else continue;

            SCMTrigger trigger = project.getTrigger(SCMTrigger.class);
            if (trigger!=null) triggerFound = true; else continue;

            GitSCM git = (GitSCM) scm;
            for (RemoteConfig repository : git.getRepositories()) {
                boolean repositoryMatches = false;
                for (URIish remoteURL : repository.getURIs()) {
                    if (url.equals(remoteURL)) { repositoryMatches = true; break; }
                }
                if (repositoryMatches) urlFound = true; else continue;

                trigger.run();
            }
        }

        if (url == null)    LOGGER.warning("Couldn't read url: " + urlString);
        else if (!scmFound) LOGGER.warning("No git jobs found");
        else if (!triggerFound) LOGGER.warning("No git jobs using SCM polling");
        else if (!urlFound) LOGGER.warning("No git jobs using repository: " + url.toString());

        rsp.setStatus(SC_OK);
    }

    private static final Logger LOGGER = Logger.getLogger(GitStatus.class.getName());
}

Add an action extension to remotely trigger a poll for a given git repository


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

package net.imagej.ops;

/**
 * Interface for objects with a typed output parameter that can be changed.
 *
 * @author Curtis Rueden
 * @see Output
 */
public interface OutputMutable<O> extends Output<O> {

	void setOutput(O output);

}

Add interface for ops with mutable output values

This will be useful in particular for ComputerOp, which has
an output that is also an input (i.e., of type ItemIO.BOTH).


/*
 *  Copyright (c) 2018-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.flipper.plugins.navigation;

import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.MatcherAssert.assertThat;

import com.facebook.flipper.core.FlipperObject;
import com.facebook.flipper.testing.FlipperConnectionMock;
import com.facebook.flipper.testing.FlipperResponderMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;

@RunWith(RobolectricTestRunner.class)
public class NavigationFlipperPluginTest {

  @Test
  public void greetingTest() throws Exception {
    final NavigationFlipperPlugin plugin = new NavigationFlipperPlugin();
    final FlipperConnectionMock connection = new FlipperConnectionMock();
    final FlipperResponderMock responder = new FlipperResponderMock();

    plugin.onConnect(connection);
    connection.receivers.get("greet").onReceive(null, responder);

    assertThat(
        responder.successes, hasItem(new FlipperObject.Builder().put("greeting", "Hello").build()));
  }
}

Add Flipper plugin for Navigation

Add Flipper plugin for Navigation

Summary:
The main goal is to update visitation id for our targeted tabs requirements (https://fb.quip.com/2jZiA97DTATi). In doing so, we want an easier way to debug whether everything is working as expected.

I've been meaning to add something like this for a while since it's a pain to explain what the visitation id and HSM look like as you navigate the app, so this should help the other teams who're using visitation id as well.

Will probably also start adding navigation events and any other data that we feel is useful.

Run:
```
fbsource/xplat/sonar/scripts/facebook/create-plugin.py Navigation --android
```
Then clean a few things up and fix lints.

Differential Revision: D14759995

fbshipit-source-id: 066dcbf70eed7056f995053cc9ba80dcbbafdb03


/*
 *    GeoTools - The Open Source Java GIS Toolkit
 *    http://geotools.org
 *
 *    (C) 2002-2010, Open Source Geospatial Foundation (OSGeo)
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation;
 *    version 2.1 of the License.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 */
package org.geotools.geojson;

import java.io.IOException;
import java.io.StringReader;
import java.lang.StringBuilder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.Random;

import junit.framework.TestCase;

/**
 * Exploit bug GEOT-5036, concurrent use of GeoJSONUtil.
 * @author Guido Grazioli <guido.grazioli@gmail.com>
 *
 */
public class GEOT5036RegressionTest extends TestCase {

    private Random rand = new Random();
    private Map<Date, Future<String>> expectationMap = new HashMap<Date, Future<String>>();

    public class Task implements Callable<String> {
        private final Date date;

        public Task(Date d) {
            this.date = d;
        }

        public String call() throws Exception {
            StringBuilder sb = new StringBuilder();
            GeoJSONUtil.literal(date, sb);
            return sb.toString();
        }
    }

    public void setUp() throws java.lang.Exception {
        SimpleDateFormat sdf = GeoJSONUtil.DATE_FORMAT;
        // perform 50 conversions
        for (int i = 0; i < 50; i++) {
            Date date = new Date(System.currentTimeMillis() - rand.nextInt(100) * 1000 * 3600 * 24);
            expectationMap.put(date, null);
        }
    }

    public void testDateFormatterResults() throws Exception {
        SimpleDateFormat sdf = GeoJSONUtil.DATE_FORMAT;

        // pool with 8 threads
        ExecutorService exec = Executors.newFixedThreadPool(8);

        // perform date conversions
        for (Date key : expectationMap.keySet()) {
            Task task = new Task(key);
            expectationMap.put(key, exec.submit(task));
        }
        exec.shutdown();

        // look at the results
        for (Map.Entry<Date, Future<String>> entry : expectationMap.entrySet()) {
            assertEquals("incorrect date string was returned: ", entry.getValue().get(),
                    "\"" + sdf.format(entry.getKey()) + "\"");
        }
    }

}

Add regression test for bug GEOT-5036

Add regression test for bug GEOT-5036

The class GeoJSONUtil is using a shared static instance of SimpleDateFormat,
which is not thread-safe. Use of the class in a multithreaded environment
causes unexpected results and/or runtime exceptions.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ch.heigvd.amt.selenium;

import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
 *
 * @author Mario Ferreira
 */
public class MoussaRaserTest2 {
    private final String baseUrl = "localhost:8080/MoussaRaser/";
    private WebDriver driver;

    @Before
    public void openBrowser() {
        driver = new FirefoxDriver();
    }

}

Create JUnit to part 2.

Create JUnit to part 2.


package sample.jcu.unsafe;

import org.junit.Test;

/**
 * @author soyona
 * @Package sample.jcu.unsafe
 * @Desc: 申请Integer.MAX_VALUE内存，VM 还是 direct byte buffers
 * @date 2018/7/14 12:49
 */
public class ArraySizeTest {

    /**
     * allocate an array that has more than Integer.MAX_VALUE entries.
     *
     * You will get the exception: java.lang.OutOfMemoryError: Requested array size exceeds VM limit
     */
    @Test
    public void arrayInVMTest(){
        // 2的31次幂-1，1Byte=8bit，1KByte = 1024Byte = 2的10次Byte
        // 1MByte = 1024 * 1KByte = 2的20次Byte
        // 1GByte = 1024 * 1MByte = 2的30次Byte
        // 2GByte = 1GByte * 2    = 2的31次Byte
        // Integer.MAX_VALUE
        long unit = 1L;
        long int_max = (unit << 31) -1;
        System.out.println(int_max);
        System.out.println(Integer.MAX_VALUE);
        // 大约2G-1内存，在堆中无法创建
        byte[] strings = new byte[Integer.MAX_VALUE];
    }
}

Test for allocating an array that has more than Integer.MAX_VALUE entries.


/*******************************************************************************
 * Copyright (c) 2015 Bosch Software Innovations GmbH and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * and Eclipse Distribution License v1.0 which accompany this distribution.
 *
 * The Eclipse Public License is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * The Eclipse Distribution License is available at
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 * Bosch Software Innovations GmbH - Please refer to git log
 *******************************************************************************/
package org.eclipse.vorto.repository.model;

/**
 * We need this views because of the difference in how data is structured between API
 * in the client and server.
 */
public class UploadResultView {
	String handleId;
	String errorMessage;
	boolean valid;
	ModelView modelResource;

	public UploadResultView() {

	}

	public boolean statusOk() {
		return handleId != null && valid;
	}

	public String getHandleId() {
		return handleId;
	}

	public void setHandleId(String handleId) {
		this.handleId = handleId;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public ModelView getModelResource() {
		return modelResource;
	}

	public void setModelResource(ModelView modelResource) {
		this.modelResource = modelResource;
	}

	public boolean isValid() {
		return valid;
	}

	public void setValid(boolean valid) {
		this.valid = valid;
	}

	@Override
	public String toString() {
		return "UploadResult [handleId=" + handleId + ", errorMessage=" + errorMessage + ", valid=" + valid
				+ ", modelResource=" + modelResource + "]";
	}
}

Rename this pojo to make it uniform with ModelView

Signed-off-by: Erle Czar Mantos <6a196122cf8cbb3973e05953127115c7f1ea016d@bosch-si.com>


package gr.aueb.dmst.istlab.unixtools.util;

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

import org.apache.commons.lang3.SystemUtils;

public final class SystemInfo {

  private SystemInfo() {}

  public static List<String> getSystemShellInfo() {
    List<String> shellInfo = new ArrayList<>();

    if (SystemUtils.IS_OS_LINUX) {
      shellInfo.add("/bin/bash");
      shellInfo.add("-c");
    } else if (SystemUtils.IS_OS_FREE_BSD) {
      shellInfo.add("");
      shellInfo.add("");
    } else if (SystemUtils.IS_OS_WINDOWS) {
      shellInfo.add("");
      shellInfo.add("");
    } else if (SystemUtils.IS_OS_MAC_OSX) {
      shellInfo.add("/bin/sh");
      shellInfo.add("-c");
    }

    return shellInfo;
  }

}

Add utility class to get specific system info


/*
 * Copyright 2014 Timothy Brooks
 *
 * 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 net.uncontended.precipice.core.concurrent;

import net.uncontended.precipice.core.Status;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

public class Eventual<T> implements Future<T> {
    private volatile T result;
    private Exception error;
    private final CountDownLatch latch = new CountDownLatch(1);
    private final AtomicReference<Status> status = new AtomicReference<>(Status.PENDING);

    @Override
    public T get() throws InterruptedException, ExecutionException {
        latch.await();
        return result;
    }

    @Override
    public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
        if (latch.await(timeout, unit)) {
            if (result != null) {
                return result;
            } else {
                throw new ExecutionException(error);
            }
        } else {
            throw new TimeoutException();
        }
    }

    @Override
    public boolean isDone() {
        return status.get() != Status.PENDING;
    }

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

    @Override
    public boolean cancel(boolean mayInterruptIfRunning) {
        throw new UnsupportedOperationException("Cancelling is not supported at this time");
    }
}

Work on implementing new context for results


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

package org.gradle.internal.service.scopes;

import org.gradle.internal.service.ServiceRegistration;

public class AbstractPluginServiceRegistry implements PluginServiceRegistry {
    @Override
    public void registerGlobalServices(ServiceRegistration registration) {

    }

    @Override
    public void registerBuildSessionServices(ServiceRegistration registration) {

    }

    public void registerBuildTreeServices(ServiceRegistration registration) {

    }

    @Override
    public void registerBuildServices(ServiceRegistration registration) {

    }

    @Override
    public void registerGradleServices(ServiceRegistration registration) {

    }

    @Override
    public void registerProjectServices(ServiceRegistration registration) {

    }
}

Add abstract base class for PluginServiceRegistry implementations


package org.jtheque.utils;

import org.slf4j.LoggerFactory;

/*
 * Copyright JTheque (Baptiste Wicht)
 *
 * 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.
 */

public class ThreadUtils {
    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static int processors(){
        return PROCESSORS;
    }

    public static void joinAll(Iterable<Thread> threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e);
            }
        }
    }
}

Add some utilities for Threads

Add some utilities for Threads