package org.hamcrest.text;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsNot.not;
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
import static org.hamcrest.text.IsEmptyString.emptyString;

import org.hamcrest.AbstractMatcherTest;
import org.hamcrest.Matcher;

public class IsEmptyStringTest extends AbstractMatcherTest {

  @Override
  protected Matcher<?> createMatcher() {
    return emptyOrNullString();
  }

  public void testEmptyOrNullIsNull() {
    assertThat(null, emptyOrNullString());
  }

  public void testEmptyIsNotNull() {
    assertThat(null, not(emptyString()));
  }

  public void testMatchesEmptyString() {
    assertMatches("empty string", emptyString(), "");
    assertMatches("empty string", emptyOrNullString(), "");
  }

  public void testDoesNotMatchNonEmptyString() {
    assertDoesNotMatch("non empty string", emptyString(), "a");
  }

  public void testHasAReadableDescription() {
    assertDescription("an empty string", emptyString());
    assertDescription("(null or an empty string)", emptyOrNullString());
  }
}

package org.hamcrest.text;

import static org.hamcrest.AbstractMatcherTest.assertDescription;
import static org.hamcrest.AbstractMatcherTest.assertDoesNotMatch;
import static org.hamcrest.AbstractMatcherTest.assertMatches;
import static org.hamcrest.AbstractMatcherTest.assertMismatchDescription;
import static org.hamcrest.AbstractMatcherTest.assertNullSafe;
import static org.hamcrest.AbstractMatcherTest.assertUnknownTypeSafe;
import static org.hamcrest.text.IsEmptyString.emptyOrNullString;
import static org.hamcrest.text.IsEmptyString.emptyString;

import org.hamcrest.Matcher;
import org.junit.Test;

public final class IsEmptyStringTest {

    @Test public void
    copesWithNullsAndUnknownTypes() {
        Matcher<String> matcher = emptyOrNullString();

        assertNullSafe(matcher);
        assertUnknownTypeSafe(matcher);
    }

    @Test public void
    matchesNullAppropriately() {
        assertMatches("didn't match", emptyOrNullString(), null);
        assertDoesNotMatch("matched unexpectedly", emptyString(), null);
    }

    @Test public void
    matchesEmptyString() {
        assertMatches("didn't match", emptyOrNullString(), "");
        assertMatches("didn't match", emptyString(), "");
    }

    @Test public void
    doesNotmatchFilledString() {
        assertDoesNotMatch("matched unexpectedly", emptyOrNullString(), "a");
        assertDoesNotMatch("matched unexpectedly", emptyString(), "a");
    }

    @Test public void
    describesItself() {
        assertDescription("an empty string", emptyString());
        assertDescription("(null or an empty string)", emptyOrNullString());
    }

    @Test public void
    describesAMismatch() {
        assertMismatchDescription("was \"a\"", emptyString(), "a");
        assertMismatchDescription("was \"a\"", emptyOrNullString(), "a");
    }
}

Convert test to JUnit4 (and add mismatch description tests) in preparation for enhancement.


package io.dropwizard.logging;

import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;

import java.util.regex.Pattern;

import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;

/**
 * A {@link RootCauseFirstThrowableProxyConverter} that prefixes stack traces with {@code !}.
 */
public class PrefixedRootCauseFirstThrowableProxyConverter
        extends RootCauseFirstThrowableProxyConverter {

    private static final String CAUSING = PREFIX + "Causing:";
    private static final Pattern CAUSING_PATTERN = Pattern.compile(
            "^" + Pattern.quote(PrefixedThrowableProxyConverter.PREFIX) + "Wrapped by:",
            Pattern.MULTILINE);

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        final String prefixed = PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX);
        return CAUSING_PATTERN.matcher(prefixed).replaceAll(CAUSING);
    }
}

package io.dropwizard.logging;

import ch.qos.logback.classic.pattern.RootCauseFirstThrowableProxyConverter;
import ch.qos.logback.classic.spi.IThrowableProxy;

import java.util.regex.Pattern;

import static io.dropwizard.logging.PrefixedThrowableProxyConverter.*;

/**
 * A {@link RootCauseFirstThrowableProxyConverter} that prefixes stack traces with {@code !}.
 */
public class PrefixedRootCauseFirstThrowableProxyConverter
        extends RootCauseFirstThrowableProxyConverter {

    private static final String CAUSING = PREFIX + "Causing:";
    private static final Pattern CAUSING_PATTERN = Pattern.compile("^" + Pattern.quote(PREFIX) + "Wrapped by:", Pattern.MULTILINE);

    @Override
    protected String throwableProxyToString(IThrowableProxy tp) {
        final String prefixed = PATTERN.matcher(super.throwableProxyToString(tp)).replaceAll(PREFIX);
        return CAUSING_PATTERN.matcher(prefixed).replaceAll(CAUSING);
    }
}

Remove a needless static reference

Remove a needless static reference

The static method has been imported, no need to explicitly name the
class.


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

package com.linecorp.bot.model.manageaudience;

import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;

public enum AudienceGroupJobFailedType {
    /**
     * Internal server error.
     */
    INTERNAL_ERROR,
    @JsonEnumDefaultValue
    UNKNOWN
}

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

package com.linecorp.bot.model.manageaudience;

import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;

public enum AudienceGroupJobFailedType {
    /**
     * Internal server error.
     */
    INTERNAL_ERROR,
    /**
     * Audience is insufficient.
     */
    AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT,
    @JsonEnumDefaultValue
    UNKNOWN
}

Add Audience group job failed type: AUDIENCE_GROUP_AUDIENCE_INSUFFICIENT


package com.osdu.model.dto;

import com.google.cloud.firestore.annotation.ServerTimestamp;
import java.util.Date;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class SrnToRecordDto {

  String recordId;
  String srn;
  @ServerTimestamp
  Date created;

}

package com.osdu.model.dto;

import com.google.cloud.firestore.annotation.ServerTimestamp;
import java.util.Date;
import lombok.Data;

@Data
public class SrnToRecordDto {

  String recordId;
  String srn;
  @ServerTimestamp
  Date created;

}

Fix RuntimeException for Firestore entity.


package com.danielflower.apprunner.runners;

import com.danielflower.apprunner.Config;
import org.apache.commons.exec.CommandLine;
import org.apache.maven.shared.invoker.InvocationRequest;

import javax.annotation.Nullable;
import java.util.Map;

public interface HomeProvider extends CommandLineProvider {
    HomeProvider default_java_home = new HomeProvider() {
        public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; }

        public CommandLine commandLine(@Nullable Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); }
    };

    InvocationRequest mungeMavenInvocationRequest(InvocationRequest request);
}

package com.danielflower.apprunner.runners;

import com.danielflower.apprunner.Config;
import org.apache.commons.exec.CommandLine;
import org.apache.maven.shared.invoker.InvocationRequest;

import javax.annotation.Nullable;
import java.util.Map;

public interface HomeProvider extends CommandLineProvider {
    HomeProvider default_java_home = new HomeProvider() {
        public InvocationRequest mungeMavenInvocationRequest(InvocationRequest request) { return request; }

        public CommandLine commandLine(Map<String, String> envVarsForApp) { return new CommandLine(Config.javaExecutableName()); }
    };

    InvocationRequest mungeMavenInvocationRequest(InvocationRequest request);
}

Remove Nullable annotation to avoid build warning


package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
	BREEDING,
	BUILD_IRONGOLEM,
	BUILD_SNOWMAN,
	BUILD_WITHER,
	/**
	 * Deprecated as of 1.14, no longer used.
	 */
	CHUNK_GEN,
	/**
	 * Spawned by plugins
	 */
	CUSTOM,
	/**
	 * Missing spawn reason
	 */
	DEFAULT,
	/**
	 * The kind of egg you throw
	 */
	EGG,
	JOCKEY,
	LIGHTNING,
	NATURAL,
	REINFORCEMENTS,
	SHOULDER_ENTITY,
	SLIME_SPLIT,
	SPAWNER,
	SPAWNER_EGG,
	VILLAGE_DEFENSE,
	VILLAGE_INVASION,
	NETHER_PORTAL,
	DISPENSE_EGG,
	INFECTION,
	CURED,
	OCELOT_BABY,
	SILVERFISH_BLOCK,
	MOUNT,
	TRAP,
	ENDER_PEARL,
	DROWNED,
}

package com.laytonsmith.abstraction.enums;

import com.laytonsmith.annotations.MEnum;

@MEnum("com.commandhelper.SpawnReason")
public enum MCSpawnReason {
	BREEDING,
	BUILD_IRONGOLEM,
	BUILD_SNOWMAN,
	BUILD_WITHER,
	/**
	 * Deprecated as of 1.14, no longer used.
	 */
	CHUNK_GEN,
	/**
	 * Spawned by plugins
	 */
	CUSTOM,
	/**
	 * Missing spawn reason
	 */
	DEFAULT,
	/**
	 * The kind of egg you throw
	 */
	EGG,
	JOCKEY,
	LIGHTNING,
	NATURAL,
	REINFORCEMENTS,
	SHOULDER_ENTITY,
	SLIME_SPLIT,
	SPAWNER,
	SPAWNER_EGG,
	VILLAGE_DEFENSE,
	VILLAGE_INVASION,
	NETHER_PORTAL,
	DISPENSE_EGG,
	INFECTION,
	CURED,
	OCELOT_BABY,
	SILVERFISH_BLOCK,
	MOUNT,
	TRAP,
	ENDER_PEARL,
	DROWNED,
	SHEARED
}

Add missing SHEARED spawn reason

Add missing SHEARED spawn reason


package by.triumgroup.recourse.document.model.provider.impl;

import by.triumgroup.recourse.document.model.provider.ContentProvider;
import by.triumgroup.recourse.entity.dto.Student;
import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark;

import java.util.*;
import java.util.stream.Collectors;

public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> {
    @Override
    public String createTitle(Student mainEntity) {
        return mainEntity.getName() + " " + mainEntity.getSurname();
    }

    @Override
    public String createFilename(Student user) {
        return String.format("%s_%s_profile", user.getName(), user.getSurname());
    }

    @Override
    public Map<String, String> createSubtitles(Student mainEntity) {
        return new HashMap<String, String>(){{
            put("Total average mark", mainEntity.getTotalAverageMark().toString());
        }};
    }

    @Override
    public List<String> getHeaders() {
        return Arrays.asList("Title", "Average mark");
    }

    @Override
    public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) {
        return "Courses";
    }

    @Override
    public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) {
        return courses.stream()
                .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString()))
                .collect(Collectors.toList());
    }
}

package by.triumgroup.recourse.document.model.provider.impl;

import by.triumgroup.recourse.document.model.provider.ContentProvider;
import by.triumgroup.recourse.entity.dto.Student;
import by.triumgroup.recourse.entity.dto.StudentCourseAverageMark;

import java.util.*;
import java.util.stream.Collectors;

public class StudentProfileContentProvider implements ContentProvider<Student, StudentCourseAverageMark> {
    @Override
    public String createTitle(Student mainEntity) {
        return mainEntity.getFullName();
    }

    @Override
    public String createFilename(Student user) {
        return String.format("%s_profile", user.getFullName());
    }

    @Override
    public Map<String, String> createSubtitles(Student mainEntity) {
        return new HashMap<String, String>(){{
            put("Total average mark", mainEntity.getTotalAverageMark().toString());
        }};
    }

    @Override
    public List<String> getHeaders() {
        return Arrays.asList("Title", "Average mark");
    }

    @Override
    public String createTableTitle(Student user, Collection<StudentCourseAverageMark> courses) {
        return "Courses";
    }

    @Override
    public List<List<String>> createRows(Collection<StudentCourseAverageMark> courses) {
        return courses.stream()
                .map(studentCourse -> Arrays.asList(studentCourse.getTitle(), studentCourse.getAverageMark().toString()))
                .collect(Collectors.toList());
    }
}

Replace name, surname concatenation with getFullName


package org.liveontologies.protege.justification.proof.service;

import java.util.Set;

import org.liveontologies.puli.InferenceJustifier;
import org.liveontologies.puli.Proof;
import org.semanticweb.owlapi.model.OWLAxiom;

public interface JustificationCompleteProof<C> extends Proof<C>, InferenceJustifier<C, Set<? extends OWLAxiom>> {

	C getGoal();
}

package org.liveontologies.protege.justification.proof.service;

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

import java.util.Set;

import org.liveontologies.puli.InferenceJustifier;
import org.liveontologies.puli.Proof;
import org.semanticweb.owlapi.model.OWLAxiom;

public interface JustificationCompleteProof<C> extends Proof<C>, InferenceJustifier<C, Set<? extends OWLAxiom>> {

	C getGoal();
}

Update file header with license information


package org.torquebox.stomp.component;

import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;

public class DirectStompletComponent implements Stomplet {

    public DirectStompletComponent(XAStompletComponent component) {
        this.component = component;
    }

    @Override
    public void initialize(StompletConfig config) throws StompException {
        this.component._callRubyMethod( "configure", config );
    }

    @Override
    public void destroy() throws StompException {
        this.component._callRubyMethod( "destroy" );
    }

    @Override
    public void onMessage(StompMessage message) throws StompException {
        this.component._callRubyMethod( "on_message", message );
    }

    @Override
    public void onSubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethod( "on_subscribe", subscriber );
    }

    @Override
    public void onUnsubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethod( "on_unsubscribe", subscriber );
    }

    private XAStompletComponent component;

}

package org.torquebox.stomp.component;

import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomplet.Stomplet;
import org.projectodd.stilts.stomplet.StompletConfig;
import org.projectodd.stilts.stomplet.Subscriber;

public class DirectStompletComponent implements Stomplet {

    public DirectStompletComponent(XAStompletComponent component) {
        this.component = component;
    }

    @Override
    public void initialize(StompletConfig config) throws StompException {
        this.component._callRubyMethodIfDefined( "configure", config );
    }

    @Override
    public void destroy() throws StompException {
        this.component._callRubyMethodIfDefined( "destroy" );
    }

    @Override
    public void onMessage(StompMessage message) throws StompException {
        this.component._callRubyMethodIfDefined( "on_message", message );
    }

    @Override
    public void onSubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethodIfDefined( "on_subscribe", subscriber );
    }

    @Override
    public void onUnsubscribe(Subscriber subscriber) throws StompException {
        this.component._callRubyMethodIfDefined( "on_unsubscribe", subscriber );
    }

    private XAStompletComponent component;

}

Call the methods only if they exist.

Call the methods only if they exist.


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

@ValueAnnotation("Branch One")
package given.reflect.root.branch1.foo;

import given.reflect.annotation.ValueAnnotation;

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

/**
 * This package is annotated.
 * One of its {@linkplain given.reflect.root.branch1.foo.sub1 sub-packages} is also annotated
 * with the same type, but a different value.
 */
@ValueAnnotation("Branch One")
package given.reflect.root.branch1.foo;

import given.reflect.annotation.ValueAnnotation;

Improve documentation of the test env.

Improve documentation of the test env.


package utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import models.Project;
import models.User;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CacheStore
 */
public class CacheStore {
    public static Map<String, User> sessionMap = new ConcurrentHashMap<>();
    public static Map<String, Project> projectMap = new HashMap<>();
    public static final int MAXIMUM_CACHED_MARKDOWN_ENTRY = 10000;

    /**
     * Introduced to using LRU Cache. It depends on google Guava.
     * <p>
     * Size expectation: 500 char-per-item * 3 byte * 10000 rendered-entry % 70 gzipped = ~10Mb
     */
    public static LoadingCache<Integer, byte[]> renderedMarkdown = CacheBuilder.newBuilder()
            .maximumSize(MAXIMUM_CACHED_MARKDOWN_ENTRY)
            .build(
                    new CacheLoader<Integer, byte[]>() {
                        public Map<Integer, byte[]> renderedMarkdownMap = new ConcurrentHashMap<>();

                        public byte[] load(@Nonnull Integer key) {
                            return renderedMarkdownMap.get(key);
                        }
                    });
}

package utils;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import models.Project;
import models.User;

import javax.annotation.Nonnull;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * CacheStore
 */
public class CacheStore {
    public static Map<String, User> sessionMap = new ConcurrentHashMap<>();
    public static Map<String, Project> projectMap = new HashMap<>();
    public static final int MAXIMUM_CACHED_MARKDOWN_ENTRY = 10000;

    /**
     * Introduced to using LRU Cache. It depends on google Guava.
     * <p>
     * Size expectation: 500 char-per-item * 3 byte * 10000 rendered-entry % 70 gzipped = ~10Mb
     */
    public static LoadingCache<Integer, byte[]> renderedMarkdown = CacheBuilder.newBuilder()
            .maximumSize(MAXIMUM_CACHED_MARKDOWN_ENTRY)
            .build(
                    new CacheLoader<Integer, byte[]>() {
                        public byte[] load(@Nonnull Integer key) {
                            return null;
                        }
                    });
}

fix: Remove redundant codes from cache loader


package com.groupon.seleniumgridextras.tasks;

import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.sun.net.httpserver.HttpServer;

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

import java.net.InetSocketAddress;

import static org.junit.Assert.assertEquals;

public class StopGridTest {

  private StopGrid task;
  private HttpServer server;
  private final int port = 9999;

  @Before
  public void setUp() throws Exception {
    task = new StopGrid();
    server = HttpServer.create(new InetSocketAddress(port), 0);
    server.setExecutor(null);
    server.start();
  }

  @After
  public void tearDown() throws Exception {
    server.stop(0);
  }

  @Test
  public void testGetWindowsCommand() throws Exception {
    assertEquals(
        "",task.getWindowsCommand("5555"));
  }

  @Test
  public void testGetLinuxCommand() throws Exception {
    String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid();
    assertEquals(expected, task.getLinuxCommand(port));

    final String portToNeverBeFound = "4444444444444444444444444444444";
    assertEquals("", task.getLinuxCommand(portToNeverBeFound));
  }

}

package com.groupon.seleniumgridextras.tasks;

import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.sun.net.httpserver.HttpServer;

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

import java.net.InetSocketAddress;

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

public class StopGridTest {

  private StopGrid task;
  private HttpServer server;
  private final int port = 9999;

  @Before
  public void setUp() throws Exception {
    task = new StopGrid();
    server = HttpServer.create(new InetSocketAddress(port), 0);
    server.setExecutor(null);
    server.start();
  }

  @After
  public void tearDown() throws Exception {
    server.stop(0);
  }

  @Test
  public void testGetWindowsCommand() throws Exception {
    assertTrue(task.getWindowsCommand("5555").contains("taskkill -F -IM "));
  }

  @Test
  public void testGetLinuxCommand() throws Exception {
    String expected = "kill -9 " + RuntimeConfig.getOS().getCurrentPid();
    assertEquals(expected, task.getLinuxCommand(port));

    final String portToNeverBeFound = "4444444444444444444444444444444";
    assertEquals("", task.getLinuxCommand(portToNeverBeFound));
  }

}

Improve the stop grid command test

Improve the stop grid command test


/*
 * Copyright (c) 2014 aleon GmbH.
 * 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:
 *    Markus Rathgeb - initial API and implementation and/or initial documentation
 */
package eu.aleon.aleoncean.packet.radio.userdata;

import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;

/**
 *
 * @author Markus Rathgeb <maggu2810@gmail.com>
 */
public class UserData4BS extends UserData {

    public static final int DATA_LENGTH = 4;

    public UserData4BS() {
        super(DATA_LENGTH);
    }

    public UserData4BS(final byte[] data) {
        super(data);
        assert data.length == DATA_LENGTH;
    }

    public boolean isTeachIn() {
        return isTeachIn(getUserData());
    }

    public static boolean isTeachIn(final byte[] userData) {
        return getDataBit(userData, 0, 3) == 0;
    }

    @Override
    public RadioPacket4BS generateRadioPacket() {
        final RadioPacket4BS packet = new RadioPacket4BS();
        packet.setUserDataRaw(getUserData());
        return packet;
    }

}

/*
 * Copyright (c) 2014 aleon GmbH.
 * 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:
 *    Markus Rathgeb - initial API and implementation and/or initial documentation
 */
package eu.aleon.aleoncean.packet.radio.userdata;

import eu.aleon.aleoncean.packet.radio.RadioPacket4BS;

/**
 *
 * @author Markus Rathgeb <maggu2810@gmail.com>
 */
public class UserData4BS extends UserData {

    public static final int DATA_LENGTH = 4;

    private static final int TEACH_IN_DB = 0;
    private static final int TEACH_IN_BIT = 3;

    public static boolean isTeachIn(final byte[] userData) {
        return getDataBit(userData, TEACH_IN_DB, TEACH_IN_BIT) == 0;
    }

    public UserData4BS() {
        super(DATA_LENGTH);
    }

    public UserData4BS(final byte[] data) {
        super(data);
        assert data.length == DATA_LENGTH;
    }

    public boolean isTeachIn() {
        return isTeachIn(getUserData());
    }

    public void setTeachIn(final boolean teachIn) {
        setDataBit(TEACH_IN_DB, TEACH_IN_BIT, teachIn ? 0 : 1);
    }

    @Override
    public RadioPacket4BS generateRadioPacket() {
        final RadioPacket4BS packet = new RadioPacket4BS();
        packet.setUserDataRaw(getUserData());
        return packet;
    }

}

Add function to modify teach-in bit

Add function to modify teach-in bit


/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertFalse("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

Revert "fail test again to check email notification"

This reverts commit c58395304e61c5afcc9817d5e5254209d6223487.


package com.ecchilon.sadpanda.api;

import java.util.List;

import com.ecchilon.sadpanda.overview.GalleryEntry;
import com.google.inject.Inject;
import lombok.Getter;
import rx.Observable;

public class GalleryScroller {

	private final GalleryClient galleryClient;

	@Getter
	private boolean isLoading = false;
	@Getter
	private boolean hasMoreItems = true;

	@Inject
	GalleryScroller(GalleryClient galleryClient) {
		this.galleryClient = galleryClient;
	}

	public Observable<List<GalleryEntry>> loadPage(String base, int page) {
		isLoading = true;
		return galleryClient.getGalleryIndex(base, page).doOnNext(galleryEntries -> {
			isLoading = false;
			if (galleryEntries.size() < DataLoader.GALLERIES_PER_PAGE) {
				hasMoreItems = false;
			}
		});
	}
}

package com.ecchilon.sadpanda.api;

import java.util.List;

import com.ecchilon.sadpanda.overview.GalleryEntry;
import com.google.inject.Inject;
import lombok.Getter;
import rx.Observable;

public class GalleryScroller {

	private final GalleryClient galleryClient;

	@Getter
	private boolean isLoading = false;
	@Getter
	private boolean hasMoreItems = true;

	@Inject
	GalleryScroller(GalleryClient galleryClient) {
		this.galleryClient = galleryClient;
	}

	public Observable<List<GalleryEntry>> loadPage(String base, int page) {
		isLoading = true;
		return galleryClient.getGalleryIndex(base, page).doOnNext(galleryEntries -> {
			isLoading = false;
			if (galleryEntries.isEmpty()) {
				hasMoreItems = false;
			}
		});
	}
}

Fix early stop of gallery

Fix early stop of gallery

Sometimes it returns an item less than expected (due to expunging for example). Assume it's only complete when you get a completely empty collection


package network.thunder.core.communication;

import network.thunder.core.communication.objects.subobjects.AuthenticationObject;

public class Node {
	private byte[] pubkey;
	private boolean isAuth;
	private boolean sentAuth;
	private boolean authFinished;
	private boolean isReady;
	private boolean hasOpenChannel;

	public boolean processAuthentication (AuthenticationObject authentication) {
		//TODO: Check authentication based on the supplied pubkey

		return true;
	}

	public AuthenticationObject getAuthenticationObject () {
		//TODO: Produce a proper authentication object..

		return new AuthenticationObject();
	}

	public boolean hasSentAuth () {
		return sentAuth;
	}

	public boolean isAuth () {
		return isAuth;
	}

	public boolean allowsAuth () {
		return !isAuth;
	}

	public void finishAuth () {
		authFinished = true;
	}

	public boolean isAuthFinished () {
		return authFinished;
	}
}

package network.thunder.core.communication;

import network.thunder.core.communication.objects.subobjects.AuthenticationObject;

public class Node {
	private byte[] pubkey;
	private boolean isAuth;
	private boolean sentAuth;
	private boolean authFinished;
	private boolean isReady;
	private boolean hasOpenChannel;

	public boolean processAuthentication (AuthenticationObject authentication) {
		//TODO: Check authentication based on the supplied pubkey

		isAuth = true;
		if (sentAuth) {
			authFinished = true;
		}
		return true;
	}

	public AuthenticationObject getAuthenticationObject () {
		//TODO: Produce a proper authentication object..

		sentAuth = true;
		return new AuthenticationObject();
	}

	public boolean hasSentAuth () {
		return sentAuth;
	}

	public boolean isAuth () {
		return isAuth;
	}

	public boolean allowsAuth () {
		return !isAuth;
	}

	public void finishAuth () {
		authFinished = true;
	}

	public boolean isAuthFinished () {
		return authFinished;
	}
}

Fix node to set sentAuth whenever the object was generated


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import com.mojang.datafixers.DataFixUtils;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraft.util.SharedConstants;
import net.minecraft.util.datafix.*;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(DataFixesManager.getDataFixer().getSchema(DataFixUtils.makeKey(SharedConstants.getVersion().getWorldVersion())).getChoiceType(TypeReferences.BLOCK_ENTITY, register.getModid() + ":" + name)));
	}

	public void register(IEventBus bus) {
		register.register(bus);
	}

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.tileentity.*;
import net.minecraft.tileentity.TileEntityType.Builder;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class TileEntityTypeDeferredRegister {

	public static TileEntityTypeDeferredRegister create(String modid) {
		return new TileEntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<TileEntityType<?>> register;

	protected TileEntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.TILE_ENTITIES, modid);
	}

	public <T extends TileEntity> RegistryObject<TileEntityType<T>> register(String name, Supplier<Builder<T>> supplier) {
		return register.register(name, () -> supplier.get().build(null));
	}

	public void register(IEventBus bus) {
		register.register(bus);
	}

	public CommonDeferredRegister<TileEntityType<?>> getRegister() {
		return register;
	}

}

Fix the tile entity type (just push out null. We don't need this here)


// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol.test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;

public class TestFileUtil {
    protected static final String DATA_PATH = "./test/crosslanguagefiles";

    public static void writeToFile(String path, byte[] data) throws IOException {
        try (FileOutputStream stream = new FileOutputStream(path)) {
            stream.write(data);
        }
    }

    /**
     * Write `data` to `path` using UTF-8 as binary encoding format.
     */
    public static void writeToFile(String path, String data) throws IOException {
        writeToFile(path, data.getBytes(Charset.forName("UTF-8")));
    }

    /**
     * Returns the path to use for data files.
     *
     * @param filename The name of the file to include in the path.
     * @return The data file path.
     */
    public static String getPath(String filename) {
        return DATA_PATH + "/" + filename;
    }

    public static byte[] readFile(String path) throws IOException {
        try (FileInputStream stream = new FileInputStream(path)) {
            byte[] data = new byte[stream.available()];
            int read = stream.read(data);
            if (read != data.length) {
                throw new IOException(String.format("Truncated read (expected %d bytes, read %d)", data.length, read));
            }
            return data;
        }
    }

}

// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.documentapi.messagebus.protocol.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

public class TestFileUtil {
    protected static final String DATA_PATH = "./test/crosslanguagefiles";

    public static void writeToFile(String path, byte[] data) throws IOException {
        try (FileOutputStream stream = new FileOutputStream(path)) {
            stream.write(data);
        }
    }

    /**
     * Write `data` to `path` using UTF-8 as binary encoding format.
     */
    public static void writeToFile(String path, String data) throws IOException {
        writeToFile(path, data.getBytes(Charset.forName("UTF-8")));
    }

    /**
     * Returns the path to use for data files.
     *
     * @param filename The name of the file to include in the path.
     * @return The data file path.
     */
    public static String getPath(String filename) {
        return DATA_PATH + "/" + filename;
    }

    public static byte[] readFile(String path) throws IOException {
        return Files.readAllBytes(Paths.get(path));
    }
}

Fix loading of file so it loads full file every time.


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

package org.gradle.testfixtures.internal;

import org.gradle.internal.nativeintegration.services.NativeServices;

import java.io.File;

public class NativeServicesTestFixture {
    static NativeServices nativeServices;
    static boolean initialized;

    public static synchronized void initialize() {
        if (!initialized) {
            File nativeDir = getNativeServicesDir();
            NativeServices.initialize(nativeDir);
            initialized = true;
        }
    }

    public static synchronized NativeServices getInstance() {
        if (nativeServices == null) {
            initialize();
            nativeServices = NativeServices.getInstance();
        }
        return nativeServices;
    }

    public static File getNativeServicesDir() {
        return new File("build/native-libs");
    }
}

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

package org.gradle.testfixtures.internal;

import org.gradle.internal.nativeintegration.services.NativeServices;

import java.io.File;

public class NativeServicesTestFixture {
    static NativeServices nativeServices;
    static boolean initialized;

    public static synchronized void initialize() {
        if (!initialized) {
            System.setProperty("org.gradle.native", "true");
            File nativeDir = getNativeServicesDir();
            NativeServices.initialize(nativeDir);
            initialized = true;
        }
    }

    public static synchronized NativeServices getInstance() {
        if (nativeServices == null) {
            initialize();
            nativeServices = NativeServices.getInstance();
        }
        return nativeServices;
    }

    public static File getNativeServicesDir() {
        return new File("build/native-libs");
    }
}

Fix tests depending on native services

Fix tests depending on native services


/*******************************************************************************
 * Copyright (c) 2005, 2006 Subclipse project and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Subclipse project committers - initial API and implementation
 ******************************************************************************/
package org.tigris.subversion.subclipse.core;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;

/**
 * Preference Initializer.
 * Called at startup by Eclipse to initialize any default preferences.
 *
 * @author markphip
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer {

    public PreferenceInitializer() {
        super();
    }

    public void initializeDefaultPreferences() {
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_RECURSIVE_STATUS_UPDATE, true);
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_SHOW_OUT_OF_DATE_FOLDERS, false);
    }

}

/*******************************************************************************
 * Copyright (c) 2005, 2006 Subclipse project and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Subclipse project committers - initial API and implementation
 ******************************************************************************/
package org.tigris.subversion.subclipse.core;

import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;

/**
 * Preference Initializer.
 * Called at startup by Eclipse to initialize any default preferences.
 *
 * @author markphip
 */
public class PreferenceInitializer extends AbstractPreferenceInitializer {

    public PreferenceInitializer() {
        super();
    }

    public void initializeDefaultPreferences() {
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_RECURSIVE_STATUS_UPDATE, true);
        SVNProviderPlugin.getPlugin().getPluginPreferences().setDefault(ISVNCoreConstants.PREF_SHOW_OUT_OF_DATE_FOLDERS, true);
    }

}

Make Show Out of Date folders preference on by default. Now that the performance problems are fixed, it should be on since it resolves a lot of user problems.


package net.omniscimus.fireworks.commands;

import java.io.UnsupportedEncodingException;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import net.omniscimus.fireworks.ShowHandler;
import net.omniscimus.fireworks.commands.exceptions.WrongArgumentsNumberException;

/**
 * This command stops all currently running fireworks shows.
 *
 * @author Omniscimus
 */
public class StopallCommand extends FireworksCommand {

    private final ShowHandler showHandler;

    public StopallCommand(ShowHandler showHandler) {
	this.showHandler = showHandler;
    }

    @Override
    public void run(CommandSender sender, String[] args)
	    throws WrongArgumentsNumberException, UnsupportedEncodingException {

	if (args.length == 0) {
	    showHandler.stopAllShows();
	    sender.sendMessage(ChatColor.GOLD + "All " + showHandler.getNumberOfRunningShows() + " fireworks shows have stopped.");
	} else {
	    throw new WrongArgumentsNumberException();
	}

    }

}

package net.omniscimus.fireworks.commands;

import java.io.UnsupportedEncodingException;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;

import net.omniscimus.fireworks.ShowHandler;
import net.omniscimus.fireworks.commands.exceptions.WrongArgumentsNumberException;

/**
 * This command stops all currently running fireworks shows.
 *
 * @author Omniscimus
 */
public class StopallCommand extends FireworksCommand {

    private final ShowHandler showHandler;

    public StopallCommand(ShowHandler showHandler) {
	this.showHandler = showHandler;
    }

    @Override
    public void run(CommandSender sender, String[] args)
	    throws WrongArgumentsNumberException, UnsupportedEncodingException {

	if (args.length == 0) {
            int number = showHandler.getNumberOfRunningShows();
	    showHandler.stopAllShows();
	    sender.sendMessage(ChatColor.GOLD + "All " + number + " fireworks shows have stopped.");
	} else {
	    throw new WrongArgumentsNumberException();
	}

    }

}

Fix wrong number of stopped shows in stopall cmd

This occurred because the number of running shows was checked after
stopping them all. Therefore it was always 0.


/**
 * Copyright Google Inc. 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.firebase.codelab.friendlychat;

import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    // Add instrumentation test here
}

/**
 * Copyright Google Inc. 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.firebase.codelab.friendlychat;

import android.support.test.espresso.matcher.ViewMatchers;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityEspressoTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule =
            new ActivityTestRule<>(MainActivity.class);

    // Add instrumentation test here
    @Test
    public void verifySignUpButtonDisplayed() {
        onView(ViewMatchers.withId(R.id.sign_in_button)).check(matches(isDisplayed()));
    }
}

Configure Firebase Test Lab Espresso test for MainActivity


package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.BaseCheckTestCase;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;

import java.io.File;
public class ReturnCountCheckTest extends BaseCheckTestCase
{
    public void testDefault() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        final String[] expected = {
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }
}

package com.puppycrawl.tools.checkstyle.checks.coding;

import com.puppycrawl.tools.checkstyle.BaseCheckTestCase;
import com.puppycrawl.tools.checkstyle.DefaultConfiguration;

import java.io.File;
public class ReturnCountCheckTest extends BaseCheckTestCase
{
    public void testDefault() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        final String[] expected = {
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }

    public void testFormat() throws Exception
    {
        final DefaultConfiguration checkConfig =
            createCheckConfig(ReturnCountCheck.class);
        checkConfig.addAttribute("format", "^$");
        final String[] expected = {
            "5:5: Return count is 7 (max allowed is 2).",
            "18:5: Return count is 7 (max allowed is 2).",
            "35:17: Return count is 6 (max allowed is 2).",
        };
        verify(checkConfig, getPath("coding" + File.separator + "InputReturnCount.java"), expected);
    }
}

Test for format property of ReturnCount check


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

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

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

package org.chromium.sdk.internal.wip.protocol.input;

import java.util.List;

import org.chromium.sdk.internal.protocolparser.JsonOptionalField;
import org.chromium.sdk.internal.protocolparser.JsonProtocolParseException;
import org.chromium.sdk.internal.protocolparser.JsonSubtypeCasting;
import org.chromium.sdk.internal.protocolparser.JsonType;

@JsonType(subtypesChosenManually=true)
public interface WipTabList {
  @JsonSubtypeCasting List<TabDescription> asTabList() throws JsonProtocolParseException;

  @JsonType interface TabDescription {
    String faviconUrl();
    String title();
    String url();

    String thumbnailUrl();

    // TODO: consider adding enum here
    String type();

    @JsonOptionalField
    String devtoolsFrontendUrl();

    @JsonOptionalField
    String webSocketDebuggerUrl();
  }
}

Add 'type' field to tab enumeration JSON protocol

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


package org.graphwalker.core.machine;

import org.graphwalker.core.condition.VertexCoverage;
import org.graphwalker.core.generator.ShortestAllPaths;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Edge;
import org.graphwalker.core.model.Model;
import org.graphwalker.core.model.Vertex;
import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.core.Is.is;

/**
 * @author Nils Olsson
 */
public class AccessModelTest {

    @Test
    public void read() {
        ExecutionContext context = createContext();
        Assert.assertThat((Double)context.getAttribute("x"), is(1.0));
    }

    @Test
    public void write() {
        ExecutionContext context = createContext();
        context.setAttribute("y", 2);
        Assert.assertThat((Integer)context.getAttribute("y"), is(2));
    }

    private ExecutionContext createContext() {
        Model model = new Model();
        model.addEdge(new Edge()
                .setSourceVertex(new Vertex())
                .setTargetVertex(new Vertex()));
        ExecutionContext context = new TestExecutionContext(model, new ShortestAllPaths(new VertexCoverage(100)));
        context.execute(new Action("x = 1;"));
        return context;
    }
}

package org.graphwalker.core.machine;

import org.graphwalker.core.condition.VertexCoverage;
import org.graphwalker.core.generator.ShortestAllPaths;
import org.graphwalker.core.model.Action;
import org.graphwalker.core.model.Edge;
import org.graphwalker.core.model.Model;
import org.graphwalker.core.model.Vertex;
import org.junit.Assert;
import org.junit.Test;

import static org.hamcrest.core.Is.is;

/**
 * @author Nils Olsson
 */
public class AccessModelTest {

    @Test
    public void read() {
        ExecutionContext context = createContext();
        Assert.assertThat(round(context.getAttribute("x")), is(1));
    }

    private int round(Object value) {
        if (value instanceof Double) {
            return (int) Math.round((Double) value);
        } else {
            return (Integer) value;
        }
    }

    @Test
    public void write() {
        ExecutionContext context = createContext();
        context.setAttribute("y", 2);
        Assert.assertThat((Integer)context.getAttribute("y"), is(2));
    }

    private ExecutionContext createContext() {
        Model model = new Model();
        model.addEdge(new Edge()
                .setSourceVertex(new Vertex())
                .setTargetVertex(new Vertex()));
        ExecutionContext context = new TestExecutionContext(model, new ShortestAllPaths(new VertexCoverage(100)));
        context.execute(new Action("x = 1;"));
        return context;
    }
}

Fix test issue with different jdk (javascript engines)


package algorithms;

import java.util.Arrays;

public class MaxPairwiseProduct {
	static long getMaxPairwiseProduct(Integer[] numbers) {
		if (numbers.length == 1) {
			return 0;
		}
		Arrays.sort(numbers, (x, y) -> x - y);
		int lastIndex = numbers.length - 1;
		long bigResult = (long) numbers[lastIndex] * numbers[lastIndex - 1];
		return bigResult;
	}

	public static void main(String[] args) {
		System.out.println(
				"Type number to calculate the maximum pairwise product. "
						+ "The first number is a total count of numbers.");
		FastScanner scanner = new FastScanner(System.in);
		int numberOfNumbers = scanner.popNextInt();
		if (numberOfNumbers > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
		}
		Integer[] numbers = new Integer[numberOfNumbers];
		for (int i = 0; i < numberOfNumbers; i++) {
			numbers[i] = scanner.popNextInt();
		}
		System.out.println(getMaxPairwiseProduct(numbers));
	}
}

package algorithms;

public class MaxPairwiseProduct {
	static long getMaxPairwiseProduct(Integer[] numbers) {
		if (numbers.length == 1) {
			return 0;
		}
		Integer maxIndex1 = null;
		Integer maxIndex2 = null;
		for (int i = 0; i < numbers.length; ++i) {
			if (maxIndex1 == null || numbers[i] > numbers[maxIndex1]) {
				maxIndex2 = maxIndex1;
				maxIndex1 = i;
			} else if (maxIndex2 == null || numbers[i] > numbers[maxIndex2]) {
				maxIndex2 = i;
			}
		}
		return ((long) (numbers[maxIndex1])) * numbers[maxIndex2];
	}

	public static void main(String[] args) {
		System.out.println(
				"Type number to calculate the maximum pairwise product. "
						+ "The first number is a total count of numbers.");
		FastScanner scanner = new FastScanner(System.in);
		int numberOfNumbers = scanner.popNextInt();
		if (numberOfNumbers > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("Too many numbers, the max is: " + Integer.MAX_VALUE);
		}
		Integer[] numbers = new Integer[numberOfNumbers];
		for (int i = 0; i < numberOfNumbers; i++) {
			numbers[i] = scanner.popNextInt();
		}
		System.out.println(getMaxPairwiseProduct(numbers));
	}
}

Improve efficiency to constant O(n)

Improve efficiency to constant O(n)


package com.strohwitwer.awesomevalidation.validator;

import android.app.Activity;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utils.ValidationCallback;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Validator {

    protected ArrayList<ValidationHolder> mValidationHolderList;

    public Validator() {
        mValidationHolderList = new ArrayList<ValidationHolder>();
    }

    public void set(EditText editText, String regex, String errMsg) {
        Pattern pattern = Pattern.compile(regex);
        ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg);
        mValidationHolderList.add(validationHolder);
    }

    public void set(Activity activity, int viewId, String regex, int errMsgId) {
        EditText editText = (EditText) activity.findViewById(viewId);
        String errMsg = activity.getResources().getString(errMsgId);
        set(editText, regex, errMsg);
    }

    protected boolean checkFields(ValidationCallback callback) {
        boolean result = true;
        for (ValidationHolder validationHolder : mValidationHolderList) {
            Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText());
            if (!matcher.matches()) {
                callback.execute(validationHolder, matcher);
                result = false;
            }
        }
        return result;
    }

    public abstract boolean trigger();

    public abstract void halt();

}

package com.strohwitwer.awesomevalidation.validator;

import android.app.Activity;
import android.widget.EditText;

import com.strohwitwer.awesomevalidation.ValidationHolder;
import com.strohwitwer.awesomevalidation.utils.ValidationCallback;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Validator {

    protected ArrayList<ValidationHolder> mValidationHolderList;

    public Validator() {
        mValidationHolderList = new ArrayList<ValidationHolder>();
    }

    public void set(EditText editText, String regex, String errMsg) {
        Pattern pattern = Pattern.compile(regex);
        ValidationHolder validationHolder = new ValidationHolder(editText, pattern, errMsg);
        mValidationHolderList.add(validationHolder);
    }

    public void set(Activity activity, int viewId, String regex, int errMsgId) {
        EditText editText = (EditText) activity.findViewById(viewId);
        String errMsg = activity.getResources().getString(errMsgId);
        set(editText, regex, errMsg);
    }

    protected boolean checkFields(ValidationCallback callback) {
        boolean result = true;
        boolean hasFailed = false;
        for (ValidationHolder validationHolder : mValidationHolderList) {
            Matcher matcher = validationHolder.getPattern().matcher(validationHolder.getText());
            if (!matcher.matches()) {
                callback.execute(validationHolder, matcher);
                if (!hasFailed) {
                    EditText editText = validationHolder.getEditText();
                    editText.requestFocus();
                    editText.setSelection(editText.getText().length());
                    hasFailed = true;
                }
                result = false;
            }
        }
        return result;
    }

    public abstract boolean trigger();

    public abstract void halt();

}

Set focus to the first failed validation field.


// Copyright (C) 2013 The Android Open Source Project
//
// 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.googlesource.gerrit.plugins.javamelody;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.gerrit.httpd.plugins.HttpPluginModule;
import com.google.inject.Scopes;

public class HttpModule extends HttpPluginModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), AllRequestFilter.class)
        .to(GerritMonitoringFilter.class)
        .in(Scopes.SINGLETON);
  }
}

// Copyright (C) 2013 The Android Open Source Project
//
// 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.googlesource.gerrit.plugins.javamelody;

import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.gerrit.httpd.AllRequestFilter;
import com.google.inject.Scopes;
import com.google.inject.servlet.ServletModule;

public class HttpModule extends ServletModule {
  @Override
  protected void configureServlets() {
    DynamicSet.bind(binder(), AllRequestFilter.class)
        .to(GerritMonitoringFilter.class)
        .in(Scopes.SINGLETON);
  }
}

Extend ServletModule instead of HttpPluginModule

As described in I3b89150d1.

Change-Id: Ic91ce95719c6bccc73cc29a2139a2274f20d1939


package fr.epicanard.globalmarketchest.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerMoveEvent;

import fr.epicanard.globalmarketchest.GlobalMarketChest;
import fr.epicanard.globalmarketchest.gui.InventoryGUI;

public class ChatListener implements Listener {
  private Boolean isChatEditing(Player player) {
    if (player != null) {
      InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(player.getUniqueId());
      return (inv != null && inv.getChatEditing());
    }
    return false;
  }

  @EventHandler
  public void onPlayerMove(PlayerMoveEvent event) {
    if (this.isChatEditing(event.getPlayer())) {
      event.setCancelled(true);
    }
  }

  @EventHandler
  public void onPlayerBreakBlock(BlockBreakEvent  event) {
    if (this.isChatEditing(event.getPlayer())) {
      event.setCancelled(true);
    }
  }

  @EventHandler
  public void onChatEvent(AsyncPlayerChatEvent event) {
    InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(event.getPlayer().getUniqueId());
    if (inv != null && inv.getChatEditing()) {
      inv.setChatReturn(event.getMessage());
      event.setCancelled(true);
    }
  }

}

package fr.epicanard.globalmarketchest.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerMoveEvent;

import fr.epicanard.globalmarketchest.GlobalMarketChest;
import fr.epicanard.globalmarketchest.gui.InventoryGUI;

public class ChatListener implements Listener {
  private Boolean isChatEditing(Player player) {
    if (player != null) {
      InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(player.getUniqueId());
      return (inv != null && inv.getChatEditing());
    }
    return false;
  }

  @EventHandler
  public void onPlayerMove(PlayerMoveEvent event) {
    if (this.isChatEditing(event.getPlayer())) {
      event.setCancelled(true);
    }
  }

  @EventHandler
  public void onPlayerBreakBlock(BlockBreakEvent  event) {
    if (this.isChatEditing(event.getPlayer())) {
      event.setCancelled(true);
    }
  }

  @EventHandler
  public void onChatEvent(AsyncPlayerChatEvent event) {
    if (this.isChatEditing(event.getPlayer())) {
      InventoryGUI inv = GlobalMarketChest.plugin.inventories.getInventory(event.getPlayer().getUniqueId());
      inv.setChatReturn(event.getMessage());
      event.setCancelled(true);
    }
  }

}

Fix onChatEvent to handle player null

Fix onChatEvent to handle player null


/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * 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.  For additional information contact info@OpenLMIS.org.
 */

package org.openlmis.stockmanagement.domain.reason;

import lombok.Getter;

public enum ReasonType {
  CREDIT(2),
  DEBIT(1),
  BALANCE_ADJUSTMENT(0);

  @Getter
  private int priority;

  ReasonType(int priority) {
    this.priority = priority;
  }
}

/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * 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.  For additional information contact info@OpenLMIS.org.
 */

package org.openlmis.stockmanagement.domain.reason;

import lombok.Getter;

public enum ReasonType {
  CREDIT(2),
  DEBIT(1),
  BALANCE_ADJUSTMENT(0);

  /**
   * Value of this field will be used to set correct order of stock card line items if both
   * occurred and processed dates have the same date for the following line items. It is
   * important that types that are used to increase (like {@link #CREDIT}) should have higher
   * priority than types that are used to decrease (like {@link #DEBIT}).
   */
  @Getter
  private int priority;

  ReasonType(int priority) {
    this.priority = priority;
  }
}

Revert "Revert "OLMIS-3533: Added javadoc for Reason type priority field""

This reverts commit 68cd7a11b50c4f4a194f6d439e6b83b3b2f46243.


package de.philipphager.disclosure.feature.sync.api.usecases;

import de.philipphager.disclosure.api.DisclosureApi;
import de.philipphager.disclosure.database.library.model.Library;
import de.philipphager.disclosure.service.LibraryService;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;

public class SyncLibraries {
  private final DisclosureApi disclosureApi;
  private final LibraryService libraryService;

  @Inject public SyncLibraries(DisclosureApi disclosureApi,
      LibraryService libraryService) {
    this.disclosureApi = disclosureApi;
    this.libraryService = libraryService;
  }

  public Observable<List<Library>> run() {
    return libraryService.lastUpdated()
        .first()
        .flatMap(lastUpdated -> new Paginator<Library>() {
          @Override protected Observable<List<Library>> queryPage(int page, int limit) {
            return disclosureApi.allLibraries(lastUpdated, page, limit);
          }
        }.join())
        .doOnNext(libraryService::insertOrUpdate);
  }
}

package de.philipphager.disclosure.feature.sync.api.usecases;

import de.philipphager.disclosure.api.DisclosureApi;
import de.philipphager.disclosure.database.library.model.Library;
import de.philipphager.disclosure.service.LibraryService;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;
import timber.log.Timber;

public class SyncLibraries {
  private final DisclosureApi disclosureApi;
  private final LibraryService libraryService;

  @Inject public SyncLibraries(DisclosureApi disclosureApi,
      LibraryService libraryService) {
    this.disclosureApi = disclosureApi;
    this.libraryService = libraryService;
  }

  public Observable<List<Library>> run() {
    return libraryService.lastUpdated()
        .first()
        .flatMap(lastUpdated -> new Paginator<Library>() {
          @Override protected Observable<List<Library>> queryPage(int page, int limit) {
            Timber.d("fetch libraries from api, page: %d, limit: %d", page, limit);
            return disclosureApi.allLibraries(lastUpdated, page, limit);
          }
        }.join())
        .doOnNext(libraryService::insertOrUpdate);
  }
}

Add log message to library syncer

Add log message to library syncer


/*
 *
 * Copyright (c) 2005, Karl Trygve Kalleberg <karltk@ii.uib.no>
 *
 * Licensed under the GNU General Public License, v2
 */
package org.spoofax.interpreter.library.ecj;

import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry;

public class ECJLibrary extends AbstractStrategoOperatorRegistry {

    public static final String REGISTRY_NAME = "ECJ";

    ECJLibrary() {
        init();
    }

    private void init() {
        add(new ECJ_parse_only());
        add(new ECJ_parse_and_resolve());
        add(new ECJ_open_project());
        add(new ECJ_create_project());
        add(new ECJ_add_source_folder());
        add(new ECJ_add_jar());
        add(new ECJ_binding_of_name());
        add(new ECJ_type_of_type());
        add(new ECJ_type_of_typedecl());
        add(new ECJ_type_of_typeparameter());
        add(new ECJ_method_of_methoddecl());
        add(new ECJ_method_of_methodinvoc());
        add(new ECJ_method_of_supermethodinvoc());
        add(new ECJ_method_of_superctorinvoc());
        add(new ECJ_type_of_expr());
        add(new ECJ_is_cast_compatible());
        add(new ECJ_is_subtype_compatible());
    }
}

/*
 *
 * Copyright (c) 2005, Karl Trygve Kalleberg <karltk@ii.uib.no>
 *
 * Licensed under the GNU General Public License, v2
 */
package org.spoofax.interpreter.library.ecj;

import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry;

public class ECJLibrary extends AbstractStrategoOperatorRegistry {

    public static final String REGISTRY_NAME = "ECJ";

    public ECJLibrary() {
        init();
    }

    private void init() {
        add(new ECJ_parse_only());
        add(new ECJ_parse_and_resolve());
        add(new ECJ_open_project());
        add(new ECJ_create_project());
        add(new ECJ_add_source_folder());
        add(new ECJ_add_jar());
        add(new ECJ_binding_of_name());
        add(new ECJ_type_of_type());
        add(new ECJ_type_of_typedecl());
        add(new ECJ_type_of_typeparameter());
        add(new ECJ_method_of_methoddecl());
        add(new ECJ_method_of_methodinvoc());
        add(new ECJ_method_of_supermethodinvoc());
        add(new ECJ_method_of_superctorinvoc());
        add(new ECJ_type_of_expr());
        add(new ECJ_is_cast_compatible());
        add(new ECJ_is_subtype_compatible());
    }
}

Make visible to interpreter "compositions" outside this package.

svn path=/spoofax/trunk/spoofax/org.spoofax.interpreter.adapter.ecj/; revision=16660


/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "l";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

/*
 * Copyright 1999-2010 Luca Garulli (l.garulli--at--orientechnologies.com)
 *
 * 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.orientechnologies.orient.core.serialization.serializer.stream;

import java.io.IOException;

import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

public class OStreamSerializerLong implements OStreamSerializer {
	public static final String								NAME			= "lo";

	public static final OStreamSerializerLong	INSTANCE	= new OStreamSerializerLong();

	public String getName() {
		return NAME;
	}

	public Object fromStream(final byte[] iStream) throws IOException {
		return OBinaryProtocol.bytes2long(iStream);
	}

	public byte[] toStream(final Object iObject) throws IOException {
		return OBinaryProtocol.long2bytes((Long) iObject);
	}
}

Fix by Sylvain on duplicated name for serializers Record and Long

git-svn-id: 9ddf022f45b579842a47abc018ed2b18cdc52108@4811 3625ad7b-9c83-922f-a72b-73d79161f2ea


/*
 * 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.oak.spi.security.authentication;

import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

/**
 * Created by angela on 28/02/17.
 */
class ThrowingCallbackHandler implements CallbackHandler {

    private boolean throwIOException;

    ThrowingCallbackHandler(boolean throwIOException) {
        this.throwIOException = throwIOException;
    }

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        if (throwIOException) {
            throw new IOException();
        } else {
            throw new UnsupportedCallbackException(new Callback() {
            });
        }
    }
}

OAK-5793: Improve coverage for security code in oak-core

Missing license header

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1784852 13f79535-47bb-0310-9956-ffa450edef68


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

import static com.clicktravel.cheddar.server.application.lifecycle.LifecycleStatus.INACTIVE;
import static com.clicktravel.cheddar.server.application.lifecycle.LifecycleStatus.RUNNING;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class LifecycleStatusHolder {

    private volatile LifecycleStatus lifecycleStatus;

    @Autowired
    public LifecycleStatusHolder(@Value("${blue.green.mode}") final boolean blueGreenMode) {
        lifecycleStatus = blueGreenMode ? INACTIVE : RUNNING;
    }

    public LifecycleStatus getLifecycleStatus() {
        return lifecycleStatus;
    }

    public void setLifecycleStatus(final LifecycleStatus lifecycleStatus) {
        this.lifecycleStatus = lifecycleStatus;
    }

}

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

import static com.clicktravel.cheddar.server.application.lifecycle.LifecycleStatus.INACTIVE;
import static com.clicktravel.cheddar.server.application.lifecycle.LifecycleStatus.RUNNING;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class LifecycleStatusHolder {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private volatile LifecycleStatus lifecycleStatus;

    @Autowired
    public LifecycleStatusHolder(@Value("${blue.green.startup:false}") final boolean blueGreenStartup) {
        logger.debug("Blue-green startup: " + blueGreenStartup);
        lifecycleStatus = blueGreenStartup ? INACTIVE : RUNNING;
    }

    public LifecycleStatus getLifecycleStatus() {
        return lifecycleStatus;
    }

    public void setLifecycleStatus(final LifecycleStatus lifecycleStatus) {
        this.lifecycleStatus = lifecycleStatus;
    }

}

[FC-77] Allow blue-green startup to be specified from "-Dblue.green.startup" param.


package com.thoughtworks.xstream.core.util;

public final class ClassStack {

    private Class[] stack;
    private int pointer;

    public ClassStack(int initialCapacity) {
        stack = new Class[initialCapacity];
    }

    public void push(Class value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
    }

    public void popSilently() {
        pointer--;
    }

    public Class pop() {
        return stack[--pointer];
    }

    public Class peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public Class get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Class[] newStack = new Class[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }
}

package com.thoughtworks.xstream.core.util;

public final class ClassStack {

    private Class[] stack;
    private int pointer;

    public ClassStack(int initialCapacity) {
        stack = new Class[initialCapacity];
    }

    public void push(Class value) {
        if (pointer + 1 >= stack.length) {
            resizeStack(stack.length * 2);
        }
        stack[pointer++] = value;
    }

    public void popSilently() {
        stack[--pointer] = null;
    }

    public Class pop() {
        final Class result = stack[--pointer];
        stack[pointer] = null;
        return result;
    }

    public Class peek() {
        return pointer == 0 ? null : stack[pointer - 1];
    }

    public int size() {
        return pointer;
    }

    public Class get(int i) {
        return stack[i];
    }

    private void resizeStack(int newCapacity) {
        Class[] newStack = new Class[newCapacity];
        System.arraycopy(stack, 0, newStack, 0, Math.min(stack.length, newCapacity));
        stack = newStack;
    }
}

Drop references from popped classes.

Drop references from popped classes.


package org.gbif.registry;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.solr.SolrHealthContributorAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication(
  scanBasePackages = {
    "org.gbif.ws.server.interceptor",
    "org.gbif.ws.server.aspect",
    "org.gbif.ws.server.filter",
    "org.gbif.ws.security",
    "org.gbif.registry"},
  exclude = {
    SolrAutoConfiguration.class,
    SolrHealthContributorAutoConfiguration.class
  })
@MapperScan("org.gbif.registry.persistence.mapper")
@EnableConfigurationProperties
public class RegistryWsApplication {
  public static void main(String[] args) {
    SpringApplication.run(RegistryWsApplication.class, args);
  }
}

package org.gbif.registry;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.solr.SolrHealthContributorAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication(
  scanBasePackages = {
    "org.gbif.ws.server.interceptor",
    "org.gbif.ws.server.aspect",
    "org.gbif.ws.server.filter",
    "org.gbif.ws.server.advice",
    "org.gbif.ws.security",
    "org.gbif.registry"},
  exclude = {
    SolrAutoConfiguration.class,
    SolrHealthContributorAutoConfiguration.class
  })
@MapperScan("org.gbif.registry.persistence.mapper")
@EnableConfigurationProperties
public class RegistryWsApplication {
  public static void main(String[] args) {
    SpringApplication.run(RegistryWsApplication.class, args);
  }
}

Add package org.gbif.ws.server.advice to scan


package com.github.krooken.edxvideoviewer;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class LoginScreen extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_screen);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login_screen, menu);
		return true;
	}

}

package com.github.krooken.edxvideoviewer;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.WindowManager;
import android.webkit.WebView;

public class LoginScreen extends Activity {

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_screen);

		WebView loginWebView = (WebView)findViewById(R.id.login_web_view);
		loginWebView.getSettings().setJavaScriptEnabled(true);
		loginWebView.loadUrl("https://courses.edx.org/login");
		getWindow().setSoftInputMode(
			      WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login_screen, menu);
		return true;
	}

}

Load EdX login screen in WebView on create.


/*
 * Copyright 2011-2015 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.api.rest;

/**
 * @since 1.0
 */
public abstract class AbstractRestService {

	/**
	 * The currently supported versioned media type of the snowowl RESTful API.
	 */
	public static final String SO_MEDIA_TYPE = "application/vnd.com.b2international.snowowl+json";

}

/*
 * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.api.rest;

/**
 * @since 1.0
 */
public abstract class AbstractRestService {

	/**
	 * The currently supported versioned media type of the snowowl RESTful API.
	 */
	public static final String SO_MEDIA_TYPE = "application/vnd.com.b2international.snowowl+json";

	public static final String CSV_MEDIA_TYPE = "text/csv";

}

Add text/csv media type constant

SO-3379: Add text/csv media type constant


/*
 *  Copyright 2007-2008 University Of Southern California
 *
 *  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.usc.glidein.db;

import javax.naming.Context;
import javax.naming.InitialContext;

// TODO: Record event times in the database to match Condor event times

public abstract class Database
{
	public static Database getDatabase() throws DatabaseException
	{
		String location = "java:comp/env/glidein/Database";
		try {
			Context initialContext = new InitialContext();
	    	return (Database)initialContext.lookup(location);
		} catch (Exception e) {
			throw new DatabaseException("Unable to load database: "+location,e);
		}
	}

	public abstract SiteDAO getSiteDAO();
	public abstract GlideinDAO getGlideinDAO();
}

/*
 *  Copyright 2007-2008 University Of Southern California
 *
 *  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.usc.glidein.db;

import javax.naming.Context;
import javax.naming.InitialContext;

// TODO: Combine SQL DAOs and eliminate duplicate code

public abstract class Database
{
	public static Database getDatabase() throws DatabaseException
	{
		String location = "java:comp/env/glidein/Database";
		try {
			Context initialContext = new InitialContext();
	    	return (Database)initialContext.lookup(location);
		} catch (Exception e) {
			throw new DatabaseException("Unable to load database: "+location,e);
		}
	}

	public abstract SiteDAO getSiteDAO();
	public abstract GlideinDAO getGlideinDAO();
}

Remove date todo Add DRY todo

Remove date todo
Add DRY todo

git-svn-id: bdb5f82b9b83a1400e05d69d262344b821646179@1452 e217846f-e12e-0410-a4e5-89ccaea66ff7


package com.novoda.downloadmanager;

import android.support.annotation.WorkerThread;

import java.util.List;

import static com.novoda.downloadmanager.DownloadBatchStatus.Status.*;

final class DownloadBatchSizeCalculator {

    private DownloadBatchSizeCalculator() {
        // non instantiable
    }

    @WorkerThread
    static long getTotalSize(List<DownloadFile> downloadFiles, DownloadBatchStatus.Status status, DownloadBatchId downloadBatchId) {
        long totalBatchSize = 0;
        for (DownloadFile downloadFile : downloadFiles) {
            if (status == DELETING || status == DELETED || status == PAUSED) {
                Logger.w("abort getTotalSize file " + downloadFile.id().rawId()
                             + " from batch " + downloadBatchId.rawId()
                             + " with status " + status
                             + " returns 0 as totalFileSize");
                return 0;
            }

            long totalFileSize = downloadFile.getTotalSize();
            if (totalFileSize == 0) {
                Logger.w("file " + downloadFile.id().rawId()
                             + " from batch " + downloadBatchId.rawId()
                             + " with status " + status
                             + " returns 0 as totalFileSize");
                return 0;
            }

            totalBatchSize += totalFileSize;
        }
        return totalBatchSize;
    }
}

package com.novoda.downloadmanager;

import android.support.annotation.WorkerThread;

import java.util.List;

import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETING;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.DELETED;
import static com.novoda.downloadmanager.DownloadBatchStatus.Status.PAUSED;

final class DownloadBatchSizeCalculator {

    private DownloadBatchSizeCalculator() {
        // non instantiable
    }

    @WorkerThread
    static long getTotalSize(List<DownloadFile> downloadFiles, DownloadBatchStatus.Status status, DownloadBatchId downloadBatchId) {
        long totalBatchSize = 0;
        for (DownloadFile downloadFile : downloadFiles) {
            if (status == DELETING || status == DELETED || status == PAUSED) {
                Logger.w("abort getTotalSize file " + downloadFile.id().rawId()
                             + " from batch " + downloadBatchId.rawId()
                             + " with status " + status
                             + " returns 0 as totalFileSize");
                return 0;
            }

            long totalFileSize = downloadFile.getTotalSize();
            if (totalFileSize == 0) {
                Logger.w("file " + downloadFile.id().rawId()
                             + " from batch " + downloadBatchId.rawId()
                             + " with status " + status
                             + " returns 0 as totalFileSize");
                return 0;
            }

            totalBatchSize += totalFileSize;
        }
        return totalBatchSize;
    }
}

Replace star inport with explicit ones

Replace star inport with explicit ones


package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
}

package br.com.bloder.blormlib.validation;

import br.com.bloder.blormlib.validation.validations.Checked;
import br.com.bloder.blormlib.validation.validations.Email;
import br.com.bloder.blormlib.validation.validations.Filled;
import br.com.bloder.blormlib.validation.validations.Number;

/**
 * Created by bloder on 05/06/16.
 */
public class Validations {

  public static Validation filled = new Filled();
  public static Validation checked = new Checked();
  public static Validation email = new Email();
  public static Validation number = new Number();
}

Add number validation in validations class


package hu.eltesoft.modelexecution.ide.debug.ui;

import java.util.List;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.papyrus.moka.ui.presentation.AnimationUtils;

public class MokaAnimationBase {

	protected static final AnimationUtils UTILS = AnimationUtils.getInstance();

	public MokaAnimationBase() {
		super();
	}

	protected void openContainingDiagram(EObject element) {
		List<Diagram> diagrams = UTILS.getDiagrams(element);
		for (Diagram diagram : diagrams) {
			UTILS.openDiagram(diagram, false);
		}
	}

}

package hu.eltesoft.modelexecution.ide.debug.ui;

import java.util.List;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.papyrus.moka.ui.presentation.AnimationUtils;
import org.eclipse.swt.widgets.Display;

public class MokaAnimationBase {

	protected static final AnimationUtils UTILS = AnimationUtils.getInstance();

	public MokaAnimationBase() {
		super();
	}

	protected void openContainingDiagram(EObject element) {
		Display.getDefault().asyncExec(() -> {
			List<Diagram> diagrams = UTILS.getDiagrams(element);
			if (!diagrams.isEmpty()) {
				UTILS.openDiagram(diagrams.get(0), false);
			}
		});
	}

}

Put opening diagrams to a UI thread

Put opening diagrams to a UI thread


// Copyright 2006 Google Inc.  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.enterprise.connector.traversal;

/**
 * A mock query traverser that runs forever.
 */
public class NeverEndingQueryTraverser implements Traverser {

  /* (non-Javadoc)
   * @see com.google.enterprise.connector.traversal.Traverser#runBatch(int)
   */
  public int runBatch(int batchHint) throws InterruptedException {
    boolean breakLoop = true;
    while (breakLoop) {
      // infinite loop
    }
    return batchHint;
  }

}

// Copyright 2006 Google Inc.  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.enterprise.connector.traversal;

/**
 * A mock query traverser that runs forever.
 */
public class NeverEndingQueryTraverser implements Traverser {

  /* (non-Javadoc)
   * @see com.google.enterprise.connector.traversal.Traverser#runBatch(int)
   */
  public int runBatch(int batchHint) throws InterruptedException {
    boolean breakLoop = true;
    // infinite loop
    while (breakLoop) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException ie) {
        // do nothing
      }
    }
    return batchHint;
  }

}

Make never ending traverser consume less CPU.

Max, please review.