/*
 * 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

git-svn-id: 156d99fefae263fe7040597dc4e7b98918e91509@331718 13f79535-47bb-0310-9956-ffa450edef68


/**
 * 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]

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

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

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

[AS7-5053] Allow EJB deployments as OSGi bundles

was: 2a05cfb2ece5bdfe559432cd45faae4c81154f3f


/*
 * 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

JCR-3072: Add a factory for creating new sessions

Add an initial SessionFactory class. Work in progress.

git-svn-id: 02b679d096242155780e1604e997947d154ee04a@1176586 13f79535-47bb-0310-9956-ffa450edef68


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.

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

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

This closes #763


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.

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.

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.

FEA: ItEr75S27PerProjectDashboard


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

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

Test for previously committed strategy

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@464 0d517254-b314-0410-acde-c619094fa49f


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

Test getThreshold of the CategoryClient

git-svn-id: afcf11d89342f630bd950d18a70234a9e277d909@97577 523d945c-050c-4681-91ec-863ad3bb968a


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

Add test for neodatis service manager.

Signed-off-by: Michael Handler <331a76cd0f162b0218893a3dfa4df5a8bf659d1e@fullstop.at>


/*
 * 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

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

Providing only access to this interface rather than handing
out a full AnsiTerminal allows a more controlled access. In
particular, it will be easier to track the state the terminal
will end up in.

--
Change-Id: Ic47b14a045ece2a84113698632a61daf7948c3b4
Reviewed-on: https://bazel-review.googlesource.com/#/c/3013
MOS_MIGRATED_REVID=115533760


/*
 * 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

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

This class logs each request to a local file under logs/. Default is
the S3 logger.


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


package com.evgenii.aescrypto.test;

import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.ImageButton;

import com.evgenii.aescrypto.MainActivity;
import com.evgenii.aescrypto.R;

public class OpenHelpFromMainTests extends ActivityUnitTestCase<MainActivity> {
	public Intent mMainIntent;

	public OpenHelpFromMainTests() {
		super(MainActivity.class);
	}

	@Override
	protected void setUp() throws Exception {
		super.setUp();
		mMainIntent = new Intent(getInstrumentation().getTargetContext(), MainActivity.class);
	}

	@MediumTest
	public void testHelpActivityWasLaunchedWithIntent() {
		startActivity(mMainIntent, null, null);
		final ImageButton openHelpButton = (ImageButton) getActivity().findViewById(
				R.id.helpImageButton);
		openHelpButton.performClick();

		final Intent launchIntent = getStartedActivityIntent();
		assertNotNull("Intent was null", launchIntent);
		assertEquals("com.evgenii.aescrypto.HelpActivity", launchIntent.getComponent()
				.getClassName());
		assertFalse(isFinishCalled());
	}
}

Test for opening help activity

Test for opening help activity


package exporter.examples;

import java.util.Date;

import org.apache.commons.cli.BasicParser;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

// Example of application using CLI
public class DateApp {

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

		// create Options object
		Options options = new Options();

		// add t option
		options.addOption("time", false, "displays current time");
		options.addOption("date", false, "displays current time");

		// There are several implementations to parse command line arguments,
		// the recommended one is the DefaultParser but I can't find it in the
		// library, probably outdated documentation
		BasicParser parser = new BasicParser();
		CommandLine cmd = parser.parse(options, args);

		if (cmd.hasOption("time")) {

			Date date = new Date();
			// current time
			String str = String.format("Current Time : %tT", date);
			System.out.printf(str);

		} else if (cmd.hasOption("date")) {

			Date date = new Date();
			// current date
			String str = String.format("Current Date : %tF", date);
			System.out.printf(str);

		}

	}
}

Add example using command line interface


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

import com.github.aureliano.achmed.command.CommandResponse;
import com.github.aureliano.achmed.resources.properties.PackageProperties;

public class GemPackageManager implements IPackageManager {

	private PackageProperties properties;

	public GemPackageManager() {
		super();
	}

	public CommandResponse install() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public CommandResponse uninstall() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public String latest() {
		throw new UnsupportedOperationException("Method not implemented yet.");
	}

	public void setPackageProperties(PackageProperties properties) {
		this.properties = properties;
	}

	public PackageProperties getPackageProperties() {
		return this.properties;
	}
}

Create template of gem package manager.

Create template of gem package manager.


package org.spongepowered.common.effect.particle;

import org.spongepowered.api.ResourceKey;
import org.spongepowered.api.effect.particle.ParticleOption;
import org.spongepowered.api.effect.particle.ParticleType;
import org.spongepowered.common.SpongeCatalogType;

import java.util.Map;
import java.util.Optional;

public final class NumericalParticleType extends SpongeCatalogType implements ParticleType {

    private final int id;
    private final Map<ParticleOption<?>, Object> defaultOptions;

    public NumericalParticleType(int id, ResourceKey key, Map<ParticleOption<?>, Object> defaultOptions) {
        super(key);
        this.id = id;
        this.defaultOptions = defaultOptions;
    }

    public int getId() {
        return this.id;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <V> Optional<V> getDefaultOption(final ParticleOption<V> option) {
        return Optional.ofNullable((V) this.defaultOptions.get(option));
    }

    @Override
    public Map<ParticleOption<?>, Object> getDefaultOptions() {
        return this.defaultOptions;
    }
}

Implement ParticleType for dumb numerical ID'd particles.


/**
 * Copyright 2013 Netflix, Inc.
 *
 * 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.netflix.servo.publish;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.netflix.servo.Metric;

import java.util.List;

/**
 * An observer that will transform the list of metrics using a given function.
 */
public class MetricTransformObserver implements MetricObserver {
    private final Function<Metric, Metric> transformer;
    private final MetricObserver observer;

    /**
     * Create a new MetricTransformObserver using the given transfomer function
     * @param transformer The function used to transform metrics.
     * @param observer    The MetricObserver that will receive the transfomed metrics.
     */
    public MetricTransformObserver(Function<Metric, Metric> transformer, MetricObserver observer) {
        this.transformer = transformer;
        this.observer = observer;
    }

    @Override
    public void update(List<Metric> metrics) {
        final List<Metric> newMetrics = Lists.newArrayListWithCapacity(metrics.size());
        for (Metric m : metrics) {
            newMetrics.add(transformer.apply(m));
        }
        observer.update(newMetrics);
    }

    @Override
    public String getName() {
        return "MetricTransformObserver";
    }
}

Add an observer that can transfom a list of metrics before forwarding them to the underlying observer


package com.hubspot.singularity.data;

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

import com.google.inject.Inject;
import com.hubspot.singularity.SingularityTestBaseNoDb;

public class InactiveSlaveManagerTest extends SingularityTestBaseNoDb {
  @Inject
  InactiveSlaveManager inactiveSlaveManager;

  @Test
  public void itShouldContainAnInactiveHostWhenHostDeactivated() {
    inactiveSlaveManager.deactiveSlave("localhost");

    Assert.assertTrue(inactiveSlaveManager.getInactiveSlaves().contains("localhost"));
  }

  @Test
  public void itShouldNotContainHostAfterActivatingHost() {
    inactiveSlaveManager.deactiveSlave("localhost");
    inactiveSlaveManager.activateSlave("localhost");

    Assert.assertFalse(inactiveSlaveManager.getInactiveSlaves().contains("localhost"));
  }
}

Add small test suite for inactive slave manager

Add a pair of tests for the the `InactiveSlaveManager`. This is mostly
just to make sure that I get what's going on; in practice the tests
don't do much more than run Curator through a very small trial run.


package tars.commons.events.storage;

import tars.commons.core.Config;
import tars.commons.events.BaseEvent;

/*
 * @@author A0124333U
 * An event where the user changes the Tars Storage Directory/File Path
 */

public class TarsStorageDirectoryChangedEvent extends BaseEvent {

    private final String newFilePath;
    private final Config newConfig;

    public TarsStorageDirectoryChangedEvent (String newFilePath, Config newConfig) {
        this.newFilePath = newFilePath;
        this.newConfig = newConfig;
    }

    public String getNewFilePath() {
        return this.newFilePath;
    }

    public Config getNewConfig() {
        return this.newConfig;
    }

    @Override
    public String toString() {
        return "File Path changed to " + this.newFilePath;
    }

}

Add event to indicate that TARS Storage Directory has changed


/*******************************************************************************
 * Copyright (c) 2017 Pivotal, Inc.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Pivotal, Inc. - initial API and implementation
 *******************************************************************************/
package org.springframework.ide.vscode.boot.java.handlers;

import java.util.Collection;

import org.springframework.ide.vscode.commons.boot.app.cli.SpringBootApp;

public class RunningAppProvider {

	public static final RunningAppProvider DEFAULT = new RunningAppProvider();

	public Collection<SpringBootApp> getAllRunningSpringApps() throws Exception {
		return SpringBootApp.getAllRunningSpringApps().values();
	}

}

Include the running app provider

Include the running app provider


package co.uk.jiveelection.campaign.output.twitter;

import co.uk.jiveelection.campaign.jive.Jive;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;

import static org.mockito.Mockito.verify;

/**
 * Unit Tests for TwitterOutput
 */
@RunWith(MockitoJUnitRunner.class)
public class TwitterOutputTest {

    @Mock
    Jive mockJiveBot;

    @Mock
    Twitter mockTwitter;

    private TwitterOutput twitterOutput;

    @Before
    public void setUp() {
        twitterOutput = new TwitterOutput(mockJiveBot, "jivebot_token", "jivebot_token_secret");
    }

    @Test
    public void should_CallJiveComplete_When_OutputCompletes() {
        // Given
        final Status status = new StatusBuilder()
                .text("tweet tweet")
                .build();

        // When
        twitterOutput.onOutputComplete(status);

        // Then
        verify(mockJiveBot).onJiveComplete(status);
    }

    @Test
    @Ignore
    public void should_UpdateStatus_When_OutputJiveCalled() throws TwitterException {
        // Given
        final String jive = "jive";

        // When
        twitterOutput.outputJive(jive);

        // Then
        verify(mockTwitter).updateStatus(jive);
        // TODO: collaborate with the Twitter object and verify
    }
}

Add unit test for TwitterOutput

Add unit test for TwitterOutput


package com.elmakers.mine.bukkit.action.builtin;

import com.elmakers.mine.bukkit.action.CompoundAction;
import com.elmakers.mine.bukkit.api.action.ActionHandler;
import com.elmakers.mine.bukkit.api.action.CastContext;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.wand.Wand;
import org.bukkit.configuration.ConfigurationSection;

public class CheckManaAction extends CompoundAction {
    private boolean requireNotFull = false;
    private boolean requireEmpty = false;
    private double requireAmount = 0;

    @Override
    public void prepare(CastContext context, ConfigurationSection parameters) {
        super.prepare(context, parameters);
        requireAmount = parameters.getDouble("require_mana", 0);
        requireNotFull = parameters.getBoolean("require_mana_not_full", false);
        requireEmpty = parameters.getBoolean("require_mana_empty", false);
    }

    protected boolean isAllowed(CastContext context) {
        Wand wand = context.getWand();
        if (wand == null) {
            return false;
        }
        double currentMana = wand.getMana();
        if (requireAmount > 0 && currentMana < requireAmount) {
            return false;
        }
        if (requireEmpty && currentMana > 0) {
            return false;
        }
        int manaMax = wand.getManaMax();
        if (requireNotFull && currentMana >= manaMax) {
            return false;
        }
        return true;
    }

    @Override
    public SpellResult step(CastContext context) {
        boolean allowed = isAllowed(context);
        ActionHandler actions = getHandler("actions");
        if (actions == null || actions.size() == 0) {
            return allowed ? SpellResult.CAST : SpellResult.STOP;
        }

        if (!allowed) {
            return SpellResult.NO_TARGET;
        }
        return startActions();
    }

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

Add CheckMana action, for stopping a spell if mana does not meet some requirements (empty, full, certain amount)


package org.springframework.security.ui;

import org.springframework.core.Ordered;

/**
 * Stores the default order numbers of all Spring Security filters for use in configuration.
 *
 * @author luke
 * @version $Id$
 */
public class FilterChainOrderUtils {
    /**
     * The first position at which a Spring Security filter will be found. Any filter with an order less than this will
     * be guaranteed to be placed before the Spring Security filters in the stack.
     */
    public static final int FILTER_CHAIN_FIRST = Ordered.HIGHEST_PRECEDENCE + 1000;
    private static final int INTERVAL = 100;

    public static final int CHANNEL_PROCESSING_FILTER_ORDER            = FILTER_CHAIN_FIRST + INTERVAL;
    public static final int CONCURRENT_SESSION_FILTER_ORDER            = FILTER_CHAIN_FIRST + INTERVAL * 2;
    public static final int HTTP_SESSION_CONTEXT_FILTER_ORDER          = FILTER_CHAIN_FIRST + INTERVAL * 3;
    public static final int LOGOUT_FILTER_ORDER                        = FILTER_CHAIN_FIRST + INTERVAL * 4;
    public static final int AUTH_PROCESSING_FILTER_ORDER               = FILTER_CHAIN_FIRST + INTERVAL * 5;
    public static final int CAS_PROCESSING_FILTER_ORDER                = FILTER_CHAIN_FIRST + INTERVAL * 5;
    public static final int LOGIN_PAGE_FILTER_ORDER                    = FILTER_CHAIN_FIRST + INTERVAL * 6;
    public static final int BASIC_PROCESSING_FILTER_ORDER              = FILTER_CHAIN_FIRST + INTERVAL * 7;
    public static final int SECURITY_CONTEXT_HOLDER_AWARE_FILTER_ORDER = FILTER_CHAIN_FIRST + INTERVAL * 8;
    public static final int REMEMBER_ME_FILTER_ORDER                   = FILTER_CHAIN_FIRST + INTERVAL * 9;
    public static final int ANON_PROCESSING_FILTER_ORDER               = FILTER_CHAIN_FIRST + INTERVAL * 10;
    public static final int SWITCH_USER_FILTER_ORDER                   = FILTER_CHAIN_FIRST + INTERVAL * 11;
    public static final int EXCEPTION_TRANSLATION_FILTER_ORDER         = FILTER_CHAIN_FIRST + INTERVAL * 12;
    public static final int FILTER_SECURITY_INTERCEPTOR_ORDER          = FILTER_CHAIN_FIRST + INTERVAL * 13;

}

Store the default order values of security filters.


package com.example.butterknife;

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

import static org.fest.assertions.api.ANDROID.assertThat;
import static org.robolectric.Robolectric.shadowOf;

@RunWith(RobolectricTestRunner.class)
public class SimpleActivityTest {
  @Test public void verifyContentViewInjection() {
    SimpleActivity activity = new SimpleActivity();
    shadowOf(activity).callOnCreate(null);

    assertThat(activity.title).hasId(R.id.title);
    assertThat(activity.subtitle).hasId(R.id.subtitle);
    assertThat(activity.hello).hasId(R.id.hello);
    assertThat(activity.listOfThings).hasId(R.id.list_of_things);
    assertThat(activity.footer).hasId(R.id.footer);
  }
}

Add test to verify activity injection works.


/*
 * Copyright 2016 Shredder121.
 *
 * 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.shredder121.gh_event_api.model;

import static org.hamcrest.Matchers.is;

public class TeamSerializationTest extends AbstractSerializationTest<Team> {

    private static final String SAMPLE_TEAM
            = "{\n"
            + "  \"name\": \"Hackers\",\n"
            + "  \"id\": 1919074,\n"
            + "  \"slug\": \"hackers\",\n"
            + "  \"description\": \"All the members\",\n"
            + "  \"permission\": \"pull\",\n"
            + "  \"privacy\": \"closed\",\n"
            + "  \"url\": \"https://api.github.com/teams/1919074\",\n"
            + "  \"members_url\": \"https://api.github.com/teams/1919074/members{/member}\",\n"
            + "  \"repositories_url\": \"https://api.github.com/teams/1919074/repos\"\n"
            + "}";

    public TeamSerializationTest() {
        super(Team.class);
    }

    @Override
    protected String getSample() {
        return SAMPLE_TEAM;
    }

    @Override
    protected void checkDeserialized(Team team) {
        errorCollector.checkThat(team.getName(), is("Hackers"));

        errorCollector.checkThat(team.getSlug(), is("hackers"));

        errorCollector.checkThat(team.getDescription(), is("All the members"));

        errorCollector.checkThat(team.getPermission(), is("pull"));
    }
}

Add serialization test for Team

Add serialization test for Team


package de.retest.recheck.review.workers;

import static de.retest.recheck.configuration.ProjectConfiguration.RECHECK_IGNORE;
import static de.retest.recheck.configuration.ProjectConfiguration.RECHECK_IGNORE_JSRULES;
import static de.retest.recheck.configuration.ProjectConfiguration.RETEST_PROJECT_CONFIG_FOLDER;
import static de.retest.recheck.configuration.ProjectConfiguration.RETEST_PROJECT_ROOT;
import static org.assertj.core.api.Assertions.assertThat;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;

import de.retest.recheck.review.GlobalIgnoreApplier;
import de.retest.recheck.review.counter.NopCounter;
import de.retest.recheck.util.junit.jupiter.SystemProperty;

class LoadShouldIgnoreWorkerTest {

	Path defaultIgnoreFile;

	@BeforeEach
	void setUp( @TempDir final Path temp ) throws Exception {
		final Path configFolder = temp.resolve( RETEST_PROJECT_CONFIG_FOLDER );
		Files.createDirectory( configFolder );

		final Path jsIgnoreFile = configFolder.resolve( RECHECK_IGNORE_JSRULES );
		Files.createFile( jsIgnoreFile );

		defaultIgnoreFile = configFolder.resolve( RECHECK_IGNORE );
		Files.copy( Paths.get( "src/main/resources/default-" + RECHECK_IGNORE ), defaultIgnoreFile );

		System.setProperty( RETEST_PROJECT_ROOT, configFolder.toString() );
	}

	@Test
	@SystemProperty( key = RETEST_PROJECT_ROOT )
	void loaded_ignore_file_should_match_default_ignore_file() throws Exception {
		final LoadShouldIgnoreWorker cut = new LoadShouldIgnoreWorker( NopCounter.getInstance() );
		final GlobalIgnoreApplier globalIgnoreApplier = cut.load();
		final List<String> loadedIgnoreFileLines = globalIgnoreApplier.persist().getIgnores().stream() //
				.map( Object::toString ) //
				.collect( Collectors.toList() );

		final List<String> defaultIgnoreFileLines = Files.readAllLines( defaultIgnoreFile );
		assertThat( loadedIgnoreFileLines ).isEqualTo( defaultIgnoreFileLines );
	}

}

Add tests that shows the problem

Add tests that shows the problem

The empty lines are missing, which causes ugly diffs when you apply from e.g. review.


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

package org.tinylog.runtime;

/**
 * Representation for a defined stack trace element in the current stack trace.
 */
public interface StackTraceLocation {

	/**
	 * Adjusts the stack trace location for passing it to a method call.
	 *
	 * <p>
	 *     Whenever a stack trace location should be passed to another method, the result of this methods has to passed
	 *     instead of the original stack location object. The reason is that every method call increases the stack trace
	 *     by pushing an addition stack trace element.
	 * </p>
	 *
	 * @return Stack trace location that can be passed to another method
	 */
	StackTraceLocation push();

	/**
	 * Retrieved the fully-qualified class name of the caller.
	 *
	 * @return The fully-qualified class name of the caller
	 */
	String getCallerClassName();

	/**
	 * Retrieved the complete stack trace element of the caller.
	 *
	 * @return The complete stack trace element of the caller
	 */
	StackTraceElement getCallerStackTraceElement();

}

Add interface for stack trace locations

Add interface for stack trace locations


package com.fasterxml.jackson.databind.mixins;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.BaseMapTest;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TestMixinInheritance
    extends BaseMapTest
{
    // [Issue-14]
    static class Beano {
        public int ido = 42;
        public String nameo = "Bob";
    }

    static class BeanoMixinSuper {
        @JsonProperty("name")
        public String nameo;
    }

    static class BeanoMixinSub extends BeanoMixinSuper {
        @JsonProperty("id")
        public int ido;
    }

    public void testMixinInheritance() throws IOException
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.addMixInAnnotations(Beano.class, BeanoMixinSub.class);
        Map<String,Object> result;
        result = writeAndMap(mapper, new Beano());
        assertEquals(2, result.size());
        assertTrue(result.containsKey("id"));
        assertTrue(result.containsKey("name"));
    }
}

Add a unit test for [Issue-14]; minor javadoc improvements


/*
 * 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.beam.sdk.testing;

import org.apache.beam.sdk.transforms.ParDo;

/**
 * Category tag for validation tests which utilize stateful {@link ParDo}.
 */
public interface UsesStatefulParDo {}

Add JUnit category for stateful ParDo tests


/**
 * 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.hadoop.hive.metastore;

import org.apache.hadoop.hive.conf.HiveConf;

public class TestRemoteHiveMetaStore extends TestHiveMetaStore {
  private static final String METASTORE_PORT = "29083";
  private static boolean isServerRunning = false;

  private static class RunMS implements Runnable {

      @Override
      public void run() {
        System.out.println("Running metastore!");
        String [] args = new String [1];
        args[0] = METASTORE_PORT;
        HiveMetaStore.main(args);
      }

    }

  @Override
  protected void setUp() throws Exception {
    super.setUp();
    if(isServerRunning) {
      return;
    }
    Thread t = new Thread(new RunMS());
    t.start();

    // Wait a little bit for the metastore to start. Should probably have
    // a better way of detecting if the metastore has started?
    Thread.sleep(5000);

    // hive.metastore.local should be defined in HiveConf
    hiveConf.set("hive.metastore.local", "false");
    hiveConf.setVar(HiveConf.ConfVars.METASTOREURIS, "thrift://localhost:" + METASTORE_PORT);
    hiveConf.setIntVar(HiveConf.ConfVars.METATORETHRIFTRETRIES, 3);

    client = new HiveMetaStoreClient(hiveConf);
    isThriftClient = true;

    // Now you have the client - run necessary tests.
    isServerRunning = true;
  }

}

Add TestRemoteHiveMetastor removed by mistake

git-svn-id: 1dd3918e4fc7dfd96526d8ea96bfafeec5472371@999761 13f79535-47bb-0310-9956-ffa450edef68


package leetcode.maximal_square;

public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix.length == 0 || matrix[0].length == 0) return 0;
        int h = matrix.length, w = matrix[0].length;
        int[][] maxSqrSize = new int[h][w];
        int max = 0;
        for(int i = 0; i < h; i++){
            for(int j = 0; j < w; j++){
                if(matrix[i][j] == '1'){
                    int m = 1;
                    if(i > 0 && j > 0){
                        m = Math.min(maxSqrSize[i - 1][j], maxSqrSize[i][j - 1]);
                        if(matrix[i - m][j - m] == '1'){
                            m++;
                        }
                    }
                    maxSqrSize[i][j] = m;
                    max = Math.max(m, max);
                }
            }
        }
        return max * max;
    }
}

Add java solution for 221. Maximal Square

221. Maximal Square: https://leetcode.com/problems/maximal-square/


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

package com.android.webview.chromium;

/**
 * Helper class used to fix up resource ids.
 * This is mostly a copy of the code in frameworks/base/core/java/android/app/LoadedApk.java.
 * TODO: Remove if a cleaner mechanism is provided (either public API or AAPT is changed to generate
 * this code).
 */
class ResourceRewriter {
    /**
     * Rewrite the R 'constants' for the WebView library apk.
     */
    public static void rewriteRValues(final int packageId) {
        // TODO: We should use jarjar to remove the redundant R classes here, but due
        // to a bug in jarjar it's not possible to rename classes with '$' in their name.
        // See b/15684775.
        com.android.webview.chromium.R.onResourcesLoaded(packageId);
        org.chromium.android_webview.R.onResourcesLoaded(packageId);
        org.chromium.content.R.onResourcesLoaded(packageId);
        org.chromium.ui.R.onResourcesLoaded(packageId);
    }
}

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

package com.android.webview.chromium;

/**
 * Helper class used to fix up resource ids.
 */
class ResourceRewriter {
    /**
     * Rewrite the R 'constants' for the WebView library apk.
     */
    public static void rewriteRValues(final int packageId) {
        // This list must be kept up to date to include all R classes depended on directly or
        // indirectly by android_webview_java.
        // TODO(torne): find a better way to do this, http://crbug.com/492166.
        com.android.webview.chromium.R.onResourcesLoaded(packageId);
        org.chromium.android_webview.R.onResourcesLoaded(packageId);
        org.chromium.components.web_contents_delegate_android.R.onResourcesLoaded(packageId);
        org.chromium.content.R.onResourcesLoaded(packageId);
        org.chromium.ui.R.onResourcesLoaded(packageId);
    }
}

Add missing R class to WebView resource rewriting.

We weren't rewriting the resources for web_contents_delegate_android,
resulting in crashes any time a resource was loaded by that component
(e.g. popup bubbles for HTML form validation failures). Add it to the
list and also clean up outdated comments here that refer to previous
versions of this code. Add a TODO to track finding a better way to do
this which is less fragile.

BUG=490826

Review URL: https://codereview.chromium.org/1154853005

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#331356}