package com.google.slurp.servlets;

import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;

/**
 * Servlet context listener that is looked for whenever the backend server
 * receives a startup or shutdown request.
 */
@WebListener
public class ServerListener implements ServletContextListener {

  /**
   * {@inheritDoc}
   *
   * Initialize the Firebase Admin app for the server.
   */
  @Override
  public void contextInitialized(ServletContextEvent event) {
    System.out.println("Server initialized and starting up...");

    try {
      FirebaseOptions options = new FirebaseOptions.Builder()
          .setCredentials(GoogleCredentials.getApplicationDefault())
          .build();

      FirebaseApp.initializeApp(options);
    } catch (IOException error) {
      System.err.println("Error obtaining the Application Default Credentials:");
      error.printStackTrace();
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    System.out.println("Server destroyed and shutting down...");
  }
}

Add WebListener for the backend server

Add WebListener for the backend server


package kg.apc.jmeter.reporters;

import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
import org.loadosophia.jmeter.LoadosophiaAPIClient;
import org.loadosophia.jmeter.StatusNotifierCallback;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;

class FakeAPIClient extends LoadosophiaAPIClient {
    private static final Logger log = LoggingManager.getLoggerForClass();

    private LinkedList<String[]> response;

    private FakeAPIClient(StatusNotifierCallback aThis, LinkedList<String[]> aresponse) {
        super(aThis, "TEST", "TEST", COLOR_NONE, "TEST", "TEST");
        response = aresponse;
    }

    @Override
    protected String[] getUploadStatus(int queueID) throws IOException {
        String[] resp = response.pop();
        log.info("Simulating response: " + Arrays.toString(resp));
        return resp;
    }

    @Override
    protected String[] multipartPost(LinkedList<Part> parts, String URL, int expectedSC) throws IOException {
        return getUploadStatus(0);
    }
}

Refactor out fake api client

Refactor out fake api client


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

import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;

/**
 * This sub-interface adds the ability to write to a lazy dataset slice-by-slice
 */
public interface ILazyWriteableDataset extends ILazyDataset {

	/**
	 * Denotes an unlimited dimension in maximum shape
	 */
	public static final int UNLIMITED = -1;

	/**
	 * @return maximum shape
	 */
	public int[] getMaxShape();

	/**
	 * Get chunking
	 * @return chunks
	 */
	public int[] getChunking();

	/**
	 * Set a slice of the dataset
	 *
	 * @param monitor
	 * @param data
	 * @param slice an n-D slice
	 * @throws Exception
	 */
	public void setSlice(final IMonitor monitor, final IDataset data, final SliceND slice) throws Exception;
}

Add new writeable dataset interface

Add new writeable dataset interface


package com.twilio.ivrrecording.servlet.extension;

import com.twilio.ivrrecording.models.Agent;
import com.twilio.ivrrecording.repositories.AgentRepository;
import com.twilio.ivrrecording.servlet.BaseTwilioServletTest;
import com.twilio.ivrrecording.servlet.menu.ShowServlet;
import org.hamcrest.CoreMatchers;
import org.jdom2.Document;
import org.jdom2.Element;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

public class ConnectServletTest extends BaseTwilioServletTest {
    @Mock
    HttpServletRequest request;

    @Mock
    HttpServletResponse response;

    @Mock
    AgentRepository agentRepository;

    @Before
    public void setUp() throws IOException {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void postMethod_WhenAnAgentIsFound_ThenRespondsByDialingTheAgentsPhoneNumber()
            throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        PrintWriter printWriter = new PrintWriter(output);

        String number = "+12025550142";

        when(agentRepository.findByExtension(anyString())).thenReturn(new Agent(1, "Brodo", number));
        when(request.getParameter("Digits")).thenReturn("2");
        when(response.getWriter()).thenReturn(printWriter);

        ConnectServlet servlet = new ConnectServlet(agentRepository);
        servlet.doPost(request, response);

        printWriter.flush();
        String content = new String(output.toByteArray(), "UTF-8");

        Document document = getDocument(content);

        assertThatContentTypeIsXML(response);
        assertThat(getAttributeValue(document, "Dial/Number", "url"), is(equalTo("/agents/screen-call")));
        assertThat(getElement(document, "Dial/Number").getValue(), is(equalTo(number)));
    }

}

Add Connect Servlets, tests and some code refactoring


/*
 * $Id: ShouldNotHappenException.java,v 1.1 2011-11-15 21:38:44 barry409 Exp $
 */

/*

Copyright (c) 2011 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.daemon;

/**
Thrown when a situation is detected that should never occur,
  * such as an internal consistency check that can fail only as a
  * result of a programming error.  This exception is not expected to
  * be handled other than by terminating the affected process or
  * computation.

  */
public class ShouldNotHappenException extends RuntimeException {

  public ShouldNotHappenException() {
    super();
  }

  public ShouldNotHappenException(String msg) {
    super(msg);
  }

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

  public ShouldNotHappenException(String msg, Throwable cause) {
    super(msg, cause);
  }
}

Add a RuntimeException to be thrown for never-happens sanity checks and detected programming errors.

git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@13388 4f837ed2-42f5-46e7-a7a5-fa17313484d4


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eas.designer.application.query.completion;

import com.bearsoft.rowset.metadata.Fields;
import com.eas.client.model.gui.IconCache;
import java.util.Map.Entry;
import org.openide.util.NbBundle;

/**
 *
 * @author mg
 */
public class TableSqlCompletionItem extends SqlCompletionItem {

    protected Fields table;

    public TableSqlCompletionItem(Entry<String, Fields> aTableEntry, int aStartOffset, int aEndOffset) {
        super(aTableEntry.getKey(), aTableEntry.getValue().getTableDescription(), aStartOffset, aEndOffset);
        icon = IconCache.getIcon("table.png");
        rightText = NbBundle.getMessage(TableSqlCompletionItem.class, "table");
    }

    public TableSqlCompletionItem(String aAlias, Fields aTable, int aStartOffset, int aEndOffset) {
        super(aAlias, aTable != null ? aTable.getTableDescription() : null, aStartOffset, aEndOffset);
        icon = IconCache.getIcon("table.png");
        if (aAlias.equalsIgnoreCase(aTable.get(1).getTableName())) {
            rightText = NbBundle.getMessage(TableSqlCompletionItem.class, "table");
        } else {
            rightText = NbBundle.getMessage(TableSqlCompletionItem.class, "aliasToTable") + " " + aTable.get(1).getTableName();
        }
    }
}

Prepare to strong referencing of stored subqueries


package net.dempsy.utils.test;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.IntStream;

/**
 * This class allows the setting and then unsetting of System properties within the scope of a test.
 */
public class SystemPropertyManager implements AutoCloseable {
    private static class OldProperty {
        public final boolean hasOldValue;
        public final String oldValue;
        public final String name;

        public OldProperty(final String name, final boolean hasOldValue, final String oldValue) {
            this.hasOldValue = hasOldValue;
            this.oldValue = oldValue;
            this.name = name;
        }
    }

    private final List<OldProperty> oldProperties = new ArrayList<>();

    public SystemPropertyManager set(final String name, final String value) {
        oldProperties.add(new OldProperty(name, System.getProperties().containsKey(name), System.getProperty(name)));
        System.setProperty(name, value);
        return this;
    }

    public SystemPropertyManager load(final String file) {
        final Properties props = new Properties();
        try (FileInputStream fis = new FileInputStream(file)) {
            props.load(fis);
            props.entrySet().stream().forEach(e -> set((String) e.getKey(), (String) e.getValue()));
            return this;
        } catch (final IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }

    @Override
    public void close() {
        final int num = oldProperties.size();
        IntStream.range(0, num).forEach(i -> revert(oldProperties.get(num - i - 1)));
    }

    private static void revert(final OldProperty op) {
        if (op.hasOldValue)
            System.setProperty(op.name, op.oldValue);
        else System.clearProperty(op.name);
    }
}

Add helper for managing System properties in tests.


package com.systelab.seed.infrastructure.security;

import javax.servlet.annotation.WebFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class XFrameOptionsFilter implements Filter {

    public XFrameOptionsFilter() {
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (response instanceof HttpServletResponse) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.addHeader("X-Frame-Options", "deny");
        }
        chain.doFilter(request, response);
    }
}

Add X-Frame-Options HTTP response header and set it to deny to reduce the risk of a clickjacking attack.


/*
 * Copyright 2019 Google LLC
 *
 * 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
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.android.gnd;

/** Project configurations. */
public final class Config {

  // TODO(#128): Reset version to 1 before releasing.
  public static final int DB_VERSION = 32;
  public static final String DB_NAME = "gnd.db";
}

Add file to store configs

Add file to store configs


package com.cathive.fx.dbus;

import javafx.application.Application;
import javafx.stage.Stage;

/**
 * @author Benjamin P. Jung
 */
public class DBusAnalyzer extends Application {

    @Override
    public void start(final Stage primaryStage) throws Exception {
    }

}

Add skeleton for DBus analyzer JavaFX app.


/*
 *  Copyright 2016 __0x277F <0x277F@gmail.com>
 *  and other copyright owners as documented in the project's IP log.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License&quot￼;
 *  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.basinmc.faucet.lang;

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

/**
 * Annotates a field or a local variable to signify that string values that each
 * might represent will be transformed (at plugin load time) into an unlocalized
 * string, which will be localized during outgoing packet processing for
 * significant packets, such as chat, item metadata (including name and lore), etc.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.TYPE})
public @interface Localize {
    /**
     * The key for which localization will be attempted. By default this will be
     * filled by the string being targeted.
     * @return A string representation of the key
     */
    String value() default "$PROVIDED$";

    /**
     * If no valid localization for the player is found, the locale to use. If this
     * is unable to function for whatever reason, the player will receive the key
     * instead.
     * @return A locale string
     */
    String defaultLocale() default "en_US";

    /**
     * A directory path where locale files (which <i>must</i> follow the format of
     * "en_US.lang" can be found. If the given path is checked and a locale file is
     * not found, the {@link Localize#defaultLocale()} will be attempted instead,
     * then the key will be sent instead.
     * @return A locale string
     */
    String localePath() default "/lang/";
}

Add a localization annotation. Because implementations are a lot of work.


package editor.gui;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import editor.collection.CardList;
import editor.gui.display.CardTable;

/**
 * This class is a listener for changes to the selection in a {@link CardTable},
 * whether that selection be by mouse click or programmatically (e.g. due to changes
 * in the backing list). Only one table in the program can have a selection at a time,
 * so when one of them is clicked, all the rest have to be cleared.
 *
 * @author Alec Roelke
 */
public class TableSelectionListener implements MouseListener, ListSelectionListener
{
    /** Main frame controlling table selection. */
    private final MainFrame frame;
    /** Table to watch. */
    private final CardTable table;
    /** Card list backing the table. */
    private final CardList list;

    /**
     * Create a new listener that listens to the given table and updates its backing
     * list.
     *
     * @param f main frame controlling table selections
     * @param t table this listener should watch
     * @param l list backing the table
     */
    public TableSelectionListener(MainFrame f, CardTable t, CardList l)
    {
        frame = f;
        table = t;
        list = l;
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        if (table.rowAtPoint(e.getPoint()) < 0)
            frame.clearSelectedTable();
        else if (frame.getSelectedTable().map((t) -> t != table).orElse(true))
            frame.setSelectedComponents(table, list);
    }

    @Override
    public void valueChanged(ListSelectionEvent e)
    {
        if (!e.getValueIsAdjusting())
        {
            if (table.getSelectedRow() >= 0)
                frame.setDisplayedCard(list.get(table.convertRowIndexToModel(table.getSelectedRow())));
            else
                frame.clearSelectedCard();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}
}

Add class for table selection listening

Add class for table selection listening

To reduce repeated code


package com.example.profbola.bakingtime.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.profbola.bakingtime.provider.RecipeContract.IngredientEntry;

/**
 * Created by prof.BOLA on 6/23/2017.
 */

public class IngredientDbHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "bakingapp.db";

    private static final int DATABASE_VERSION = 1;

    public IngredientDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        final String SQL_CREATE_INGREDIENTS_TABLE = "CREATE TABLE " + IngredientEntry.TABLE_NAME + " ( "       +
                IngredientEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "                                   +
                IngredientEntry.COLUMN_INGREDIENT + " STRING NOT NULL, "                                       +
                IngredientEntry.COLUMN_MEASURE + " STRING NOT NULL, "                                          +
                IngredientEntry.COLUMN_QUANTITY + " REAL NOT NULL, "                                         +
                IngredientEntry.COLUMN_RECIPE_ID + " INTEGER, "                                                +
                " FOREIGN KEY ( " + IngredientEntry.COLUMN_RECIPE_ID + " ) REFRENCES "                         +
                RecipeContract.RecipeEntry.TABLE_NAME + " ( " + RecipeContract.RecipeEntry.COLUMN_ID + ")"     +

                " UNIQUE ( " + IngredientEntry.COLUMN_INGREDIENT + " ) ON CONFLICT REPLACE "                   +
                ");";

        db.execSQL(SQL_CREATE_INGREDIENTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + IngredientEntry.TABLE_NAME);

        onCreate(db);
    }
}

Create DB schema for Ingredient

Create DB schema for Ingredient


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2017 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.type.data.universal;

import java.math.BigDecimal;
import java.math.MathContext;

import nom.bdezonia.zorbage.type.algebra.Group;
import nom.bdezonia.zorbage.type.algebra.Power;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ExponentialCalculation {

	private static final MathContext context = new MathContext(100);

	/**
	 * Create a numeric value from an exponential description. Works in
	 * BigDecimals for accuracy and rounds to 100 decimal places. Passed
	 * in type assigned from universal string parsing representation.
	 *
	 * @param group
	 * @param fraction
	 * @param base
	 * @param power
	 * @param result
	 */
	public static <T extends Group<T,U> & Power<U>, U>
		void compute(T group, BigDecimal fraction, int base, int power, U result)
	{
		if (base < 0)
			throw new IllegalArgumentException("negative bases not allowed");
		if (base == 0 && power == 0)
			throw new IllegalArgumentException("0^0 is not a number");
		BigDecimal b = BigDecimal.valueOf(base);
		BigDecimal exponentiation = b.pow(power, context);
		BigDecimal x = fraction.multiply(exponentiation);
		x = x.round(context);
		U tmp = group.construct(x.toString());
		group.assign(tmp, result);
	}
}

Add a sci notation like universal numeric constructor


package com.netflix.ndbench.geode.plugin;

import org.junit.Test;

public class GeodeCloudPluginTest {

  @Test
  public void invalidVcapServicesVariableTest(){

  }

  @Test
  public void validVcapServicesCreatesClientCacheTest(){

  }

}

Add support for Geode and Cloud Foundry

Add support for Geode and Cloud Foundry

 Updated
 1. Provided new discovery implementation for Cloud Foundry. Now you can
 push NdBench on Cloud Foundry and run.
 2. Added a new plugin for Geode in `local` and `cloud` mode.
 3. Updated read me on how to run NdBench on Cloud Foundry.


package jasenmoloy.wirelesscontrol.io;

/**
 * Created by jasenmoloy on 2/25/16.
 */
public interface OnGeofenceSaveFinishedListener {
    void onGeofenceSaveError();

    void onGeofenceSaveSuccess();
}

Create a Geofance save listener

Create a Geofance save listener


package org.fxmisc.richtext.api;

import com.nitorcreations.junit.runners.NestedRunner;
import javafx.stage.Stage;
import org.fxmisc.richtext.InlineCssTextAreaAppTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static javafx.scene.input.KeyCode.DELETE;

@RunWith(NestedRunner.class)
public class MiscellaneousTests {

    public class WhenAreaEndsWithEmptyLine extends InlineCssTextAreaAppTest {

        @Override
        public void start(Stage stage) throws Exception {
            super.start(stage);
            area.replaceText(0, 0, "abc\n");
        }

        public class AndAllTextIsSelected {

            @Before
            public void selectAllText() {
                interact(() -> area.selectAll());
            }

            @Test
            public void pressingDeleteShouldNotThrowException() {
                push(DELETE);
            }

        }
    }
}

Add test: UI-initiated all-text deletion should not throw exception


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

package org.apache.commons.logging.log4j.log4j12;

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

import org.apache.commons.logging.PathableClassLoader;
import org.apache.commons.logging.PathableTestSuite;
import org.apache.commons.logging.impl.ServletContextCleaner;

/**
 * Tests for ServletContextCleaner utility class.
 */

public class BasicServletTestCase extends TestCase {

    /**
     * Return the tests included in this test suite.
     */
    public static Test suite() throws Exception {
        // LogFactory in parent
        // LogFactory in child (loads test)
        // LogFactory in tccl
        //
        // Having the test loaded via a loader above the tccl emulates the situation
        // where a web.xml file specifies ServletContextCleaner as a listener, and
        // that class is deployed via a shared classloader.

        PathableClassLoader parent = new PathableClassLoader(null);
        parent.useSystemLoader("junit.");
        parent.addLogicalLib("commons-logging");
        parent.addLogicalLib("servletapi");

        PathableClassLoader child = new PathableClassLoader(parent);
        child.setParentFirst(false);
        child.addLogicalLib("commons-logging");
        child.addLogicalLib("testclasses");

        PathableClassLoader tccl = new PathableClassLoader(child);
        tccl.setParentFirst(false);
        tccl.addLogicalLib("commons-logging");

        Class testClass = child.loadClass(BasicServletTestCase.class.getName());
        return new PathableTestSuite(testClass, tccl);
    }

    /**
     * Test that calling ServletContextCleaner.contextDestroyed doesn't crash.
     * Testing anything else is rather difficult...
     */
    public void testBasics() {
        ServletContextCleaner scc = new ServletContextCleaner();
        scc.contextDestroyed(null);
    }
}

Add unit tests for ServletContextCleaner class.

git-svn-id: 6ecf90c357d929aee58b51a998def805f2e9c62f@370739 13f79535-47bb-0310-9956-ffa450edef68


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

package com.owncloud.android.lib.test_project.test;

import com.owncloud.android.lib.operations.common.OCShare;
import com.owncloud.android.lib.operations.common.RemoteOperationResult;
import com.owncloud.android.lib.test_project.TestActivity;

import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;

public class RemoveShareTest extends ActivityInstrumentationTestCase2<TestActivity> {

	private static final String TAG = RemoveShareTest.class.getSimpleName();

	private TestActivity mActivity;

	public RemoveShareTest() {
		super(TestActivity.class);

	}

	@Override
	  protected void setUp() throws Exception {
	    super.setUp();
	    setActivityInitialTouchMode(false);
	    mActivity = getActivity();
	}

	/**
	 * Test Remove Share: the server must support SHARE API
	 */
	public void testRemoveShare() {
		// Get the shares
		RemoteOperationResult result = mActivity.getShares();
		if (result.isSuccess()) {
			int size = result.getData().size();

			if (size > 0) {
				OCShare share = ((OCShare) result.getData().get(size -1));
				long id = share.getIdRemoteShared();
				Log.d(TAG, "File to unshare: " + share.getPath() );
				result = mActivity.removeShare((int) id);	// Unshare
				assertTrue(result.isSuccess());
			} else {
				assertTrue(true);
			}
		} else {
			assertTrue(true);
		}
	}
}

OC-2738: Create unitTests in the library: unshare a item.


/*
 * AsTest.java
 *
 * Created on 10. September 2001, 09:44
 */

package freetds;
import java.sql.*;
import java.math.BigDecimal;
import com.internetcds.util.Logger;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import junit.framework.AssertionFailedError;
import java.io.*;
import java.lang.reflect.*;

/**
 *
 * @author  builder
 * @version
 */
public class AsTest extends DatabaseTestCase {

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

  public static void main(String args[]) {
    try {
      Logger.setActive(true);
    }
    catch (java.io.IOException ex) {
      throw new RuntimeException("Unexpected Exception " + ex + " occured in main");
    }
    if (args.length > 0) {
      junit.framework.TestSuite s = new TestSuite();
      for (int i = 0; i < args.length; i++) {
        s.addTest(new AsTest(args[i]));
      }
      junit.textui.TestRunner.run(s);
    }
    else
      junit.textui.TestRunner.run(AsTest.class);
  }

  public void testProc1() throws Exception
  {

    boolean passed = false;
    Statement stmt = con.createStatement();
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec')) drop procedure spTestExec");
    stmt.executeUpdate("  if (exists (select * from sysobjects where name = 'spTestExec2')) drop procedure spTestExec2");

    stmt.executeUpdate(" create procedure spTestExec2 as " +
                    "select 'Did it work?' as Result");
    stmt.executeUpdate("create procedure spTestExec as " +
		"create table #tmp ( Result varchar(50) ) " +
		"insert #tmp execute spTestExec2 " +
		"select * from #tmp");
    CallableStatement cstmt = con.prepareCall("exec spTestExec");
    ResultSet rs = cstmt.executeQuery();
    while (rs.next()) {
      passed = true;
    }
    assertTrue(passed);
    // stmt.executeQuery("execute spTestExec");

  }

}

Test PMoores Problem with Procedure sptestexec

git-svn-id: 344b71073909399dbfbb72461917dbf939dfdc0a@23 97a8069c-bbaa-4fa2-9e49-561d8e0b19ef


package org.sakaiproject.entity.api;

/**
 * Services which implement ContentExistsAware declare that they are able to determine if they contain content for the site they are in.
 * Note that services must also be registered EntityProducers.
 *
 * @since 11.0
 * @author Steve Swinsburg (steve.swinsburg@gmail.com)
 */
public interface ContentExistsAware {

	/**
	 * Does this tool contain content in this site?
	 *
	 * @param siteId the siteId to use when checking if content exists
	 */
	public boolean hasContent(String siteId);

}

Add marker interface that tools can implement to show that they know if they have content or not


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

import com.facebook.presto.testing.LocalQueryRunner;

import static com.facebook.presto.benchmark.BenchmarkQueryRunner.createLocalQueryRunner;

public class CastJsonParseBenchmark
        extends AbstractSqlBenchmark
{
    public CastJsonParseBenchmark(LocalQueryRunner localQueryRunner)
    {
        super(
                localQueryRunner,
                "sql_cast_json_parse",
                10,
                100,
                "select cast(json_parse('[' || array_join(repeat(totalprice, 100), ',') || ']') as array(real)) from orders");
    }

    public static void main(String[] args)
    {
        new CastJsonParseBenchmark(createLocalQueryRunner()).runBenchmark(new SimpleLineBenchmarkResultWriter(System.out));
    }
}

Add CAST with JSON_PARSE benchmark

Add CAST with JSON_PARSE benchmark

New benchmark to evaluate the performance gain with the optimization on
CAST with JSON_PARSE


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import java.awt.Component;

import javax.swing.JComponent;
import javax.swing.JInternalFrame;
import javax.swing.JRootPane;
import javax.swing.JToolBar;

/**
 * Is the window for this toolbar active?
 */
public class ToolBarHasNorthToolBarState extends State {

    private static final State isNorthState = new ToolBarNorthState();

    public ToolBarHasNorthToolBarState() {
        super("HasNorthToolBar");
    }

    public boolean isInState(JComponent c) {
        Component parent = c.getParent();
        while (parent.getParent() != null) {
            if (parent instanceof JInternalFrame || parent instanceof JRootPane) {
                break;
            }
            parent = parent.getParent();
        }
        Component[] cArray = null;
        if (parent != null) {
            if (parent instanceof JInternalFrame) {
                cArray = ((JInternalFrame) parent).getContentPane().getComponents();
            } else if (parent instanceof JRootPane) {
                cArray = ((JRootPane) parent).getContentPane().getComponents();
            }
        }

        if (cArray != null) {
            for (Component comp : cArray) {
                if (comp instanceof JToolBar) {
                    if (comp != c && isNorthState.isInState((JComponent) comp)) {
                        return true;
                    }
                }
            }
        }

        return false;
    }
}

Determine whether a toolbar is in a pane with a north toolbar that is not itself.


package org.gbif.checklistbank.cli;

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jdk.nashorn.internal.ir.annotations.Ignore;
import org.junit.Test;

/**
 * Manual terst to inspect the uber jar to list number of files to get an idea whats inside.
 */
@Ignore
public class JarTest {

    @Test
    public void countJar() throws IOException {
        JarFile jar = new JarFile("target/checklistbank-cli.jar");

        System.out.println(
                Collections.list(jar.entries()).size()
        );
        Pattern rootPath = Pattern.compile("^(org\\/(apache|neo4j(\\/cypher\\/internal\\/compiler)?)|[a-z0-9_-]+)\\/[a-z0-9_-]+", Pattern.CASE_INSENSITIVE);
        Map<String, AtomicInteger> counts = new TreeMap<String, AtomicInteger>();
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry e = entries.nextElement();
            String key;
            Matcher m = rootPath.matcher(e.getName());
            if (m.find()) {
                key = m.group(0);
            } else {
                key = e.getName();
            }
            if (!counts.containsKey(key)) {
                counts.put(key, new AtomicInteger(1));
            } else {
                counts.get(key).getAndIncrement();
            }
        }

        for (Map.Entry<String, AtomicInteger> e : counts.entrySet()) {
            if (e.getValue().get() > 100) {
                System.out.println(e.getKey() + "   " + e.getValue());
            }
        }
    }
}

Add manual test to count shaded jar files


package com.vladmihalcea.book.hpjp.hibernate.concurrency.upsert;

import com.vladmihalcea.book.hpjp.util.AbstractSQLServerIntegrationTest;
import org.hibernate.annotations.NaturalId;
import org.junit.Test;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.LockModeType;
import javax.persistence.Table;
import java.util.concurrent.CountDownLatch;

/**
 * @author Vlad Mihalcea
 */
public class SQLServerUpsertAlternativeTest extends AbstractSQLServerIntegrationTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[]{
            Book.class
        };
    }

    @Test
    public void testUpsertWithInsertAndUpdateLock() {
        CountDownLatch aliceCountDownLatch = new CountDownLatch(1);

        doInJPA(entityManager -> {
            Book book = new Book();
            book.setId(1L);
            book.setTitle("Book 1");

            entityManager.persist(book);
            entityManager.flush();

            executeAsync(() -> {
                doInJPA(_entityManager -> {
                    try {
                        LOGGER.info("Bob tries to lock the record");
                        Book _book = _entityManager.find(Book.class, 1L, LockModeType.PESSIMISTIC_READ);
                        if (_book == null) {
                            LOGGER.info("Bob inserts");
                            _book = new Book();
                            _book.setId(1L);
                            _book.setTitle("Book 2");
                            _entityManager.persist(_book);
                        } else {
                            LOGGER.info("Bob updates");
                            _book.setTitle("Book 2");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        aliceCountDownLatch.countDown();
                    }
                });
            });

            LOGGER.info("Alice starts sleeping");
            sleep(5000);
            LOGGER.info("Alice woke up and releases the logs after she commits");
        });

        LOGGER.info("");
        awaitOnLatch(aliceCountDownLatch);
    }

    @Entity(name = "Book")
    @Table(name = "book")
    public static class Book {

        @Id
        private Long id;

        @NaturalId
        private String isbn;

        private String title;

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getIsbn() {
            return isbn;
        }

        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }
}

Add SQL Server UPSERT alternative using locks


package arez.integration.dagger.codegen;

import arez.annotations.ArezComponent;
import arez.annotations.Feature;
import arez.annotations.InjectMode;
import arez.annotations.PerInstance;
import org.testng.annotations.Test;

public class NoInjectionsConsumeFactoryIntegrationTest
  extends AbstractCodegenIntegrationTest
{
  @ArezComponent( dagger = Feature.ENABLE, allowEmpty = true, inject = InjectMode.CONSUME )
  static abstract class MyComponent
  {
    MyComponent( @PerInstance int value )
    {
    }
  }

  @Test
  public void scenario()
    throws Exception
  {
    assertClassPresent( "NoInjectionsConsumeFactoryIntegrationTest_Arez_MyComponent" );
    assertClassNotPresent( "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerModule" );
    assertClassNotPresent( "NoInjectionsConsumeFactoryIntegrationTest_Arez_MyComponent$Enhancer" );
    assertClassPresent( "NoInjectionsConsumeFactoryIntegrationTest_Arez_MyComponent$Factory" );
    assertClassPresent( "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerComponentExtension" );
    assertClassNotPresent( "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerComponentExtension$InjectSupport" );
    assertClassNotPresent( "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerComponentExtension$DaggerModule" );
    assertClassNotPresent(
      "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerComponentExtension$EnhancerDaggerModule" );
    assertClassPresent(
      "NoInjectionsConsumeFactoryIntegrationTest_MyComponentDaggerComponentExtension$DaggerSubcomponent" );
  }
}

Add scenario where no injections present


package uk.ac.ebi.quickgo.client.service.loader.presets.assignedBy;

import uk.ac.ebi.quickgo.client.service.loader.presets.assignedby.AssignedByPresetsConfig;
import uk.ac.ebi.quickgo.client.service.loader.presets.ff.RawNamedPreset;

import org.junit.Before;
import org.junit.Test;
import org.springframework.batch.item.ItemProcessor;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.core.IsNull.notNullValue;

/**
 * @author Tony Wardell
 * Date: 02/08/2017
 * Time: 17:06
 * Created with IntelliJ IDEA.
 */
public class AssignedByPresetsConfigTest {

    private AssignedByPresetsConfig assignedByPresetsConfig;

    @Before
    public void setup(){
        assignedByPresetsConfig = new AssignedByPresetsConfig();
    }

    @Test
    public void preventDuplicates() throws Exception {
        final ItemProcessor<RawNamedPreset, RawNamedPreset> itemProcessor =
                assignedByPresetsConfig.duplicateChecker();
        RawNamedPreset rawNamedPreset1 = new RawNamedPreset();
        rawNamedPreset1.name = "AgBase";
        RawNamedPreset rawNamedPreset2 = new RawNamedPreset();
        rawNamedPreset2.name = "AspGD";
        RawNamedPreset rawNamedPreset3 = new RawNamedPreset();
        rawNamedPreset3.name = "ASPGD";
        RawNamedPreset rawNamedPreset4 = new RawNamedPreset();
        rawNamedPreset4.name = "Alzheimers_University_of_Toronto";

        assertThat(itemProcessor.process(rawNamedPreset1), notNullValue());
        assertThat(itemProcessor.process(rawNamedPreset2), notNullValue());
        assertThat(itemProcessor.process(rawNamedPreset3), nullValue());
        assertThat(itemProcessor.process(rawNamedPreset4), notNullValue());
    }
}

Test the duplicate checker method in AssignedByPresetsConfig works properly.


package gov.nih.nci.calab.dto.common;

/**
 * This class includes properties for User Authentication and Authorization .
 *
 *
 * @author doswellj
 *
 */

public class UserBean
{

	private String loginId;
	private String fullName;
	private String firstName;
	private String lastName;

	public UserBean() {}

	public UserBean(String strLoginId, String firstName, String lastName)
	{
		this.loginId = strLoginId;
		this.firstName= firstName;
		this.lastName= lastName;
		this.fullName = firstName + " " + lastName;
	}

	public String getLoginId()
	{
		return loginId;
	}
	public void setLoginId(String loginId)
	{
		this.loginId = loginId;
	}

	public String getFirstName()
	{
		return firstName;
	}
	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}
	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	public String getFullName() {
		return fullName;
	}

	public void setFullName(String fullName) {
		this.fullName =fullName;
	}
}

Move the package. Container user info

Move the package.  Container user info

SVN-Revision: 7817


/*
 * 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.wink.itest.client.timeout;

import org.apache.wink.client.ApacheHttpClientConfig;
import org.apache.wink.client.RestClient;

public class TimeoutApacheHTTPTest extends TimeoutTest {

    @Override
    public RestClient getConnectTimeoutClient() {
        ApacheHttpClientConfig config = new ApacheHttpClientConfig();
        config.connectTimeout(20000);
        return new RestClient(config);
    }

    @Override
    public RestClient getDefaultClient() {
        return new RestClient(new ApacheHttpClientConfig());
    }

    @Override
    public RestClient getReadTimeoutClient() {
        ApacheHttpClientConfig config = new ApacheHttpClientConfig();
        config.readTimeout(20000);
        return new RestClient(config);
    }

}

Add Apache HTTP client version of client system property timeout tests

git-svn-id: 00d204a5454029cb4c4f043d44e9809460a5ea01@923914 13f79535-47bb-0310-9956-ffa450edef68


package lombelo.model;

import lombok.Data;

/**
 * @author Niklas Wünsche
 */
@Data
public class ContentOfNote {
    private String titleOfNote;
    private String textOfNote;
}

Add model for content of a note

Add model for content of a note


public class EnclosingEnum {

    private class Inner { }
    private class InnerA extends Inner { }
    private class InnerB extends Inner { }
    private class InnerC extends Inner { }

    enum InnerEnum {
        INNER_A {
            @Override
            public Inner getInstance() {
                return new InnerA();	//Compile Error.
            }
        },
        INNER_B {
            @Override
            public Inner getInstance() {
                //return new InnerB();
                return new EnclosingEnum.InnerB();	//Compile Error.
            }
        },
        INNER_C {
            @Override
            public Inner getInstance() {
                //return new InnerC();
                return EnclosingEnum.new InnerC();	//Compile Error.
            }
        },
        ;

        public abstract Inner getInstance();
    }

    private static class InnerFactoryEnumStyled {
        public static Inner getInner(InnerEnum inner) {
            return inner.getInstance();
        }
    }

    public static void main(String[] args) {
        System.out.println("Hello World.");

        Inner inner = InnerFactoryEnumStyled.getInner(InnerEnum.INNER_A);
   }

}

Add a sample of Java inner class

Add a sample of Java inner class


package imagej.ui.swing.plugins;

import imagej.plugin.ImageJPlugin;
import imagej.plugin.Menu;
import imagej.plugin.Plugin;
import imagej.ui.swing.SwingOverlayManager;

@Plugin(menu = { @Menu(label = "Image"), @Menu(label = "Overlay"),
		@Menu(label = "OverlayManager") })
public class SwingOverlayManagerPlugin implements ImageJPlugin {

	@Override
	public void run() {
		SwingOverlayManager overlaymgr = new SwingOverlayManager();
		overlaymgr.setVisible(true);

	}

}

Make overlay manager available as a plugin.

This used to be revision r3136.


/*
 * 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.stratos.rest.endpoint.exception;

import javax.ws.rs.core.Response;

public class ApplicationSignUpRestAPIException extends RestAPIException {

    private static final long serialVersionUID = 1L;

    private String message;
    private Response.Status httpStatusCode;

    public ApplicationSignUpRestAPIException() {
        super();
    }

    public ApplicationSignUpRestAPIException(String message, Throwable cause) {
        super(message, cause);
        this.message = message;
    }

    public ApplicationSignUpRestAPIException(Response.Status httpStatusCode, String message, Throwable cause) {
        super(message, cause);
        this.message = message;
        this.httpStatusCode = httpStatusCode;
    }

    public ApplicationSignUpRestAPIException(String message) {
        super(message);
        this.message = message;
    }

    public ApplicationSignUpRestAPIException(Response.Status httpStatusCode, String message) {
        super(message);
        this.message = message;
        this.httpStatusCode = httpStatusCode;
    }

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

    public String getMessage() {
        return message;
    }

    public Response.Status getHTTPStatusCode() {
        return httpStatusCode;
    }

}

Add an exeption to handle app sign up errors


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

import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;

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

public class LatencyFaultToleranceImplTest {
    private LatencyFaultTolerance<String> latencyFaultTolerance;
    private String brokerName = "BrokerA";
    private String anotherBrokerName = "BrokerB";

    @Before
    public void init() {
        latencyFaultTolerance = new LatencyFaultToleranceImpl();
    }

    @Test
    public void testUpdateFaultItem() throws Exception {
        latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000);
        assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
        assertThat(latencyFaultTolerance.isAvailable(anotherBrokerName)).isTrue();
    }

    @Test
    public void testIsAvailable() throws Exception {
        latencyFaultTolerance.updateFaultItem(brokerName, 3000, 50);
        assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();

        TimeUnit.MILLISECONDS.sleep(70);
        assertThat(latencyFaultTolerance.isAvailable(brokerName)).isTrue();
    }

    @Test
    public void testRemove() throws Exception {
        latencyFaultTolerance.updateFaultItem(brokerName, 3000, 3000);
        assertThat(latencyFaultTolerance.isAvailable(brokerName)).isFalse();
        latencyFaultTolerance.remove(brokerName);
        assertThat(latencyFaultTolerance.isAvailable(brokerName)).isTrue();
    }

    @Test
    public void testPickOneAtLeast() throws Exception {
        latencyFaultTolerance.updateFaultItem(brokerName, 1000, 3000);
        assertThat(latencyFaultTolerance.pickOneAtLeast()).isEqualTo(brokerName);

        latencyFaultTolerance.updateFaultItem(anotherBrokerName, 1001, 3000);
        assertThat(latencyFaultTolerance.pickOneAtLeast()).isEqualTo(brokerName);
    }
}

[ROCKETMQ-52] Add unit tests for LatencyFaultTolerance


package com.inepex.ineom.shared.assistedobject;

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

public class AssistedObjectUtil {

	public static List<Long> getObjectIds(List<AssistedObject> objList){
		List<Long> idList = new ArrayList<Long>();
		for(AssistedObject obj : objList){
			idList.add(obj.getId());
		}
		return idList;
	}

}

Add util class, to hold assisted object related util methods

git-svn-id: 1119f77b1e9a9b65230954af94f4d37570a443ef@1230 7ef67a20-634e-90e6-9ab5-3f2075439470


package pt.fccn.mobile.arquivo.tests.imagesearch;

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

import org.junit.Test;
import org.openqa.selenium.By;

import pt.fccn.arquivo.selenium.Retry;
import pt.fccn.arquivo.selenium.WebDriverTestBaseParalell;

/**
 *
 * @author Ivo Branco <ivo.branco@fccn.pt>
 *
 */
public class ImageSearchQuerySuggestionTest extends WebDriverTestBaseParalell {

	public ImageSearchQuerySuggestionTest(String os, String version, String browser, String deviceName,
			String deviceOrientation) {
		super(os, version, browser, deviceName, deviceOrientation);
	}

	@Test
	@Retry
	public void pageSearchTest() {
		run("Search with testre", () -> {
			driver.findElement(By.id("txtSearch")).clear();
			driver.findElement(By.id("txtSearch")).sendKeys("testre");
			driver.findElement(By.xpath("//*[@id=\"buttonSearch\"]/button")).click();
		});

		run("Search images instead of text", () -> {
			waitUntilElementIsVisibleAndGet(By.id("ImageButton")).click();
		});

		assertThat("Verify if a suggestion is presented",
				driver.findElement(By.xpath("//*[@class=\"suggestion\"]/a")).getText(), containsString("teste"));
	}

}

Add new image search query suggestion test.


package com.tacitknowledge.performance.degrade;

import com.tacitknowledge.performance.Component;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;

/** @author Ivan Frolov (ifrolov@tacitknowledge.com) */
public class PeerClose implements Component
{
    @Override
    public void initChannel(final SocketChannel ch)
    {
        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
            @Override
            public void channelActive(final ChannelHandlerContext ctx) throws Exception
            {
                ctx.channel().close();
            }
        });
    }
}

Implement peer close on connection degradation handler.


import java.util.*;
import java.io.*;

class Abbreviation {

	static boolean isUpperCase(char c) {
		return (c >= 'A' && c <= 'Z');
	}

	static char upperCase(char c) {
		if(isUpperCase(c)) return c;
		return (char)(c + 32);
	}

	boolean dp[][];

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int queries = Integer.parseInt(sc.nextLine());
		dp = new int[1011][1011];
		while(queries--!=0){
			String a = sc.nextLine();
			String b = sc.nextLine();
			for(int i=0;i<=a.length();i++){
				for(int j=0;j<=b.length();j++){
					dp[i][j] = false;
				}
			}
			dp[0][0] = true;
			for(int i=0;i<a.length();i++){
				for(int j=0;j<=b.length();j++){
					if(dp[i][j])
				}
			}
		}
	}
}

Add solution of 1 DP problem

Add solution of 1 DP problem


package flyway.paikkis;

import fi.nls.oskari.db.BundleHelper;
import fi.nls.oskari.domain.map.view.Bundle;
import fi.nls.oskari.util.FlywayHelper;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;

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

/**
 * Registers and adds 'terrain-profile' bundle to default and user views.
 */
public class V2_25__add_terrain_profile_to_default_views implements JdbcMigration {
    private static final String BUNDLE_ID = "terrain-profile";

    public void migrate(Connection connection) throws Exception {

        // register bundle
        Bundle bundle = new Bundle();
        bundle.setName(BUNDLE_ID);
        bundle.setStartup(BundleHelper.getBundleStartup("/Oskari/packages/paikkatietoikkuna/bundle/", BUNDLE_ID, BUNDLE_ID));
        BundleHelper.registerBundle(bundle, connection);

        // add to default/user views
        final List<Long> views = FlywayHelper.getUserAndDefaultViewIds(connection);
        for(Long viewId : views){
            if (FlywayHelper.viewContainsBundle(connection, BUNDLE_ID, viewId)) {
                continue;
            }
            FlywayHelper.addBundleWithDefaults(connection, viewId, BUNDLE_ID);
        }
    }
}

Add terrain profile to pti

Add terrain profile to pti


package alien4cloud.it.utils.websocket;

import java.nio.charset.Charset;
import java.util.Set;

import lombok.extern.slf4j.Slf4j;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.WriteTimeoutHandler;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;

@Slf4j
public class WebSocketClientOutHandler extends WriteTimeoutHandler {

    public WebSocketClientOutHandler (int timeout) {
      super(timeout);
    }

    private final AttributeKey<Set<Cookie>> ctxCookies = AttributeKey.valueOf("cookies");

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof HttpRequest) {
            Set<Cookie> cookies = ctx.attr(ctxCookies).get();
            if (cookies != null && !cookies.isEmpty()) {
                HttpRequest request = (HttpRequest) msg;
                request.headers().set("cookie", ClientCookieEncoder.encode(cookies));
                if (log.isDebugEnabled()) {
                    log.debug("Write HttpRequest {} enriched with security cookie", request);
                }
            }
            super.write(ctx, msg, promise);
            return;
        }
        String wrappedFrame = ((ByteBuf) msg).toString(Charset.forName("UTF-8"));
        if (log.isDebugEnabled()) {
            log.debug("Write text frame {}", wrappedFrame);
        }
        WebSocketFrame webSocketFrame = new TextWebSocketFrame(wrappedFrame);
        super.write(ctx, webSocketFrame, promise);
    }

}

Upgrade ES 6 (new for alien4cloud-rest-it/netty4)


package edu.afs.robot;

/**
 * The RobotMap is a mapping from the ports sensors and actuators are wired into
 * to a variable name. This provides flexibility changing wiring, makes checking
 * the wiring easier and significantly reduces the number of magic numbers
 * floating around.
 */
public class RobotMap {
    // For example to map the left and right motors, you could define the
    // following variables to use with your drivetrain subsystem.
    // public static final int leftMotor = 1;
    // public static final int rightMotor = 2;

    // If you are using multiple modules, make sure to define both the port
    // number and the module. For example you with a rangefinder:
    // public static final int rangefinderPort = 1;
    // public static final int rangefinderModule = 1;

    // Drive Subsystem
    // Digital Sidecar PWM outputs
    public static final int DRIVE_LEFT_MOTOR_CHANNEL = 1;
    public static final int DRIVE_RIGHT_MOTOR_CHANNEL = 2;

    // Analog Breakout
    public static final int GYRO_CHANNEL = 1;
    // Driver Station
    public static final int JOYSTICK_PORT = 1;
////////////////////////////////////////////////////////////////////////////////

    // Auto-Ranger Subsystem
    // Analog Breakout
    public static final int ULTRASONIC_RANGER_CHANNEL = 2;
////////////////////////////////////////////////////////////////////////////////

    // Launcher Subsystem
    // Digital Sidecar PWM outputs
    public static final int LAUNCHER_LEFT_MOTOR_CHANNEL = 5;
    public static final int LAUNCHER_RIGHT_MOTOR_CHANNEL = 6;
    // Digital Sidecar GPIO Inputs
    public static final int LAUNCHER_ENCODER_A_CHANNEL = 1;
    public static final int LAUNCHER_ENCODER_B_CHANNEL = 2;
    public static final int LAUNCHER_ENCODER_MODULE = 1;
////////////////////////////////////////////////////////////////////////////////

    // Forklift Subsystem
    // Digital Sidecar PWM outputs
    public static final int CLAMPER_MOTOR_CHANNEL = 7;
    public static final int FORKLIFT_MOTOR_CHANNEL = 8;
    // Digital Sidecar GPIO Inputs
    public static final int CLAMPER_ENCODER_A_CHANNEL = 3;
    public static final int CLAMPER_ENCODER_B_CHANNEL = 4;
    public static final int CLAMPER_ENCODER_MODULE = 2;
    public static final int FORKLIFT_ENCODER_A_CHANNEL = 5;
    public static final int FORKLIFT_ENCODER_B_CHANNEL = 6;
    public static final int FORKLIFT_ENCODER_MODULE = 3;
////////////////////////////////////////////////////////////////////////////////

}

Revise drive system to use two motor controllers.


// sort
import java.util.*;

class Solution {

    private Map<Integer, Integer> map = new HashMap<>();

    public int getKth(int lo, int hi, int k) {

        for (int index = 1; index <= hi; index++) {
            int power = 0;
            int i = index;
            while (i != 1) {
                if (this.map.containsKey(i)) {
                    power += this.map.get(i);
                    break;
                }else {
                    if (i % 2 == 0) {
                        i = i / 2;
                    } else {
                        i = 3 * i + 1;
                    }
                    power++;
                }
            }
            this.map.put(index, power);
        }
        List<Item> list = new ArrayList<>();

        for (int i = lo; i <= hi; i++) {
            Item item = new Item();
            item.value = i;
            item.power = this.map.get(i);
            list.add(item);
        }
        list.sort(new Comparator<Item>(){
            public int compare(Item i1, Item i2) {
                if (i1.power == i2.power) {
                    return i1.value - i2.value;
                } else {
                    return i1.power - i2.power;
                }
            }
        });
        return list.get(k-1).value;
    }

    public static class Item{
        public Integer value;
        public Integer power;
    }

}

// heap
import java.util.*;

class Solution {

    private Map<Integer, Integer> map = new HashMap<>();

    public int getKth(int lo, int hi, int k) {

        for (int index = 1; index <= hi; index++) {
            int power = 0;
            int i = index;
            while (i != 1) {
                if (this.map.get(i) != null) {
                    power += this.map.get(i);
                    break;
                }else {
                    if (i % 2 == 0) {
                        i = i / 2;
                    } else {
                        i = 3 * i + 1;
                    }
                    power++;
                }
            }
            this.map.put(index, power);
        }

        PriorityQueue<Item> pq = new PriorityQueue(new Comparator<Item>(){
            public int compare(Item i1, Item i2) {
                if (i1.power == i2.power) {
                    return i2.value - i1.value;
                }
                return i2.power - i1.power;
            }
        });
        for (int i = lo; i <= hi; i++) {
            Item item = new Item();
            item.value = i;
            item.power = this.map.get(i);
            pq.offer(item);
        }
        while (pq.size() > k) {
            Item item = pq.poll();
        }
        return pq.peek().value;
    }

    public static class Item{
        public Integer value = 0;
        public Integer power = 0;
    }

}

Sort Integers by The Power Value

Sort Integers by The Power Value


package org.openlmis.report.builder.helpers;

import org.apache.commons.lang.StringUtils;

import static org.apache.ibatis.jdbc.SqlBuilder.WHERE;

public class RequisitionPredicateHelper {

  public static void whereMultiProductFilter(String products){
    if(products.equals("-1")){
      WHERE("p.tracer = true");
    } else if(!products.equals("0") && !products.isEmpty()){
      WHERE(" p.id = ANY(array[" + products + " ]::INT[])");
    }
  }

  public static void whereProductCategory(Long productCategory){
    if(productCategory > 0){
      WHERE( "ppc.productCategoryId = #{filterCriteria.productCategory}");
    }
  }

  public static void whereFacilityPermission(){
    WHERE("f.id in (select facility_id from vw_user_facilities where user_id = #{userId} and program_id = #{filterCriteria.program}) " );
  }

  public static void whereGeographicZoneFilter(Long geographicZone){
    if(geographicZone != 0){
      WHERE( "(d.zone_id = #{filterCriteria.zone} or d.parent = #{filterCriteria.zone} or d.region_id = #{filterCriteria.zone} or d.district_id = #{filterCriteria.zone}) ") ;
    }
  }

  public static void whereProgramFilter(){
    WHERE("r.programId = #{filterCriteria.program}");
  }

  public static void wherePeriodFilter(){
    WHERE("r.periodId = #{filterCriteria.period}");
  }

}

Introduce Requisition Predicate Helper - Helper applies most common requisition related where conditions. Note: this is only usable based on predefined alias for r for requisitions, p for programs, pr for products tables. A later version should remove the aliases for less confusion.


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

import org.gradle.util.Jvm;
import java.io.File;

/**
 * Allows the tests to get hold of an alternative JAVA_HOME when needed.
 *
 * This is used in the DaemonLifecycleSpec to test that daemons don't use difference JAVA_HOME's between client and browser.
 */
abstract public class AvailableJavaHomes {

    public static File getJavaHome(String label) {
        String value = System.getenv().get(getEnvVarName(label));
        return value == null ? null : new File(value);
    }

    public static String getEnvVarName(String label) {
        return String.format("JDK_%s", label);
    }

    public static File getBestAlternative() {
        Jvm jvm = Jvm.current();
        if (jvm.isJava6Compatible()) {
            return firstAvailable("15", "17");
        } else if (jvm.isJava5Compatible()) {
            return firstAvailable("16", "17");
        } else {
            return null;
        }
    }

    public static File firstAvailable(String... labels) {
        for (String label : labels) {
            File found = getJavaHome(label);
            if (found != null) {
                return found;
            }
        }
        return null;
    }
}

Add utility for finding available JAVA_HOMEs to use in our tests.

It looks for env vars JDK_15, JDK_16 and JDK_17.


package com.github.aureliano.evtbridge.core.agent;

import java.util.Map;
import java.util.Properties;

public interface IDataReader extends IAgent {

	public abstract void initializeResources();

	public abstract void finalizeResources();

	public abstract String readNextLine();

	public abstract String readLine();

	public abstract String nextData();

	public abstract Map<String, Object> executionLog();

	public abstract boolean keepReading();

	public abstract void loadLastExecutionLog(Properties properties);

	public abstract void executeBeforeReadingListeners();

	public abstract void executeAfterReadingListeners(String data);
}

Create interface to data reader.

Create interface to data reader.


package com.netflix.genie.agent.cli;

import com.beust.jcommander.JCommander;
import com.google.common.collect.Sets;
import com.netflix.genie.test.categories.IntegrationTest;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Test CLI beans in context.
 */
@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
@SpringBootTest
public class CommandsConfigIntegrationTest {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * Test creation of AgentArguments bean.
     * @throws Exception for error
     */
    @Test
    public void globalAgentArguments() throws Exception {
        Assert.assertNotNull(applicationContext.getBean(GlobalAgentArguments.class));
    }

    /**
     * Test creation of JCommander bean.
     * @throws Exception for error
     */
    @Test
    public void jCommander() throws Exception {
        Assert.assertNotNull(applicationContext.getBean(JCommander.class));
    }

    /**
     * Test creation of CommandFactory bean.
     * @throws Exception for error
     */
    @Test
    public void commandFactory() throws Exception {
        final CommandFactory factory = applicationContext.getBean(CommandFactory.class);
        Assert.assertNotNull(factory);

        final List<String> commandNames = Arrays.stream(CommandNames.class.getDeclaredFields())
            .filter(f -> Modifier.isStatic(f.getModifiers()))
            .filter(f -> f.getType() == String.class)
            .map((Field f) -> {
                try {
                    return (String) f.get(null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException("Failed to get value for field " + f.getName());
                }
            })
            .collect(Collectors.toList());

        Assert.assertEquals(
            Sets.newHashSet(commandNames),
            Sets.newHashSet(factory.getCommandNames())
        );

        for (String commandName : commandNames) {
            final AgentCommand command = factory.get(commandName);
            Assert.assertNotNull(command);
        }
    }

    /**
     * Test creation of ArgumentParser bean.
     * @throws Exception for error
     */
    @Test
    public void argumentParser() throws Exception {
        Assert.assertNotNull(applicationContext.getBean(ArgumentParser.class));
    }
}

Add integration test for CLI beans

Add integration test for CLI beans


package org.simpleframework.xml.core;

import java.io.StringWriter;

import junit.framework.TestCase;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;

public class PathConstructorAmbiguityTest extends TestCase {

   @Root(name="test1")
   public static class Test1 {

      @Attribute(name="iri")
      final String identifier;

      @Path(value="resource")
      @Attribute(name="iri")
      final String identifier1;

      public Test1(
            @Attribute(name="iri")  String identifier,
            @Path(value="resource") @Attribute(name="iri") String identifier1)
      {
         this.identifier = identifier;
         this.identifier1 = identifier1;
      }
   }

      public void testParameters() throws Exception{
         Serializer s = new Persister();
         StringWriter sw = new StringWriter();
         s.write(new Test1("a", "b"), sw);
         String serializedForm = sw.toString();
         System.out.println(serializedForm);
         Test1 o = s.read(Test1.class, serializedForm);
      }
}

Add test for attribute ambiguity

Add test for attribute ambiguity


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

package io.spine.server.storage.jdbc.query;

import io.spine.server.storage.jdbc.ConnectionWrapper;
import io.spine.server.storage.jdbc.DatabaseException;
import io.spine.server.storage.jdbc.IdColumn;
import org.junit.Test;

import java.sql.PreparedStatement;
import java.sql.SQLException;

import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;

/**
 * @author Dmytro Grankin
 */
public class SelectEventRecordsByIdShould {

    @SuppressWarnings("unchecked")
    @Test(expected = DatabaseException.class)
    public void handle_invalid_fetch_size() throws SQLException {
        final IdColumn idColumn = mock(IdColumn.class);
        final SelectEventRecordsById query = spy(SelectEventRecordsById.newBuilder("table")
                                                                       .setIdColumn(idColumn)
                                                                       .build());
        final ConnectionWrapper connection = mock(ConnectionWrapper.class);
        final PreparedStatement statement = mock(PreparedStatement.class);
        doReturn(connection).when(query)
                            .getConnection(anyBoolean());
        doReturn(statement).when(query)
                           .prepareStatement(connection);

        final int invalidFetchSize = -1;
        doThrow(SQLException.class).when(statement)
                                   .setFetchSize(invalidFetchSize);
        query.execute(invalidFetchSize);
    }
}

Add a test for `SelectEventRecordsById`

Add a test for `SelectEventRecordsById`


package com.example.crystalgame.library.datawarehouse;

import java.io.Serializable;

/**
 * An interface describing the expected behaviour of a database
 * @author Balazs Pete, Allen Thomas Varghese
 *
 */
public interface KeyValueStore {

	/**
	 * Put a value into the database with an associated key
	 * @param key The key of the value
	 * @param value The value to store
	 * @return True if successful
	 */
	public boolean put(String key, Serializable value);

	/**
	 * Get a value using the associated key
	 * @param key The key
	 * @return The value or null
	 */
	public Serializable get(String key);

	/**
	 * Delete a value in the store
	 * @param key The key of the value
	 * @return True if removed
	 */
	public boolean delete(String key);

}

Add the key/value store interface

Add the key/value store interface


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.CollapseNumeric;
import net.imglib2.RandomAccessible;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.view.Views;
import net.imglib2.view.composite.CompositeView;
import net.imglib2.view.composite.NumericComposite;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.CollapseNumeric.class, name = ViewOps.CollapseNumeric.NAME)
public class DefaultCollapseNummeric2CompositeView<T extends NumericType<T>>
		extends
		AbstractView<RandomAccessible<T>, CompositeView<T, NumericComposite<T>>>
		implements
		CollapseNumeric<RandomAccessible<T>, CompositeView<T, NumericComposite<T>>> {

	@Parameter(type = ItemIO.INPUT)
	private int numChannels;

	@Override
	public CompositeView<T, NumericComposite<T>> compute(
			RandomAccessible<T> input) {
		return Views.collapseNumeric(input, numChannels);
	}

}

Add default implementation of CollapseNumeric to CompositeView.


package eu.pericles.processcompiler.testutils;

import static org.junit.Assert.fail;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class RegenerateFilesUUIDs {

	static String[] files = {};//{"ExtractMD.bpmn2", "GetMD.bpmn2", "UpdateMD.bpmn2", "StoreMD.bpmn2"};
	private String path;

	public RegenerateFilesUUIDs(String file) {
		this.path = "src/test/resources/narrative2/" + file;
	}

	@Parameters(name="{0}")
    public static Collection<String> files() {
        return Arrays.asList(files);
    }

	@Test
	public void regenerateFilesUUIDs() {
		try {
			Utils.replaceUUIDsInFile(path);
		} catch (IOException e) {
			fail("regenerateFilesUUIDs() " + e.getMessage());
		}
	}

}

Add Regenerate UUIDs in test files

Add Regenerate UUIDs in test files


/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010(Year date of delivery) United States Government, as represented by the Secretary of Health and Human Services.  All rights reserved.
 *
 */
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gov.hhs.fha.nhinc.mpi.adapter.component;

import gov.hhs.fha.nhinc.mpilib.Patients;

/**
 *
 * @author rayj
 */
public class CommonChecks {

    public static boolean isSingleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() == 1));
    }

    public static boolean isMultipleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() > 1));
    }

    public static boolean isZeroSearchResult(Patients patients) {
        return ((patients == null) || (patients.size() == 0));
    }

}

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2010(Year date of delivery) United States Government, as represented by the Secretary of Health and Human Services.  All rights reserved.
 *
 */
package gov.hhs.fha.nhinc.mpi.adapter.component;

import gov.hhs.fha.nhinc.mpilib.Patients;
import gov.hhs.fha.nhinc.patientdb.model.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author rayj
 */
public class CommonChecks {

    // MPI XML Checks

    public static boolean isSingleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() == 1));
    }

    public static boolean isMultipleSearchResult(Patients patients) {
        return ((patients != null) && (patients.size() > 1));
    }

    public static boolean isZeroSearchResult(Patients patients) {
        return ((patients == null) || (patients.size() == 0));
    }

    // MPI DB Checks

    public static boolean isSinglePerAASearchResult(List<Patient> patients) {
        boolean result = true;

        Map testMap = new HashMap();
        if (patients != null) {
            for (Patient patient : patients) {
                if (patient.getIdentifiers() != null &&
                        patient.getIdentifiers().size() > 0 &&
                        patient.getIdentifiers().get(0) != null) {
                    String orgId = patient.getIdentifiers().get(0).getOrganizationId();
                    if (testMap.containsKey(orgId)) {
                        result = false;
                        break;
                    }
                }
            }
        }

        return result;
    }

    public static boolean isZeroPerAASearchResult(List<Patient> patients) {
        return ((patients == null) || (patients.size() == 0));
    }

}

CONNECT MPI Adapter - DB implementation - implemented MPI DB Checks


package io.quarkus.spring.web.test;

import static io.restassured.RestAssured.when;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import io.quarkus.test.QuarkusUnitTest;

public class ResponseStatusAndExceptionHandlerTest {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(ExceptionController.class, RestExceptionHandler.class));

    @Test
    public void testRootResource() {
        when().get("/exception").then().statusCode(400);
    }

    @RestController
    @RequestMapping("/exception")
    public static class ExceptionController {

        @GetMapping
        @ResponseStatus(HttpStatus.OK)
        public String throwException() {
            throw new RuntimeException();
        }
    }

    @RestControllerAdvice
    public static class RestExceptionHandler {

        @ExceptionHandler(RuntimeException.class)
        public ResponseEntity<Object> handleException(Exception ex) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }
}

Add test for case where @ResponseStatus is used along with @ExceptionHandler

Relates to: #16321


package org.synyx.urlaubsverwaltung.calendar;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;

import java.util.Optional;

import static org.hamcrest.Matchers.hasProperty;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;

@RunWith(MockitoJUnitRunner.class)
public class CalendarSharingViewControllerTest {

    private CalendarSharingViewController sut;

    @Mock
    private PersonCalendarService personCalendarService;

    @Before
    public void setUp() {
        sut = new CalendarSharingViewController(personCalendarService);
    }

    @Test
    public void index() throws Exception {

        when(personCalendarService.getPersonCalendar(1)).thenReturn(Optional.of(new PersonCalendar()));

        perform(get("/web/persons/1/calendar/share"))
            .andExpect(view().name("calendarsharing/index"))
            .andExpect(status().isOk());
    }

    @Test
    public void indexNoPersonCalendar() throws Exception {

        when(personCalendarService.getPersonCalendar(1)).thenReturn(Optional.empty());

        perform(get("/web/persons/1/calendar/share"))
            .andExpect(view().name("calendarsharing/index"))
            .andExpect(model().attributeExists("privateCalendarShare"))
            .andExpect(status().isOk());
    }

    @Test
    public void linkPrivateCalendar() throws Exception {

        perform(post("/web/persons/1/calendar/share/me"))
            .andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/web/persons/1/calendar/share"));

        verify(personCalendarService).createCalendarForPerson(1);
    }

    @Test
    public void unlinkPrivateCalendar() throws Exception {

        perform(post("/web/persons/1/calendar/share/me").param("unlink", ""))
            .andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/web/persons/1/calendar/share"));

        verify(personCalendarService).deletePersonalCalendarForPerson(1);
    }

    private ResultActions perform(MockHttpServletRequestBuilder builder) throws Exception {
        return standaloneSetup(sut).build().perform(builder);
    }
}

Add test for overview share controller

Add test for overview share controller


package cmu.core;

public class MatOperation {
	/**
	 * Generalized matrix multiplication
	 * @param src1
	 * @param src2
	 * @return
	 */
	public static<T extends Number> Mat<T> gemm(Mat<T> src1, Mat<T> src2) {
		Mat<T> result = new Mat<T>();
		return result;
	}

	/**
	 * Per-element sum of two matrix
	 * @param src1
	 * @param src2
	 * @return
	 */
	public static<T extends Number> Mat<T> add(Mat<T> src1, Mat<T> src2) {

	}

	/*
	 * Enumerate supported norm operation type
	 */
	private static enum NormType {NORM_L1, NORM_L2};

	/**
	 * Calculates a matrix norm, norm type is specified by NormType
	 * @param src
	 * @param normType
	 * @return
	 */
	public static <T extends Number> double norm(Mat<T> src, NormType normType) {
		return 0.0;
	}
}

Add matrix operation code template. All methods are static.


import java.util.Scanner;

public class Calculator{

	static double result, num1, num2;

	public static double add(double a, double b){
		result = a + b;
		return result;
	}
	public static double subtract(double a, double b){
		result = a - b;
		return result;
	}
	public static double multiply(double a, double b){
		result = a * b;
		return result;
	}
	public static double divide(double a, double b){
		result = a / b;
		return result;
	}
	public static double sqrt(double a, double b){
		result = Math.sqrt(a);
		return result;
	}
	public static double power(double a, double b){
		result = Math.pow(a,b);
		return result;
	}
	public static double mod(double a, double b){
		result = a % b;
		return result;
	}
	public static double average(double a, double b){
		result = (a + b) / 2;
		return result;
	}
	public static void main(String[] args) {

		Scanner input = new Scanner(System.in);

		System.out.println("What would you like to do? \n 1. Add \n 2. Subtract \n 3. Multiply \n 4. Divide \n 5. Square Root \n 6. Power \n 7. Modulus \n 8. Average");

		int operation = input.nextInt();

		while (operation < 1 || operation > 8) {
			System.out.println("Please try again:");
			operation = input.nextInt();
		}

		// If correct operation is entered
		if (operation >=1 && operation <= 8) {
			if (operation == 5) {
				System.out.println("Enter Value");
				num1 = input.nextDouble();
			} else {
				System.out.println("Enter Value 1:");
				num1 = input.nextDouble();
				System.out.println("Enter Value 2:");
				num2 = input.nextDouble();
			}

			switch (operation){
				case 1:
					add(num1, num2);
				break;
				case 2:
					subtract(num1, num2);
				break;
				case 3:
					multiply(num1, num2);
				break;
				case 4:
					divide(num1, num2);
				break;
				case 5:
					sqrt(num1, num2);
				break;
				case 6:
					power(num1, num2);
				break;
				case 7:
					mod(num1, num2);
				break;
				case 8:
					average(num1, num2);
				break;
				default :
	            System.out.println("Wrong Operation!");
			}
			System.out.println("Your solution is: " + result);
		}
		// If wrong operation is entered
		else {
			System.out.println("Wrong Operation!!!");
		}

	}
}

Create a calculator class. Allows users to add, subtract, multiply, divide, square-root, exponent, modulus, and average


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package it.infn.ct.futuregateway.apiserver.v1;

import javax.persistence.EntityManagerFactory;
import org.junit.Test;

/**
 *
 * @author Marco Fargetta <marco.fargetta@ct.infn.it>
 */
public class InfrastructureServiceTest {

    /**
     * EMF.
     */
    EntityManagerFactory emf;

    /**
     * Build.
     */
    public InfrastructureServiceTest() {
    }

    /**
     * Test of getInfraDetails method, of class InfrastructureService.
     */
    @Test
    public void testGetInfraDetails() {
    }

    /**
     * Test of deleteInfra method, of class InfrastructureService.
     */
    @Test
    public void testDeleteInfra() {
    }

}

Create the skeleton for the first unit test


package leetcode;

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

/**
 * https://leetcode.com/problems/sort-list/
 */
public class Problem148 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode sortList(ListNode head) {
        // I know this is cheating
        if (head == null) {
            return head;
        }
        List<ListNode> nodes = new ArrayList<>();
        for (ListNode n = head; n != null; n = n.next) {
            nodes.add(n);
        }
        Collections.sort(nodes, (a, b) -> Integer.valueOf(a.val).compareTo(Integer .valueOf(b.val)));
        ListNode newHead = null;
        ListNode node = null;
        nodes.get(nodes.size()-1).next = null;
        for (int i = 0; i < nodes.size(); i++) {
            if (i == 0) {
                newHead = nodes.get(i);
                node = newHead;
            } else {
                node.next = nodes.get(i);
                node = node.next;
            }
        }
        return newHead;
    }
}

Solve problem 148 with O(N) space

Solve problem 148 with O(N) space


package com.bloatit.framework.exceptions.lowlevel;

public class MalformedArgumentException extends IllegalArgumentException {
    private static final long serialVersionUID = -316403949660231531L;

    public MalformedArgumentException() {
        super();
    }

    public MalformedArgumentException(final String s) {
        super(s);
    }

    public MalformedArgumentException(final Throwable cause) {
        super(cause);
    }

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

}

Add the forgotten file for malformed exception


package com.workshop.wilqor.testing.bonus.examples;

import org.junit.Test;

import java.io.IOException;

/**
 * Example demonstrating basic behavior of exceptions in JUnit
 * and serving as a base for discussing exception handling in tests.
 *
 * @author wilqor
 */
public class ExceptionsExampleTest {
    @Test
    public void uncheckedExceptionThrown() {
        // does not need to be caught, handled properly
        throw new NullPointerException();
        // does the test pass?
    }

    @Test
    public void checkedExceptionThrownAndCaught() {
        try {
            throw new IOException("Network connection timeout");
        } catch (IOException e) {
            System.err.println("Caught exception: " + e);
        }
        // does the test pass? was this behavior correct?
    }

    @Test
    public void checkedExceptionAddedToSignature() throws IOException {
        throw new IOException("Network connection timeout");
        // does the test pass?
    }

    @Test
    public void genericExceptionSignature() throws Exception {
        throw new CustomException("Custom exception with message");
        // what does it give us?
    }

    @Test(expected = CustomException.class)
    public void checkedExceptionExpected() throws Exception {
        throw new CustomException("Custom exception with message");
        // when should we use this method?
    }

    private static class CustomException extends Exception {
        CustomException(String message) {
            super(message);
        }
    }
}

Add bonus content related to exceptions in test


package com.antew.redditinpictures.library.json;

import android.content.Intent;
import android.os.Bundle;

import com.antew.redditinpictures.library.service.RedditService;
import com.antew.redditinpictures.library.service.RequestCode;

public abstract class JsonResult {
    private Bundle      mExtraData;
    private RequestCode mRequestCode;
    private int         mHttpStatusCode;
    private String      mJson;

    public JsonResult(Intent result) {
        mExtraData = result.getBundleExtra(RedditService.EXTRA_PASS_THROUGH);

        Bundle args = result.getBundleExtra(RedditService.EXTRA_BUNDLE);
        mRequestCode = (RequestCode) args.getSerializable(RedditService.EXTRA_REQUEST_CODE);
        mHttpStatusCode = args.getInt(RedditService.EXTRA_STATUS_CODE);
        mJson = args.getString(RedditService.REST_RESULT);
    }

    public Bundle getExtraData() {
        return mExtraData;
    }

    public RequestCode getRequestCode() {
        return mRequestCode;
    }

    public int getHttpStatusCode() {
        return mHttpStatusCode;
    }

    public String getJson() {
        return mJson;
    }

}

Add generic class for Json results from the service.


package com.epam.itweek.boosenger.controller;

import java.util.Collections;
import java.util.concurrent.Callable;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import lombok.extern.slf4j.Slf4j;

@Controller
@Slf4j
public class BoosengerController {

    @RequestMapping("/{username}")
    public Callable<String> createMessage(@PathVariable("username") String username, Model model) {
        return () -> {
            model.addAttribute("username", username);

            model.addAttribute("messages", Collections.EMPTY_LIST);
            return "messaging/messages";
        };
    }

    @RequestMapping(value = "/{username}", method = RequestMethod.POST)
    public Callable<String> posMessage(@PathVariable("username") String username,
                                       @RequestParam("message") String postedMessage) {
        return () -> {
            log.info("Is about to post message '{}' for username: '{}'", postedMessage, username);
            return "redirect:/" + username;
        };
    }
}

Add MVC controller to create messages

Add MVC controller to create messages


package keymix;

import java.util.HashMap;
import javafx.scene.input.KeyCode;
import java.io.File;

/**
 * HashMap to map keycodes to the corresponding sound they should produce.
 */
public class SoundMap {

    /* Maps keycodes to string containing the file name of the sound byte. */
    HashMap<KeyCode, String> sounds = new HashMap<KeyCode, String>();

    /* KeyCodes for all valid keys. */
    KeyCode[] codes = new KeyCode[]{KeyCode.A, KeyCode.B, KeyCode.C, KeyCode.D, KeyCode.E, KeyCode.F, KeyCode.G,
            KeyCode.H, KeyCode.I, KeyCode.J, KeyCode.K, KeyCode.L, KeyCode.M, KeyCode.N, KeyCode.O, KeyCode.P,
            KeyCode.Q, KeyCode.R, KeyCode.S, KeyCode.T, KeyCode.U, KeyCode.V, KeyCode.W, KeyCode.X, KeyCode.Y, KeyCode.Z,
            KeyCode.DIGIT0, KeyCode.DIGIT1, KeyCode.DIGIT2, KeyCode.DIGIT3, KeyCode.DIGIT4, KeyCode.DIGIT5,
            KeyCode.DIGIT6, KeyCode.DIGIT7, KeyCode.DIGIT8, KeyCode.DIGIT9,
            KeyCode.SPACE, KeyCode.SHIFT, KeyCode.CONTROL, KeyCode.BACK_SPACE};

    /* Filepaths for all sound bytes to be available. */
    String[] filepaths = new String[]{
        // Insert filepaths as Strings
    };

    /* Given a filepath as a String, return the name of the file. */
    public static String name(String filepath) {
        File f = new File(filepath);
        return f.getName();
    }

    public static HashMap<KeyCode, String> map(KeyCode[] c, String[] fp, HashMap<KeyCode, String> m) {
        for(int i = 0; i < c.length; i += 1) {
            m.put(c[i], name(fp[i]));
        }
        return m;
    }
}

Create sound HashMap for KeyCode to file name