package org.squiddev.plethora.gameplay.modules.glasses.objects;

import net.minecraft.item.Item;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.method.wrapper.FromTarget;
import org.squiddev.plethora.api.method.wrapper.Optional;
import org.squiddev.plethora.api.method.wrapper.PlethoraMethod;
import org.squiddev.plethora.gameplay.modules.glasses.objects.object3d.Item3D;

import javax.annotation.Nonnull;

/**
 * An object which contains an item.
 */
public interface ItemObject {
	@Nonnull
	Item getItem();

	void setItem(@Nonnull Item item);

	int getDamage();

	void setDamage(int damage);

	@PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false)
	static MethodResult getItem(@FromTarget Item3D object) {
		return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage());
	}

	@PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false)
	static void setItem(@FromTarget Item3D object, Item item, @Optional(defInt = 0) int damage) {
		object.setItem(item);
		object.setDamage(damage);
	}
}

package org.squiddev.plethora.gameplay.modules.glasses.objects;

import net.minecraft.item.Item;
import org.squiddev.plethora.api.method.MethodResult;
import org.squiddev.plethora.api.method.wrapper.FromTarget;
import org.squiddev.plethora.api.method.wrapper.Optional;
import org.squiddev.plethora.api.method.wrapper.PlethoraMethod;

import javax.annotation.Nonnull;

/**
 * An object which contains an item.
 */
public interface ItemObject {
	@Nonnull
	Item getItem();

	void setItem(@Nonnull Item item);

	int getDamage();

	void setDamage(int damage);

	@PlethoraMethod(doc = "function(): string, number -- Get the item and damage value for this object.", worldThread = false)
	static MethodResult getItem(@FromTarget ItemObject object) {
		return MethodResult.result(object.getItem().getRegistryName().toString(), object.getDamage());
	}

	@PlethoraMethod(doc = "-- Set the item and damage value for this object.", worldThread = false)
	static void setItem(@FromTarget ItemObject object, Item item, @Optional(defInt = 0) int damage) {
		object.setItem(item);
		object.setDamage(damage);
	}
}

Fix {get,set}Object not being available on 2D items


package com.xengar.android.weather;

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.EditTextPreference;
import android.util.AttributeSet;

public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.LocationEditTextPreference,
                0, 0);
        try {
            mMinLength = a.getInteger(R.styleable.LocationEditTextPreference_minLength,
                    DEFAULT_MINIMUM_LOCATION_LENGTH);
        } finally {
            a.recycle();
        }
    }
}

package com.xengar.android.weather;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.widget.Button;
import android.widget.EditText;

public class LocationEditTextPreference extends EditTextPreference {
    static final private int DEFAULT_MINIMUM_LOCATION_LENGTH = 2;
    private int mMinLength;

    public LocationEditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.LocationEditTextPreference,
                0, 0);
        try {
            mMinLength = a.getInteger(R.styleable.LocationEditTextPreference_minLength,
                    DEFAULT_MINIMUM_LOCATION_LENGTH);
        } finally {
            a.recycle();
        }
    }

    @Override
    protected void showDialog(Bundle state) {
        super.showDialog(state);

        EditText et = getEditText();
        et.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Dialog d = getDialog();
                if (d instanceof AlertDialog) {
                    AlertDialog dialog = (AlertDialog) d;
                    Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
                    // Check if the EditText is empty
                    if (s.length() < mMinLength) {
                        // Disable OK button
                        positiveButton.setEnabled(false);
                    } else {
                        // Re-enable the button.
                        positiveButton.setEnabled(true);
                    }
                }
            }
        });
    }
}

Use AlertDialog with EditTextPreference and TextWatcher to disable setting the preference if the location is too short.


/*
 * Copyright 2015 Bridje Framework.
 *
 * 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.bridje.core.ioc.test;

import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;

@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
    @Override
    public void preCreateComponent(Class<DummyComponent> clazz)
    {
        System.out.println("preCreate: " + clazz.getName());
    }

    @Override
    public void preInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("preInit: " + clazz.getName());
    }

    @Override
    public void postInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("postInit: " + clazz.getName());
    }
}

/*
 * Copyright 2015 Bridje Framework.
 *
 * 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.bridje.core.ioc.test;

import org.bridje.core.ioc.ContextListener;
import org.bridje.core.ioc.annotations.Component;

@Component
public class ContextListenerDummy implements ContextListener<DummyComponent>
{
    @Override
    public void preCreateComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is preCreate");
    }

    @Override
    public void preInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is preInit");
    }

    @Override
    public void postInitComponent(Class<DummyComponent> clazz)
    {
        System.out.println("This method is called only when DummyComponent is postInit");
    }
}

Change the text on the test


/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.rcp;

import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;

/** Handler for opening files from command line
 *
 *  <p>See
 *  Opening Files from Command-Line - org.csstudio.openfile
 *  in CS-Studio docbook.
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
    @Override
    public void openDisplay(final String path, final String data) throws Exception
    {
        final Macros macros = MacroXMLUtil.readMacros(data);
        final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros);
        new OpenDisplayAction(info).run();
    }
}

/*******************************************************************************
 * Copyright (c) 2015-2016 Oak Ridge National Laboratory.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/
package org.csstudio.display.builder.rcp;

import org.csstudio.display.builder.model.macros.MacroXMLUtil;
import org.csstudio.display.builder.model.macros.Macros;
import org.csstudio.openfile.IOpenDisplayAction;

/** Handler for opening files from command line
 *
 *  <p>See
 *  Opening Files from Command-Line - org.csstudio.openfile
 *  in CS-Studio docbook.
 *
 *  @author Kay Kasemir
 */
@SuppressWarnings("nls")
public class OpenDisplayFile implements IOpenDisplayAction
{
    @Override
    public void openDisplay(final String path, final String data) throws Exception
    {
        final Macros macros = MacroXMLUtil.readMacros(data);
        // 'resolve', i.e. use *.bob over *.opi if found
        final DisplayInfo info = new DisplayInfo(path, "Display from command line", macros, true);
        new OpenDisplayAction(info).run();
    }
}

Use *.bob over *.opi when called from alarm UI, cmd line


package com.ksoichiro.task.repository;

import com.ksoichiro.task.domain.Account;
import com.ksoichiro.task.domain.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface TagRepository extends JpaRepository<Tag, Integer> {
    @Query("SELECT t FROM #{#entityName} t "
        + "WHERE t.account = ? ")
    Page<Tag> findByAccount(Account account, Pageable pageable);

    @Query("SELECT t from #{#entityName} t "
        + "WHERE t.id = ?1 "
        + "AND t.account = ?2")
    Tag findByIdAndAccount(Integer id, Account account);
}

package com.ksoichiro.task.repository;

import com.ksoichiro.task.domain.Account;
import com.ksoichiro.task.domain.Tag;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface TagRepository extends JpaRepository<Tag, Integer> {
    @Query("SELECT t FROM #{#entityName} t "
        + "WHERE t.account = ?1 ")
    Page<Tag> findByAccount(Account account, Pageable pageable);

    @Query("SELECT t from #{#entityName} t "
        + "WHERE t.id = ?1 "
        + "AND t.account = ?2")
    Tag findByIdAndAccount(Integer id, Account account);
}

Fix HQL parameter is not numbered


package valandur.webapi.handlers;

import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ErrorHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;

public class CustomErrorHandler extends ErrorHandler {
    @Override
    protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
        if (message == null)
            message= HttpStatus.getMessage(code);

        writer.write("{ code: " + code + ", message: \"" + message + "\" }");
    }
}

package valandur.webapi.handlers;

import com.google.gson.JsonObject;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.handler.ErrorHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Writer;

public class CustomErrorHandler extends ErrorHandler {
    @Override
    protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message) throws IOException {
        if (message == null)
            message= HttpStatus.getMessage(code);

        JsonObject obj = new JsonObject();
        obj.addProperty("code", code);
        obj.addProperty("message", message);
        writer.write(obj.toString());
    }
}

Use actual json object in error handler


package org.jboss.arquillian.moco.client;

import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

public class MocoArchiveAppender implements AuxiliaryArchiveAppender {

	@Override
	public Archive<?> createAuxiliaryArchive() {

		 return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
		            .addClass(ReflectionHelper.class)
		            .addPackage(MocoRemoteExtension.class.getPackage())
		            .addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);

	}

}

package org.jboss.arquillian.moco.client;

import org.jboss.arquillian.container.test.spi.RemoteLoadableExtension;
import org.jboss.arquillian.container.test.spi.client.deployment.AuxiliaryArchiveAppender;
import org.jboss.arquillian.moco.ReflectionHelper;
import org.jboss.arquillian.moco.api.Moco;
import org.jboss.arquillian.moco.container.MocoRemoteExtension;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;

public class MocoArchiveAppender implements AuxiliaryArchiveAppender {

	@Override
	public Archive<?> createAuxiliaryArchive() {

		 return ShrinkWrap.create(JavaArchive.class, "arquillian-moco.jar")
		            .addClass(ReflectionHelper.class)
		            .addPackage(Moco.class.getPackage())
		            .addPackage(MocoRemoteExtension.class.getPackage())
		            .addAsServiceProvider(RemoteLoadableExtension.class, MocoRemoteExtension.class);

	}

}

Add Arquillian Moco API to remote deployment


package io.quarkus.mutiny.runtime;

import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

import org.jboss.logging.Logger;

import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;

@Recorder
public class MutinyInfrastructure {

    public void configureMutinyInfrastructure(ExecutorService exec) {
        Infrastructure.setDefaultExecutor(exec);
    }

    public void configureDroppedExceptionHandler() {
        Logger logger = Logger.getLogger(MutinyInfrastructure.class);
        Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                logger.error("Mutiny had to drop the following exception", throwable);
            }
        });
    }

    public void configureThreadBlockingChecker() {
        Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
            @Override
            public boolean getAsBoolean() {
                String threadName = Thread.currentThread().getName();
                return !threadName.contains("vertx-eventloop-thread-");
            }
        });
    }
}

package io.quarkus.mutiny.runtime;

import java.util.concurrent.ExecutorService;
import java.util.function.BooleanSupplier;
import java.util.function.Consumer;

import org.jboss.logging.Logger;

import io.quarkus.runtime.annotations.Recorder;
import io.smallrye.mutiny.infrastructure.Infrastructure;

@Recorder
public class MutinyInfrastructure {

    public void configureMutinyInfrastructure(ExecutorService exec) {
        Infrastructure.setDefaultExecutor(exec);
    }

    public void configureDroppedExceptionHandler() {
        Infrastructure.setDroppedExceptionHandler(new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) {
                Logger.getLogger(MutinyInfrastructure.class).error("Mutiny had to drop the following exception", throwable);
            }
        });
    }

    public void configureThreadBlockingChecker() {
        Infrastructure.setCanCallerThreadBeBlockedSupplier(new BooleanSupplier() {
            @Override
            public boolean getAsBoolean() {
                String threadName = Thread.currentThread().getName();
                return !threadName.contains("vertx-eventloop-thread-");
            }
        });
    }
}

Remove the logger from the heap


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

import org.jetbrains.annotations.Nullable;

/**
 * Base class for elements that have a qualified name (classes and functions).
 *
 * @author yole
 */
public interface PyQualifiedNameOwner extends PyElement {
  /**
   * Returns the qualified name of the element.
   *
   * @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
   * is contained inside an element that doesn't have a qualified name.
   */
  @Nullable
  String getQualifiedName();
}

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

import com.intellij.openapi.util.NlsSafe;
import org.jetbrains.annotations.Nullable;

/**
 * Base class for elements that have a qualified name (classes and functions).
 *
 * @author yole
 */
public interface PyQualifiedNameOwner extends PyElement {
  /**
   * Returns the qualified name of the element.
   *
   * @return the qualified name of the element, or null if the element doesn't have a name (for example, it is a lambda expression) or
   * is contained inside an element that doesn't have a qualified name.
   */
  @Nullable
  @NlsSafe String getQualifiedName();
}

Annotate Python UML diagrams support


/**
 * File: SampleMetaTestCase.java
 * Created by: dstaines
 * Created on: May 1, 2009
 * CVS:  $$
 */
package org.ensembl.healthcheck.testcase.eg_core;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.testcase.AbstractTemplatedTestCase;

/**
 * Base class for EnsemblGenomes core healthchecks
 *
 * @author dstaines
 *
 */
public abstract class AbstractEgCoreTestCase extends AbstractTemplatedTestCase {

	public final static String EG_GROUP = "ensembl_genomes";

	public AbstractEgCoreTestCase() {
		super();
		this.addToGroup(EG_GROUP);
		this.appliesToType(DatabaseType.CORE);
	}
}

/**
 * File: SampleMetaTestCase.java
 * Created by: dstaines
 * Created on: May 1, 2009
 * CVS:  $$
 */
package org.ensembl.healthcheck.testcase.eg_core;

import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.AbstractTemplatedTestCase;

/**
 * Base class for EnsemblGenomes core healthchecks
 *
 * @author dstaines
 *
 */
public abstract class AbstractEgCoreTestCase extends AbstractTemplatedTestCase {

	public final static String EG_GROUP = "ensembl_genomes";

	public AbstractEgCoreTestCase() {
		super();
		this.addToGroup(EG_GROUP);
		this.appliesToType(DatabaseType.CORE);
		this.setTeamResponsible(Team.ENSEMBL_GENOMES);
	}
}

Set team responsible by default


package com.hubspot.rosetta.internal;

import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;

@SuppressWarnings("serial")
public class RosettaModule extends Module {

  @Override
  public String getModuleName() {
    return "RosettaModule";
  }

  @Override
  public Version version() {
    return Version.unknownVersion();
  }

  @Override
  public void setupModule(SetupContext context) {
    context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier());

    ObjectCodec codec = context.getOwner();
    if (codec instanceof ObjectMapper) {
      ObjectMapper mapper = (ObjectMapper) codec;

      context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper));

      mapper.setSerializerProvider(new DefaultSerializerProvider.Impl());
      mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
  }
}

package com.hubspot.rosetta.internal;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;

@SuppressWarnings("serial")
public class RosettaModule extends Module {

  @Override
  public String getModuleName() {
    return "RosettaModule";
  }

  @Override
  public Version version() {
    return Version.unknownVersion();
  }

  @Override
  public void setupModule(SetupContext context) {
    context.addBeanSerializerModifier(new StoredAsJsonBeanSerializerModifier());

    ObjectCodec codec = context.getOwner();
    if (codec instanceof ObjectMapper) {
      ObjectMapper mapper = (ObjectMapper) codec;

      context.insertAnnotationIntrospector(new RosettaAnnotationIntrospector(mapper));

      mapper.setSerializerProvider(new DefaultSerializerProvider.Impl());
      mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper.setSerializationInclusion(Include.ALWAYS);
    }
  }
}

Set this in addition to annotation introspector approach


package com.codenvy.ide.ext.datasource.shared;

import com.codenvy.dto.shared.DTO;

@DTO
public interface RequestParameterDTO {

    DatabaseConfigurationDTO getDatabase();

    void setDatabase(DatabaseConfigurationDTO database);

    RequestParameterDTO withDatabase(DatabaseConfigurationDTO database);

    String getSqlRequest();

    void setSqlRequest(String sqlRequest);

    RequestParameterDTO withSqlRequest(String sqlRequest);

    int getResultLimit();

    void setResultLimit(int resultLimit);

    RequestParameterDTO withResultLimit(int resultLimit);
}

package com.codenvy.ide.ext.datasource.shared;

import com.codenvy.dto.shared.DTO;

@DTO
public interface RequestParameterDTO {

    DatabaseConfigurationDTO getDatabase();

    void setDatabase(DatabaseConfigurationDTO database);

    RequestParameterDTO withDatabase(DatabaseConfigurationDTO database);

    String getSqlRequest();

    void setSqlRequest(String sqlRequest);

    RequestParameterDTO withSqlRequest(String sqlRequest);

    int getResultLimit();

    void setResultLimit(int resultLimit);

    RequestParameterDTO withResultLimit(int resultLimit);

    MultipleRequestExecutionMode getMultipleRequestExecutionMode();

    void setMultipleRequestExecutionMode(MultipleRequestExecutionMode mode);

    RequestParameterDTO withMultipleRequestExecutionMode(MultipleRequestExecutionMode mode);
}

Add the field for request execution mode in request dto


package dk.statsbiblioteket.doms.central.connectors.fedora.methods;

import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest;
import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method;
import dk.statsbiblioteket.doms.webservices.authentication.Credentials;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: abr
 * Date: 9/13/12
 * Time: 11:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class MethodsImplTest {
    @org.junit.Test
    public void testGetMethods() throws Exception {
        MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7780/fedora"),"");
        List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile");
        assertTrue("no methods!",methodList.size() > 0);
    }

}

package dk.statsbiblioteket.doms.central.connectors.fedora.methods;

import dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest;
import dk.statsbiblioteket.doms.central.connectors.fedora.methods.generated.Method;
import dk.statsbiblioteket.doms.webservices.authentication.Credentials;

import java.util.List;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: abr
 * Date: 9/13/12
 * Time: 11:30 AM
 * To change this template use File | Settings | File Templates.
 */
public class MethodsImplTest {
    @org.junit.Test
    public void testGetMethods() throws Exception {
        MethodsImpl methods = new MethodsImpl(new FedoraRest(new Credentials("fedoraAdmin", "fedoraAdminPass"), "http://alhena:7880/fedora"),"");
        List<Method> methodList = methods.getStaticMethods("doms:ContentModel_VHSFile");
        assertTrue("no methods!",methodList.size() > 0);
    }

}

Use test server with methods


/*
 * 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.logging.log4j.core;

/**
 *
 *
 * @doubt Unchecked?
 *
 */
public class LoggingException extends RuntimeException {

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

    public LoggingException(String msg, Exception ex) {
        super(msg, ex);
    }

    public LoggingException(Exception ex) {
        super(ex);
    }
}

/*
 * 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.logging.log4j.core;

/**
 * Exception thrown when a exception occurs while logging.  In most cases exceptions will be handled
 * within Log4j but certain Appenders may be configured to allow exceptions to propagate to the
 * application. This is a RuntimeException so that the exception may be thrown in those cases without
 * requiring all Logger methods be contained with try/catch blocks.
 *
 */
public class LoggingException extends RuntimeException {

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

    public LoggingException(String msg, Exception ex) {
        super(msg, ex);
    }

    public LoggingException(Exception ex) {
        super(ex);
    }
}

Add javadoc description to resolve @doubt comment


package de.itemis.mosig.ringbuffer;

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

public class CircularBufferTest {

	@Test
	public void constructorShouldSetProvidedSize() {
		CircularBuffer underTest = new CircularBuffer(3);
		Assert.assertEquals(3, underTest.size());
	}
}

package de.itemis.mosig.ringbuffer;

import java.util.Random;

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

public class CircularBufferTest {

	@Test
	public void whenPassingRandomNbrToTheConstructorSizeShouldBeThatNbr() {
		int expectedSize = new Random().nextInt(Integer.MAX_VALUE);
		CircularBuffer underTest = new CircularBuffer(expectedSize);
		Assert.assertEquals(expectedSize, underTest.size());
	}
}

Test now uses random nbr.


/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2018 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package xquery.validation;

import org.exist.test.runner.XSuite;
import org.junit.runner.RunWith;

@RunWith(XSuite.class)
@XSuite.XSuiteFiles({
        "src/test/xquery/validation"
})
public class ValidationTests {
}

/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2018 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package xquery.validation;

import org.exist.test.runner.XSuite;
import org.junit.runner.RunWith;

@RunWith(XSuite.class)
@XSuite.XSuiteFiles({
        "exist-core/src/test/xquery/validation"
})
public class ValidationTests {
}

Fix test path in Validation test


package nl.eernie.jmoribus.model;

import org.apache.commons.lang3.StringUtils;

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

public class Step  {

    private StepType stepType;
    private List<StepLine> stepLines = new ArrayList<>();

    public Step(StepType stepType) {
        this.stepType = stepType;
    }

    public StepType getStepType() {
        return stepType;
    }

    public StepLine getFirstStepLine()
    {
        return stepLines.get(0);
    }

    public List<StepLine> getStepLines()
    {
        return stepLines;
    }

    public String getCombinedStepLines(){
        String combined = "";
        for(StepLine stepLine: stepLines){
            if(StringUtils.isNotBlank(combined)){
                combined = combined + " ";
            }
            if(stepLine instanceof Table){
                int index = stepLines.indexOf(stepLine);
                combined = combined + "TABLE"+index;
            }else{
                combined = combined + stepLine.getText();
            }
        }
        return combined;
    }
}

package nl.eernie.jmoribus.model;

import org.apache.commons.lang3.StringUtils;

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

public class Step  {

    private StepType stepType;
    private List<StepLine> stepLines = new ArrayList<>();

    public Step(StepType stepType) {
        this.stepType = stepType;
    }

    public StepType getStepType() {
        return stepType;
    }

    public StepLine getFirstStepLine()
    {
        return stepLines.get(0);
    }

    public List<StepLine> getStepLines()
    {
        return stepLines;
    }

    public String getCombinedStepLines(){
        StringBuffer buffer = new StringBuffer();
        for(StepLine stepLine: stepLines){
            if(StringUtils.isNotBlank(buffer.toString())){
                buffer.append(" ");
            }
            if(stepLine instanceof Table){
                int index = stepLines.indexOf(stepLine);
                buffer.append("TABLE"+index);
            }else{
                buffer.append(stepLine.getText());
            }
        }
        return buffer.toString();
    }
}

Remove defect for building a string in a loop


package com.peterphi.std.guice.restclient.resteasy.impl;

import com.peterphi.std.util.tracing.Tracing;
import com.peterphi.std.util.tracing.TracingConstants;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class TracingClientRequestFilter implements ClientRequestFilter
{
	@Override
	public void filter(final ClientRequestContext requestContext) throws IOException
	{
		final String traceId = Tracing.log("HTTP:req", () -> "" + requestContext.getUri());

		if (traceId != null)
		{
			requestContext.getHeaders().add(TracingConstants.HTTP_HEADER_CORRELATION_ID, traceId);

			if (Tracing.isVerbose())
				requestContext.getHeaders().add(TracingConstants.HTTP_HEADER_TRACE_VERBOSE, "true");
		}
	}
}

package com.peterphi.std.guice.restclient.resteasy.impl;

import com.peterphi.std.util.tracing.Tracing;
import com.peterphi.std.util.tracing.TracingConstants;
import org.apache.log4j.Logger;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.ext.Provider;
import java.io.IOException;

@Provider
public class TracingClientRequestFilter implements ClientRequestFilter
{
	private static final Logger log = Logger.getLogger(TracingClientRequestFilter.class);

	@Override
	public void filter(final ClientRequestContext requestContext) throws IOException
	{
		final String traceId = Tracing.log("HTTP:req", () -> "" + requestContext.getUri());

		if (traceId != null)
		{
			if (requestContext.getHeaders().containsKey(TracingConstants.HTTP_HEADER_CORRELATION_ID))
				log.warn("Duplicate call to tracing filter " +
				         this +
				         " for " +
				         requestContext +
				         " for " +
				         requestContext.getUri());

			requestContext.getHeaders().putSingle(TracingConstants.HTTP_HEADER_CORRELATION_ID, traceId);

			if (Tracing.isVerbose())
				requestContext.getHeaders().putSingle(TracingConstants.HTTP_HEADER_TRACE_VERBOSE, "true");
		}
	}
}

Add logic to prevent the addition of duplicate X-Correlation-ID headers if the tracing filter is called multiple times (also logs a warning if this happens)


package com.akikanellis.kata01;

import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;

public class TenPercentOffEverything extends OfferStrategy {

    private TenPercentOffEverything(long id) { super(id, "10% off everything"); }

    public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }

    @Override public Offers calculateOffers(Items items) {
        Price itemsPrice = items.stream()
                .map(QuantifiedItem::totalPrice)
                .reduce(Price::add)
                .orElse(Price.ZERO);

        Price discount = itemsPrice.multiplyBy(0.10).negate();
        Offer offer = Offer.create(description(), discount);
        QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);

        return Offers.fromSingle(quantifiedOffer);
    }
}

package com.akikanellis.kata01;

import com.akikanellis.kata01.item.Items;
import com.akikanellis.kata01.item.QuantifiedItem;
import com.akikanellis.kata01.offer.Offer;
import com.akikanellis.kata01.offer.OfferStrategy;
import com.akikanellis.kata01.offer.Offers;
import com.akikanellis.kata01.offer.QuantifiedOffer;
import com.akikanellis.kata01.price.Price;

/**
 * An example offer strategy used for testing where all of our items are discounted by 10%.
 */
public class TenPercentOffEverything extends OfferStrategy {
    private static final double TEN_PERCENT = 0.10;

    private TenPercentOffEverything(long id) { super(id, "10% off everything"); }

    public static OfferStrategy create(int id) { return new TenPercentOffEverything(id); }

    @Override public Offers calculateOffers(Items items) {
        Price itemsTotalPrice = calculateItemsTotalPrice(items);
        Price discount = itemsTotalPrice.multiplyBy(TEN_PERCENT).negate();

        Offer offer = Offer.create(description(), discount);
        QuantifiedOffer quantifiedOffer = QuantifiedOffer.create(offer, 1);

        return Offers.fromSingle(quantifiedOffer);
    }

    private Price calculateItemsTotalPrice(Items items) {
        return items.stream()
                .map(QuantifiedItem::totalPrice)
                .reduce(Price::add)
                .orElse(Price.ZERO);
    }
}

Refactor ten percent off everything strategy


package io.quarkus.jackson.deployment;

import java.util.Calendar;
import java.util.Date;

import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.quarkus.test.QuarkusUnitTest;

public class JacksonTimeZonePropertiesTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withConfigurationResource("application-timezone-properties.properties");

    @Inject
    ObjectMapper objectMapper;

    @Test
    public void testTimezone() throws JsonProcessingException {
        Assertions.assertThat(objectMapper.writeValueAsString(new Pojo(new Date(2021, Calendar.MARCH, 3, 11, 5))))
                .contains("+07");
    }

    public static class Pojo {

        private final Date date;

        public Pojo(Date date) {
            this.date = date;
        }

        public Date getDate() {
            return date;
        }
    }
}

package io.quarkus.jackson.deployment;

import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

import javax.inject.Inject;

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.quarkus.test.QuarkusUnitTest;

public class JacksonTimeZonePropertiesTest {

    @RegisterExtension
    static final QuarkusUnitTest config = new QuarkusUnitTest()
            .withConfigurationResource("application-timezone-properties.properties");

    @Inject
    ObjectMapper objectMapper;

    @Test
    public void testTimezone() throws JsonProcessingException {
        Assertions.assertThat(objectMapper.writeValueAsString(new Pojo(Date.from(
                ZonedDateTime.of(LocalDateTime.of(2021, Month.MARCH, 3, 11, 5), ZoneId.of("GMT")).toInstant()))))
                .contains("+07");
    }

    public static class Pojo {

        private final Date date;

        public Pojo(Date date) {
            this.date = date;
        }

        public Date getDate() {
            return date;
        }
    }
}

Replace deprecated Date constructor use in Jackson test


/**
 * 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.camel.component.kafka;

/**
 *
 */
public final class KafkaConstants {

    public static final String DEFAULT_GROUP = "group1";

    public static final String PARTITION_KEY = "kafka.PARTITION_KEY";
    public static final String PARTITION = "kafka.EXCHANGE_NAME";
    public static final String KEY = "kafka.CONTENT_TYPE";
    public static final String TOPIC = "kafka.TOPIC";
    public static final String OFFSET = "kafka.OFFSET";

    public static final String KAFKA_DEFAULT_ENCODER = "kafka.serializer.DefaultEncoder";
    public static final String KAFKA_STRING_ENCODER = "kafka.serializer.StringEncoder";

    private KafkaConstants() {
        // Utility class
    }
}

/**
 * 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.camel.component.kafka;

/**
 *
 */
public final class KafkaConstants {

    public static final String DEFAULT_GROUP = "group1";

    public static final String PARTITION_KEY = "kafka.PARTITION_KEY";
    public static final String PARTITION = "kafka.PARTITION";
    public static final String KEY = "kafka.KEY";
    public static final String TOPIC = "kafka.TOPIC";
    public static final String OFFSET = "kafka.OFFSET";

    public static final String KAFKA_DEFAULT_ENCODER = "kafka.serializer.DefaultEncoder";
    public static final String KAFKA_STRING_ENCODER = "kafka.serializer.StringEncoder";

    private KafkaConstants() {
        // Utility class
    }
}

Make Kafka KEY and PARTITION values more intuitive.


package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Change;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import org.dom4j.Element;

public class AddXmlSerializer extends AbstractChangeXmlSerializer {
    private static final String ADD = "add";
    private static final String INDEX = "index";

    public AddXmlSerializer(Study study) {
        super(study);
    }

    protected Change changeInstance() {
        return new Add();
    }

    protected String elementName() {
        return ADD;
    }

    protected void addAdditionalAttributes(final Change change, Element element) {
        element.addAttribute(INDEX, ((Add)change).getIndex().toString());
        PlanTreeNode<?> planTreeNode = ((Add)change).getChild();
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(planTreeNode);
        Element ePlanTreeNode = serializer.createElement(planTreeNode);
        element.add(ePlanTreeNode);
    }

    protected void setAdditionalProperties(final Element element, Change change) {
        ((Add)change).setIndex(new Integer(element.attributeValue(INDEX)));
        // TODO: Call PlanTreeNodeXmlSerializer
    }
}

package edu.northwestern.bioinformatics.studycalendar.xml.writers;

import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Change;
import edu.northwestern.bioinformatics.studycalendar.domain.Study;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;
import org.dom4j.Element;

import java.util.List;

public class AddXmlSerializer extends AbstractChangeXmlSerializer {
    private static final String ADD = "add";
    private static final String INDEX = "index";

    public AddXmlSerializer(Study study) {
        super(study);
    }

    protected Change changeInstance() {
        return new Add();
    }

    protected String elementName() {
        return ADD;
    }

    protected void addAdditionalAttributes(final Change change, Element element) {
        element.addAttribute(INDEX, ((Add)change).getIndex().toString());
        PlanTreeNode<?> planTreeNode = ((Add)change).getChild();
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(planTreeNode);
        Element ePlanTreeNode = serializer.createElement(planTreeNode);
        element.add(ePlanTreeNode);
    }

    protected void setAdditionalProperties(final Element element, Change add) {
        ((Add)add).setIndex(new Integer(element.attributeValue(INDEX)));
        List<Element> ePlanTreeNodes = element.elements();
        Element ePlanTreeNode = ePlanTreeNodes.get(0);
        AbstractPlanTreeNodeXmlSerializer serializer = getPlanTreeNodeSerializerFactory().createPlanTreeNodeXmlSerializer(ePlanTreeNode);
        PlanTreeNode<?> planTreeNode = serializer.readElement(ePlanTreeNode);
        ((Add)add).setChild(planTreeNode);
    }
}

Add change will now de-serialize a PlanTreeNode children when readElement is called.


package com.github.blindpirate.gogradle.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionHandler {
    public static RuntimeException uncheckException(Throwable e) {
        return new IllegalStateException(e);
    }

    public static String getStackTrace(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
}

package com.github.blindpirate.gogradle.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class ExceptionHandler {
    public static class UncheckedException extends RuntimeException {
        public UncheckedException(Throwable e) {
            super(e);
        }
    }

    public static RuntimeException uncheckException(Throwable e) {
        return new UncheckedException(e);
    }

    public static String getStackTrace(Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        return sw.toString();
    }
}

Throw exceptions with type UncheckedException


package com.blogspot.nurkiewicz.lazyseq.samples;

import com.blogspot.nurkiewicz.lazyseq.AbstractBaseTestCase;
import com.blogspot.nurkiewicz.lazyseq.LazySeq;
import org.testng.annotations.Test;

import static java.util.Arrays.asList;
import static org.fest.assertions.api.Assertions.assertThat;

/**
 * @author Tomasz Nurkiewicz
 * @since 5/12/13, 3:30 PM
 */
public class FibonacciTest extends AbstractBaseTestCase {

	@Test
	public void shouldGenerateFibonacciSequence() throws Exception {
		final LazySeq<Integer> fib = lastTwoFib(0, 1);

		assertThat(fib.startsWith(asList(0, 1, 1, 2, 3, 5, 8, 13, 21)));
	}

	private static LazySeq<Integer> lastTwoFib(int first, int second) {
		return 	LazySeq.<Integer>of(
				first,
				() -> lastTwoFib(second, first + second)
		);

	}

	@Test
	public void shouldReturnGreaterFibonacciNumber() throws Exception {
		final LazySeq<Integer> fib = lastTwoFib(0, 1);
		assertThat(fib.get(5)).isEqualTo(5);
		assertThat(fib.get(45)).isEqualTo(1_134_903_170);
	}

}

package com.blogspot.nurkiewicz.lazyseq.samples;

import com.blogspot.nurkiewicz.lazyseq.AbstractBaseTestCase;
import com.blogspot.nurkiewicz.lazyseq.LazySeq;
import org.testng.annotations.Test;

import static java.util.Arrays.asList;
import static org.fest.assertions.api.Assertions.assertThat;

/**
 * @author Tomasz Nurkiewicz
 * @since 5/12/13, 3:30 PM
 */
public class FibonacciTest extends AbstractBaseTestCase {

	@Test
	public void shouldGenerateFibonacciSequence() throws Exception {
		final LazySeq<Integer> fib = lastTwoFib(0, 1);

		assertThat(fib.startsWith(asList(0, 1, 1, 2, 3, 5, 8, 13, 21)));
	}

	private static LazySeq<Integer> lastTwoFib(int first, int second) {
		return LazySeq.cons(
				first,
				() -> lastTwoFib(second, first + second)
		);
	}

	@Test
	public void shouldReturnGreaterFibonacciNumber() throws Exception {
		final LazySeq<Integer> fib = lastTwoFib(0, 1);
		assertThat(fib.get(5)).isEqualTo(5);
		assertThat(fib.get(45)).isEqualTo(1_134_903_170);
	}

}

Use cons() instead of of() to improve performance


package org.kohsuke.github;

/**
 * A branch in a repository.
 *
 * @author Yusuke Kokubo
 */
public class GHBranch {
    private GitHub root;
    private GHRepository owner;

    private String name;
    private Commit commit;

    public static class Commit {
        String sha,url;
    }

    public GitHub getRoot() {
        return root;
    }

    /**
     * Repository that this branch is in.
     */
    public GHRepository getOwner() {
        return owner;
    }

    public String getName() {
        return name;
    }

    /**
     * The commit that this branch currently points to.
     */
    public String getSHA1() {
        return commit.sha;
    }

    @Override
    public String toString() {
        return "Branch:" + name + " in " + owner.getUrl();
    }

    /*package*/ GHBranch wrap(GHRepository repo) {
        this.owner = repo;
        this.root = repo.root;
        return this;
    }
}

package org.kohsuke.github;

/**
 * A branch in a repository.
 *
 * @author Yusuke Kokubo
 */
public class GHBranch {
    private GitHub root;
    private GHRepository owner;

    private String name;
    private Commit commit;

    public static class Commit {
        String sha,url;
    }

    public GitHub getRoot() {
        return root;
    }

    /**
     * Repository that this branch is in.
     */
    public GHRepository getOwner() {
        return owner;
    }

    public String getName() {
        return name;
    }

    /**
     * The commit that this branch currently points to.
     */
    public String getSHA1() {
        return commit.sha;
    }

    @Override
    public String toString() {
        final String url = owner != null ? owner.getUrl().toString() : "unknown";
        return "Branch:" + name + " in " + url;
    }

    /*package*/ GHBranch wrap(GHRepository repo) {
        this.owner = repo;
        this.root = repo.root;
        return this;
    }
}

Fix potential NPE in the code


package io.teiler.api.endpoint;

import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.post;

import io.teiler.api.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class GroupEndpoint implements Endpoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(GroupEndpoint.class);

    @Autowired
    GroupService groupService;

    @Override
    public void register() {
        before((req, res) -> LOGGER.debug("API call to '" + req.pathInfo() + "'"));

        post("/v1/group", (req, res) -> {
            return groupService.handlePost(req);
        });

        get("/v1/group", (req, res) -> {
            return groupService.handleGet(req);
        });

    }
}

package io.teiler.api.endpoint;

import static spark.Spark.before;
import static spark.Spark.get;
import static spark.Spark.post;

import io.teiler.api.service.GroupService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

@Controller
public class GroupEndpoint implements Endpoint {
    private static final Logger LOGGER = LoggerFactory.getLogger(GroupEndpoint.class);

    @Autowired
    private GroupService groupService;

    @Override
    public void register() {
        before((req, res) -> LOGGER.debug("API call to '" + req.pathInfo() + "'"));

        post("/v1/group", (req, res) -> groupService.handlePost(req));

        get("/v1/group", (req, res) -> groupService.handleGet(req));
    }
}

Make instance private, reorder lambda


package uk.ac.ebi.quickgo.annotation.service.converter;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.when;

/**
 * @author Tony Wardell
 * Date: 29/04/2016
 * Time: 17:39
 * Created with IntelliJ IDEA.
 */
@RunWith(MockitoJUnitRunner.class)
public class AnnotationDocConverterImplTest {

    @Test
    public void convertSuccessfully(){
        AnnotationDocConverter docConverter = new AnnotationDocConverterImpl();
        Annotation model = docConverter.convert(  AnnotationDocMocker.createAnnotationDoc("A0A000"));
        assertThat(model.assignedBy, equalTo("InterPro"));
    }
}

package uk.ac.ebi.quickgo.annotation.service.converter;

import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.Annotation;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.when;

/**
 * @author Tony Wardell
 * Date: 29/04/2016
 * Time: 17:39
 * Created with IntelliJ IDEA.
 */
@RunWith(MockitoJUnitRunner.class)
public class AnnotationDocConverterImplTest {

    @Test
    public void convertAssignedBySuccessfully(){
        AnnotationDocConverter docConverter = new AnnotationDocConverterImpl();
        Annotation model = docConverter.convert(  AnnotationDocMocker.createAnnotationDoc("A0A000"));
        assertThat(model.assignedBy, equalTo("InterPro"));
    }
}

Make test name less generic.


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

/**
 * Tests for global node properties issue. See JENKINS-34818.
 * @since 1.6
 */
package org.biouno.unochoice.issue34818;

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

/**
 * Tests for global node properties issue. See JENKINS-34818.
 * @since 1.5.x
 */
package org.biouno.unochoice.issue34818;

Use the correct since value


package org.marsik.elshelves.api.entities;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import org.marsik.elshelves.ember.EmberModelName;
import org.marsik.elshelves.api.entities.idresolvers.CodeIdResolver;

import javax.validation.constraints.NotNull;
import java.util.UUID;

@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", resolver = CodeIdResolver.class)
@JsonTypeName("code")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        property = "_type",
        visible = true,
        defaultImpl = CodeApiModel.class)
public class CodeApiModel extends AbstractEntityApiModel {
    public CodeApiModel(UUID id) {
        super(id);
    }

    public CodeApiModel() {
    }

    public CodeApiModel(String uuid) {
        super(uuid);
    }

    @NotNull
    String type; // CODE_TYPE - EAN, QR, UPC...
    @NotNull
    String code; // CODE_VALUE

    AbstractNamedEntityApiModel reference;

    UserApiModel belongsTo;

    @Override
    public boolean equals(Object o) {
        return super.equals(o);
    }

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

package org.marsik.elshelves.api.entities;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import lombok.Getter;
import lombok.Setter;
import org.marsik.elshelves.ember.EmberModelName;
import org.marsik.elshelves.api.entities.idresolvers.CodeIdResolver;

import javax.validation.constraints.NotNull;
import java.util.UUID;

@Getter
@Setter
@JsonIdentityInfo(generator = ObjectIdGenerators.None.class, property = "id", resolver = CodeIdResolver.class)
@JsonTypeName("code")
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
        include = JsonTypeInfo.As.EXISTING_PROPERTY,
        property = "_type",
        visible = true,
        defaultImpl = CodeApiModel.class)
public class CodeApiModel extends AbstractEntityApiModel {
    public CodeApiModel(UUID id) {
        super(id);
    }

    public CodeApiModel() {
    }

    public CodeApiModel(String uuid) {
        super(uuid);
    }

    @NotNull
    String type; // CODE_TYPE - EAN, QR, UPC...
    @NotNull
    String code; // CODE_VALUE

    AbstractOwnedEntityApiModel reference;

    UserApiModel belongsTo;

    @Override
    public boolean equals(Object o) {
        return super.equals(o);
    }

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

Allow codes for owned entities in the api models


package com.proxerme.library.result.success;

import android.support.annotation.NonNull;

import com.afollestad.bridge.annotations.Body;
import com.proxerme.library.entity.News;
import com.proxerme.library.result.ProxerResult;

/**
 * TODO: Describe Class
 *
 * @author Ruben Gees
 */
public class NewsResult implements ProxerResult<News[]> {

    @Body(name = "notifications")
    public News[] item;

    NewsResult() {

    }

    public NewsResult(@NonNull News[] item) {
        this.item = item;
    }

    @Override
    @NonNull
    public News[] getItem() {
        return item;
    }
}

package com.proxerme.library.result.success;

import android.support.annotation.NonNull;

import com.afollestad.bridge.annotations.Body;
import com.proxerme.library.entity.News;
import com.proxerme.library.result.ProxerResult;

/**
 * TODO: Describe Class
 *
 * @author Ruben Gees
 */
public class NewsResult implements ProxerResult<News[]> {

    @Body(name = "notifications")
    News[] item;

    NewsResult() {

    }

    public NewsResult(@NonNull News[] item) {
        this.item = item;
    }

    @Override
    @NonNull
    public News[] getItem() {
        return item;
    }
}

Check if package protected visibility works


package com.googlecode.jslint4java.eclipse.preferences;

import java.util.EnumSet;
import java.util.Set;

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

import com.googlecode.jslint4java.Option;
import com.googlecode.jslint4java.eclipse.JSLintPlugin;

/**
 * Set up the default preferences. By default,we enable:
 *

 *
 {@link Option#EQEQEQ}
 *
 {@link Option#UNDEF}
 *
 {@link Option#WHITE}
 *

 */
public class PreferencesInitializer extends AbstractPreferenceInitializer {

    private static final int DEFAULT_INDENT = 4;
    private final Set<Option> defaultEnable = EnumSet.of(Option.EQEQEQ, Option.UNDEF, Option.WHITE);

    @Override
    public void initializeDefaultPreferences() {
        IEclipsePreferences node = new DefaultScope().getNode(JSLintPlugin.PLUGIN_ID);
        for (Option o : defaultEnable) {
            node.putBoolean(o.getLowerName(), true);
        }
        // Hand code these.
        node.putInt(Option.INDENT.getLowerName(), DEFAULT_INDENT);
    }

}

package com.googlecode.jslint4java.eclipse.preferences;

import java.util.EnumSet;
import java.util.Set;

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

import com.googlecode.jslint4java.Option;
import com.googlecode.jslint4java.eclipse.JSLintPlugin;

/**
 * Set up the default preferences. By default,we enable:
 *

 *
 {@link Option#EQEQEQ}
 *
 {@link Option#UNDEF}
 *
 {@link Option#WHITE}
 *

 */
public class PreferencesInitializer extends AbstractPreferenceInitializer {

    private static final int DEFAULT_INDENT = 4;
    private static final int DEFAULT_MAXERR = 50;

    private final Set<Option> defaultEnable = EnumSet.of(Option.EQEQEQ, Option.UNDEF, Option.WHITE);

    @Override
    public void initializeDefaultPreferences() {
        IEclipsePreferences node = new DefaultScope().getNode(JSLintPlugin.PLUGIN_ID);
        for (Option o : defaultEnable) {
            node.putBoolean(o.getLowerName(), true);
        }
        // Hand code these.
        node.putInt(Option.INDENT.getLowerName(), DEFAULT_INDENT);
        node.putInt(Option.MAXERR.getLowerName(), DEFAULT_MAXERR);
    }

}

Add another default from JSLint.


package org.github.pesan.tools.servicespy.action;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.subjects.ReplaySubject;
import io.reactivex.subjects.Subject;
import org.github.pesan.tools.servicespy.action.entry.LogEntry;
import org.github.pesan.tools.servicespy.action.entry.RequestEntry;
import org.github.pesan.tools.servicespy.action.entry.ResponseEntry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ActionService {

    private final RequestIdGenerator requestIdGenerator;
    private final int maxEntryCount;

    private Subject<LogEntry> buffer;
    private ReplaySubject<LogEntry> replay;

    public ActionService(
            RequestIdGenerator requestIdGenerator,
            @Value("${actions.limit:200}") int maxEntryCount) {
        this.requestIdGenerator = requestIdGenerator;
        this.maxEntryCount = maxEntryCount;
        init();
    }

    private void init() {
        replay = ReplaySubject.createWithSize(maxEntryCount);
        buffer = replay.toSerialized();
    }

    public Observable<LogEntry> list() {
        return replay.take(1, TimeUnit.MILLISECONDS);
    }

    public Observable<LogEntry> streamList() {
        return replay;
    }

    public void log(RequestEntry requestEntry, ResponseEntry responseEntry) {
        buffer.onNext(new LogEntry(requestIdGenerator.next(), requestEntry, responseEntry));
    }

    public Completable clear() {
        return Completable.fromAction(this::init);
    }
}

package org.github.pesan.tools.servicespy.action;

import io.reactivex.Completable;
import io.reactivex.Observable;
import io.reactivex.subjects.ReplaySubject;
import io.reactivex.subjects.Subject;
import org.github.pesan.tools.servicespy.action.entry.LogEntry;
import org.github.pesan.tools.servicespy.action.entry.RequestEntry;
import org.github.pesan.tools.servicespy.action.entry.ResponseEntry;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class ActionService {

    private final RequestIdGenerator requestIdGenerator;
    private final int maxEntryCount;

    private Subject<LogEntry> buffer;

    public ActionService(
            RequestIdGenerator requestIdGenerator,
            @Value("${actions.limit:200}") int maxEntryCount) {
        this.requestIdGenerator = requestIdGenerator;
        this.maxEntryCount = maxEntryCount;
        init();
    }

    private void init() {
        buffer = ReplaySubject.<LogEntry>createWithSize(maxEntryCount).toSerialized();
    }

    public Observable<LogEntry> list() {
        return buffer.take(1, TimeUnit.MILLISECONDS);
    }

    public Observable<LogEntry> streamList() {
        return buffer;
    }

    public void log(RequestEntry requestEntry, ResponseEntry responseEntry) {
        buffer.onNext(new LogEntry(requestIdGenerator.next(), requestEntry, responseEntry));
    }

    public Completable clear() {
        return Completable.fromAction(this::init);
    }
}

Use serialized subject where possible


/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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 io.gravitee.plugin.core.api;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER, SERVICE;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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 io.gravitee.plugin.core.api;

/**
 * @author David BRASSELY (brasseld at gmail.com)
 */
public enum PluginType {

    POLICY, REPORTER, SERVICE, REPOSITORY;

    public static PluginType from(String sType) {
        for(PluginType pluginType : values()) {
            if (pluginType.name().equalsIgnoreCase(sType)) {
                return pluginType;
            }
        }

        throw new IllegalArgumentException("Invalid PolicyType: " + sType);
    }
}

Manage repository as a plugin


package net.grandcentix.thirtyinch.sample;

import com.jakewharton.rxbinding.view.RxView;

import net.grandcentrix.thirtyinch.Presenter;
import net.grandcentrix.thirtyinch.android.ThirtyInchActivity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.widget.TextView;

import rx.Observable;

public class HelloWorldActivity extends ThirtyInchActivity<HelloWorldView>
        implements HelloWorldView {

    private Button mButton;

    private TextView mOutput;

    private TextView mUptime;

    @Override
    public Observable<Void> onButtonClicked() {
        return RxView.clicks(mButton);
    }

    @Override
    public void showPresenterUpTime(final Long uptime) {
        mUptime.setText(String.format("Presenter alive fore %ss", uptime));
    }

    @Override
    public void showText(final String text) {
        mOutput.setText(text);
    }

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

        mButton = (Button) findViewById(R.id.button);
        mOutput = (TextView) findViewById(R.id.output);
        mUptime = (TextView) findViewById(R.id.uptime);
    }

    @NonNull
    @Override
    protected Presenter<HelloWorldView> providePresenter(
            @NonNull final Bundle activityIntentBundle) {
        return new HelloWorldPresenter();
    }

    @NonNull
    @Override
    protected HelloWorldView provideView() {
        return this;
    }
}

package net.grandcentix.thirtyinch.sample;

import com.jakewharton.rxbinding.view.RxView;

import net.grandcentrix.thirtyinch.android.ThirtyInchActivity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.widget.TextView;

import rx.Observable;

public class HelloWorldActivity extends ThirtyInchActivity<HelloWorldPresenter, HelloWorldView>
        implements HelloWorldView {

    private Button mButton;

    private TextView mOutput;

    private TextView mUptime;

    @Override
    public Observable<Void> onButtonClicked() {
        return RxView.clicks(mButton);
    }

    @NonNull
    @Override
    public HelloWorldPresenter providePresenter(final Bundle activityIntentBundle) {
        return new HelloWorldPresenter();
    }

    @Override
    public void showPresenterUpTime(final Long uptime) {
        mUptime.setText(String.format("Presenter alive fore %ss", uptime));
    }

    @Override
    public void showText(final String text) {
        mOutput.setText(text);
    }

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

        mButton = (Button) findViewById(R.id.button);
        mOutput = (TextView) findViewById(R.id.output);
        mUptime = (TextView) findViewById(R.id.uptime);
    }

    @NonNull
    @Override
    protected HelloWorldView provideView() {
        return this;
    }
}

Update sample for static presenter typing


package com.braintreepayments.cardform.view;

import android.content.Context;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneNumberUtils;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.InputType;
import android.util.AttributeSet;

import com.braintreepayments.cardform.R;

/**
 * Input for mobile number. Validated for presence only due to the wide variation of mobile number formats worldwide.
 */
public class MobileNumberEditText extends ErrorEditText {

    public MobileNumberEditText(Context context) {
        super(context);
        init();
    }

    public MobileNumberEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MobileNumberEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setInputType(InputType.TYPE_CLASS_PHONE);
        InputFilter[] filters = { new LengthFilter(14) };
        setFilters(filters);
        addTextChangedListener(new PhoneNumberFormattingTextWatcher());
    }

    /**
     * @return the unformatted mobile number entered by the user
     */
    public String getMobileNumber() {
        return PhoneNumberUtils.stripSeparators(getText().toString());
    }

    @Override
    public boolean isValid() {
        return isOptional() || getText().toString().length() >= 8;
    }

    @Override
    public String getErrorMessage() {
        return getContext().getString(R.string.bt_mobile_number_required);
    }
}

package com.braintreepayments.cardform.view;

import android.content.Context;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneNumberUtils;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.text.InputType;
import android.util.AttributeSet;

import com.braintreepayments.cardform.R;

/**
 * Input for mobile number. Validated for presence only due to the wide variation of mobile number formats worldwide.
 */
public class MobileNumberEditText extends ErrorEditText {

    public MobileNumberEditText(Context context) {
        super(context);
        init();
    }

    public MobileNumberEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public MobileNumberEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        if (isInEditMode()) {
            return;
        }

        setInputType(InputType.TYPE_CLASS_PHONE);
        InputFilter[] filters = { new LengthFilter(14) };
        setFilters(filters);
        addTextChangedListener(new PhoneNumberFormattingTextWatcher());
    }

    /**
     * @return the unformatted mobile number entered by the user
     */
    public String getMobileNumber() {
        return PhoneNumberUtils.stripSeparators(getText().toString());
    }

    @Override
    public boolean isValid() {
        return isOptional() || getText().toString().length() >= 8;
    }

    @Override
    public String getErrorMessage() {
        return getContext().getString(R.string.bt_mobile_number_required);
    }
}

Fix error in visual layout editor


package com.crowdin.cli.commands.parts;

import com.crowdin.cli.commands.functionality.PropertiesBuilder;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import picocli.CommandLine;

import java.io.File;

public abstract class PropertiesBuilderCommandPart extends Command {

    @CommandLine.Option(names = {"--identity"}, paramLabel = "...", description = "Set a path to user-specific credentials")
    private File identityFile;

    @CommandLine.ArgGroup(exclusive = false, heading = "@|underline CONFIG OPTIONS|@(to use instead configuration file):%n")
    private Params params;

    @CommandLine.Option(names = {"-c", "--config"}, paramLabel = "...", description = "Set a path to the configuration file. Default: crowdin.yml", defaultValue = "crowdin.yml")
    private File configFile;

    protected PropertiesBean buildPropertiesBean() {
        return (new PropertiesBuilder(configFile, identityFile, params)).build();
    }
}

package com.crowdin.cli.commands.parts;

import com.crowdin.cli.commands.functionality.PropertiesBuilder;
import com.crowdin.cli.properties.Params;
import com.crowdin.cli.properties.PropertiesBean;
import picocli.CommandLine;

import java.io.File;

public abstract class PropertiesBuilderCommandPart extends Command {

    @CommandLine.Option(names = {"--identity"}, paramLabel = "...", description = "Set a path to user-specific credentials")
    private File identityFile;

    @CommandLine.ArgGroup(exclusive = false, heading = "@|underline CONFIG OPTIONS|@:%n")
    private Params params;

    @CommandLine.Option(names = {"-c", "--config"}, paramLabel = "...", description = "Set a path to the configuration file. Default: crowdin.yml", defaultValue = "crowdin.yml")
    private File configFile;

    protected PropertiesBean buildPropertiesBean() {
        return (new PropertiesBuilder(configFile, identityFile, params)).build();
    }
}

Remove description for config options


// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cloudConfig;

import com.intellij.openapi.wm.StatusBar;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

/**
 * @author Alexander Lobas
 */
public abstract class CloudConfigTestProvider {
  private static CloudConfigTestProvider myProvider;

  public static @Nullable CloudConfigTestProvider getProvider() {
    return myProvider;
  }

  public static void setProvider(@NotNull CloudConfigTestProvider provider) {
    myProvider = provider;
  }

  public abstract void initLocalClient(@NotNull File location);

  public abstract @NotNull String getStatusInfo();

  public abstract @NotNull String getActions(@NotNull StatusBar statusBar);

  public abstract void runAction(@NotNull StatusBar statusBar, @NotNull String name);
}

// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.cloudConfig;

import com.intellij.openapi.wm.StatusBar;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;

/**
 * @author Alexander Lobas
 */
public abstract class CloudConfigTestProvider {
  private static CloudConfigTestProvider myProvider;

  public static @Nullable CloudConfigTestProvider getProvider() {
    return myProvider;
  }

  public static void setProvider(@NotNull CloudConfigTestProvider provider) {
    myProvider = provider;
  }

  public abstract void initLocalClient(@NotNull File location);

  public abstract @NotNull String getStatusInfo();

  public abstract @NotNull String getPluginsInfo();

  public abstract @NotNull String getActions(@NotNull StatusBar statusBar);

  public abstract void runAction(@NotNull StatusBar statusBar, @NotNull String name);
}

Prepare plugin for gui testing with remote-robot


/**
 * Copyright 2012 The PlayN 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 playn.ios;

import playn.core.Log;

class IOSLog implements Log
{
  @Override
  public void error(String msg, Throwable e) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void error(String msg) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void info(String msg) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void info(String msg, Throwable e) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void debug(String msg) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void debug(String msg, Throwable e) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void warn(String msg) {
    throw new RuntimeException("TODO");
  }

  @Override
  public void warn(String msg, Throwable e) {
    throw new RuntimeException("TODO");
  }
}

/**
 * Copyright 2012 The PlayN 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 playn.ios;

import cli.System.Console;

import playn.core.Log;

class IOSLog implements Log
{
  // TODO: stack traces

  @Override
  public void debug(String msg) {
    Console.WriteLine("DEBUG: " + msg);
  }

  @Override
  public void debug(String msg, Throwable e) {
    debug(msg + ": " + e.getMessage());
  }

  @Override
  public void info(String msg) {
    Console.WriteLine(msg);
  }

  @Override
  public void info(String msg, Throwable e) {
    info(msg + ": " + e.getMessage());
  }

  @Override
  public void warn(String msg) {
    Console.WriteLine("WARN: " + msg);
  }

  @Override
  public void warn(String msg, Throwable e) {
    warn(msg + ": " + e.getMessage());
  }

  @Override
  public void error(String msg) {
    Console.WriteLine("ERROR: " + msg);
  }

  @Override
  public void error(String msg, Throwable e) {
    error(msg + ": " + e.getMessage());
  }
}

Implement simple logging to console.


/*
 * Copyright (c) 2016 Applivery
 *
 * 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.applivery.applvsdklib.domain.appconfig.update;

import com.applivery.applvsdklib.AppliverySdk;

/**
 * Created by Sergio Martinez Rodriguez
 * Date 11/1/16.
 */
public class AppConfigChecker {

  private final LastConfigReader lastConfigReader;

  public AppConfigChecker(LastConfigReader lastConfigReader) {
    this.lastConfigReader = lastConfigReader;
  }

  public boolean shouldCheckAppConfigForUpdate() {

    if (AppliverySdk.isSdkFirstTime()) {
      AppliverySdk.setSdkFirstTimeFalse();
      return false;
    }

    if (AppliverySdk.isSdkRestarted()) {
      AppliverySdk.setSdkRestartedFalse();
      return true;
    }

    if (lastConfigReader.notExistsLastConfig()) {
      return true;
    }

    return AppliverySdk.getCheckForUpdatesBackground();
  }
}

/*
 * Copyright (c) 2016 Applivery
 *
 * 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.applivery.applvsdklib.domain.appconfig.update;

import com.applivery.applvsdklib.AppliverySdk;

/**
 * Created by Sergio Martinez Rodriguez
 * Date 11/1/16.
 */
public class AppConfigChecker {

  private final LastConfigReader lastConfigReader;

  public AppConfigChecker(LastConfigReader lastConfigReader) {
    this.lastConfigReader = lastConfigReader;
  }

  public boolean shouldCheckAppConfigForUpdate() {

    if (AppliverySdk.isSdkFirstTime()) {
      AppliverySdk.setSdkFirstTimeFalse();
      AppliverySdk.setSdkRestartedFalse();
      return false;
    }

    if (AppliverySdk.isSdkRestarted()) {
      AppliverySdk.setSdkRestartedFalse();
      return true;
    }

    if (lastConfigReader.notExistsLastConfig()) {
      return true;
    }

    return AppliverySdk.getCheckForUpdatesBackground();
  }
}

Fix sdk restarted true bug


package com.epam.ta.reportportal.ws.converter.converters;

import com.epam.ta.reportportal.entity.Activity;
import com.epam.ta.reportportal.ws.model.ActivityResource;

import java.sql.Date;
import java.time.ZoneId;
import java.util.function.Function;

public final class ActivityConverter {

	private ActivityConverter() {
		//static only
	}

	public static final Function<Activity, ActivityResource> TO_RESOURCE = activity -> {
		ActivityResource resource = new ActivityResource();
		resource.setActivityId(activity.getId().toString());
		resource.setLastModifiedDate(Date.from(activity.getCreatedAt().atZone(ZoneId.systemDefault()).toInstant()));
		resource.setObjectType(activity.getEntity().name());
		resource.setActionType(activity.getAction());
		resource.setProjectRef(activity.getProjectId().toString());
		resource.setUserRef(activity.getUserId().toString());
		resource.setLoggedObjectRef(activity.getObjectId().toString());
		resource.setDetails(activity.getDetails());
		return resource;
	};
}

package com.epam.ta.reportportal.ws.converter.converters;

import com.epam.ta.reportportal.entity.Activity;
import com.epam.ta.reportportal.ws.model.ActivityResource;

import java.util.function.Function;

import static com.epam.ta.reportportal.commons.EntityUtils.TO_DATE;

public final class ActivityConverter {

	private ActivityConverter() {
		//static only
	}

	public static final Function<Activity, ActivityResource> TO_RESOURCE = activity -> {
		ActivityResource resource = new ActivityResource();
		resource.setActivityId(activity.getId().toString());
		resource.setLastModifiedDate(TO_DATE.apply(activity.getCreatedAt()));
		resource.setObjectType(activity.getActivityEntityType().name());
		resource.setActionType(activity.getAction());
		resource.setProjectRef(activity.getProjectId().toString());
		resource.setUserRef(activity.getUserId().toString());
		resource.setLoggedObjectRef(activity.getObjectId().toString());
		resource.setDetails(activity.getDetails());
		return resource;
	};
}

Use converter from the EntityUtils


package ru.nsu.ccfit.bogush.factory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
	private Storage<T> storage;
	private static final long DEFAULT_PERIOD = 0;
	private Class<T> thingClass;
	private Thread thread;

	private static final String LOGGER_NAME = "Supplier";
	private static final Logger logger = LogManager.getLogger(LOGGER_NAME);

	public Supplier(Storage<T> storage, Class<T> thingClass) {
		this(storage, thingClass, DEFAULT_PERIOD);
	}

	public Supplier(Storage<T> storage, Class<T> thingClass, long period) {
		super(period);
		logger.trace("initialize with period " + period);
		this.storage = storage;
		this.thingClass = thingClass;
		this.thread = new Thread(this);
		thread.setName(toString());
	}

	@Override
	public void run() {
		while (true) {
			try {
				storage.store(thingClass.newInstance());
				waitPeriod();
			} catch (InterruptedException | IllegalAccessException | InstantiationException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public String toString() {
		return getClass().getSimpleName() + "-" + thread.getId();
	}

	public Thread getThread() {
		return thread;
	}
}

package ru.nsu.ccfit.bogush.factory;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Supplier<T extends CarFactoryObject> extends SimplePeriodical implements Runnable {
	private Storage<T> storage;
	private static final long DEFAULT_PERIOD = 0;
	private Class<T> contentType;
	private Thread thread;

	private static final String LOGGER_NAME = "Supplier";
	private static final Logger logger = LogManager.getLogger(LOGGER_NAME);

	public Supplier(Storage<T> storage, Class<T> contentType) {
		this(storage, contentType, DEFAULT_PERIOD);
	}

	public Supplier(Storage<T> storage, Class<T> contentType, long period) {
		super(period);
		logger.trace("initialize with period " + period);
		this.storage = storage;
		this.contentType = contentType;
		this.thread = new Thread(this);
		thread.setName(toString());
	}

	@Override
	public void run() {
		while (true) {
			try {
				storage.store(contentType.newInstance());
				waitPeriod();
			} catch (InterruptedException | IllegalAccessException | InstantiationException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public String toString() {
		return contentType.getSimpleName() + "-" + getClass().getSimpleName() + "-" + thread.getId();
	}

	public Thread getThread() {
		return thread;
	}
}

Change toString() Rename field thingClass to contentType


package ch.rasc.eds.starter.util;

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

import org.bson.conversions.Bson;

import com.mongodb.client.model.Sorts;

import ch.ralscha.extdirectspring.bean.ExtDirectStoreReadRequest;
import ch.ralscha.extdirectspring.bean.SortDirection;
import ch.ralscha.extdirectspring.bean.SortInfo;

public abstract class QueryUtil {

	public static List<Bson> getSorts(ExtDirectStoreReadRequest request) {
		List<Bson> sorts = new ArrayList<>();
		for (SortInfo sortInfo : request.getSorters()) {

			if (sortInfo.getDirection() == SortDirection.ASCENDING) {
				sorts.add(Sorts.ascending(sortInfo.getProperty()));
			}
			else {
				sorts.add(Sorts.descending(sortInfo.getProperty()));
			}
		}
		return sorts;
	}

}

package ch.rasc.eds.starter.util;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import org.bson.conversions.Bson;

import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Sorts;

import ch.ralscha.extdirectspring.bean.ExtDirectStoreReadRequest;
import ch.ralscha.extdirectspring.bean.SortDirection;
import ch.ralscha.extdirectspring.bean.SortInfo;

public abstract class QueryUtil {

	public static List<Bson> getSorts(ExtDirectStoreReadRequest request) {
		List<Bson> sorts = new ArrayList<>();
		for (SortInfo sortInfo : request.getSorters()) {

			if (sortInfo.getDirection() == SortDirection.ASCENDING) {
				sorts.add(Sorts.ascending(sortInfo.getProperty()));
			}
			else {
				sorts.add(Sorts.descending(sortInfo.getProperty()));
			}
		}
		return sorts;
	}

	public static <T> List<T> toList(FindIterable<T> iterable) {
		return StreamSupport.stream(iterable.spliterator(), false)
				.collect(Collectors.toList());
	}

	public static <T> Stream<T> stream(FindIterable<T> iterable) {
		return StreamSupport.stream(iterable.spliterator(), false);
	}
}

Add helper methods that convert a FindIterable to a List and Stream


/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation = translate.translate(
      text,
      TranslateOption.sourceLanguage("en"),
      TranslateOption.targetLanguage("ru")
    );

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

/*
  Copyright 2016, Google, Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package com.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();

    // The text to translate
    String text = "Hello, world!";

    // Translates some text into Russian
    Translation translation =
        translate.translate(
            text,
            TranslateOption.sourceLanguage("en"),
            TranslateOption.targetLanguage("ru"));

    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

Add quickstarts to root module.


package io.tracee.contextlogger.jaxws.container;

public final class TraceeContextLoggerJaxwsConstants {

	private TraceeContextLoggerJaxwsConstants() { }

	public static final String TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL =
			"/src/main/resources/io/tracee/contextlogger/jaxws/TraceeWithErrorLoggingHandlerChain.xml";

}

package io.tracee.contextlogger.jaxws.container;

/**
 * This class is not directly used but exists for the users convenience
 * (Like adding @HandlerChain(xmlFile=TraceeContextLoggerJaxwsConstants.TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL)
 */
@SuppressWarnings("UnusedDeclaration")
public final class TraceeContextLoggerJaxwsConstants {

	private TraceeContextLoggerJaxwsConstants() { }

	public static final String TRACEE_WITH_ERROR_LOGGING_HANDLER_CHAIN_URL =
			"/src/main/resources/io/tracee/contextlogger/jaxws/TraceeWithErrorLoggingHandlerChain.xml";

}

Add comment and SuppressWarning annotation