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

/**
 * Represents the state of an AMQP resource.
 */
public enum EndpointState {
    UNINITIALIZED,  // TODO - Better names ?
    ACTIVE,
    CLOSED,
}

Add an endpoint state enum for consideration


/*
 * Copyright 2016 Jaakko Hannikainen
 *
 * 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 fi.jgke.tagger.unit.repository;

import fi.jgke.tagger.domain.Source;
import fi.jgke.tagger.exception.SourceNotFoundException;
import fi.jgke.tagger.repository.SourceRepository;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.when;

public class SourceRepositoryTest {
// Wake me up when Mockito 2 works with spring
    /*
    @Mock
    SourceRepository sourceRepository;

    @Before
    public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void findOneWorks() throws Exception {
        Long id = 5L;
        Source source = new Source();
        when(sourceRepository.findOne(id)).thenReturn(source);
        when(sourceRepository.findOneOrThrow(id)).thenCallRealMethod();
        Source result = sourceRepository.findOneOrThrow(id);
        Assert.assertEquals(source, result);
    }

    @Test(expected = SourceNotFoundException.class)
    public void findOneThrows() throws Exception {
        Long id = 5L;
        when(sourceRepository.findOne(id)).thenReturn(null);
        when(sourceRepository.findOneOrThrow(id)).thenCallRealMethod();
        sourceRepository.findOneOrThrow(id);
    }
*/
}

Add a "test" for SourceRepository

Add a "test" for SourceRepository

Sadly, Mockito 2 doesn't work with spring-boot that well, which means
that interfaces' default methods cannot be unit tested.


package io.enmasse.systemtest.executor;

import java.io.*;
import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * Class provide execution of external command
 */
public class Executor {
    private Process process;
    private String stdOut;
    private String stdErr;

    /**
     * Getter for stdOutput
     * @return string stdOut
     */
    public String getStdOut() {
        return stdOut;
    }

    /**
     * Getter for stdErrorOutput
     * @return string stdErr
     */
    public String getStdErr() {
        return stdErr;
    }

    /**
     * Method executes external command
     * @param commands arguments for command
     * @return returns true if command exit code is 0
     * @throws IOException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    protected boolean execute(ArrayList<String> commands) throws IOException, InterruptedException, ExecutionException {
        return execute(commands, 0);
    }

    /**
     * Method executes external command
     * @param commands arguments for command
     * @param timeout timeout in ms for kill
     * @return returns true if command exit code is 0
     * @throws IOException
     * @throws InterruptedException
     * @throws ExecutionException
     */
    protected boolean execute(ArrayList<String> commands, int timeout) throws IOException, InterruptedException, ExecutionException{
        process = Runtime.getRuntime().exec((commands.toArray(new String[0])));

        Future<String> output = readStdOutput();
        Future<String> error = readStdError();

        int retCode = 1;
        if(timeout > 0){
            if (process.waitFor(5000, TimeUnit.MILLISECONDS)){
                retCode = process.exitValue();
            }
        }else{
            retCode = process.waitFor();
        }

        stdOut = output.get();
        stdErr = error.get();

        return retCode == 0;
    }

    /**
     * Get standard output of execution
     * @return future string output
     */
    private Future<String> readStdOutput() {
        StreamGobbler errorGobbler = new
                StreamGobbler(process.getInputStream());
        return errorGobbler.read();
    }

    /**
     * Get standard error output of execution
     * @return future string error output
     */
    private Future<String> readStdError(){
        StreamGobbler errorGobbler = new
                StreamGobbler(process.getErrorStream());
        return errorGobbler.read();
    }

    /**
     * Class represent async reader
     */
    class StreamGobbler {
        private final ExecutorService executorService = Executors.newSingleThreadExecutor();
        private InputStream is;

        /**
         * Constructor of StreamGobbler
         * @param is input stream for reading
         */
        StreamGobbler(InputStream is) {
            this.is = is;
        }

        /**
         * read method
         * @return return future string of output
         */
        public Future<String> read() {
            Future<String> future = executorService.submit(() -> {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder builder = new StringBuilder();
                while ( (line = br.readLine()) != null)
                    builder.append(line).append('\n');
                isr.close();
                br.close();
                return builder.toString();
            });

            return future;
        }
    }
}

Implement executor for external commands


/*
 * Copyright 2008-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        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.broadleafcommerce.common.util;

import org.broadleafcommerce.common.web.BroadleafRequestContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;

/**
 * Convenience class to faciliate getting internationalized messages.
 *
 * Note that this class is scanned as a bean to pick up the applicationContext, but the methods
 * this class provides should be invoked statically.
 *
 * @author Andre Azzolini (apazzolini)
 */
@Service("blBLCMessageUtils")
public class BLCMessageUtils implements ApplicationContextAware {

    protected static ApplicationContext applicationContext;

    /**
     * Returns the message requested by the code with no arguments and the currently set Java Locale on
     * the {@link BroadleafRequestContext} as returned by {@link BroadleafRequestContext#getJavaLocale()}
     *
     * @param code
     * @return the message
     */
    public static String getMessage(String code) {
        return getMessage(code, null);
    }

    /**
     * Returns the message requested by the code with the specified arguments and the currently set Java Locale on
     * the {@link BroadleafRequestContext} as returned by {@link BroadleafRequestContext#getJavaLocale()}
     *
     * @param code
     * @return the message
     */
    public static String getMessage(String code, Object[] args) {
        BroadleafRequestContext brc = BroadleafRequestContext.getBroadleafRequestContext();
        return getMessageSource().getMessage(code, args, brc.getJavaLocale());
    }

    /**
     * @return the "messageSource" bean from the application context
     */
    protected static MessageSource getMessageSource() {
        return (MessageSource) applicationContext.getBean("messageSource");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BLCMessageUtils.applicationContext = applicationContext;
    }

}

Add a utility class for looking up internationalized messages


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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onosproject.vtnrsc.AllocationPool;
import org.onosproject.vtnrsc.DefaultAllocationPool;

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for DefaultAllocationPool class.
 */
public class DefaultAllocationPoolTest {

    final IpAddress startIP1 = IpAddress.valueOf("192.168.1.1");
    final IpAddress startIP2 = IpAddress.valueOf("192.168.1.2");
    final IpAddress endIP1 = IpAddress.valueOf("192.168.1.1");
    final IpAddress endIP2 = IpAddress.valueOf("192.168.1.2");

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

    /**
     * Checks the operation of equals() methods.
     */
    @Test
    public void testEquals() {
        AllocationPool pool1 = new DefaultAllocationPool(startIP1, endIP1);
        AllocationPool pool2 = new DefaultAllocationPool(startIP1, endIP1);
        AllocationPool pool3 = new DefaultAllocationPool(startIP2, endIP2);
        new EqualsTester().addEqualityGroup(pool1, pool2)
                .addEqualityGroup(pool3).testEquals();
    }

    /**
     * Checks the construction of a DefaultAllocationPool object.
     */
    @Test
    public void testConstruction() {
        final AllocationPool apool = new DefaultAllocationPool(startIP1, endIP1);
        assertThat(startIP1, is(apool.startIp()));
        assertThat(endIP1, is(apool.endIp()));
    }
}

[ONOS-3245] Add the junit test code of DefaultAllocationPool

Change-Id: Ifa4fd9b97ef16fc842e621db40029040a2ac0df7


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

/*
 * @author max
 */
package com.intellij.openapi.keymap.impl;

import java.util.Arrays;
import java.util.List;

public class DefaultBundledKeymaps implements BundledKeymapProvider {
  public List<String> getKeymapFileNames() {
    return Arrays.asList(
      "Keymap_Default.xml",
      "Keymap_Mac.xml",
      "Keymap_MacClassic.xml",
      "Keymap_Emacs.xml",
      "Keymap_VisualStudio.xml",
      "Keymap_GNOME.xml",
      "Keymap_XWin.xml",
      "Keymap_KDE.xml",
      "Keymap_Eclipse.xml",
      "Keymap_Netbeans.xml"
    );
  }
}

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

/*
 * @author max
 */
package com.intellij.openapi.keymap.impl;

import java.util.Arrays;
import java.util.List;

public class DefaultBundledKeymaps implements BundledKeymapProvider {
  public List<String> getKeymapFileNames() {
    return Arrays.asList(
      "Keymap_Default.xml",
      "Keymap_Mac.xml",
      "Keymap_MacClassic.xml",
      "Keymap_Emacs.xml",
      "Keymap_VisualStudio.xml",
      "Keymap_XWin.xml",
      "Keymap_GNOME.xml",
      "Keymap_KDE.xml",
      "Keymap_Eclipse.xml",
      "Keymap_Netbeans.xml"
    );
  }
}

Fix GNOME keymap missing shortcuts.

Fix GNOME keymap missing shortcuts.


package net.kencochrane.raven.sentrystub;

import net.kencochrane.raven.sentrystub.auth.AuthValidator;
import net.kencochrane.raven.sentrystub.auth.InvalidAuthException;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@WebFilter(servletNames = "SentryHttpServlet")
public class SentryAuthenticationFilter implements Filter {
    private static final String SENTRY_AUTH = "X-Sentry-Auth";
    private AuthValidator authValidator;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        authValidator = new AuthValidator();
        //TODO: Load filter config to add users!
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //TODO: respond to everything that isn't "https://example.com/sentry/api/project-id/store/"
        String pathInfo = req.getPathInfo();

        if (!validateAuth(req, resp)) return;

        chain.doFilter(request, response);
    }

    private boolean validateAuth(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, String> sentryAuthDetails = extractSentryAuthDetails(req);
        String projectId = req.getPathInfo().substring(1, req.getPathInfo().indexOf('/', 1));

        try {
            authValidator.validateSentryAuth(sentryAuthDetails, projectId);
        } catch (InvalidAuthException iae) {
            resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
            PrintWriter writer = resp.getWriter();
            for (String message : iae.getDetailedMessages()) {
                writer.println(message);
            }
            return false;
        }
        return true;
    }

    private Map<String, String> extractSentryAuthDetails(HttpServletRequest request) {
        String sentryAuth = request.getHeader(SENTRY_AUTH);
        if (sentryAuth == null) {
            return Collections.emptyMap();
        }

        String[] authParameters = sentryAuth.split(",");
        Map<String, String> authDetails = new HashMap<String, String>(authParameters.length);
        for (String authParameter : authParameters) {
            String[] splitParameter = authParameter.split("=");
            authDetails.put(splitParameter[0], splitParameter[1]);
        }

        return authDetails;
    }

    @Override
    public void destroy() {
    }
}

Add a filter checking the Authorisation to access the API


package net.mostlyoriginal.api.component.graphics;

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

public class ColorTest {

	@Test
	public void should_convert_hex1_to_r()
	{
		Color color = new Color("FF000000");
		assertColor(color, 1f, 0f, 0f, 0f);
	}

	@Test
	public void should_convert_hex2_to_g()
	{
		Color color = new Color("00FF0000");
		assertColor(color, 0f, 1f, 0f, 0f);
	}

	@Test
	public void should_convert_hex3_to_b()
	{
		Color color = new Color("0000FF00");
		assertColor(color, 0f, 0f, 1f, 0f);
	}

	@Test
	public void should_convert_hex4_to_a()
	{
		Color color = new Color("000000FF");
		assertColor(color, 0f, 0f, 0f, 1f);
	}

	protected void assertColor(Color color, float r, float g, float b, float a) {
		Assert.assertEquals(r, color.r, 0.01f);
		Assert.assertEquals(g, color.g, 0.01f);
		Assert.assertEquals(b, color.b, 0.01f);
		Assert.assertEquals(a, color.a, 0.01f);
	}
}

Add test to color hex constructor.

Add test to color hex constructor.


package com.github.aureliano.achmed.os.fs;

import com.github.aureliano.achmed.resources.properties.FileProperties;

public class PosixFileProvider implements IFileProvider {

	private FileProperties properties;

	public PosixFileProvider() {
		super();
	}

	@Override
	public void setFileMode() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void setFileOwner() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void copyFile() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void copyFolder() {
		throw new UnsupportedOperationException("Not implemented yet.");
	}

	@Override
	public void setFileProperties(FileProperties properties) {
		this.properties = properties;
	}

	@Override
	public FileProperties getFileProperties() {
		return this.properties;
	}
}

Create file provider which implements POSIX pattern on file system commands.


package org.opennms.netmgt.dao.support;

import java.io.IOException;

import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.ValidationException;
import org.opennms.netmgt.dao.CastorDataAccessFailureException;
import org.springframework.dao.DataAccessException;

/**
 * This is modelled after the Spring SQLExceptionTrnaslator.
 *
 * @author DJ Gregor
 */
public class CastorExceptionTranslator {
    public DataAccessException translate(String task, IOException e) {
        return new CastorDataAccessFailureException("Failed to perform IO while " + task + ": " + e, e);
    }

    public DataAccessException translate(String task, ValidationException e) {
        return new CastorDataAccessFailureException("Failed to validate XML file while " + task + ": " + e, e);
    }

    public DataAccessException translate(String task, MarshalException e) {
        return new CastorDataAccessFailureException("Failed to marshal/unmarshal XML file while " + task + ": " + e, e);
    }
}

Add a translator for Castor exceptions (IOException, ValidationException, MarshalException) to Spring DataAccessException.


package se.michaelthelin.spotify.methods;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import se.michaelthelin.spotify.Api;
import se.michaelthelin.spotify.JsonUtilTest;
import se.michaelthelin.spotify.SpotifyProtos.Track;
import se.michaelthelin.spotify.SpotifyProtos.Album;
import se.michaelthelin.spotify.SpotifyProtos.Artist;

import java.util.List;

import static junit.framework.Assert.assertEquals;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class SearchRequestTest {

  @Test
  public void shouldGetArtistsResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("David Bowie").type("artist").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("artists.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Artist> artists = spy.getArtists();
    assertEquals(2, artists.size());

    Artist firstArtist = artists.get(0);
    Artist secondArtist = artists.get(1);

    assertEquals("0oSGxfWSnnOXhD2fKuz2Gy", firstArtist.getId());
    assertEquals("3dBVyJ7JuOMt4GE9607Qin", secondArtist.getId());
  }

  @Test
  public void shouldGetTracksResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("Mr. Brightside").type("track").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("tracks.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Track> tracks = spy.getTracks();

    assertEquals(2, tracks.size());

    Track firstTrack = tracks.get(0);
    assertEquals("0eGsygTp906u18L0Oimnem", firstTrack.getId());

    Track secondTrack = tracks.get(1);
    assertEquals("1lDWb6b6ieDQ2xT7ewTC3G", secondTrack.getId());
  }

  @Test
  public void shouldGetAlbumsResult() throws Exception {
    Api api = Api.DEFAULT_API;
    SearchRequest request = api.search().query("The Best Of Keane").type("album").build();

    // Mock response
    String responseFixture = JsonUtilTest.readTestData("albums.json");
    SearchRequest spy = spy(request);
    when(spy.getJson()).thenReturn(responseFixture);

    List<Album> albums = spy.getAlbums();

    assertEquals(2, albums.size());

    Album firstAlbum = albums.get(0);
    assertEquals("41MnTivkwTO3UUJ8DrqEJJ", firstAlbum.getId());

    Album secondAlbum = albums.get(1);
    assertEquals("6JWc4iAiJ9FjyK0B59ABb4", secondAlbum.getId());
  }

}

Add test for Search request

Add test for Search request


import stroom.search.elastic.search.SearchExpressionQueryBuilder;
import stroom.util.test.StroomJUnit4ClassRunner;

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

import java.util.List;

@RunWith(StroomJUnit4ClassRunner.class)
public class TestSearchExpressionQueryBuilder {
    SearchExpressionQueryBuilder builder;

    @Before
    public void init() {
        builder = new SearchExpressionQueryBuilder(
                null,
                null,
                null,
                System.currentTimeMillis()
        );
    }

    @Test
    public void testSimple() {
        Assert.assertEquals("Is true", 42, 42);
    }

    @Test
    public void testTokenizeExpression() {
        String expr = "123, 456,789";
        String[] expected = { "123", "456", "789" };
        String[] actual = builder.tokenizeExpression(expr);
        Assert.assertArrayEquals("Expression tokens were extracted", expected, actual);
    }
}

Add first ES unit test

Add first ES unit test


package com.rainliu.emojipanel.span;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;

import java.lang.ref.WeakReference;

public class EmojiSpan extends DynamicDrawableSpan {

  private Context mContext;

  private int mIconId;

  private Drawable mDrawable;

  private int mSize = 50; // Should not be hard-coded

  public EmojiSpan(Context context, int resourceId, int size) {
    this.mContext = context;
    this.mIconId = resourceId;
    mSize = size;
  }

  @Override
  public Drawable getDrawable() {
    if (null == this.mDrawable) {
      this.mDrawable = this.mContext.getResources().getDrawable(this.mIconId);
      this.mDrawable.setBounds(0, 0, mSize, mSize);
    }

    return this.mDrawable;
  }

  @Override public int getSize(final Paint paint, final CharSequence text, final int start,
                               final int end, final Paint.FontMetricsInt fontMetrics) {
    if (fontMetrics != null) {
      final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
      fontMetrics.top = (int) paintFontMetrics.top;
      fontMetrics.bottom = (int) paintFontMetrics.bottom;
    }

    return (int) mSize;
  }

  @Override public void draw(final Canvas canvas, final CharSequence text, final int start,
                             final int end, final float x, final int top, final int y,
                             final int bottom, final Paint paint) {
    final Drawable drawable = getDrawable();
    final Paint.FontMetrics paintFontMetrics = paint.getFontMetrics();
    final float fontHeight = paintFontMetrics.descent - paintFontMetrics.ascent;
    final float centerY = y + paintFontMetrics.descent - fontHeight / 2;
    final float transitionY = centerY - mSize / 2;

    canvas.save();
    canvas.translate(x, transitionY);
    drawable.draw(canvas);
    canvas.restore();
  }

  private Drawable getCachedDrawable() {
    WeakReference<Drawable> wr = mDrawableRef;
    Drawable d = null;

    if (wr != null)
        d = wr.get();

    if (d == null) {
        d = getDrawable();
        mDrawableRef = new WeakReference<Drawable>(d);
    }

    return d;
}

  private WeakReference<Drawable> mDrawableRef;
}

Move a copy to emojipicker library where there should be one


package com.github.aureliano.achmed.exception;

public class UnsupportedPackageManagerException extends RuntimeException {

	private static final long serialVersionUID = -4089891118124103597L;

	public UnsupportedPackageManagerException() {
		super();
	}

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

	public UnsupportedPackageManagerException(Throwable throwable) {
		super(throwable);
	}

	public UnsupportedPackageManagerException(String message, Throwable throwable) {
		super(message, throwable);
	}
}

Create unsupported package manager exception.


package com.averi.worldscribe.activities;

import android.support.v7.app.AppCompatActivity;

/**
 * Created by mark on 05/07/16.
 *
 * ArticleActivity is the superclass for each Activity that displays a certain Category of Articles.
 *
 * All subclasses must implement {@link #getLayoutResourceID} and call
 * {@link #setUpArticleCore} within onCreate.
 */
public abstract class ArticleActivity extends AppCompatActivity {

    /**
     * Load data pertaining to the selected Article, and use it in set-up processes that are common
     * to Article Activities of all Categories.
     */
    protected void setUpArticleCore() {

    }

    /**
     * @return The Android Resource ID of this Activity's layout resource file.
     */
    protected abstract int getLayoutResourceID();

}

Create a superclass for Article Activities

As all five Categories of Articles will share some common Views (such as
names, images, Connections, and Snippets), it would be beneficial to
leverage inheritance in order to prevent repetition.


package org.ensembl.healthcheck.testcase.generic;

/*
 * Copyright (C) 2003 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

import java.sql.Connection;
import java.util.HashMap;
import java.util.Iterator;

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

/**
 * Check that there are no blank db_display_name fields in external_db.
 */

public class ExternalDBDisplayName extends SingleDatabaseTestCase {

	/**
   * Create a new PredictedXrefs testcase.
   */
	public ExternalDBDisplayName() {

		addToGroup("release");
		addToGroup("core_xrefs");
		setDescription("Check that there are no blank db_display_name fields in external_db");

	}

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

		boolean result = true;

		Connection con = dbre.getConnection();

		int rows = getRowCount(con, "SELECT COUNT(*) FROM external_db WHERE db_display_name IS NULL OR db_display_name LIKE ' %'");

		if (rows > 0) {

			ReportManager.problem(this, con, rows + " rows in external_db have null or blank db_display_name - this will mean their label is missing on the web page");
			result = false;

		} else {

			ReportManager.correct(this, con, "No blank db_display_name fields in external_db");

		}

		return result;

	} // run

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

} // ExternalDBDisplayName

Check that there are no blank or null db_display_name fields in external_db - would cause problems for web display.


package org.ovirt.engine.core.utils;

import static org.junit.Assert.assertEquals;
import static org.junit.runners.Parameterized.Parameters;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

@RunWith(Parameterized.class)
public class XmlUtilsTest {
    @Rule
    public RandomUtilsSeedingRule rusr = new RandomUtilsSeedingRule();

    private int level;
    private String value;

    public XmlUtilsTest(int level, String value) {
        this.level = level;
        this.value = value;
    }

    @Parameters
    public static List<Object[]> data() {
        List<Object[]> params = new ArrayList<>();
        // XmlUtils.getXYZValue support recursive searching from a depth of 2 and above, e.g.:
        // <tag><innerTag>value</innerTag><tag>
        for (int i = 2; i < 10; ++i) {
            params.add(new Object[]{i, String.valueOf(RandomUtils.instance().nextInt())});
        }
        return params;
    }

    @Test
    public void testGetIntValueNesting() throws Exception {
        int actual = XmlUtils.getIntValue(stringToElement(buildNestedXml(level, value)), "Level1");
        assertEquals(Integer.valueOf(value).intValue(), actual);
    }

    @Test
    public void testGetTextValue() throws Exception {
        String actual = XmlUtils.getTextValue(stringToElement(buildNestedXml(level, value)), "Level1");
        assertEquals(value, actual);
    }

    private static Element stringToElement(String s) throws ParserConfigurationException, IOException, SAXException {
        return DocumentBuilderFactory.newInstance()
                .newDocumentBuilder()
                .parse(new ByteArrayInputStream(s.getBytes("UTF-8")))
                .getDocumentElement();
    }

    private static String buildNestedXml (int count, String s) {
        if (count == 0) {
            return s;
        }
        return "<Level" + count + '>' + buildNestedXml(count - 1, s) + "</Level" + count + '>';
    }
}

Add minimal tests to XmlUtils

core: Add minimal tests to XmlUtils

Change-Id: I81c895335dae1ca370320e4dd437dc5da8ba36cd
Singed-off-by: Idan Shaby <7d282434a997b05b417940edadd292e8428dbe3c@redhat.com>
Signed-off-by: Allon Mureinik <abc9ddaceaf0c059a5d9bc2aed71f25cb5370dba@redhat.com>


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.

Add bean test for AlphaPainter.

git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@3838 1312f61e-266d-0410-97fa-c3b71232c9ac


package org.ow2.proactive.workflow_catalog.rest.controller;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ow2.proactive.workflow_catalog.rest.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

/**
 * Created by paraita on 1/7/16.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class WorkflowControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Before
    public void setup() {
        //this.mockMvc = standaloneSetup(new WorkflowController()).build();
        this.mockMvc = webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testList() throws Exception {
        this.mockMvc.perform(get("/buckets/1/workflows")).andExpect(status().isNotFound());
    }
}

Test the list method implementation of the workflows rest controller

The test is an integration test


package com.gmail.nossr50.events;

import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

import com.gmail.nossr50.datatypes.SkillType;

/**
 * Called when a user levels up in a skill
 */
@SuppressWarnings("serial")
public class McMMOPlayerLevelUpEvent extends Event {
	private Player player;
	private SkillType skill;
	private int levelsGained;

	public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
		this.player = player;
		this.skill = skill;
		this.levelsGained = 1;	// Always 1 for now as we call in the loop where the levelups are calculated, could change later!
	}

	/**
	 * @return Player leveling up
	 */
	public Player getPlayer() {
		return player;
	}

	/**
	 * @return SkillType that is being leveled up
	 */
	public SkillType getSkill() {
		return skill;
	}

	/**
	 * @return The number of levels gained in this event
	 */
	public int getLevelsGained() {
		return levelsGained;
	}

	/** Rest of file is required boilerplate for custom events **/
	private static final HandlerList handers = new HandlerList();

	public HandlerList getHandlers() {
		return handers;
	}

	public static HandlerList getHandlerList() {
		return handers;
	}
}

package com.gmail.nossr50.events;

import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;

import com.gmail.nossr50.datatypes.SkillType;

/**
 * Called when a user levels up in a skill
 */
@SuppressWarnings("serial")
public class McMMOPlayerLevelUpEvent extends Event {
	private Player player;
	private SkillType skill;
	private int levelsGained;

	public McMMOPlayerLevelUpEvent(Player player, SkillType skill) {
		this.player = player;
		this.skill = skill;
		this.levelsGained = 1;	// Always 1 for now as we call in the loop where the levelups are calculated, could change later!
	}

	/**
	 * @return Player leveling up
	 */
	public Player getPlayer() {
		return player;
	}

	/**
	 * @return SkillType that is being leveled up
	 */
	public SkillType getSkill() {
		return skill;
	}

	/**
	 * @return The number of levels gained in this event
	 */
	public int getLevelsGained() {
		return levelsGained;
	}

	/** Rest of file is required boilerplate for custom events **/
	private static final HandlerList handlers = new HandlerList();

	public HandlerList getHandlers() {
		return handlers;
	}

	public static HandlerList getHandlerList() {
		return handlers;
	}
}

Fix typo Stop programming at late night

Fix typo
Stop programming at late night


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

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

import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;

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

import com.pinterest.secor.common.SecorConfig;
import com.pinterest.secor.message.Message;
import com.pinterest.secor.message.ParsedMessage;

/**
 * PerfMetricsDateParser extracts timestamp field (specified by 'message.timestamp.name')
 * and creates custom output dirs based on a custom formatter, defined by defaultFormatter
 * the output dir will look like s3://<bucket>/<topic>/yyyy/MM/dd/HH/<file_name>
 *
 * @see http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
 *
 *
 *
 */
public class PerfMetricsDateParser extends MessageParser {
    private static final Logger LOG = LoggerFactory.getLogger(PerfMetricsDateParser.class);
    protected static final String defaultFormatter = "yyyy/MM/dd/HH";

    public PerfMetricsDateParser(SecorConfig config) {
        super(config);
    }

    @Override
    public String[] extractPartitions(Message message) {
        JSONObject jsonObject = (JSONObject) JSONValue.parse(message.getPayload());
        String result[]={};
        if (jsonObject != null) {
            Object fieldValue = jsonObject.get(mConfig.getMessageTimestampName());
            Object inputPattern = mConfig.getMessageTimestampInputPattern();
            if (fieldValue != null && inputPattern != null) {
                try {
                    SimpleDateFormat inputFormatter = new SimpleDateFormat(inputPattern.toString());
                    SimpleDateFormat outputFormatter = new SimpleDateFormat(defaultFormatter);
                    Date dateFormat = inputFormatter.parse(fieldValue.toString());
                    result[] = {outputFormatter.format(dateFormat)};
                    return result;
                } catch (Exception e) {
                    LOG.warn("Impossible to convert date = " + fieldValue.toString()
                            + " for the input pattern = " + inputPattern.toString());
                }
            }
        }

        return result;
    }
}

Add parser for parsing PerfMetrics msg date


package com.hewgill.android.nzsldict;

import android.content.Context;
import android.content.SharedPreferences;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

public class VocabSheetRepository {
    private final Context mContext;
    private final SharedPreferences mPrefsStore;
    private final String KEY = "NZSL_VOCAB_SHEET";
    private final String PREF_KEY = "VOCAB_SHEET_ITEMS";

    public VocabSheetRepository(Context ctx) {
        mContext = ctx;
        mPrefsStore = ctx.getSharedPreferences(KEY, Context.MODE_PRIVATE);
    }

    public List<DictItem> all() {
        List<DictItem> allItems = new ArrayList<>();
        Dictionary dict = new Dictionary(mContext);
        for (String key : allKeys()) {
            DictItem item = dict.getWord(key);
            if (item != null) { allItems.add(item); }
        }

        return allItems;
    }

    public void add(DictItem item) {
        SharedPreferences.Editor edit = mPrefsStore.edit();
        Set<String> newKeys = allKeys();
        newKeys.add(item.uniqueKey());
        edit.putStringSet(PREF_KEY, newKeys);
        edit.apply();
    }

    public void remove(DictItem item) {
        SharedPreferences.Editor edit = mPrefsStore.edit();
        Set<String> newKeys = allKeys();
        newKeys.remove(item.uniqueKey());
        (new DictItemOfflineAvailability(mContext, item)).unavailableOffline();
        edit.putStringSet(PREF_KEY, newKeys);
        edit.apply();
    }

    public boolean contains(DictItem item) {
        return allKeys().contains(item.uniqueKey());
    }

    private Set<String> allKeys() {
        Set<String> defaultValue = new TreeSet<>();
        return mPrefsStore.getStringSet(PREF_KEY, defaultValue);
    }
}

Add repository class for loading and saving vocab sheet items


package com.duastone.stalactite.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Version Controller.
 * Get project basic infomation.
 * Such as version
 * Created by Fernando on 9/24/16.
 */
@RestController
public class VersionController {

    @RequestMapping(value="/version", method= RequestMethod.GET)
    public JSONObject get() {
        JSONObject object = new JSONObject();
        object.put("name", "Stalactite");
        object.put("version", "v0.1.2");
        object.put("news", "Add version module and support subject total size.");
        return object;
    }
}

Add version support in stalactite

Add version support in stalactite


/*
 * #%L
 * TestNG System.out printer
 * %%
 * Copyright (C) 2014 Mats Henrikson
 * %%
 * 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 com.little_fluffy_clouds.testng;

import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestNGMethod;
import org.testng.ITestResult;

/**
 * A very simple class that simply prints the class and method names of TestNG tests being run,
 * together with the elapsed time in milliseconds and the test outcome.
 */
public class SystemOutTestPrinter implements IInvokedMethodListener {

    @Override
    public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) { }

    @Override
    public void afterInvocation(final IInvokedMethod m, final ITestResult r) {
        if (!m.isTestMethod()) return;

        final ITestNGMethod method = m.getTestMethod();
        final String testName = method.getTestClass().getRealClass().getSimpleName();
        final ITestResult testResult = m.getTestResult();
        final long elapsed = testResult.getEndMillis() - testResult.getStartMillis();
        System.out.printf("%s.%s(): %s, %d millis\n",
                testName, method.getMethodName(), Status.forCode(testResult.getStatus()), elapsed);
    }

    /**
     * {@link org.testng.ITestResult}
     */
    @SuppressWarnings({"MagicNumber", "UnusedDeclaration"})
    private enum Status {
        OK(1),
        FAIL(2),
        SKIP(3),
        OK_PCT_FAIL(4),
        STARTED(16),
        UNKNOWN(-1);

        final int code;

        Status(final int code) { this.code = code; }

        static Status forCode(final int c) {
            for (final Status s : Status.values()) {
                if (s.code == c) return s;
            }
            return UNKNOWN;
        }
    }
}

Add the actual java class.

Add the actual java class.


package redis.clients.jedis.tests.benchmark;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.tests.HostAndPortUtil;
import redis.clients.jedis.tests.HostAndPortUtil.HostAndPort;

public class HashingBenchmark {
    private static HostAndPort hnp1 = HostAndPortUtil.getRedisServers().get(0);
    private static HostAndPort hnp2 = HostAndPortUtil.getRedisServers().get(1);
    private static final int TOTAL_OPERATIONS = 100000;

    public static void main(String[] args) throws UnknownHostException,
            IOException {
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        JedisShardInfo shard = new JedisShardInfo(hnp1.host, hnp1.port);
        shard.setPassword("foobared");
        shards.add(shard);
        shard = new JedisShardInfo(hnp2.host, hnp2.port);
        shard.setPassword("foobared");
        shards.add(shard);
        ShardedJedis jedis = new ShardedJedis(shards);
        Collection<Jedis> allShards = jedis.getAllShards();
        for (Jedis j : allShards) {
            j.flushAll();
        }

        long begin = Calendar.getInstance().getTimeInMillis();

        for (int n = 0; n <= TOTAL_OPERATIONS; n++) {
            String key = "foo" + n;
            jedis.set(key, "bar" + n);
            jedis.get(key);
        }

        long elapsed = Calendar.getInstance().getTimeInMillis() - begin;

        jedis.disconnect();

        System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops");
    }
}

Add benchmark for hashing algos

Add benchmark for hashing algos


package io.trigger.forge.android.modules.tabs;

import android.webkit.JavascriptInterface;

import io.trigger.forge.android.core.ForgeLog;

/**
 * Created by antoine on 16/03/18.
 */
public class DummyJSBridge {
    @JavascriptInterface
    public void callJavaFromJavaScript(final String callid, final String method, final String params) {
        ForgeLog.d("DummyJSBridge.callJavaFromJavaScript -> " + method + " -> " + params);
    }
}

Move vanilla code back into main source tree


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

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * Status of a reindex operation.
 *
 * @author Carlos Munoz camunoz@redhat.com
 */
@XmlRootElement(name = "reindexStatus")
@XmlType(name = "reindexStatusType")
public class ReindexStatus
{
   private boolean startedReindex;

   private long percentageComplete;

   private long indexedElements;

   private long totalElements;

   private String currentElementType;

   private long timeElapsed;

   private long timeRemaining;

   public boolean isStartedReindex()
   {
      return startedReindex;
   }

   public void setStartedReindex(boolean startedReindex)
   {
      this.startedReindex = startedReindex;
   }

   @XmlElement
   public long getPercentageComplete()
   {
      return this.indexedElements * 100 / this.totalElements;
   }

   @XmlElement
   public long getIndexedElements()
   {
      return indexedElements;
   }

   public void setIndexedElements(long indexedElements)
   {
      this.indexedElements = indexedElements;
   }

   @XmlElement
   public long getTotalElements()
   {
      return totalElements;
   }

   public void setTotalElements(long totalElements)
   {
      this.totalElements = totalElements;
   }

   @XmlElement
   public String getCurrentElementType()
   {
      return currentElementType;
   }

   public void setCurrentElementType(String currentElementType)
   {
      this.currentElementType = currentElementType;
   }

   @XmlElement
   public long getTimeElapsed()
   {
      return timeElapsed;
   }

   public void setTimeElapsed(long timeElapsed)
   {
      this.timeElapsed = timeElapsed;
   }

   @XmlElement
   public long getTimeRemaining()
   {
      return timeRemaining;
   }

   public void setTimeRemaining(long timeRemaining)
   {
      this.timeRemaining = timeRemaining;
   }
}

Add DTO for indexing status.

Add DTO for indexing status.


/*
  Copyright (C) 2003 EBI, GRL

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package org.ensembl.healthcheck.testcase;

import java.sql.*;

import org.ensembl.healthcheck.*;

import org.ensembl.healthcheck.util.*;

/**
 * An EnsEMBL Healthcheck test case that looks for broken foreign-key relationships.
 */

public class ComparaForeignKeyTestCaseHomologyId extends EnsTestCase {

  /**
   * Create an OrphanTestCase that applies to a specific set of databases.
   */
  public ComparaForeignKeyTestCaseHomologyId() {
      databaseRegexp = "^ensembl_compara_.*";
      addToGroup("compara_db_constraints");
      setDescription("Check for broken foreign-key relationships in ensembl_compara databases.");
  }

  public TestResult run() {

    boolean result = true;

    DatabaseConnectionIterator it = getDatabaseConnectionIterator();
    int orphans = 0;

    while (it.hasNext()) {

      Connection con = (Connection)it.next();
      // 1 test to check gene_relationship_id used as foreign key

      if( getRowCount( con, "select count(*) from homology" ) > 0 ) {
        orphans = countOrphans(con, "homology_member", "homology_id", "homology", "homology_id", false );
        if( orphans == 0 ) {
	    ReportManager.correct(this, con, "homology_member <-> homology relationships PASSED");
	} else if( orphans > 0 ) {
	    ReportManager.problem(this, con, "homology_member has unlinked entries in homology FAILED");
        } else {
	    ReportManager.problem(this, con, "homology_member <-> homology TEST NOT COMPLETED, look at the StackTrace if any");
        }
      } else {
	  ReportManager.correct(this, con, "NO ENTRIES in homology table, so nothing to test IGNORED");
      }

      result &= (orphans == 0);

    }

    return new TestResult(getShortTestName(), result);

  }

} // OrphanTestCase

Check homology_id when used as ForeignKey


package bluemix;

import java.io.File;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Map;

import com.ibm.streamsx.topology.TStream;
import com.ibm.streamsx.topology.Topology;
import com.ibm.streamsx.topology.context.AnalyticsServiceProperties;
import com.ibm.streamsx.topology.context.JobProperties;
import com.ibm.streamsx.topology.context.StreamsContext;
import com.ibm.streamsx.topology.context.StreamsContext.Type;
import com.ibm.streamsx.topology.context.StreamsContextFactory;

/**
 * Sample demonstrating submission of a topology
 * to Streaming Analytic Service on Bluemix.
 *
 */
public class Submit2StreamingAnalyticService {

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

        String vcapFile = args[0];
        String serviceName = args[1];

        /*
         * Create a simple topology, focus of the
         * sample is the submission of the job
         * to the service.
         *
         * This topology is just like simple.HelloWorld
         * with different values printed to the console log.
         */
        Topology topology = new Topology("Submit2StreamingAnalyticService");
        topology.strings(
                "Hello", "Streaming Analytic Service",
                serviceName, "running on IBM Bluemix").print();

        // Require a configuration object.
        Map<String,Object> config = new HashMap<>();

        // Here the VCAP_SERVICES information is in a local file
        // (as serialized JSON)
        config.put(AnalyticsServiceProperties.VCAP_SERVICES, new File(vcapFile));

        // Explicitly state which service is the job will be submitted to
        // The service must be in the Streaming Analytic Service section
        // of the VCAP services.
        config.put(AnalyticsServiceProperties.SERVICE_NAME, serviceName);

        // Optionally we can specify a job name
        // (note job names must be unique within the instance).
        config.put(JobProperties.NAME, "BluemixSubmitSample");

        // Submit to the ANALYICS_SERVICE context
        @SuppressWarnings("unchecked")
        StreamsContext<BigInteger> context =
             (StreamsContext<BigInteger>) StreamsContextFactory.getStreamsContext(Type.ANALYTICS_SERVICE);

        BigInteger jobId = context.submit(topology, config).get();

        System.out.println("Submitted job with jobId=" + jobId);

    }
}

Add sample for submission to bluemix

Add sample for submission to bluemix


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

package org.scijava.script.process;

import org.scijava.log.LogService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.script.ScriptInfo;
import org.scijava.script.ScriptLanguage;
import org.scijava.script.ScriptService;

/**
 * A {@link ScriptProcessor} which looks for a {@code #!} at the beginning of a
 * script, and set the language accordingly.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ScriptProcessor.class)
public class ShebangScriptProcessor implements ScriptProcessor {

	@Parameter
	private ScriptService scriptService;

	@Parameter
	private LogService log;

	private ScriptInfo info;
	private boolean first = true;

	// -- ScriptProcessor methods --

	@Override
	public void begin(final ScriptInfo scriptInfo) {
		info = scriptInfo;
	}

	@Override
	public void process(final String line) {
		if (!first) return;
		if (line.startsWith("#!")) {
			// shebang!
			final String langName = line.substring(2);
			final ScriptLanguage lang = scriptService.getLanguageByName(langName);
			if (lang != null) info.setLanguage(lang);
			else log.warn("Unknown script language: " + langName);
		}
		first = false;
	}
}

Add script processor for shebang syntax

Add script processor for shebang syntax

This lets a script declare its own intended language.

See:
https://github.com/hadim/scijava-jupyter-kernel/issues/51#issuecomment-301816226


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

import com.github.pedrovgs.app.binarytree.BinaryNode;
import java.util.List;

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

  public List<BinaryNode> get(BinaryNode<Integer> root) {
    return null;
  }
}

Add statement for problem 16

Add statement for problem 16


package com.drumonii.loltrollbuild.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

/**
 * Configuration for web mvc related beans.
 */
@Configuration
public class WebMvcConfig {

    @Bean
    public ShallowEtagHeaderFilter shallowEtagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
    }

}

Add ShallowEtagHeaderFilter to go with CacheControl headers


package org.frc4931.robot.command.autonomous;

import org.frc4931.robot.Subsystems;

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

public class FollowWall extends Command{
	private final static double TOLERANCE=0.01;
	private final double targetDistance;

	public FollowWall(double targetDistance) {
		this.targetDistance = targetDistance;
	}

	private double getTargetDistance(){
		//TODO Implement this method
		return targetDistance;
	}

	private double getCurrentDistance(){
		//TODO Implement this method
		return 0.0;
	}

	protected void end() {
		Subsystems.driveTrain.stop();
	}

	protected void execute() {
		Subsystems.driveTrain.setDriveSpeed(0.0);
		Subsystems.driveTrain.setTurnSpeed(0.0);

		if(getCurrentDistance()<getTargetDistance()-(getTargetDistance()*TOLERANCE)){
			Subsystems.driveTrain.setTurnSpeed(0.1);
		}else if(getCurrentDistance()>getTargetDistance()+(getTargetDistance()*TOLERANCE)){
			Subsystems.driveTrain.setTurnSpeed(-0.1);
		}else{
			Subsystems.driveTrain.setDriveSpeed(0.1);
		}
	}

	protected void initialize() {
	}

	protected void interrupted() {
		end();
	}

	protected boolean isFinished() {
		return false;
	}

}

Create the basic command to follow a wall


package in.twizmwaz.cardinal.module.modules.destroyable;

import in.twizmwaz.cardinal.module.GameObjective;
import in.twizmwaz.cardinal.teams.PgmTeam;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.block.BlockBreakEvent;

import java.util.List;

public class Destroyable implements GameObjective {

    private final PgmTeam team;
    private final String name;
    private final String id;

    private List<Block> blocks;
    private double complete;
    private double required;
    private boolean completed;

    protected Destroyable(final PgmTeam team, final String name, final String id, final List<Block> blocks, double required) {
        this.team = team;
        this.name = name;
        this.id = id;
        this.blocks = blocks;
        this.complete = 0;
        this.required = required;
        this.completed = false;
    }

    @Override
    public PgmTeam getTeam() {
        return this.team;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public boolean isTouched() {
        return this.complete > 0;
    }

    @Override
    public boolean isComplete() {
        return this.completed;
    }

    @Override
    public void unload() {
        HandlerList.unregisterAll(this);
    }

    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        if (this.blocks.contains(event.getBlock())) this.complete = this.complete + (1 / this.blocks.size());
        if (this.complete >= this.required) this.completed = true;
    }

}

Add destroyable module without parser

Add destroyable module without parser


package edu.berkeley.eecs.cfc_tracker.wrapper;

/**
 * Created by shankari on 7/12/15.
 */
public class Transition {
    private String currState;
    private String transition;
    // Should we put newState in here as well?
    // If so, we will need to change the location of the save

    public Transition() {}
    public Transition(String currState, String transition) {
        this.currState = currState;
        this.transition = transition;
    }
}

Add a new BagOfProperties class for a transition

A simple string is not serializable, and if we have to create a wrapper class,
we might as well record the previous state.


package com.github.jeffgbutler;

import static org.hamcrest.core.Is.*;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.junit.Test;

/**
 * This is what's usually shown to illustrate map/filter/reduce.  It is useful to understand
 * the basic concepts, but no one has these problems in the real world.
 */
public class TypicalStreamExamplesTest {

    @Test
    public void testIntStreamMapReduce() {
        int answer = IntStream.rangeClosed(1, 10)
                .map(i -> i * 3)
                .filter(i -> i % 2 == 0)
                .reduce(0, (i1, i2) -> i1 + i2);

        assertThat(answer, is(90));
    }

    @Test
    public void testIntStreamBuiltIns() {
        int answer = IntStream.rangeClosed(1, 10)
                .map(i -> i * 3)
                .filter(i -> i % 2 == 0)
                .sum();

        assertThat(answer, is(90));
    }

    @Test
    public void testStrings() {
        String[] strings = {"fred", "pebbles", "wilma"};

        List<String> outlist = Arrays.stream(strings)
                .filter(s -> s.length() <= 5)
                .map(String::toUpperCase)
                .collect(Collectors.toList());

        assertThat(outlist.size(), is(2));
        assertThat(outlist.get(0), is("FRED"));
        assertThat(outlist.get(1), is("WILMA"));
    }
}

Add some typical stream examples

Add some typical stream examples


import java.sql.*;

public class DatabaseStreams {

    public static void method() {

        Connection connection = null;
        Statement statement = null;

        try {
            connection = DriverManager.getConnection("blah");
            statement = connection.createStatement();
            // do something with statement
        }
        catch (SQLException e) {
            System.err.println("Error: " + e);
        }
        finally {
            if (statement != null) {
                try {
                    statement.close();
                }
                catch (SQLException e) {
                    System.err.println("Error closing statement: " + e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                }
                catch (SQLException e) {
                    System.err.println("Error closing connection: " + e);
                }
            }
        }
    }
}

Check for closing database streams.

Check for closing database streams.

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


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

import com.ning.http.client.Body;
import com.ning.http.client.BodyGenerator;

import java.io.IOException;
import java.nio.ByteBuffer;

public class ByteArrayBodyGenerator implements BodyGenerator {

    private final byte[] bytes;
    private boolean eof = false;
    private int lastPosition = 0;

    public ByteArrayBodyGenerator(byte[] bytes) {
        this.bytes = bytes;
    }

    protected final class ByteBody implements Body {

        public long getContentLength() {
            return bytes.length;
        }

        public long read(ByteBuffer byteBuffer) throws IOException {

            if (eof) {
                return -1;
            }

            if (bytes.length - lastPosition <= byteBuffer.capacity()) {
                byteBuffer.put(bytes, lastPosition, bytes.length);
                eof = true;
            } else {
                byteBuffer.put(bytes, lastPosition, byteBuffer.capacity());
                lastPosition = bytes.length - byteBuffer.capacity();
            }
            return bytes.length;
        }

        public void close() throws IOException {
            lastPosition = 0;
            eof = false;
        }
    }

    public Body createBody() throws IOException {
        return new ByteBody();
    }
}

Add a BodyGenerator backed by a byte array


package de.fabiankeller.palladio.builder.util.impl;

import de.fabiankeller.palladio.builder.util.PalladioResourceRepository;
import org.palladiosimulator.pcm.core.entity.Entity;
import org.palladiosimulator.pcm.resourcetype.CommunicationLinkResourceType;
import org.palladiosimulator.pcm.resourcetype.ProcessingResourceType;
import org.palladiosimulator.pcm.resourcetype.ResourceRepository;
import org.palladiosimulator.pcm.resourcetype.ResourceType;

import java.util.HashMap;
import java.util.Map;

public class PalladioResourceRepositoryImpl implements PalladioResourceRepository {

    private final ResourceRepository repository;

    private static final String CPU = "CPU";
    private static final String LAN = "LAN";
    private static final String HDD = "HDD";
    private static final String DELAY = "DELAY";

    private final Map<String, Entity> resourceTypes = new HashMap<>();

    public PalladioResourceRepositoryImpl(final ResourceRepository repository) {
        this.repository = repository;
    }

    @Override
    public ProcessingResourceType cpu() {
        return (ProcessingResourceType) getResourceTypeByName(CPU);
    }

    @Override
    public ProcessingResourceType hdd() {
        return (ProcessingResourceType) getResourceTypeByName(HDD);
    }

    @Override
    public ProcessingResourceType delay() {
        return (ProcessingResourceType) getResourceTypeByName(DELAY);
    }

    @Override
    public CommunicationLinkResourceType lan() {
        return (CommunicationLinkResourceType) getResourceTypeByName(LAN);
    }

    private Entity getResourceTypeByName(final String entityName) {
        if (!this.resourceTypes.containsKey(entityName)) {
            for (final ResourceType type : this.repository.getAvailableResourceTypes_ResourceRepository()) {
                if (type.getEntityName().equals(entityName)) {
                    this.resourceTypes.put(entityName, type);
                    break;
                }
            }
            throw new RuntimeException(String.format("Could not find resource type '%s'", entityName));
        }
        return this.resourceTypes.get(entityName);
    }
}

Feature: Implement facade to retrieve Palladio resource types


package uk.ac.ebi.atlas.utils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.servlet.ModelAndView;

import javax.inject.Inject;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"/applicationContext.xml", "/solrContext.xml", "/oracleContext.xml"})
public class DBSolrStatusControllerIT {

    @Inject
    private DBSolrStatusController subject;

    @Test
    public void dbAndSolrStatus() throws Exception {
        ModelAndView mav = subject.dbAndSolrStatus();
        assertThat((String) mav.getModel().get("DB"), is("UP"));
        assertThat((String) mav.getModel().get("Solr"), is("UP"));
    }
}

Add test for the health-check URL

Add test for the health-check URL


package com.jetbrains.python.console;

import com.intellij.execution.console.LanguageConsoleViewImpl;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.console.pydev.PydevConsoleCommunication;

/**
 * @author oleg
 */
public class PydevLanguageConsoleView extends LanguageConsoleViewImpl {

  public PydevLanguageConsoleView(final Project project, final String title) {
    super(project, new PydevLanguageConsole(project, title));
  }

  public void setPydevConsoleCommunication(final PydevConsoleCommunication communication){
    ((PydevLanguageConsole)getConsole()).setPydevConsoleCommunication(communication);
  }
}

package com.jetbrains.python.console;

import com.intellij.execution.console.LanguageConsoleViewImpl;
import com.intellij.openapi.project.Project;
import com.jetbrains.python.console.pydev.PydevConsoleCommunication;

/**
 * @author oleg
 */
public class PydevLanguageConsoleView extends LanguageConsoleViewImpl {

  public PydevLanguageConsoleView(final Project project, final String title) {
    super(project, new PydevLanguageConsole(project, title));
  }

  public void setPydevConsoleCommunication(final PydevConsoleCommunication communication){
    ((PydevLanguageConsole)myConsole).setPydevConsoleCommunication(communication);
  }
}

Revert "yet another back compatibility fix"

This reverts commit 4b8f9e9e3085fca2aefea3176f74dc06710d4e47.


package pipe.gui.plugin.concrete;

import pipe.gui.analysis.GSPNAnalysis;
import pipe.gui.plugin.GuiModule;
import uk.ac.imperial.pipe.models.petrinet.PetriNet;

import javax.swing.*;
import java.awt.FileDialog;

public class GSPNAnalysisModule implements GuiModule {
    /**
     * Starts the GSPN analysis module
     * @param petriNet current Petri net to use
     */
    @Override
    public void start(PetriNet petriNet) {
        JFrame frame = new JFrame("GSPN analysis");
        FileDialog selector = new FileDialog(frame, "Select petri net", FileDialog.LOAD);

        frame.setContentPane(new GSPNAnalysis(petriNet, selector).getMainPanel());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    /**
     *
     * @return GSPN Analysis
     */
    @Override
    public String getName() {
        return "GSPN Analysis";
    }
}

Add GSPN analysis to PIPE

Add GSPN analysis to PIPE


package com.github.sparkcaller.variantdiscovery;

import com.github.sparkcaller.BaseGATKProgram;
import org.broadinstitute.gatk.engine.CommandLineGATK;

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

public class GenotypeGVCF extends BaseGATKProgram {

    public GenotypeGVCF(String pathToReference, String extraArgs) {
        super("GenotypeGVCFs", extraArgs);
        setReference(pathToReference);
    }

    public File performJointGenotyping(List<File> vcfFilenames, String outputFilename) throws Exception {
        for (File vcfFile : vcfFilenames) {
            addArgument("--variant", vcfFile.getPath());
        }

        setOutputFile(outputFilename);
        executeProgram();

        return new File(outputFilename);
    }
}

[Genomics]: Create the class which will be used when performing joint genotyping.


package wissolsoft.porada.webapp.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import wissolsoft.porada.webapp.model.Law;

@Controller
public class LawsController {

    @RequestMapping("/laws*")
    public String execute(ModelMap model) {
    	final List<Law> laws = new ArrayList<Law>();
    	final Law testLaw1 = new Law();
    	testLaw1.setCaption("Проект Закону про усунення негативних наслідків та недопущення переслідування та покарання осіб з приводу подій, які мали місце під час проведення мирних зібрань");
    	testLaw1.setDate(new Date());
    	testLaw1.setId(3787);
    	testLaw1.setLink("http://w1.c1.rada.gov.ua/pls/zweb2/webproc4_1?pf3511=49375");
    	laws.add(testLaw1);
    	final Law testLaw2 = new Law();
    	testLaw2.setCaption("Проект Закону про внесення змін до Закону України 'Про спеціальну (вільну) економічну зону 'Порто-франко' на території Одеського морського торговельного порту' (щодо регулювання інвестиційної діяльності на території СЕЗ 'Порто-франко')");
    	testLaw2.setDate(new Date());
    	testLaw2.setId(3788);
    	testLaw2.setLink("http://w1.c1.rada.gov.ua/pls/zweb2/webproc4_1?pf3511=49371");
    	laws.add(testLaw2);

        model.addAttribute("laws", laws);
        return "lawlist";
    }

}

Add contrller for laws page with sample data


package org.simpleframework.xml.core;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.lang.reflect.Method;

import junit.framework.TestCase;

public class ObjectStreamClassTest extends TestCase {

   public static class Tuple implements Serializable{
      private String name;
      private String value;
      public Tuple(String name, String value) {
         this.name = name;
         this.value = value;
      }
   }
   public void testObjectStreamTest() throws Exception {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      ObjectOutputStream oout = new ObjectOutputStream(out);
      Tuple tuple = new Tuple("a", "b");

      oout.writeObject(tuple);
      byte[] array = out.toByteArray();
      ByteArrayInputStream in = new ByteArrayInputStream(array);
      ObjectInputStream oin = new ObjectInputStream(in);

      tuple = (Tuple)oin.readObject();
   }

   public void testInstantiation() throws Exception {
      ObjectStreamClass factory = ObjectStreamClass.lookup(Tuple.class);
      Method method = ObjectStreamClass.class.getDeclaredMethod("newInstance");

      if(!method.isAccessible()) {
         method.setAccessible(true);
      }
      Tuple tuple = (Tuple)method.invoke(factory);

      assertEquals(tuple.name, null);
      assertEquals(tuple.value, null);
   }

}

Update the object stream test

Update the object stream test


/*******************************************************************************
 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
 *
 * 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.eclipse.egit.ui.internal.actions;

import java.util.List;

import org.eclipse.egit.core.op.IEGitOperation;
import org.eclipse.egit.core.op.ResetOperation;
import org.eclipse.egit.ui.UIText;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Hard reset to selected revision
 */
public class HardResetToRevisionAction extends AbstractRevCommitOperationAction {

	@Override
	protected IEGitOperation createOperation(final List<RevCommit> commits) {
		return new ResetOperation(getActiveRepository(),
				commits.get(0).getName(),
				ResetOperation.ResetType.HARD);
	}

	@Override
	protected String getJobName() {
		return UIText.HardResetToRevisionAction_hardReset;
	}
}

/*******************************************************************************
 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
 *
 * 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.eclipse.egit.ui.internal.actions;

import java.util.List;

import org.eclipse.egit.core.op.IEGitOperation;
import org.eclipse.egit.core.op.ResetOperation;
import org.eclipse.egit.ui.UIText;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jgit.revwalk.RevCommit;

/**
 * Hard reset to selected revision
 */
public class HardResetToRevisionAction extends AbstractRevCommitOperationAction {

	@Override
	protected IEGitOperation createOperation(final List<RevCommit> commits) {
		return new ResetOperation(getActiveRepository(),
				commits.get(0).getName(),
				ResetOperation.ResetType.HARD);
	}

	@Override
	protected String getJobName() {
		return UIText.HardResetToRevisionAction_hardReset;
	}

	@Override
	public void run(IAction act) {
		if (!MessageDialog.openQuestion(wp.getSite().getShell(),
				UIText.ResetTargetSelectionDialog_ResetQuestion,
				UIText.ResetTargetSelectionDialog_ResetConfirmQuestion))
			return;
		super.run(act);
	}

}

Add missing confirmation dialog for hard reset

Added the missing confirmation dialog for Reset->Hard
action in History view.

Bug: 319947
Change-Id: I1fab712e20a0087ce6f91903968416c24e3d902a
Signed-off-by: Jens Baumgart <6d4d33e37bca550188034acaf6d86b3d82efd688@sap.com>


package com.tacitknowledge.performance.data;

import com.tacitknowledge.performance.Component;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.string.StringEncoder;

/** @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class SimpleMessage implements Component
{
    private final String message;

    public SimpleMessage(final String message)
    {
        this.message = message;
    }

    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.pipeline().addLast(new StringEncoder());
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception
            {
                ctx.channel().writeAndFlush(message).addListener(ChannelFutureListener.CLOSE);
            }
        });
    }
}

Implement simple string message handler

Implement simple string message handler


/*
 * Copyright (C) 2016 Reece H. Dunn
 *
 * 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 uk.co.reecedunn.intellij.plugin.xquery.tests.lexer;

import com.intellij.lexer.Lexer;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.SyntaxHighlighter;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryLexer;
import uk.co.reecedunn.intellij.plugin.xquery.lexer.XQueryTokenType;

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

public class SyntaxHighlighterTest extends XQueryLexerTest {
    public void testHighlightingLexer() {
        Lexer lexer = new SyntaxHighlighter().getHighlightingLexer();
        assertThat(lexer.getClass().getName(), is(XQueryLexer.class.getName()));
    }

    public void testTokenHighlights() {
        SyntaxHighlighter highlighter = new SyntaxHighlighter();

        assertThat(highlighter.getTokenHighlights(null).length, is(0));

        assertThat(highlighter.getTokenHighlights(XQueryTokenType.INTEGER_LITERAL).length, is(1));
        assertThat(highlighter.getTokenHighlights(XQueryTokenType.INTEGER_LITERAL)[0], is(SyntaxHighlighter.NUMBER));

        assertThat(highlighter.getTokenHighlights(XQueryTokenType.DECIMAL_LITERAL).length, is(1));
        assertThat(highlighter.getTokenHighlights(XQueryTokenType.DECIMAL_LITERAL)[0], is(SyntaxHighlighter.NUMBER));

        assertThat(highlighter.getTokenHighlights(XQueryTokenType.DOUBLE_LITERAL).length, is(1));
        assertThat(highlighter.getTokenHighlights(XQueryTokenType.DOUBLE_LITERAL)[0], is(SyntaxHighlighter.NUMBER));
    }
}

Add tests for the SyntaxHighlighter class.


package com.nexmo.quickstart.voice;

import com.nexmo.client.NexmoClient;
import com.nexmo.client.voice.Call;
import com.nexmo.client.voice.ncco.Ncco;
import com.nexmo.client.voice.ncco.TalkAction;

import static com.nexmo.quickstart.Util.configureLogging;
import static com.nexmo.quickstart.Util.envVar;

public class OutboundTextToSpeechWithNcco {
    public static void main(String[] args) throws Exception {
        configureLogging();

        final String NEXMO_APPLICATION_ID = envVar("NEXMO_APPLICATION_ID");
        final String NEXMO_PRIVATE_KEY_PATH = envVar("NEXMO_PRIVATE_KEY_PATH");

        NexmoClient client = NexmoClient.builder()
                .applicationId(NEXMO_APPLICATION_ID)
                .privateKeyPath(NEXMO_PRIVATE_KEY_PATH)
                .build();

        final String NEXMO_NUMBER = envVar("NEXMO_NUMBER");
        final String TO_NUMBER = envVar("TO_NUMBER");

        Ncco ncco = new Ncco(TalkAction.builder("This is a text to speech call from Nexmo").build());

        client.getVoiceClient().createCall(new Call(TO_NUMBER, NEXMO_NUMBER, ncco));
    }
}

Add example of TTS with NCCO

Add example of TTS with NCCO


/*
 * Copyright 2016-present 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.store.resource.impl;

import com.google.common.collect.ImmutableSet;
import org.onosproject.net.resource.DiscreteResource;
import org.onosproject.net.resource.DiscreteResourceId;

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

/**
 * Represents an empty set of discrete resource.
 */
final class EmptyDiscreteResources implements DiscreteResources {
    static final DiscreteResources INSTANCE = new EmptyDiscreteResources();

    // for serializer
    private EmptyDiscreteResources() {}

    @Override
    public Optional<DiscreteResource> lookup(DiscreteResourceId id) {
        return Optional.empty();
    }

    @Override
    public DiscreteResources difference(DiscreteResources other) {
        return this;
    }

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

    @Override
    public boolean containsAny(List<DiscreteResource> other) {
        return false;
    }

    @Override
    public DiscreteResources add(DiscreteResources other) {
        return other;
    }

    @Override
    public DiscreteResources remove(List<DiscreteResource> removed) {
        return this;
    }

    @Override
    public Set<DiscreteResource> values() {
        return ImmutableSet.of();
    }
}

Add a DiscreteResources sub type representing an empty set

This is for ONOS-4281

Change-Id: Ic4b6e2f00555681bb2af39dc1cf764d325ae8744
(cherry picked from commit abdf2df31ce11ed1fa8ee3ee83c6df41dbb2be4e)


package de.stevenschwenke.java.writingawesomejavacodeworkshop.programmingstyle;

/**
 * Pure functions can be used to write maintainable code that is much easier to debug.
 */
public class PureFunctions {

    /*
        Pure functions are functions that
        1. always evaluates the same result value given the same argument value(s)
        2. don't have any side effects.
     */

    private int y;

    private int myPureFunction(int x) {
        return x + 1;
    }

    private int myPureFunction2(int x) {
        return x + y +1;
    }

    private int myNotSoPureFunction(int x) {
        System.out.println(x); // Side effect!
        return x + 1;
    }

    private int myNotSoPureFunction2(int x) {
        y = 0;  // Side effect!
        return x + 1;
    }

    /*
        Main benefits of using pure functions:
        - Much easier to understand, especially when debugging.
        - Developers tend to write shorter methods when these methods are pure functions

        Finding out if a method is a pure function:
        - add a temporary "static"
        - let the IDE do the work for you: IDEA shows a little icon at the line of the method
     */

}

Add chapter about Pure Functions

Add chapter about Pure Functions


package pl.schibsted.flume.interceptor.json;

import org.apache.commons.lang.StringUtils;
import org.apache.flume.Context;
import org.apache.flume.conf.ComponentConfiguration;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.google.common.base.Preconditions;

public class JsonInterceptorDateTimeFormatSerializer implements
        JsonInterceptorSerializer {
    private DateTimeFormatter inputFormatter;
    private DateTimeFormatter outputFormatter;
    @Override
    public void configure(Context context) {
        String inputPattern = context.getString("inputpattern");
        String outputPattern = context.getString("outputpattern");
        Preconditions.checkArgument(!StringUtils.isEmpty(inputPattern),
                "Must configure with a valid inputpattern");
        Preconditions.checkArgument(!StringUtils.isEmpty(outputPattern),
                "Must configure with a valid outputpattern");
        inputFormatter = DateTimeFormat.forPattern(inputPattern);
        outputFormatter = DateTimeFormat.forPattern(outputPattern);
    }
    @Override
    public String serialize(String value) {
        DateTime dateTime = inputFormatter.parseDateTime(value);
        return outputFormatter.print(dateTime.getMillis());
    }
    @Override
    public void configure(ComponentConfiguration conf) {
    }
}

Add date time output format serializer

Add date time output format serializer


package net.dummydigit.qbranch.ut.mocks;

import net.dummydigit.qbranch.QBranchSerializable;
import net.dummydigit.qbranch.annotations.QBranchGeneratedCode;
import net.dummydigit.qbranch.generic.QTypeArg;
import net.dummydigit.qbranch.generic.StructT;

@QBranchGeneratedCode(compilerName = "mock", version = "version.mock")
public class JGenericTypeBase<T1, T2> implements QBranchSerializable {

    public JGenericTypeBase(JGenericTypeBaseT<T1, T2> qTypeArgs) {
        baseFieldT1 = qTypeArgs.getBaseFieldT1().newInstance();
        baseFieldT2 = qTypeArgs.getBaseFieldT2().newInstance();
    }

    private JGenericTypeBase() { }

    private T1 baseFieldT1;
    private T2 baseFieldT2;

    public static class JGenericTypeBaseT<T1, T2> extends StructT<JGenericTypeBase<T1, T2>> {

        public JGenericTypeBaseT(QTypeArg<T1> qTypeArgT1, QTypeArg<T2> qTypeArgT2) {
            this.baseFieldT1 = qTypeArgT1;
            this.baseFieldT2 = qTypeArgT2;
            this.refObj = new JGenericTypeBase<>(); // Light weight object. Just to get class
        }

        @Override
        public StructT<?> getBaseClassT () {
            return null;
        }

        @Override
        public JGenericTypeBase<T1, T2> newInstance() {
            return new JGenericTypeBase<>(this);
        }

        @Override
        @SuppressWarnings("unchecked")
        public Class<JGenericTypeBase<T1, T2>> getGenericType() {
            return (Class<JGenericTypeBase<T1, T2>>)refObj.getClass();
        }

        private QTypeArg<T1> baseFieldT1;
        private QTypeArg<T2> baseFieldT2;
        private JGenericTypeBase<T1, T2> refObj;

        public QTypeArg<T1> getBaseFieldT1() {
            return baseFieldT1;
        }

        public QTypeArg<T2> getBaseFieldT2() {
            return baseFieldT2;
        }
    }

    public static<T1, T2> JGenericTypeBaseT asQTypeArg(QTypeArg<T1> qTypeArgT1, QTypeArg<T2> qTypeArgT2) {
        return new JGenericTypeBaseT<>(qTypeArgT1, qTypeArgT2);
    }
}

[New] Add second java class to demo how to create generic class.


package org.opennms.netmgt.model;

import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;

public class OnmsRestrictions {
    private static final StringType STRING_TYPE = new StringType();

    /**
     * Performs an iplike match on the ipAddr column of the current table.
     *
     * @param value iplike match
     * @return SQL restriction for this iplike match
     */
    public static Criterion ipLike(String value) {
        return Restrictions.sqlRestriction("iplike({alias}.ipAddr, ?)", value, STRING_TYPE);
    }
}

Add our own Restrictions object like Hibernate, for OpenNMS-specific Restrictions. Right now, it provides a way to do an iplike match.


package de.retest.recheck.configuration;

import java.nio.file.Path;

public class ProjectConfigurationUtil {

	private ProjectConfigurationUtil() {

	}

	public static Path findProjectConfigurationFolder() {
		return ProjectRootFinderUtil.getProjectRoot().resolve( ProjectConfiguration.RETEST_PROJECT_CONFIG_FOLDER );
	}

	public static Path findProjectConfiguration() {
		return findProjectConfigurationFolder().resolve( ProjectConfiguration.RETEST_PROJECT_PROPERTIES );
	}

}

Add util to find project configuration

Add util to find project configuration


package com.truphone.cascades;

import java.io.PrintStream;

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

import com.truphone.cascades.FakeDevice.FakeDeviceListener;
import com.truphone.cascades.commands.QmlCommand;
import com.truphone.cascades.replys.IReply;

/**
 * Test class.
 * @author STruscott
 *
 */
public final class TestQmlCommand {
	/**
	 * Test the key command.
	 * @throws TimeoutException Thrown if the command times out
	 */
	@Test
	public void testKeyCommand() throws TimeoutException {
		final FakeDeviceListener response = new FakeDeviceListener() {
			@Override
			public void messageReceived(String message, PrintStream replyStream) {
				if ("qml appContext.function".equals(message)) {
					replyStream.println(FakeDevice.OK_MESSAGE);
				} else {
					Assert.fail(message);
				}
			}
		};
		FakeDevice.DEVICE.getProcess().addListener(response);
		final IReply reply = FakeDevice.CONN.transmit(new QmlCommand("appContext.function"), FakeDevice.DEFAULT_TIMEOUT);
		FakeDevice.DEVICE.getProcess().removeListener(response);
		Assert.assertTrue(reply.isSuccess());
	}
}

Add unit test for the QML Command

Add unit test for the QML Command


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

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

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

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 21, constants = BuildConfig.class)
public class FormAttributeEntityTest {

    @Test
    public void shouldSetFormAttributeEntityTest() {
        FormAttributeEntity formAttributeEntity = TestEntityFixtures.getFormAttributeEntity();
        assertThat(formAttributeEntity).isNotNull();
        assertThat(formAttributeEntity.getKey()).isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getFormId())
                .isEqualTo(1l);
        assertThat(formAttributeEntity.getKey())
                .isEqualTo("test_varchar");
        assertThat(formAttributeEntity.getLabel())
                .isEqualTo("Test varchar");
        assertThat(formAttributeEntity.getRequired())
                .isFalse();
        assertThat(formAttributeEntity.getPriority())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getCardinality())
                .isEqualTo(1);
        assertThat(formAttributeEntity.getOptions()).isNull();
    }
}

Add test for form attribute

Add test for form attribute


package com.cloudbees.plugins.credentials.impl;

import com.cloudbees.plugins.credentials.CredentialsSnapshotTaker;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;

import hudson.Extension;
import hudson.util.Secret;

@Extension
public class UsernamePasswordCredentialsSnapshotTaker extends CredentialsSnapshotTaker<StandardUsernamePasswordCredentials> {

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<StandardUsernamePasswordCredentials> type() {
        return StandardUsernamePasswordCredentials.class;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public StandardUsernamePasswordCredentials snapshot(StandardUsernamePasswordCredentials credentials) {
        return new UsernamePasswordCredentialsImpl(credentials.getScope(), credentials.getId(), credentials.getDescription(), credentials.getUsername(), Secret.toString(credentials.getPassword()));
    }
}

Add snapshot taker for StandardUsernamePasswordCredentials


package com.github.havarunner.beforeafter;

import com.github.havarunner.HavaRunner;
import com.github.havarunner.annotation.RunSequentially;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.junit.Before;
import org.junit.Test;

import static com.github.havarunner.TestHelper.run;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class BeforeCallOrderTest {
    static long grandParentBeforeCalled;
    static long parentBeforeCalled;
    static long childBeforeCalled;

    @Test
    public void HavaRunner_calls_the_ancestor_befores_first() {
        run(new HavaRunner(Child.class));
        assertTrue(grandParentBeforeCalled < parentBeforeCalled);
        assertTrue(parentBeforeCalled < childBeforeCalled);
    }

    static class Child extends Parent {
        @Before
        void childBefore() throws InterruptedException {
            Thread.sleep(1);
            childBeforeCalled = System.currentTimeMillis();
        }

        @Test
        void hello() {}
    }

    abstract static class Parent extends GrandParent {
        @Before
        void parentBefore() throws InterruptedException {
            Thread.sleep(1);
            parentBeforeCalled = System.currentTimeMillis();
        }
    }

    @RunSequentially
    abstract static class GrandParent {
        @Before
        void grandParentBefore() throws InterruptedException {
            Thread.sleep(1);
            grandParentBeforeCalled = System.currentTimeMillis();
        }
    }
}

Add spec on @Before call order

Add spec on @Before call order


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.
 */

/**
 * Formatters for replacing placeholders with real values in text messages.
 */
package org.tinylog.core.formatters;

Add Java package for formatters

Add Java package for formatters