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

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

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

public class ByteArrayBodyGenerator implements BodyGenerator {

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

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

    protected final class ByteBody implements Body {

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

        public long read(ByteBuffer byteBuffer) throws IOException {

            if (eof) {
                return -1;
            }

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

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

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

Add a BodyGenerator backed by a byte array


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

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

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

public class PalladioResourceRepositoryImpl implements PalladioResourceRepository {

    private final ResourceRepository repository;

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

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

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

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

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

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

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

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

Implement facade to retrieve Palladio resource types


package uk.ac.ebi.atlas.utils;

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

import javax.inject.Inject;

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

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

    @Inject
    private DBSolrStatusController subject;

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

Add test for the health-check URL


package com.jetbrains.python.console;

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

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

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

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

package com.jetbrains.python.console;

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

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

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

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

Revert "yet another back compatibility fix"


package pipe.gui.plugin.concrete;

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

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

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

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

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

Add GSPN analysis to PIPE


package com.github.sparkcaller.variantdiscovery;

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

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

public class GenotypeGVCF extends BaseGATKProgram {

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

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

        setOutputFile(outputFilename);
        executeProgram();

        return new File(outputFilename);
    }
}

Create the class which will be used when performing joint genotyping.


package wissolsoft.porada.webapp.controller;

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

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

import wissolsoft.porada.webapp.model.Law;

@Controller
public class LawsController {

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

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

}

Add contrller for laws page with sample data


package org.simpleframework.xml.core;

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

import junit.framework.TestCase;

public class ObjectStreamClassTest extends TestCase {

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

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

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

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

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

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

}

Update the object stream test


/*******************************************************************************
 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.eclipse.egit.ui.internal.actions;

import java.util.List;

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

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

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

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

/*******************************************************************************
 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.eclipse.egit.ui.internal.actions;

import java.util.List;

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

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

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

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

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

}

Add missing confirmation dialog for hard reset


package com.tacitknowledge.performance.data;

import com.tacitknowledge.performance.Component;

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

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

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

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

Implement simple string message handler


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

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

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

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

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

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

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

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

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

Add tests for the SyntaxHighlighter class.


package com.nexmo.quickstart.voice;

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

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

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

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

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

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

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

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

Add example of TTS with NCCO


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

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

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

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

    // for serializer
    private EmptyDiscreteResources() {}

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

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

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

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

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

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

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

Add a DiscreteResources sub type representing an empty set


package de.stevenschwenke.java.writingawesomejavacodeworkshop.programmingstyle;

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

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

    private int y;

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

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

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

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

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

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

}

Add chapter about Pure Functions


package pl.schibsted.flume.interceptor.json;

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

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

Add date time output format serializer


package net.dummydigit.qbranch.ut.mocks;

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

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

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

    private JGenericTypeBase() { }

    private T1 baseFieldT1;
    private T2 baseFieldT2;

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

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

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

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

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

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

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

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

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

Add second java class to demo how to create generic class.


package org.opennms.netmgt.model;

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

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

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

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


package de.retest.recheck.configuration;

import java.nio.file.Path;

public class ProjectConfigurationUtil {

	private ProjectConfigurationUtil() {

	}

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

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

}

Add util to find project configuration


package com.truphone.cascades;

import java.io.PrintStream;

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

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

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

Add unit test for the QML Command


package com.ushahidi.android.data.entity;

import com.ushahidi.android.BuildConfig;

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

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

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

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

Add test for form attribute


package com.cloudbees.plugins.credentials.impl;

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

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

@Extension
public class UsernamePasswordCredentialsSnapshotTaker extends CredentialsSnapshotTaker<StandardUsernamePasswordCredentials> {

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

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

Add snapshot taker for StandardUsernamePasswordCredentials


package com.github.havarunner.beforeafter;

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

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

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

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

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

        @Test
        void hello() {}
    }

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

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

Add spec on @Before call order


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

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

Add Java package for formatters


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

import junit.framework.TestCase;

import org.apache.ftpserver.filesystem.NativeFileSystemView;
import org.apache.ftpserver.ftplet.FileSystemView;
import org.apache.ftpserver.usermanager.BaseUser;

public class DirectoryListerTest extends TestCase {

    private DirectoryLister directoryLister;

    private FileSystemView fileSystemView;

    protected void setUp() throws Exception {
        BaseUser baseUser = new BaseUser();
        baseUser.setHomeDirectory("/");
        fileSystemView = new NativeFileSystemView(baseUser) {

        };
        directoryLister = new DirectoryLister(fileSystemView);
    }

    /*
     * Test method for 'org.apache.ftpserver.DirectoryLister.parse(String)'
     */
    public void testParse() {
        assertEquals(true, directoryLister.parse("-ls /abcd"));
        assertEquals("/abcd", directoryLister.m_file);
        assertEquals(true, directoryLister.m_isDetailOption);
        assertEquals(false, directoryLister.m_isAllOption);

        assertEquals(true, directoryLister.parse("-ls /ab cd"));
        assertEquals("/ab cd", directoryLister.m_file);
        assertEquals(true, directoryLister.m_isDetailOption);
        assertEquals(false, directoryLister.m_isAllOption);
    }

}

Test package structure as suggested by Sergey Vladimirov


/**
 * Illustrates Kryo serialization in Java
 */
package com.oreilly.learningsparkexamples.java;

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

import org.apache.commons.lang.StringUtils;

import org.apache.spark.SparkConf;
import org.apache.spark.serializer.KryoRegistrator;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;

import com.esotericsoftware.kryo.Kryo;

public class BasicAvgWithKryo {
  // This is our custom class we will configure Kyro to serialize
  class AvgCount {
    public AvgCount(int total, int num) {
      total_ = total;
      num_ = num;
    }
    public int total_;
    public int num_;
    public float avg() {
      return total_ / (float) num_;
    }
  }

  public class AvgRegistrator implements KryoRegistrator {
    public void registerClasses(Kryo kryo) {
      kryo.register(AvgCount.class);
    }
  }

  public static void main(String[] args) throws Exception {
		String master;
		if (args.length > 0) {
      master = args[0];
		} else {
			master = "local";
		}
    BasicAvg avg = new BasicAvg();
    avg.run(master);
  }

  public void run(String master) throws Exception {
    SparkConf conf = new SparkConf().setMaster(master).setAppName("basicavgwithkyro");
    conf.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer");
    conf.set("spark.kryo.registrator", AvgRegistrator.class.getName());
		JavaSparkContext sc = new JavaSparkContext(conf);
    JavaRDD<Integer> rdd = sc.parallelize(Arrays.asList(1, 2, 3, 4));
    Function2<AvgCount, Integer, AvgCount> addAndCount = new Function2<AvgCount, Integer, AvgCount>() {
      @Override
      public AvgCount call(AvgCount a, Integer x) {
        a.total_ += x;
        a.num_ += 1;
        return a;
      }
    };
    Function2<AvgCount, AvgCount, AvgCount> combine = new Function2<AvgCount, AvgCount, AvgCount>() {
      @Override
      public AvgCount call(AvgCount a, AvgCount b) {
        a.total_ += b.total_;
        a.num_ += b.num_;
        return a;
      }
    };
    AvgCount initial = new AvgCount(0,0);
    AvgCount result = rdd.aggregate(initial, addAndCount, combine);
    System.out.println(result.avg());
	}
}

Add a basic avg with kryo example in Java


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

package io.spine.server.storage.datastore;

import io.spine.server.aggregate.AggregateStorageTruncationTest;
import io.spine.server.storage.StorageFactory;
import org.junit.jupiter.api.DisplayName;

@DisplayName("DsAggregateStorage after truncation should")
public class DsAggregateStorageTruncationTest extends AggregateStorageTruncationTest {

    @Override
    protected StorageFactory storageFactory() {
        return TestDatastoreStorageFactory.defaultInstance();
    }
}

Use the test for storage truncation from `core-java`


package org.cinchapi.concourse;

import org.cinchapi.concourse.thrift.Operator;
import org.cinchapi.concourse.util.TestData;
import org.junit.Assert;
import org.junit.Test;

/**
 * Unit tests the following alias operators: LIKE, NOT_LIKE and LINK_TO.
 *
 * @author remie
 *
 */
public class OperatorAliasTest extends ConcourseIntegrationTest {

	@Test
	public void testLikeAlias() {
		String key = TestData.getString();
		int record = TestData.getScaleCount();
		client.add(key, 1, record);
		Assert.assertEquals(client.find(key, Operator.LIKE, record),
				client.find(key, Operator.REGEX, record));
	}

	@Test
	public void testNotLikeAlias() {
		String key = TestData.getString();
		int record = TestData.getScaleCount();
		client.add(key, 1, record);
		Assert.assertEquals(client.find(key, Operator.NOT_LIKE, record),
				client.find(key, Operator.NOT_REGEX, record));
	}

	@Test
	public void testLinkToAlias() {
		String key = TestData.getString();
		int record = TestData.getScaleCount();
		client.add(key, 1, record);
		Assert.assertEquals(client.find(key, Operator.LINKS_TO, record),
				client.find(key, Operator.EQUALS, record));
	}
}

Create unit tests for the following alias operators: LIKE, NOT_LIKE and LINK_TO


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

package com.facebook.imagepipeline.producers;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.Executor;

import android.net.Uri;
import android.util.Base64;

import com.facebook.common.internal.Preconditions;
import com.facebook.common.internal.VisibleForTesting;
import com.facebook.imagepipeline.memory.PooledByteBufferFactory;
import com.facebook.imagepipeline.request.ImageRequest;

/**
 * Producer for data URIs.
 *
 *
Data URIs embed the data in the URI itself. They don't point to a file location;
 * the URI is the data. Data can be encoded in either base-64 or escaped ASCII.
 * See the spec for full details.
 *
 *
Data URIs are intended for small pieces of data only, since the URI lives on the Java
 * heap. For large data, use a another URI type.
 *
 *
Charsets specified in the URI are ignored. Only UTF-8 encoding is currently supported.
 */
public class DataFetchProducer extends LocalFetchProducer {

  private static final String PRODUCER_NAME = "DataFetchProducer";

  public DataFetchProducer(
      Executor executor,
      PooledByteBufferFactory pooledByteBufferFactory) {
    super(executor, pooledByteBufferFactory);
  }

  @Override
  protected InputStream getInputStream(ImageRequest imageRequest) throws IOException {
    return new ByteArrayInputStream(getData(imageRequest.getSourceUri().toString()));
  }

  @Override
  protected int getLength(ImageRequest imageRequest) {
    return getData(imageRequest.getSourceUri().toString()).length;
  }

  @Override
  protected String getProducerName() {
    return PRODUCER_NAME;
  }

  @VisibleForTesting
  static byte[] getData(String uri) {
    /*
     * Format of a data URL:
     * data:mime/type;param=value;param=value;base64,actual_data
     * everything is optional except the actual data, which is either
     * base-64 or escaped ASCII encoded.
     */
    Preconditions.checkArgument(uri.substring(0, 5).equals("data:"));
    int commaPos = uri.indexOf(',');

    String dataStr = uri.substring(commaPos + 1, uri.length());
    if (isBase64(uri.substring(0, commaPos))) {
      return Base64.decode(dataStr, Base64.DEFAULT);
    } else {
      String str = Uri.decode(dataStr);
      byte[] b = str.getBytes();
      return b;
    }
  }

  @VisibleForTesting
  static boolean isBase64(String prefix) {
    if (!prefix.contains(";")) {
      return false;
    }
    String[] parameters = prefix.split(";");
    return parameters[parameters.length - 1].equals("base64");
  }
}

Add support for data URIs in [Part 1]


package de.bigprak.transform.csv;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.QuoteMode;
import org.apache.commons.io.FileUtils;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple3;

public class CSVParsingTest {
    public static void main(String[] args) throws Exception {
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        CSVFormat csvFormat = CSVFormat.newFormat(',')
                .withEscape('\\')
                .withQuoteMode(QuoteMode.NONE)
                .withNullString("");

        File in = File.createTempFile("de.bigprak.transform.csv", "CSVParsingTest-in");
        File out = File.createTempFile("de.bigprak.transform.csv", "CSVParsingTest-out");
        in.deleteOnExit();
        out.deleteOnExit();
        out.delete();

        // Extract (in this order) the id, the first Name and the message;
        // ignore second name and time
        String csv = "Peter,Franz,1,Hallo Franz\\, wie geht es dir?,1456076785\n" +
                     "Franz,Peter,2,Sehr gut\\, danke\\, und dir?,1456076892\n" +
                     "Peter,Franz,3,Alles in Ordnung!,1456076899";
        int[] indices = {2,0,3};
        Class<?>[] types = {Long.class, String.class, String.class};

        FileUtils.writeStringToFile(in, csv, StandardCharsets.UTF_8);

        env.readFile(new CommonsCSVInputFormat(csvFormat), in.getAbsolutePath())
           .map(new CSVRecordToTupleMap<Tuple3<Long, String, String>>(indices, types))
           // necessary, because flink cannot deduce return type from generic Mapper
           .returns("Tuple3<Long, String, String>")
           .writeAsCsv(out.getAbsolutePath());

        env.setParallelism(1);
        env.execute();

        String result = FileUtils.readFileToString(out, StandardCharsets.UTF_8);

        // show results
        System.out.println();
        System.out.println("Input csv: ");
        System.out.println(csv);

        System.out.println();
        System.out.println("Extraction parameters: " + Arrays.toString(indices) + " (" + Arrays.toString(types) + ")");

        System.out.println();
        System.out.println("Resulting csv: ");
        System.out.println(result);
    }
}

Add test for the new CommonsCSVInputFormat and CSVRecordToTupleMap


package org.bitrepository.integrityservice.utils;

/**
 * Util class to handle the presentation of time in a human readable form
 */
public class TimeUtils {

	private static final int MS_PER_S = 1000;
	private static final int S_PER_M = 60;
	private static final int M_PER_H = 60;
	private static final int H_PER_D = 24;
	private static final int MS_PER_MINUTE = MS_PER_S * S_PER_M;
	private static final int MS_PER_HOUR = MS_PER_MINUTE * M_PER_H;
	private static final long MS_PER_DAY = MS_PER_HOUR * H_PER_D;

	/** Private constructor, util class.*/
	private TimeUtils() {}

	public String millisecondsToSeconds(long ms) {
		return "" + (ms / MS_PER_S) + "seconds";
	}

	public String millisecondsToMinutes(long ms) {
		return "" + (ms / ( MS_PER_S * S_PER_M )) + "minutes";
	}

	public String millisecondsToHours(long ms) {
		return "" + (ms /( MS_PER_S * S_PER_M * M_PER_H )) + "hours";
	}

	public String millisecondsToDays(long ms) {
		return "" + (ms /( MS_PER_S * S_PER_M * M_PER_H * H_PER_D)) + "days";
	}

	public String millisecondsToHuman(long ms) {
		StringBuilder sb = new StringBuilder();
		int days = 0, hours = 0, minutes = 0, seconds = 0;
		if(ms > 0) {
			days = (int) (ms / MS_PER_DAY);
			if(days > 0) {
				sb.append("" + days + "d");
			}
			ms = (ms % MS_PER_DAY);
			if(ms > 0) {
				hours = (int) (ms / MS_PER_HOUR);
				if(hours > 0) {
					sb.append(" " + hours + "h");
				}
				ms = (ms % MS_PER_HOUR);
				if( ms > 0) {
					minutes = (int) (ms / MS_PER_MINUTE);
					if(minutes > 0) {
						sb.append(" " + minutes + "m");
					}
					ms = (ms % MS_PER_MINUTE);
					if(ms > 0) {
						seconds = (int) (ms / MS_PER_S);
						if(seconds > 0) {
							sb.append(" " + seconds + "s");
						}
						ms = (ms % MS_PER_S);
						if(ms > 0) {
							sb.append(" " + ms + "ms");
						}
					}
				}
			}
		}
		return sb.toString();
	}

}

Add small util class for converting time intervals to a human readable format


/*
 * 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.jdbi.v3.sqlobject.locator;

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

import java.util.List;

import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.core.Something;
import org.jdbi.v3.core.config.JdbiConfig;
import org.jdbi.v3.core.rule.PgDatabaseRule;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.jdbi.v3.sqlobject.SqlObjects;
import org.jdbi.v3.sqlobject.config.RegisterBeanMapper;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.junit.Rule;
import org.junit.Test;

public class TestSqlLocator {
  @Rule
  public PgDatabaseRule dbRule = new PgDatabaseRule().withPlugin(new SqlObjectPlugin());

  @Test
  public void testLocateConfigDriven() {
    Jdbi jdbi = dbRule.getJdbi();
    jdbi.useHandle(h -> {
      h.execute("create table something (id int, name text)");

      h.execute("insert into something (id, name) values (?, ?)", 2, "Alice");
      h.execute("insert into something (id, name) values (?, ?)", 1, "Bob");
    });

    jdbi.getConfig(SqlObjects.class).setSqlLocator(
        (type, method, config) -> config.get(TestConfig.class).sql);

    jdbi.getConfig(TestConfig.class).sql = "select * from something order by id";
    assertThat(jdbi.withExtension(TestDao.class, TestDao::list))
      .containsExactly(new Something(1, "Bob"), new Something(2, "Alice"));

    jdbi.getConfig(TestConfig.class).sql = "select * from something order by name";
    assertThat(jdbi.withExtension(TestDao.class, TestDao::list))
      .containsExactly(new Something(2, "Alice"), new Something(1, "Bob"));
  }

  public static class TestConfig implements JdbiConfig<TestConfig> {
    String sql;

    public TestConfig() {}

    private TestConfig(TestConfig that) {
      this.sql = that.sql;
    }

    @Override
    public TestConfig createCopy() {
      return new TestConfig(this);
    }
  }

  @RegisterBeanMapper(Something.class)
  public interface TestDao {
    @SqlQuery
    List<Something> list();
  }

}

Add test for SQL Locator using config registry


/*
 * 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 tw.flink.jcconf2016.streaming.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * Basic streaming word count example, that reads text lines from a socket stream
 */
public class StreamingWordCount {

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

		final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

		DataStream<Tuple2<String,Integer>> counts = env
				// read stream of words from socket
				.socketTextStream("localhost", 1234)
				// split up the lines into tuple: (word, 1)
				.flatMap(new LineSplitter())
				// use the “word” as key
				.keyBy(0)
				// compute counts every 10 seconds
				.timeWindow(Time.seconds(10))
				// sum up the values
				.sum(1);

		// print result to console
		counts.print();
		// execute program
		env.execute("Socket Word Count Example");
	}

	public static class LineSplitter implements FlatMapFunction<String, Tuple2<String,Integer>> {

		@Override
		public void flatMap(String value, Collector<Tuple2<String,Integer>> out) throws Exception {
			// normalize and split lines
			String[] words = value.toLowerCase().split("\\W+");
			for (String word : words) {
				if (word.length() > 0) {
					out.collect(new Tuple2<>(word, 1));
				}
			}
		}

	}

}

Add basic streaming wordcount example


package org.reflection_no_reflection.generator.sample;

import org.junit.Before;
import org.junit.Test;
import org.reflection_no_reflection.Class;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.core.IsSame.sameInstance;
import static org.junit.Assert.assertThat;

public class ClassTest {

    @Before
    public void setUp() throws Exception {
        Class.clearAllClasses();
    }

    @Test
    public void classesShouldBeUniq() throws Exception {
        //GIVEN
        final Class stringClass = Class.forNameSafe("java.lang.String");

        //WHEN
        final Class stringClass2 = Class.forNameSafe("java.lang.String");

        //THEN
        assertThat(stringClass2, sameInstance(stringClass));
    }

    @Test
    public void classPoolContainsClasses() throws Exception {
        //GIVEN
        final Class stringClass = Class.forNameSafe("java.lang.String");

        //WHEN

        //THEN
        assertThat(Class.getClassPool().size(), is(1));
    }

    @Test
    public void classPoolCanBeCleared() throws Exception {
        //GIVEN
        final Class stringClass = Class.forNameSafe("java.lang.String");

        //WHEN
        Class.clearAllClasses();

        //THEN
        assertThat(Class.getClassPool().size(), is(0));
    }

    @Test(expected = ClassNotFoundException.class)
    public void classForNameShouldFailIfClassDoesNotExist() throws Exception {
        //GIVEN
        //WHEN
        final Class stringClass = Class.forName("java.lang.String");
        //THEN
    }

}

Add a few test cases for generated classes


package fitnesse.slim.fixtureInteraction;

import org.junit.Test;

public class CachedInteractionTest {

  @Test
  public void canBeCreated() {
    CachedInteraction interaction = new CachedInteraction();
  }
}

Add test to show CachedInteraction cannot be created


/*
 *   Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *   WSO2 Inc. 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.wso2.appcloud.core.dto;

/**
 * Represents tenant subscription plan information.
 */
public class UsageTier {

    private String planName;
    private int maxApplicationCount;
    private int maxDatabaseCount;
    private int maxReplicaCount;
    private int cpuLimit;
    private int ramLimit;

    public String getPlanName() {
        return planName;
    }

    public void setPlanName(String planName) {
        this.planName = planName;
    }

    public int getMaxApplicationCount() {
        return maxApplicationCount;
    }

    public void setMaxApplicationCount(int maxApplicationCount) {
        this.maxApplicationCount = maxApplicationCount;
    }

    public int getMaxDatabaseCount() {
        return maxDatabaseCount;
    }

    public void setMaxDatabaseCount(int maxDatabaseCount) {
        this.maxDatabaseCount = maxDatabaseCount;
    }

    public int getMaxReplicaCount() {
        return maxReplicaCount;
    }

    public void setMaxReplicaCount(int maxReplicaCount) {
        this.maxReplicaCount = maxReplicaCount;
    }

    public int getCpuLimit() {
        return cpuLimit;
    }

    public void setCpuLimit(int cpuLimit) {
        this.cpuLimit = cpuLimit;
    }

    public int getRamLimit() {
        return ramLimit;
    }

    public void setRamLimit(int ramLimit) {
        this.ramLimit = ramLimit;
    }
}

Add usage tier DTO class


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

package org.jboss.as.server.deployment;

/**
 * Marks a {@link DeploymentUnit} as a EJB deployment.
 *
 * @author Jaikiran Pai
 */
public class EjbDeploymentMarker {

    private static final AttachmentKey<Boolean> ATTACHMENT_KEY = AttachmentKey.create(Boolean.class);

    public static void mark(final DeploymentUnit deployment) {
        deployment.putAttachment(ATTACHMENT_KEY, true);
    }

    public static boolean isEjbDeployment(final DeploymentUnit deploymentUnit) {
        final Boolean val = deploymentUnit.getAttachment(ATTACHMENT_KEY);
        return val != null && val;
    }

}

Allow EJB deployments as OSGi bundles


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

import java.security.Principal;
import java.util.Collections;

import javax.jcr.RepositoryException;
import javax.security.auth.Subject;

import org.apache.jackrabbit.core.security.SecurityConstants;
import org.apache.jackrabbit.core.security.principal.AdminPrincipal;

public class SessionFactory {

    private final RepositoryContext context;

    public SessionFactory(RepositoryContext context) {
        this.context = context;
    }

    public SessionImpl createAdminSession(String workspace)
            throws RepositoryException {
        Principal admin = new AdminPrincipal(SecurityConstants.ADMIN_ID);
        Subject subject = new Subject(
                true, Collections.singleton(admin),
                Collections.emptySet(), Collections.emptySet());
        return context.getRepository().createSession(subject, workspace);
    }

}

Add a factory for creating new sessions


package com.yahoo.abicheck;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.common.collect.Iterables;
import com.yahoo.abicheck.classtree.ClassFileTree;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.junit.jupiter.api.Test;

public class ClassFileTreeTest {

  @Test
  public void testJarParsing() throws IOException {
    JarFile jarFile = mock(JarFile.class);
    JarEntry jarEntry = new JarEntry("com/yahoo/Test.class");
    InputStream jarEntryStream = mock(InputStream.class);
    when(jarFile.entries()).thenReturn(Collections
        .enumeration(Collections.singleton(jarEntry)));
    when(jarFile.getInputStream(jarEntry)).thenReturn(jarEntryStream);

    ClassFileTree cft = ClassFileTree.fromJar(jarFile);
    ClassFileTree.Package com = Iterables.getOnlyElement(cft.getRootPackages());
    assertThat(com.getFullyQualifiedName(), equalTo("com"));
    assertThat(com.getClassFiles(), empty());
    ClassFileTree.Package yahoo = Iterables.getOnlyElement(com.getSubPackages());
    assertThat(yahoo.getFullyQualifiedName(), equalTo("com.yahoo"));
    assertThat(yahoo.getSubPackages(), empty());
    ClassFileTree.ClassFile testClassFile = Iterables.getOnlyElement(yahoo.getClassFiles());
    assertThat(testClassFile.getName(), equalTo("Test.class"));
    assertThat(testClassFile.getInputStream(), sameInstance(jarEntryStream));
  }
}

Add unit test for ClassFileTree.


package com.spiddekauga.android.ui;

import android.support.annotation.StringRes;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ClickableSpan;

import com.spiddekauga.android.AppActivity;
import com.spiddekauga.android.BuildConfig;
import com.spiddekauga.utils.Strings;

/**
 * Creates a clickable SpannableString from a resource. Automatically determines where the clickable
 * part from the resource. The resource should contain the clickable part between ||clickable text||
 * i.e. between the pipes.
 */
public class SpanStringHelper {
private static final String DELIMITER = "\\|\\|";

/**
 * Creates a clickable SpannableString from a resource. Automatically determines where the clickable
 * part from the resource. The resource should contain the clickable part between ||clickable text||
 * i.e. between the pipes.
 * @param stringId the string to create the spannable text from
 * @param clickableListeners array of all clickable spans listeners, should match the number of
 * clickable lists
 */
public static SpannableString createSpannableString(@StringRes int stringId, ClickableSpan... clickableListeners) {
	String text = AppActivity.getActivity().getResources().getString(stringId);
	String[] spans = text.split(DELIMITER, -1);

	// Check so listeners matches the spans
	// It should be clickableListener * 2 + 1
	if (BuildConfig.DEBUG) {
		if (spans.length != (clickableListeners.length * 2) + 1) {
			throw new IllegalArgumentException("Text \"" + text + "\" does not contain " + clickableListeners.length + " clickable parts");
		}
	}

	String displayText = Strings.merge(spans);
	SpannableString spannableString = new SpannableString(displayText);

	// Bind each clickable state
	int totalLength = 0;
	for (int i = 0; i < spans.length - 1; i += 2) {
		int beginIndex = totalLength + spans[i].length();
		int length = spans[i + 1].length();
		int endIndex = beginIndex + length;

		spannableString.setSpan(clickableListeners[i / 2], beginIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

		totalLength = endIndex;
	}

	return spannableString;
}
}

Add helper for creating SpannedString


package org.mskcc.cbio.oncokb.importer;

import org.json.JSONArray;
import org.json.JSONObject;
import org.mskcc.cbio.oncokb.model.Gene;
import org.mskcc.cbio.oncokb.util.ApplicationContextSingleton;
import org.mskcc.cbio.oncokb.util.FileUtils;
import org.mskcc.cbio.oncokb.util.GeneUtils;

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

/**
 * @author Hongxin Zhang
 */
public final class geneNamelImporter {
    private geneNamelImporter() {
        throw new AssertionError();
    }

    private static String ALL_GENES_FILE = "ftp://ftp.ebi.ac.uk/pub/databases/genenames/new/json/hgnc_complete_set.json";

    public static void main(String[] args) throws IOException {
        String response = FileUtils.readRemote(ALL_GENES_FILE);
        JSONObject result = new JSONObject(response);
        JSONArray array = result.getJSONObject("response").getJSONArray("docs");
        Set<String> hugoSymbols = new HashSet<>();

        for (int i = 0; i < array.length(); i++) {
            JSONObject object = array.getJSONObject(i);
            hugoSymbols.add(object.getString("symbol"));
        }

        Set<Gene> genes = GeneUtils.getAllGenes();

        for (Gene gene : genes) {
            List<String> aliases = new ArrayList<>(gene.getGeneAliases());
            for (String alias : aliases) {
                if (hugoSymbols.contains(alias)) {
                    gene.getGeneAliases().remove(alias);
                    System.out.println("Alias of " + gene.getHugoSymbol() + " has been removed: " + alias);
                }
            }
        }

        ApplicationContextSingleton.getGeneBo().saveOrUpdateAll(new ArrayList<>(genes));
    }
}

Add importer to remove current in use hugoSymbol from the alias list


package jp.ne.naokiur.design.pattern.mediator;

import jp.ne.naokiur.design.pattern.mediator.character.Cabbage;
import jp.ne.naokiur.design.pattern.mediator.character.Farmer;
import jp.ne.naokiur.design.pattern.mediator.character.Goat;
import jp.ne.naokiur.design.pattern.mediator.character.Wolf;

public class CrossRiverExecutor {
    private Farmer farmer;
    private Wolf wolf;
    private Goat goat;
    private Cabbage cabbage;
    private CrossRiverMediator crossRiver;

    public CrossRiverExecutor() {
        farmer = new Farmer();
        wolf = new Wolf();
        goat = new Goat();
        cabbage = new Cabbage();

        crossRiver = new CrossRiverMediator(farmer, wolf, goat, cabbage);
        farmer.setMediator(crossRiver);
        wolf.setMediator(crossRiver);
        goat.setMediator(crossRiver);
        cabbage.setMediator(crossRiver);
    }

    public void execute() {
        farmer.cross(goat);     // こちらの岸：オオカミ、キャベツ      向こう岸：農夫、ヤギ
        farmer.cross();         // こちらの岸：農夫、オオカミ、キャベツ 向こう岸：ヤギ
        farmer.cross(cabbage);  // こちらの岸：オオカミ              向こう岸：農夫、ヤギ、キャベツ
        farmer.cross(goat);     // こちらの岸：農夫、ヤギ、オオカミ    向こう岸：キャベツ
        farmer.cross(wolf);     // こちらの岸：ヤギ                 向こう岸：農夫、オオカミ、キャベツ
        farmer.cross();         // こちらの岸：農夫、ヤギ            向こう岸：オオカミ、キャベツ
        farmer.cross(goat);     // こちらの岸：                    向こう岸：農夫、オオカミ、ヤギ、キャベツ
    }
}

Add Executor for Mediator pattern.


/*
 * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.oracle.graal.jtt.loop;

import com.oracle.graal.jtt.*;
import org.junit.*;

/*
 */
public class LoopUnroll extends JTTTest {

    public static int test(int input) {
        int ret = 2;
        int current = input;
        for (int i = 0; i < 7; i++) {
            ret *= 2 + current;
            current /= 50;
        }
        return ret;
    }

    @Test
    public void run0() throws Throwable {
        runTest("test", 42);
    }

}

Test case for loop unrolling.


/**
 * Copyright 2017 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.timelock.paxos;

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

import java.util.Set;

import org.junit.Test;

import com.google.common.collect.ImmutableSet;

public class PaxosTimeLockUriUtilsTest {
    private static final String ADDRESS_1 = "foo:1234";
    private static final String ADDRESS_2 = "bar:5678";
    private static final Set<String> ADDRESSES = ImmutableSet.of(ADDRESS_1, ADDRESS_2);

    private static final String CLIENT = "testClient";

    @Test
    public void canGetLeaderUris() {
        Set<String> leaderUris = PaxosTimeLockUriUtils.getLeaderPaxosUris(ADDRESSES);

        assertThat(leaderUris).containsExactlyInAnyOrder(
                String.join("/",
                        ADDRESS_1,
                        PaxosTimeLockConstants.INTERNAL_NAMESPACE,
                        PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE),
                String.join("/",
                        ADDRESS_2,
                        PaxosTimeLockConstants.INTERNAL_NAMESPACE,
                        PaxosTimeLockConstants.LEADER_PAXOS_NAMESPACE));
    }

    @Test
    public void canGetClientPaxosUris() {
        Set<String> clientPaxosUris = PaxosTimeLockUriUtils.getClientPaxosUris(ADDRESSES, CLIENT);

        assertThat(clientPaxosUris).containsExactlyInAnyOrder(
                String.join("/",
                        ADDRESS_1,
                        PaxosTimeLockConstants.INTERNAL_NAMESPACE,
                        PaxosTimeLockConstants.CLIENT_PAXOS_NAMESPACE,
                        CLIENT),
                String.join("/",
                        ADDRESS_2,
                        PaxosTimeLockConstants.INTERNAL_NAMESPACE,
                        PaxosTimeLockConstants.CLIENT_PAXOS_NAMESPACE,
                        CLIENT));
    }
}

Make sure Paxos URI Utils behave the way they should


/*
 * This file is part of LibrePlan
 *
 * Copyright (C) 2011 Igalia, S.L.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.libreplan.business.planner.entities.visitors;

/**
 * FIXME
 * This visitor calculates allocated/spent hours deviation
 * for finished tasks.
 * @author Nacho Barrientos <nacho@igalia.com>
 */
import java.util.ArrayList;
import java.util.List;

import org.libreplan.business.planner.entities.Task;
import org.libreplan.business.planner.entities.TaskElement;
import org.libreplan.business.planner.entities.TaskGroup;
import org.libreplan.business.util.TaskElementVisitor;
import org.libreplan.business.workingday.EffortDuration;

public class CalculateFinishedTasksEstimationDeviationVisitor extends TaskElementVisitor {

    private List<Double> deviations;

    public CalculateFinishedTasksEstimationDeviationVisitor() {
        this.deviations = new ArrayList<Double>();
    }

    public List<Double> getDeviations() {
        return this.deviations;
    }

    public int getNumberOfConsideredTasks(){
        return deviations.size();
    }

    public void visit(Task task) {
        if (task.isFinished()) {
            int allocatedHours = task.getAssignedHours();
            if (allocatedHours > 0) {
                EffortDuration spentEffort = task.getOrderElement()
                        .getSumChargedEffort().getTotalChargedEffort();
                deviations.add(new Double(
                        ((1.0*spentEffort.getHours() -
                                allocatedHours)/allocatedHours)*100));
            } else {
                deviations.add(new Double(0.0));
            }
        }

    }

    public void visit(TaskGroup taskGroup) {
        for (TaskElement each: taskGroup.getChildren()) {
            each.acceptVisitor(this);
        }
    }

}

Add visitor to calculate hours estimation deviation for finished tasks.


package com.fuzz.indicator.text;

import android.os.Parcel;
import android.support.annotation.NonNull;
import android.text.style.StyleSpan;

/**
 * Warning: this class's ancestry is not final and may change in a future commit.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
public class MigratoryStyleSpan extends StyleSpan implements MigratorySpan {

    public static final Creator<MigratoryStyleSpan> CREATOR = new Creator<MigratoryStyleSpan>() {
        @Override
        public MigratoryStyleSpan createFromParcel(Parcel in) {
            return new MigratoryStyleSpan(in);
        }

        @Override
        public MigratoryStyleSpan[] newArray(int size) {
            return new MigratoryStyleSpan[size];
        }
    };

    public MigratoryStyleSpan(int style) {
        super(style);
    }

    private MigratoryStyleSpan(Parcel in) {
        super(in);
    }

    @NonNull
    @Override
    public MigratoryRange<Float> getCoverage() {
        return MigratoryRange.from(.2f, .8f);
    }

    @Override
    public int preferredFlags(int previousFlags) {
        return previousFlags;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        super.writeToParcel(dest, flags);
    }

    @Override
    public int describeContents() {
        return super.describeContents();
    }
}

Add new StyleSpan wrapper (not final version yet)


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.dsu.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.Validator;

/**
 * A configuration that creates a JSR-303 Bean Validation API validator.
 *
 * @author Emerson Farrugia
 */
@Configuration
public class ValidationConfiguration {

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {

        return new LocalValidatorFactoryBean();
    }

    @Bean
    public Validator validator(LocalValidatorFactoryBean factoryBean) {

        return factoryBean.getValidator();
    }
}

Add a validation configuration for providing a Validator bean.


package flyway.pti;

import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.oskari.helpers.BundleHelper;

import java.sql.Connection;

/**
 * Register admin-layeranalytics bundle so we can configure it for admins
 */
public class V3_0_7__add_layeranalytics_bundle extends BaseJavaMigration {

    public void migrate(Context context) throws Exception {
        Connection connection = context.getConnection();
        BundleHelper.registerBundle(connection, "admin-layeranalytics");
    }
}

Add migration to register analytics


package edu.northwestern.bioinformatics.studycalendar.utils.hibernate;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import edu.northwestern.bioinformatics.studycalendar.domain.Participant;
import edu.northwestern.bioinformatics.studycalendar.domain.StudyParticipantAssignment;
import edu.northwestern.bioinformatics.studycalendar.domain.Activity;

/**
 * @author Rhett Sutphin
 */
public class StudyCalendarNamingStrategyTest extends StudyCalendarTestCase {
    private static final String DC = "DON'T CARE";

    private StudyCalendarNamingStrategy strategy = new StudyCalendarNamingStrategy();

    public void testForeignKeyColumn() throws Exception {
        assertEquals("planned_event_id", strategy.foreignKeyColumnName("plannedEvent", DC, DC, DC));
    }

    public void testTableName() throws Exception {
        assertEquals("participants", strategy.classToTableName(Participant.class.getName()));
        assertEquals("study_participant_assignments", strategy.classToTableName(StudyParticipantAssignment.class.getName()));
        assertEquals("activities", strategy.classToTableName(Activity.class.getName()));
    }
}

Test for previously committed strategy


package alma.alarmsystem.clients.test;
/*
 * ALMA - Atacama Large Millimiter Array (c) European Southern Observatory, 2007
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */
import cern.laser.client.data.Alarm;
import cern.laser.client.services.selection.AlarmSelectionListener;
import cern.laser.client.services.selection.LaserSelectionException;
import alma.acs.component.client.ComponentClientTestCase;
import alma.alarmsystem.clients.CategoryClient;

/**
 * Test the getThreshold method of the Category client.
 *
 * Each method of the Category client needs to be tested in a separate class due to a bug in the NC
 * (COMP-2153)
 *
 * @author acaproni
 *
 */
public class CategoryClientThreshold extends ComponentClientTestCase implements AlarmSelectionListener {

	/**
	 *  The categoryClient to test
	 */
	private CategoryClient categoryClient;

	/**
	 * Constructor
	 */
	public CategoryClientThreshold() throws Exception {
		super(CategoryClientThreshold.class.getName());
	}

	/**
	 * @see extends ComponentClientTestCase
	 */
	public void setUp() throws Exception {
		super.setUp();

		categoryClient = new CategoryClient(getContainerServices());
		assertNotNull(categoryClient);
	}

	/**
	 * @see extends ComponentClientTestCase
	 */
	public void teraDown() throws Exception {
		categoryClient.close();
		super.tearDown();
	}

	public void testGetThreashold() throws Exception {
		categoryClient.connect(this);
		int threshold = categoryClient.getMultiplicityThreshold("TEST:MCAUSE:1");
		assertEquals(3, threshold);
	}

	/**
	 * @see cern.laser.client.services.selection.AlarmSelectionListener#onAlarm(cern.laser.client.data.Alarm)
	 */
	@Override
	public void onAlarm(Alarm alarm) {	}

	/**
	 * @see cern.laser.client.services.selection.AlarmSelectionListener#onException(cern.laser.client.services.selection.LaserSelectionException)
	 */
	@Override
	public void onException(LaserSelectionException e) {}
}

Test getThreshold of the CategoryClient


/**
 * Copyright 2010 OpenEngSB Division, Vienna University of Technology
 *
 * 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.openengsb.core.persistence.internal;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.openengsb.core.persistence.PersistenceService;
import org.osgi.framework.Bundle;
import org.osgi.framework.Version;

public class NeodatisPersistenceManagerTest {

    private NeodatisPersistenceManager persistenceManager;

    private Bundle bundleMock;

    @Before
    public void setUp() {
        persistenceManager = new NeodatisPersistenceManager();
        persistenceManager.setPersistenceRootDir("target/data");
        bundleMock = Mockito.mock(Bundle.class);
        Mockito.when(bundleMock.getSymbolicName()).thenReturn("testBundle");
        Version versionMock = Mockito.mock(Version.class);
        Mockito.when(bundleMock.getVersion()).thenReturn(versionMock);
    }

    @Test
    public void getPersistenceForBundle_shouldCreatePersistenceService() {
        PersistenceService persistenceService = persistenceManager.getPersistenceForBundle(bundleMock);
        assertThat(persistenceService, notNullValue());
    }

    @Test
    public void getPersistenceForBundleTwice_shouldReturnSamePersistenceService() {
        PersistenceService first = persistenceManager.getPersistenceForBundle(bundleMock);
        PersistenceService second = persistenceManager.getPersistenceForBundle(bundleMock);
        assertThat(second == first, is(true));
    }

}

Add test for neodatis service manager.


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

/**
 * Given a positive int passed as parameter, can you write a method to return true if the number is
 * even or false if the number is odd? The only constraint you have is: you can't use this
 * operator: %.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IsEven {

}

Add statement to problem 68


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

/**
 * tinylog logging API for Java.
 */
package org.tinylog;

Add package for tinylog logging API for Java


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

import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.jetbrains.python.debugger.pydev.ExceptionBreakpointCommandFactory;

/**
 * @author traff
 */
public abstract class ExceptionBreakpointProperties<T> extends XBreakpointProperties<T> implements ExceptionBreakpointCommandFactory{
  @Attribute("exception")
  public String myException;

  public String getException() {
    return myException;
  }

  public abstract String getExceptionBreakpointId();
}

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

import com.intellij.util.xmlb.annotations.Attribute;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.jetbrains.python.debugger.pydev.ExceptionBreakpointCommandFactory;
import com.sun.istack.internal.NotNull;

/**
 * @author traff
 */
public abstract class ExceptionBreakpointProperties<T> extends XBreakpointProperties<T> implements ExceptionBreakpointCommandFactory{
  @Attribute("exception")
  public String myException;

  public String getException() {
    return myException;
  }

  public abstract String getExceptionBreakpointId();
}

Fix template exception breakpoints default.


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

import java.io.IOException;

/**
 * An append-only interface to access to a terminal.
 *
 * This interface allows to specify a text to be written to the user
 * using semantical highlighting (like failure) without any knowledge
 * about the nature of the terminal or the position the text is to be
 * written to. Callers to this interface should make no assumption
 * about how the text is rendered; if the user's terminal does not
 * support, e.g., colors, the highlighting might be done by adding
 * additional characters.
 *
 * All interface functions are supposed to return the object itself
 * to allow chaining of commands.
 */
public interface AnsiTerminalWriter {

  /**
   * Write some text to the user
   */
  AnsiTerminalWriter append(String text) throws IOException;

  /**
   * Start a new line in the way appropriate for the given terminal
   */
  AnsiTerminalWriter newline() throws IOException;

  /**
   * Tell the terminal that the following text will be a positive
   * status message.
   */
  AnsiTerminalWriter okStatus() throws IOException;

  /**
   * Tell the terminal that the following text will be an error-reporting
   * status message.
   */
  AnsiTerminalWriter failStatus() throws IOException;

  /**
   * Tell the terminal that the following text will be normal text, not
   * indicating a status or similar.
   */
  AnsiTerminalWriter normal() throws IOException;
}

Add an interface for append-only access to an AnsiTerminal


/*
 * Copyright 2009-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 info.joseluismartin.gui.form;

import info.joseluismartin.gui.AbstractView;

import java.awt.Dimension;

import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 * Database Connection Form
 *
 * @author Jose Luis Martin - (jlm@joseluismartin.info)
 */
public class DbConnectionForm  extends AbstractView<DbConnection> {

	private JComboBox database = new JComboBox();
	private JTextField port = new JTextField();
	private JTextField host = new JTextField();
	private JTextField dbName = new JTextField();

	/**
	 * @param dbConnection
	 */
	public DbConnectionForm(DbConnection dbConnection) {
		super(dbConnection);
		autobind();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected JComponent buildPanel() {
		BoxFormBuilder fb = new BoxFormBuilder();
		fb.setDebug(true);
		fb.add(getMessage("DbConnectionForm.database"),database);
		fb.row();
		fb.add(getMessage("DbConnectionForm.host"),host);
		fb.row();
		fb.add(getMessage("DbConnectionForm.port"), port);
		fb.row();
		fb.add(getMessage("DbConnectionForm.dbName"), dbName);

		JComponent c = fb.getForm();
		c.setBorder(FormUtils.createTitledBorder(getMessage("DbConnectionForm.title")));

		return c;
	}

	/**
	 * Test Method
	 * @param args none
	 */
	public static void main(String[] args) {
		JFrame f = new JFrame();
		DbConnectionForm dbf = new DbConnectionForm(new DbConnection());
		f.add(dbf.getPanel());
		f.setSize(new Dimension(600,400));
		f.setVisible(true);
	}

}

Add a Form for database connections


/*
 * Copyright 2009 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 samples.junit4.mockpolicy;

import static org.easymock.EasyMock.expect;
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.createMock;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verifyAll;

import java.lang.reflect.Method;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.MockPolicy;
import org.powermock.core.spi.PowerMockPolicy;
import org.powermock.mockpolicies.MockPolicyClassLoadingSettings;
import org.powermock.mockpolicies.MockPolicyInterceptionSettings;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import samples.mockpolicy.ResultCalculator;
import samples.mockpolicy.SimpleClassWithADependency;

@RunWith(PowerMockRunner.class)
@MockPolicy(MockPolicyExpectationsExample.class)
public class MockPolicyWithExpectationsTest {

	@Test
	public void mockPolicyWithExpectationsWorks() throws Exception {
		final SimpleClassWithADependency tested = new SimpleClassWithADependency();
		Whitebox.setInternalState(tested, new ResultCalculator(5));

		assertEquals(2.0, tested.getResult(), 0.0);

		verifyAll();
	}
}

class MockPolicyExpectationsExample implements PowerMockPolicy {
	public void applyClassLoadingPolicy(MockPolicyClassLoadingSettings settings) {
		settings.addFullyQualifiedNamesOfClassesToLoadByMockClassloader(ResultCalculator.class.getName());
	}

	public void applyInterceptionPolicy(MockPolicyInterceptionSettings settings) {
		final ResultCalculator calculatorMock = createMock(ResultCalculator.class);
		expect(calculatorMock.calculate()).andReturn(2.0);

		replay(calculatorMock);

		Method calculateMethod = Whitebox.getMethod(ResultCalculator.class, "calculate");
		settings.addSubtituteReturnValue(calculateMethod, calculatorMock.calculate());
	}
}

Test that demonstrates simple non-dynamic expectations in a mock policy


/*
Copyright 2017 Rice University

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 edu.rice.cs.caper.bayou.application.api_synthesis_server.synthesis_logging;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.text.DateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * A SynthesisLogger that stores the log message in a local file. Stores log messages as a JSON string using UTF-8 encoding.
 */
public class SynthesisLoggerLocal implements SynthesisLogger {

    /**
     * Place to send application logging information.
     */
    private static final Logger _logger = LogManager.getLogger(SynthesisLoggerLocal.class.getName());

    @Override
    public void log(UUID requestId, String searchCode, Iterable<String> results)
    {
        _logger.debug("entering");

        /*
         * Make the log message to store in local file.
         */
        String logMsg;
        {
            long now = System.currentTimeMillis();

            JSONObject recordObj = new JSONObject();
            recordObj.put("version", "1");
            recordObj.put("requestId", requestId);
            recordObj.put("searchCode", searchCode);
            recordObj.put("logMomentUtc", now);
            recordObj.put("logMomentHuman", DateFormat.getDateTimeInstance().format(new Date(now)));

            JSONArray resultsArray = new JSONArray();
            for (String result : results)
            {
                resultsArray.put(result);
            }

            recordObj.put("results", resultsArray);

            logMsg = recordObj.toString(1);
        }

        String objectKey = requestId.toString() + ".txt";
        try {
            Files.write(new File("logs", objectKey).toPath(), logMsg.getBytes());
        } catch (IOException e) {
            _logger.debug("could not log synth request");
        }

        _logger.debug("exiting");
    }

}

Add class for local logging of synthesis requests


package com.hubspot.jinjava.el.ext;

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

import com.hubspot.jinjava.Jinjava;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
import org.junit.Before;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class CollectionMembershipOperatorTest {
  private JinjavaInterpreter interpreter;

  @Before
  public void setup() {
    interpreter = new Jinjava().newInterpreter();
  }

  @Test
  public void itChecksIfStringContainsChar() {
    assertThat(interpreter.resolveELExpression("'a' in 'pastrami'", -1)).isEqualTo(true);
    assertThat(interpreter.resolveELExpression("'o' in 'pastrami'", -1)).isEqualTo(false);
  }

  @Test
  public void itChecksIfArrayContainsValue() {
    assertThat(interpreter.resolveELExpression("11 in [11, 12, 13]", -1)).isEqualTo(true);
    assertThat(interpreter.resolveELExpression("14 in [11, 12, 13]", -1))
      .isEqualTo(false);
  }

  @Test
  public void itChecksIfDictionaryContainsKey() {
    assertThat(interpreter.resolveELExpression("'a' in {'a': 1, 'b': 2}", -1))
      .isEqualTo(true);
    assertThat(interpreter.resolveELExpression("'c' in {'a': 1, 'b': 2}", -1))
      .isEqualTo(false);
  }
}

Add few tests for CollectionMembershipOperator


package eu.bcvsolutions.idm.acc.service.api;

import eu.bcvsolutions.idm.acc.entity.SysRoleSystem;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentity;
import eu.bcvsolutions.idm.core.model.entity.IdmIdentityRole;

public interface AccAccountManagementService {

	/**
	 * Create or delete accounts for this identity according their roles
	 * @param identity
	 * @return
	 */
	boolean resolveIdentityAccounts(IdmIdentity identity);

	/**
	 * Identity role is deleting, we have to delete linked identity accounts
	 * @param entity
	 */
	void deleteIdentityAccount(IdmIdentityRole entity);

	/**
	 * Return UID for this identity and roleSystem. First will be find and use
	 * transform script from roleSystem attribute. If isn't UID attribute for
	 * roleSystem defined, then will be use default UID attribute handling.
	 *
	 * @param identity
	 * @param roleSystem
	 * @return
	 */
	String generateUID(IdmIdentity identity, SysRoleSystem roleSystem);
}

Create account manager interface for acc module (support new method generate UID)


package com.orientechnologies.orient.core.sql.executor;

import com.orientechnologies.orient.core.db.ODatabaseSession;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.OrientDBConfig;
import org.junit.Assert;
import org.junit.Test;

/** @author Luigi Dell'Aquila (l.dellaquila-(at)-orientdb.com) */
public class ODropDatabaseStatementExecutionTest {

  @Test
  public void testPlain() {
    String dbName = "ODropDatabaseStatementExecutionTest_testPlain";
    OrientDB orientDb = new OrientDB("embedded:./target/", OrientDBConfig.defaultConfig());
    try {
      try (OResultSet result = orientDb.execute("create database " + dbName + " plocal")) {
        Assert.assertTrue(result.hasNext());
        OResult item = result.next();
        Assert.assertEquals(true, item.getProperty("created"));
      }
      Assert.assertTrue(orientDb.exists(dbName));

      ODatabaseSession session = orientDb.open(dbName, "admin", "admin");
      session.close();

      orientDb.execute("drop database " + dbName);
      Assert.assertFalse(orientDb.exists(dbName));
    } finally {
      orientDb.close();
    }
  }

  @Test
  public void testIfExists1() {
    String dbName = "ODropDatabaseStatementExecutionTest_testIfExists1";
    OrientDB orientDb = new OrientDB("embedded:./target/", OrientDBConfig.defaultConfig());
    try {
      try (OResultSet result = orientDb.execute("create database " + dbName + " plocal")) {
        Assert.assertTrue(result.hasNext());
        OResult item = result.next();
        Assert.assertEquals(true, item.getProperty("created"));
      }
      Assert.assertTrue(orientDb.exists(dbName));

      ODatabaseSession session = orientDb.open(dbName, "admin", "admin");
      session.close();

      orientDb.execute("drop database " + dbName + " if exists");
      Assert.assertFalse(orientDb.exists(dbName));
    } finally {
      orientDb.close();
    }
  }

  @Test
  public void testIfExists2() {
    String dbName = "ODropDatabaseStatementExecutionTest_testIfExists2";
    OrientDB orientDb = new OrientDB("embedded:./target/", OrientDBConfig.defaultConfig());
    try {
      orientDb.execute("drop database " + dbName + " if exists");
      Assert.assertFalse(orientDb.exists(dbName));
    } finally {
      orientDb.close();
    }
  }
}

Add test cases for DROP DATABASE statement