import io.datakernel.di.annotation.Inject;
import io.datakernel.di.annotation.Provides;
import io.datakernel.di.core.Injector;
import io.datakernel.di.core.InstanceInjector;
import io.datakernel.launcher.Launcher;

@SuppressWarnings("FinalClass")
public final class InstanceInjectorExample extends Launcher {
	@Inject
	String message;

	@Provides
	String message() {
		return "Hello, world!";
	}

	@Override
	protected void run() {
		System.out.println(message);
	}

	public static void main(String[] args) throws Exception {
		Launcher launcher = new InstanceInjectorExample();
		launcher.launch(args);
	}

	// internal job of post-creation objects inject.
	private void postInjectInstances(String [] args) {
		Injector injector = this.createInjector(args);
		InstanceInjector<Launcher> instanceInjector = injector.getInstanceInjector(Launcher.class);
		instanceInjector.injectInto(this);
	}

}

import io.datakernel.di.annotation.Inject;
import io.datakernel.di.annotation.Provides;
import io.datakernel.di.core.Injector;
import io.datakernel.di.core.InstanceInjector;
import io.datakernel.launcher.Launcher;

@SuppressWarnings("FinalClass")
public final class InstanceInjectorExample extends Launcher {
	//[START REGION_1]
	@Inject
	String message;

	@Provides
	String message() {
		return "Hello, world!";
	}

	@Override
	protected void run() {
		System.out.println(message);
	}

	public static void main(String[] args) throws Exception {
		Launcher launcher = new InstanceInjectorExample();
		launcher.launch(args);
	}
	//[END REGION_1]

	// internal job of post-creation objects inject.
	//[START REGION_2]
	private void postInjectInstances(String [] args) {
		Injector injector = this.createInjector(args);
		InstanceInjector<Launcher> instanceInjector = injector.getInstanceInjector(Launcher.class);
		instanceInjector.injectInto(this);
	}
	//[END REGION_2]

}

Add tags to InstanceInjector example

Add tags to InstanceInjector example


package com.vladmihalcea.book.hpjp.hibernate.statistics;

import org.hibernate.stat.internal.ConcurrentStatisticsImpl;

import java.util.concurrent.atomic.AtomicLong;

/**
 * TransactionStatistics - Transaction Statistics
 *
 * @author Vlad Mihalcea
 */
public class TransactionStatistics extends ConcurrentStatisticsImpl {

    private static final ThreadLocal<AtomicLong> transactionStartNanos = new ThreadLocal<AtomicLong>() {
        @Override
        protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private static final ThreadLocal<AtomicLong> connectionCounter = new ThreadLocal<AtomicLong>() {
        @Override
        protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private StatisticsReport report = new StatisticsReport();

    @Override public void connect() {
        connectionCounter.get().incrementAndGet();
        transactionStartNanos.get().compareAndSet(System.nanoTime(), 0);
        super.connect();
    }

    @Override public void endTransaction(boolean success) {
        report.transactionTime(System.nanoTime() - transactionStartNanos.get().longValue());
        report.connectionsCount(connectionCounter.get().longValue());
        report.generate();
        transactionStartNanos.remove();
        connectionCounter.remove();
        super.endTransaction(success);
    }
}

package com.vladmihalcea.book.hpjp.hibernate.statistics;

import org.hibernate.stat.internal.ConcurrentStatisticsImpl;

import java.util.concurrent.atomic.AtomicLong;

/**
 * TransactionStatistics - Transaction Statistics
 *
 * @author Vlad Mihalcea
 */
public class TransactionStatistics extends ConcurrentStatisticsImpl {

    private static final ThreadLocal<AtomicLong> startNanos = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private static final ThreadLocal<AtomicLong> connectionCounter = new ThreadLocal<AtomicLong>() {
        @Override protected AtomicLong initialValue() {
            return new AtomicLong();
        }
    };

    private StatisticsReport report = new StatisticsReport();

    @Override public void connect() {
        connectionCounter.get().incrementAndGet();
        startNanos.get().compareAndSet(System.nanoTime(), 0);
        super.connect();
    }

    @Override public void endTransaction(boolean success) {
        try {
            report.transactionTime(System.nanoTime() - startNanos.get().get());
            report.connectionsCount(connectionCounter.get().get());
            report.generate();
        } finally {
            startNanos.remove();
            connectionCounter.remove();
        }
        super.endTransaction(success);
    }
}

Add finally block as well

Add finally block as well


package org.jvirtanen.parity.net.pmr;

import static org.jvirtanen.parity.net.pmr.PMR.*;

import com.paritytrading.nassau.MessageListener;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * A parser for inbound messages.
 */
public class PMRParser implements MessageListener {

    private Order  order;
    private Cancel cancel;
    private Trade  trade;

    private PMRListener listener;

    /**
     * Create a parser for inbound messages.
     *
     * @param listener the message listener
     */
    public PMRParser(PMRListener listener) {
        this.order  = new Order();
        this.cancel = new Cancel();
        this.trade  = new Trade();

        this.listener = listener;
    }

    @Override
    public void message(ByteBuffer buffer) throws IOException {
        byte messageType = buffer.get();

        switch (messageType) {
        case MESSAGE_TYPE_ORDER:
            order(buffer);
            break;
        case MESSAGE_TYPE_CANCEL:
            cancel(buffer);
            break;
        case MESSAGE_TYPE_TRADE:
            trade(buffer);
            break;
        default:
            throw new PMRException("Unknown message type: " + (char)messageType);
        }
    }

    private void order(ByteBuffer buffer) throws IOException {
        order.get(buffer);

        listener.order(order);
    }

    private void cancel(ByteBuffer buffer) throws IOException {
        cancel.get(buffer);

        listener.cancel(cancel);
    }

    private void trade(ByteBuffer buffer) throws IOException {
        trade.get(buffer);

        listener.trade(trade);
    }

}

package org.jvirtanen.parity.net.pmr;

import static org.jvirtanen.parity.net.pmr.PMR.*;

import com.paritytrading.nassau.MessageListener;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * A parser for inbound messages.
 */
public class PMRParser implements MessageListener {

    private Order  order;
    private Cancel cancel;
    private Trade  trade;

    private PMRListener listener;

    /**
     * Create a parser for inbound messages.
     *
     * @param listener the message listener
     */
    public PMRParser(PMRListener listener) {
        this.order  = new Order();
        this.cancel = new Cancel();
        this.trade  = new Trade();

        this.listener = listener;
    }

    @Override
    public void message(ByteBuffer buffer) throws IOException {
        byte messageType = buffer.get();

        switch (messageType) {
        case MESSAGE_TYPE_ORDER:
            order.get(buffer);
            listener.order(order);
            break;
        case MESSAGE_TYPE_CANCEL:
            cancel.get(buffer);
            listener.cancel(cancel);
            break;
        case MESSAGE_TYPE_TRADE:
            trade.get(buffer);
            listener.trade(trade);
            break;
        default:
            throw new PMRException("Unknown message type: " + (char)messageType);
        }
    }

}

Simplify PMR parser in network protocols


package org.usfirst.frc.team1360.robot.autonomous.actions;

import edu.wpi.first.wpilibj.command.Command;
import org.usfirst.frc.team1360.robot.util.CommandData;

/**
 * AutonomousExampleCommand - Does XXY Function on XXY Subsystem
 */
public class AutonomousExampleCommand extends Command
{
    private double left;
    private double right;
    private boolean toggle;

    public AutonomousExampleCommand(CommandData commandData)
    {
        left = commandData.getDoubles().get("left");
        right = commandData.getDoubles().get("right");
        toggle = commandData.getBooleans().get("toggle");
    }

    public AutonomousExampleCommand(double left, double right, boolean toggle)
    {

    }
    public AutonomousExampleCommand()
    {

    }

    @Override
    protected void initialize()
    {

    }

    @Override
    protected void execute()
    {

    }

    @Override
    protected boolean isFinished()
    {
        return false;
    }

    @Override
    protected void end()
    {

    }

    @Override
    protected void interrupted()
    {

    }
}

Update CommandData to use HashMaps, update examplecommand accordingly.


/**
 * Copyright (C) 2015 MicroWorld (contact@microworld.org)
 *
 * 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.microworld.mangopay.exceptions;

import org.microworld.mangopay.entities.Error;

public class MangopayException extends RuntimeException {
  private static final long serialVersionUID = 2731523113620863203L;

  public MangopayException(final Error error) {
    super(createMessage(error));
  }

  private static String createMessage(final Error error) {
    final StringBuilder message = new StringBuilder();
    message.append(error.getType()).append(": ").append(error.getMessage());
    error.getErrors().forEach((k, v) -> message.append("\n").append(k).append(": ").append(v));
    return message.toString();
  }
}

/**
 * Copyright (C) 2015 MicroWorld (contact@microworld.org)
 *
 * 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.microworld.mangopay.exceptions;

import org.microworld.mangopay.entities.Error;

public class MangopayException extends RuntimeException {
  private static final long serialVersionUID = 3367303069161411738L;

  public MangopayException(final String message) {
    super(message);
  }

  public MangopayException(final Error error) {
    super(createMessage(error));
  }

  private static String createMessage(final Error error) {
    final StringBuilder message = new StringBuilder();
    message.append(error.getType()).append(": ").append(error.getMessage());
    error.getErrors().forEach((k, v) -> message.append("\n").append(k).append(": ").append(v));
    return message.toString();
  }
}

Add constructor taking a String directly.


/*
 * Copyright 2017-present Facebook, 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.facebook.buck.core.description.arg;

import com.facebook.buck.core.sourcepath.SourcePath;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.util.Set;
import org.immutables.value.Value;

/** Common arguments for build rules (but not configuration rules) */
public interface CommonDescriptionArg extends ConstructorArg, HasTargetCompatibleWith {
  String getName();

  ImmutableSet<SourcePath> getLicenses();

  @Value.NaturalOrder
  ImmutableSortedSet<String> getLabels();

  @Value.Derived
  default boolean labelsContainsAnyOf(Set<String> labels) {
    return !Sets.intersection(this.getLabels(), labels).isEmpty();
  }
}

/*
 * Copyright 2017-present Facebook, 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.facebook.buck.core.description.arg;

import com.facebook.buck.core.sourcepath.SourcePath;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import java.util.Set;
import org.immutables.value.Value;

/** Common arguments for build rules (but not configuration rules) */
public interface CommonDescriptionArg extends ConstructorArg, HasTargetCompatibleWith {
  @Hint(isConfigurable = false)
  String getName();

  ImmutableSet<SourcePath> getLicenses();

  @Value.NaturalOrder
  ImmutableSortedSet<String> getLabels();

  @Value.Derived
  default boolean labelsContainsAnyOf(Set<String> labels) {
    return !Sets.intersection(this.getLabels(), labels).isEmpty();
  }
}

Mark rule name as non-configurable

Mark rule name as non-configurable

Summary:
This diff effectively changes nothing because, `name` attribute is fetched from unconfigured graph node from hash map by string, and it will simply fail if `name` is `select` (see also D17633433).

But it's still better to add the annotation
* for documentation
* for compatibity with future buck where coersion is done on unconfigured graph

Reviewed By: bobyangyf

shipit-source-id: b26aac039b


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.base;

public interface Presenter<I> {

  void onCreateView(I view);

  void onDestroyView();

  void onResume();

  void onPause();

  void onDestroy();
}

/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.pydroid.base;

public interface Presenter<I> {

  /**
   * Bind the View to this presenter
   *
   * Usually called during the onCreate/onCreateView calls
   */
  void onCreateView(I view);

  /**
   * Unind the View to this presenter
   *
   * Usually called during the onDestroy/onDestroyView calls
   */
  void onDestroyView();

  /**
   * Used for registering the presenter to various bus subscriptions
   *
   * Generally called during onResume
   */
  void onResume();

  /**
   * Used for unregistering the presenter from various bus subscriptions
   *
   * Generally called during onPause
   */
  void onPause();

  /**
   * Called once the presenter is finally discarded
   *
   * Cleans up any remaining references to data
   */
  void onDestroy();
}

Document the various named methods in the presenter


package com.starquestminecraft.bukkit;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.bukkit.event.server.ServiceUnregisterEvent;
import org.bukkit.plugin.java.JavaPlugin;

import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;

public class SQBase extends JavaPlugin {

    private static SQBase instance;

    public static SQBase getInstance() {
        return instance;
    }

    @Override
    public void onLoad() {

        instance = this;

        saveDefaultConfig();

        StarQuest.initialize(this);

    }

    @Override
    public void onEnable() {

        StarQuest.setupVault(this);

    }

    @EventHandler(priority = EventPriority.MONITOR)
    void onServiceRegister(final ServiceRegisterEvent event) {

        Class<?> service = event.getProvider().getService();

        if(service.equals(Chat.class) || service.equals(Economy.class) || service.equals(Permission.class)) {
            StarQuest.setupVault(this);
        }

    }

    @EventHandler(priority = EventPriority.MONITOR)
    void onServiceRegister(final ServiceUnregisterEvent event) {

        Class<?> service = event.getProvider().getService();

        if(service.equals(Chat.class) || service.equals(Economy.class) || service.equals(Permission.class)) {
            StarQuest.setupVault(this);
        }

    }

}

package com.starquestminecraft.bukkit;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.server.ServiceRegisterEvent;
import org.bukkit.event.server.ServiceUnregisterEvent;
import org.bukkit.plugin.java.JavaPlugin;

import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;

public class SQBase extends JavaPlugin {

    private static SQBase instance;

    public static SQBase getInstance() {
        return instance;
    }

    @Override
    public void onLoad() {

        instance = this;

        saveDefaultConfig();

        StarQuest.initialize(this);

    }

    @Override
    public void onEnable() {

        StarQuest.setupVault(this);

    }

    @EventHandler(priority = EventPriority.MONITOR)
    void onServiceRegister(final ServiceRegisterEvent event) {

        onServiceChange(event.getProvider().getService());

    }

    @EventHandler(priority = EventPriority.MONITOR)
    void onServiceRegister(final ServiceUnregisterEvent event) {

        onServiceChange(event.getProvider().getService());

    }

    private void onServiceChange(final Class<?> service) {

        if(service.equals(Chat.class)) {
            StarQuest.setupVaultChat(this);
        }
        else if(service.equals(Economy.class)) {
            StarQuest.setupVaultEconomy(this);
        }
        else if(service.equals(Permission.class)) {
            StarQuest.setupVaultPermission(this);
        }

    }

}

Update only the changed Vault service

[StarQuest] Update only the changed Vault service


package devopsdistilled.operp.client.context;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ UIContext.class, RmiContext.class })
public class AppContext {

}

package devopsdistilled.operp.client.context;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import({ RmiContext.class, UIContext.class })
public class AppContext {

}

Create RmiContext Beans before UIContext Beans


package co.phoenixlab.discord.api.event;

import co.phoenixlab.discord.api.entities.Message;

public class MessageReceivedEvent {

    private final Message message;

    public MessageReceivedEvent(Message message) {
        this.message = message;
    }

    public Message getMessage() {
        return message;
    }
}

package co.phoenixlab.discord.api.event;

import co.phoenixlab.discord.api.entities.Message;

public class MessageReceivedEvent {

    private final Message message;

    public MessageReceivedEvent(Message message) {
        this.message = message;
    }

    public Message getMessage() {
        return message;
    }

    @Override
    public String toString() {
        return String.format("%s[msg='%s',from=%s,channelId=%s]",
                getClass().getSimpleName(),
                message.getContent(),
                message.getAuthor().getUsername(),
                message.getChannelId());
    }
}

Add toString to help with eventbus debug


package org.yukung.sandbox.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yukung
 */
public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println("start >>>");

        try (
                ServerSocket ss = new ServerSocket(8080);
                Socket socket = ss.accept();
                InputStream in = socket.getInputStream()
        ) {
            HttpRequest request = new HttpRequest(in);

            System.out.println(request.getHeaderText());
            System.out.println(request.getBodyText());
        }

        System.out.println("<<< end");
    }
}

package org.yukung.sandbox.http;

import static org.yukung.sandbox.http.HttpRequest.CRLF;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author yukung
 */
public class Main {
    public static void main(String[] args) throws IOException {
        System.out.println("start >>>");

        try (
            ServerSocket ss = new ServerSocket(8080);
            Socket socket = ss.accept();
            InputStream in = socket.getInputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()))
        ) {
            HttpRequest request = new HttpRequest(in);

            System.out.println(request.getHeaderText());
            System.out.println(request.getBodyText());

            bw.write("HTTP/1.1 200 OK" + CRLF);
        }

        System.out.println("<<< end");
    }
}

Return the status line of response header.


public class CovariantArrayDemo {

    static class Animal {}
    static class Dog extends Animal {}
    static class Cat extends Animal {}

    public static void main(String[] args) {
        Animal[] animals = new Dog[10];       // Covariance, hmmm
        try {
            animals[0] = new Cat();
        } catch (ArrayStoreException e) {
            System.out.println("Runtime type checking!");
        }
    }
}

public class CovariantArrayDemo {

    public static void main(String[] args) {
        Animal[] animals = new Sheep[10];       // Covariance, sadly
        try {
            animals[0] = new Cow("Bessie");
        } catch (ArrayStoreException e) {
            System.out.println("Runtime type checking!");
        }
    }
}

Use existing classes for the covariance example


package fr.animenfance.partenaire.controller;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import fr.animenfance.bean.Partenaire;

public interface PartenaireIndexerService {

  @GetMapping(value = "/partenaires/search", produces = APPLICATION_JSON_VALUE)
  ResponseEntity<List<Partenaire>> searchPartenaire(
    @RequestParam(name = "search") final String search,
    @RequestParam(name = "hitCount") final Integer hitCount);

  @GetMapping(value = "/partenaires/rebuild-index")
  void rebuildIndex();

}

package fr.animenfance.partenaire.controller;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;
import static org.springframework.web.bind.annotation.RequestMethod.GET;

import java.util.List;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import fr.animenfance.bean.Partenaire;

public interface PartenaireIndexerService {

  @RequestMapping(value = "/partenaires/search",
    method = GET,
    produces = APPLICATION_JSON_VALUE)
  ResponseEntity<List<Partenaire>> searchPartenaire(
    @RequestParam(name = "search") final String search,
    @RequestParam(name = "hitCount") final Integer hitCount);

  @RequestMapping(value = "/partenaires/rebuild-index",
    method = GET)
  void rebuildIndex();

}

Rollback to @RequestMapping to comply with feign validation.


package com.pm.server.player;

import java.util.List;

import org.springframework.stereotype.Repository;

@Repository
public class GhostRepositoryImpl implements GhostRepository {

	private List<Ghost> ghosts;

	public Ghost getGhostById(Integer id) {

		for(Ghost ghost : ghosts) {
			if(ghost.getId() == id) {
				return ghost;
			}
		}
		return null;

	}

	public List<Ghost> getAllGhosts() {
		return ghosts;
	}

	public void addGhost(Ghost ghost) throws Exception {

		if(getGhostById(ghost.getId()) != null) {
			ghosts.add(ghost);
		}
		else {
			throw new IllegalArgumentException(
				"addGhost() was given an id belonging to a ghost which is " +
				"already in the registry."
			);
		}

	}

}

package com.pm.server.player;

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

import org.springframework.stereotype.Repository;

@Repository
public class GhostRepositoryImpl implements GhostRepository {

	private List<Ghost> ghosts;

	GhostRepositoryImpl() {
		ghosts = new ArrayList<Ghost>();
	}

	public Ghost getGhostById(Integer id) {

		for(Ghost ghost : ghosts) {
			if(ghost.getId() == id) {
				return ghost;
			}
		}
		return null;

	}

	public List<Ghost> getAllGhosts() {
		return ghosts;
	}

	public void addGhost(Ghost ghost) throws Exception {

		if(getGhostById(ghost.getId()) != null) {
			ghosts.add(ghost);
		}
		else {
			throw new IllegalArgumentException(
				"addGhost() was given an id belonging to a ghost which is " +
				"already in the registry."
			);
		}

	}

}

Initialize ghost list in GhostRespository


// 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.jetbrains.python.buildout.config;

import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.util.NlsSafe;
import icons.PythonIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

public final class BuildoutCfgFileType extends LanguageFileType {
  public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType();
  public static final @NlsSafe String DEFAULT_EXTENSION = "cfg";
  private static final @NlsSafe String NAME = "BuildoutCfg";
  private static final @NlsSafe String DESCRIPTION = "Buildout config";

  private BuildoutCfgFileType() {
    super(BuildoutCfgLanguage.INSTANCE);
  }

  @Override
  @NotNull
  public String getName() {
    return NAME;
  }

  @Override
  @NotNull
  public String getDescription() {
    return DESCRIPTION;
  }

  @Override
  @NotNull
  public String getDefaultExtension() {
    return DEFAULT_EXTENSION;
  }

  @Override
  @Nullable
  public Icon getIcon() {
    return PythonIcons.Python.Buildout.Buildout;
  }
}

// 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.jetbrains.python.buildout.config;

import com.intellij.openapi.fileTypes.LanguageFileType;
import com.intellij.openapi.util.NlsSafe;
import icons.PythonIcons;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;

public final class BuildoutCfgFileType extends LanguageFileType {
  public static final BuildoutCfgFileType INSTANCE = new BuildoutCfgFileType();
  public static final @NlsSafe String DEFAULT_EXTENSION = "cfg";
  private static final @NlsSafe String NAME = "BuildoutCfg";
  private static final @NlsSafe String DESCRIPTION = "Buildout config";

  private BuildoutCfgFileType() {
    super(BuildoutCfgLanguage.INSTANCE);
  }

  @Override
  @NotNull
  public String getName() {
    return NAME;
  }

  @Override
  @NotNull
  public String getDescription() {
    return DESCRIPTION;
  }

  @Override
  @NotNull
  public String getDefaultExtension() {
    return DEFAULT_EXTENSION;
  }

  @Override
  @NotNull
  public Icon getIcon() {
    return PythonIcons.Python.Buildout.Buildout;
  }
}

Replace `@Nullable` with `@NotNull` since method actually always returns non-null value

GitOrigin-RevId: 4e67fd4f27ef4779939739b978c319a2aacbe78c


package name.webdizz.fabric8.ci.cd.ping;

import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DynamicPingController {

    @Autowired
    private Environment environment;

    @RequestMapping("/ping")
    public String ping() {
        return String.format("Hello, I'm a Pinger @%s of %s generation!", environment.getProperty("kubernetes.namespace"), environment.getProperty("app.version"));
    }
}

package name.webdizz.fabric8.ci.cd.ping;

import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DynamicPingController {

    @Autowired
    private Environment environment;

    @RequestMapping("/ping")
    public String ping() {
        return String.format("Hello, I'm a Pinger @%s:%s of %s generation!", environment.getProperty("hostname"), environment.getProperty("kubernetes.namespace"), environment.getProperty("app.version"));
    }
}

Add hostname to be printed on ping

Add hostname to be printed on ping


package com.ezardlabs.lostsector.objects.pickups;

import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.multiplayer.Network;
import com.ezardlabs.lostsector.objects.warframes.Warframe;

public class EnergyPickup extends Pickup {
	private static final int ENERGY = 2;

	@Override
	protected String getAtlasPath() {
		return "images/pickups/energy";
	}

	@Override
	protected String getAnimationPath() {
		return "animations/pickups/energy";
	}

	@Override
	public void onTriggerEnter(Collider other) {
		Warframe w = other.gameObject.getComponentOfType(Warframe.class);
		if (w != null && w.addEnergy(ENERGY)) {
			Network.destroy(gameObject);
		}
	}
}

package com.ezardlabs.lostsector.objects.pickups;

import com.ezardlabs.dethsquare.Collider;
import com.ezardlabs.dethsquare.multiplayer.Network;
import com.ezardlabs.lostsector.objects.warframes.Warframe;

public class EnergyPickup extends Pickup {
	private static final int ENERGY = 20;

	@Override
	protected String getAtlasPath() {
		return "images/pickups/energy";
	}

	@Override
	protected String getAnimationPath() {
		return "animations/pickups/energy";
	}

	@Override
	public void onTriggerEnter(Collider other) {
		Warframe w = other.gameObject.getComponentOfType(Warframe.class);
		if (w != null && w.addEnergy(ENERGY)) {
			Network.destroy(gameObject);
		}
	}
}

Increase energy pickup amount in line with total energy


/*
 * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.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.github.bonigarcia.wdm.test.docker;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

class DockerSafariTest {

    WebDriver driver;

    WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker();

    @BeforeEach
    void setupTest() {
        driver = wdm.create();
    }

    @AfterEach
    void teardown() {
        wdm.quit();
    }

    @Test
    void test() {
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");
        assertThat(driver.getTitle()).contains("Selenium WebDriver");
    }

}

/*
 * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.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.github.bonigarcia.wdm.test.docker;

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

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

class DockerSafariTest {

    WebDriver driver;

    WebDriverManager wdm = WebDriverManager.safaridriver().browserInDocker();

    @BeforeEach
    void setupTest() {
        driver = wdm.create();
    }

    @AfterEach
    void teardown() {
        wdm.quit();
    }

    @Test
    void test() {
        driver.get("https://github.com/bonigarcia/selenium-webdriver-java");
        assertThat(driver.getTitle()).contains("Selenium WebDriver");
    }

}

Change SUT URL in Docker Safari test (due to DST Root CA X3 Expiration)


package org.apache.cassandra.stress.settings;
/*
 *
 * 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.
 *
 */

public enum ConnectionAPI
{
    THRIFT, THRIFT_SMART, SIMPLE_NATIVE, JAVA_DRIVER_NATIVE
}

package org.apache.cassandra.stress.settings;
/*
 *
 * 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.
 *
 */

public enum ConnectionAPI
{
    THRIFT, THRIFT_SMART, SIMPLE_NATIVE, JAVA_DRIVER_NATIVE, THRIFT_DUMMY
}

Add dummy connection api type

Add dummy connection api type


/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.persistence.typeHandling.extensionTypes;

import org.terasology.utilities.Assets;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.persistence.typeHandling.StringRepresentationTypeHandler;

/**
 */
public class PrefabTypeHandler extends StringRepresentationTypeHandler<Prefab> {

    public PrefabTypeHandler() {
    }

    @Override
    public String getAsString(Prefab item) {
        if (item == null) {
            return "";
        }
        return item.getName();
    }

    @Override
    public Prefab getFromString(String representation) {
        return Assets.getPrefab(representation).orElse(null);
    }
}

/*
 * Copyright 2013 MovingBlocks
 *
 * 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.terasology.persistence.typeHandling.extensionTypes;

import org.terasology.utilities.Assets;
import org.terasology.entitySystem.prefab.Prefab;
import org.terasology.persistence.typeHandling.StringRepresentationTypeHandler;

/**
 */
public class PrefabTypeHandler extends StringRepresentationTypeHandler<Prefab> {

    public PrefabTypeHandler() {
    }

    @Override
    public String getAsString(Prefab item) {
        if (item == null) {
            return "";
        }
        return item.getName();
    }

    @Override
    public Prefab getFromString(String representation) {
        if (representation == null) {
            return null;
        }
        return Assets.getPrefab(representation).orElse(null);
    }
}

Fix a crash when a null Prefab field gets synchronized.


package ru.spoddubnyak;

public class CheckString {
    public String sub;
    public String origin;

    public  CheckString(String origin, String sub) {
        this.sub = sub;
        this.origin = origin;
    }

  public boolean checkLineEntyAnotherLine() {
    char[] subArray = this.sub.toCharArray();
    char[] originArray = this.origin.toCharArray();
    int count = 0;
    for  (int i = 0; i < originArray.length - subArray.length + 1; i++ ) {
        if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
            count = 1;
            for (int j = 1; j < subArray.length; j++) {
                if (originArray[i + j] != subArray[j]) {
                    break;
                }
                count++;
            }
         if (count == subArray.length) {
           return true;
         }
		}
    }
   return false;
  }
}

package ru.spoddubnyak;

public class CheckString {
    public String sub;
    public String origin;

    public  CheckString(String origin, String sub) {
        this.sub = sub;
        this.origin = origin;
    }

  public boolean checkLineEntyAnotherLine() {
    char[] subArray = this.sub.toCharArray();
    char[] originArray = this.origin.toCharArray();
    int count = 0;
	int i = 0;
    while ((i < originArray.length - subArray.length + 1) && (count != subArray.length)) {
        if ((originArray[i] == subArray[0]) && (subArray.length + i <= originArray.length)) {
            count = 1;
            for (int j = 1; j < subArray.length; j++) {
                if (originArray[i + j] != subArray[j]) {
                    break;
                }
                count++;
            }
        }
      i++;
    }
   return (count == subArray.length) ? true : false;
  }
}

Update job task 6.1 lesson 1

Update job task 6.1 lesson 1


package squeek.harvestcraftwaila.fixers;

import net.minecraft.block.Block;
import net.minecraft.util.Icon;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.event.EventPriority;
import net.minecraftforge.event.ForgeSubscribe;
import assets.pamharvestcraft.PamHarvestCraft;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.relauncher.ReflectionHelper;

public class IconFixer
{
	@ForgeSubscribe(priority = EventPriority.NORMAL)
	public void onPostTextureStitch(TextureStitchEvent.Post event)
	{
		try
		{
			Icon icon = Block.crops.getIcon(0, 0);
			ReflectionHelper.setPrivateValue(Block.class, PamHarvestCraft.pamCrop, icon, ObfuscationReflectionHelper.remapFieldNames(Block.class.getName(), "blockIcon", "field_94336_cN", "cW"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

package squeek.harvestcraftwaila.fixers;

import net.minecraft.block.Block;
import net.minecraft.util.Icon;
import net.minecraftforge.client.event.TextureStitchEvent;
import net.minecraftforge.event.EventPriority;
import net.minecraftforge.event.ForgeSubscribe;
import assets.pamharvestcraft.BlockPamCrop;
import assets.pamharvestcraft.PamHarvestCraft;
import cpw.mods.fml.common.ObfuscationReflectionHelper;
import cpw.mods.fml.relauncher.ReflectionHelper;

public class IconFixer
{
	@ForgeSubscribe(priority = EventPriority.NORMAL)
	public void onPostTextureStitch(TextureStitchEvent.Post event)
	{
		try
		{
			Icon icon = ((BlockPamCrop) PamHarvestCraft.pamCrop).iconArray[0][0];
			ReflectionHelper.setPrivateValue(Block.class, PamHarvestCraft.pamCrop, icon, ObfuscationReflectionHelper.remapFieldNames(Block.class.getName(), "blockIcon", "field_94336_cN", "cW"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}

Use the first HarvestCraft crop's texture in its iconArray (asparagus) as the crops block's blockIcon


package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

package com.thoughtworks.xstream.core;

import com.thoughtworks.acceptance.AbstractAcceptanceTest;
import com.thoughtworks.xstream.XStream;

public class TreeMarshallerTest extends AbstractAcceptanceTest {

    static class Thing {
        Thing thing;
    }

    protected void setUp() throws Exception {
        super.setUp();
        xstream.setMode(XStream.NO_REFERENCES);
    }

    public void testThrowsExceptionWhenDetectingCircularReferences() {
        Thing a = new Thing();
        Thing b = new Thing();
        a.thing = b;
        b.thing = a;

        try {
            xstream.toXML(a);
            fail("expected exception");
        } catch (TreeMarshaller.CircularReferenceException expected) {
            // good
        }
    }
}

Fix unit test for JDK 1.3.

Fix unit test for JDK 1.3.

git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@701 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e


package com.bitdecay.jump.leveleditor;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Launcher {

    public static void main(String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.width = 1600;
        config.height = 900;
        config.title = "Jump";
        new LwjglApplication(new EditorApp(), config);
    }
}

package com.bitdecay.jump.leveleditor;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;

public class Launcher {

    public static void main(String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.resizable = false;
        config.width = 1600;
        config.height = 900;
        config.title = "Jump Level Editor";
        new LwjglApplication(new EditorApp(), config);
    }
}

Disable resize. Change launcher window name


package com.algar.ifuckforwind.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.algar.ifuckforwind.R;
import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat;

/**
 * Created by algar on 2016-08-30
 */
public class SettingsFragment extends PreferenceFragmentCompat {

    private static final String SECTION_NUMBER = "sectionNumber";
    private int mSectionNumber;

    public SettingsFragment() {}

    public static SettingsFragment newInstance(int sectionNumber) {
        SettingsFragment settingsFragment = new SettingsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(SECTION_NUMBER, sectionNumber);
        settingsFragment.setArguments(bundle);
        return settingsFragment;
    }

    @Override
    public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preference, rootKey);
        mSectionNumber = getArguments().getInt(SECTION_NUMBER);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);

//        View rootView = inflater.inflate(R.layout.fragment_settings, container, false);
//
//        return rootView;
    }
}

package com.algar.ifuckforwind.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.algar.ifuckforwind.R;
import com.takisoft.fix.support.v7.preference.PreferenceFragmentCompat;

/**
 * Created by algar on 2016-08-30
 */
public class SettingsFragment extends PreferenceFragmentCompat {

    private static final String SECTION_NUMBER = "sectionNumber";
    private int mSectionNumber;

    public SettingsFragment() {}

    public static SettingsFragment newInstance(int sectionNumber) {
        SettingsFragment settingsFragment = new SettingsFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(SECTION_NUMBER, sectionNumber);
        settingsFragment.setArguments(bundle);
        return settingsFragment;
    }

    @Override
    public void onCreatePreferencesFix(@Nullable Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.preference, rootKey);
        mSectionNumber = getArguments().getInt(SECTION_NUMBER);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }
}

Add import statement for v14.

Add import statement for v14.


package org.synyx.urlaubsverwaltung.mail.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotEmpty;

@Validated
@ConfigurationProperties(prefix = "uv.mail")
public class UrlaubsverwaltungMailConfigurationProperties {

    @NotEmpty
    private String sender;

    @NotEmpty
    private String administrator;

    @NotEmpty
    private String applicationUrl;

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getAdministrator() {
        return administrator;
    }

    public void setAdministrator(String administrator) {
        this.administrator = administrator;
    }

    public String getApplicationUrl() {
        return applicationUrl;
    }

    public void setApplicationUrl(String applicationUrl) {
        this.applicationUrl = applicationUrl;
    }
}

package org.synyx.urlaubsverwaltung.mail.config;

import org.hibernate.validator.constraints.URL;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;

@Validated
@ConfigurationProperties(prefix = "uv.mail")
public class UrlaubsverwaltungMailConfigurationProperties {

    @Email
    @NotEmpty
    private String sender;

    @Email
    @NotEmpty
    private String administrator;

    @URL
    private String applicationUrl;

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getAdministrator() {
        return administrator;
    }

    public void setAdministrator(String administrator) {
        this.administrator = administrator;
    }

    public String getApplicationUrl() {
        return applicationUrl;
    }

    public void setApplicationUrl(String applicationUrl) {
        this.applicationUrl = applicationUrl;
    }
}

Add uv.mail validation with email and notempty


package com.ejpm.euler.math.prime;

import com.ejpm.euler.math.prime.PrimeNumber;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 *
 * @author edgar.mateus
 */
@RunWith(Parameterized.class)
public class PrimeNumberTest {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
            {37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}

        });
    }

    private final int number;
    private final boolean isPrime;

    public PrimeNumberTest(final int number, final boolean isPrime) {
        this.number = number;
        this.isPrime = isPrime;
    }

    @Test
    public void checkIfPrime() {
        assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
    }

}

package com.ejpm.euler.math.prime;

import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;

import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/**
 *
 * @author edgar.mateus
 */
@RunWith(Parameterized.class)
public class PrimeNumberTest {

    @Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
            {1, false}, {2, true}, {3, true}, {4, false}, {5, true}, {6, false},
            {37, true}, {49, false}, {199, true}, {7919, true}, {15487039, true}, {15486725, false}

        });
    }

    private final int number;
    private final boolean isPrime;

    public PrimeNumberTest(final int number, final boolean isPrime) {
        this.number = number;
        this.isPrime = isPrime;
    }

    @Test
    public void checkIfPrime() {
        assertThat(PrimeNumber.isPrime(number), is(equalTo(isPrime)));
    }

}

Remove comment from package change

Remove comment from package change


package com.proxerme.library;

import com.proxerme.library.api.ProxerApi;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockWebServer;
import okio.Okio;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;

/**
 * TODO: Describe class
 *
 * @author Ruben Gees
 */
public abstract class ApiTest {

    protected MockWebServer server;
    protected ProxerApi api;

    @Before
    public void setUp() throws IOException {
        server = new MockWebServer();
        api = new ProxerApi.Builder("mockKey")
                .okHttp(new OkHttpClient.Builder()
                        .addInterceptor(chain -> {
                            final HttpUrl oldUrl = chain.request().url();
                            final HttpUrl serverUrl = server.url(oldUrl.encodedPath());
                            final HttpUrl newUrl = oldUrl.newBuilder()
                                    .scheme(serverUrl.scheme())
                                    .host(serverUrl.host())
                                    .port(serverUrl.port())
                                    .build();

                            return chain.proceed(chain.request().newBuilder().url(newUrl).build());
                        }).build())
                .build();

        server.start();
    }

    @After
    public void tearDown() throws IOException {
        server.shutdown();
    }

    @NotNull
    protected String fromResource(@NotNull final String file) throws IOException {
        return Okio.buffer(Okio.source(getClass().getClassLoader().getResourceAsStream(file))).readUtf8();
    }
}

package com.proxerme.library;

import com.proxerme.library.api.ProxerApi;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.mockwebserver.MockWebServer;
import okio.Okio;
import org.jetbrains.annotations.NotNull;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;

/**
 * TODO: Describe class
 *
 * @author Ruben Gees
 */
public abstract class ApiTest {

    protected MockWebServer server;
    protected ProxerApi api;

    @Before
    public void setUp() throws IOException {
        server = new MockWebServer();
        api = new ProxerApi.Builder("mockKey")
                .okHttp(new OkHttpClient.Builder()
                        .addInterceptor(new Interceptor() {
                            @Override
                            public Response intercept(Chain chain) throws IOException {
                                final HttpUrl oldUrl = chain.request().url();
                                final HttpUrl serverUrl = server.url(oldUrl.encodedPath());
                                final HttpUrl newUrl = oldUrl.newBuilder()
                                        .scheme(serverUrl.scheme())
                                        .host(serverUrl.host())
                                        .port(serverUrl.port())
                                        .build();

                                return chain.proceed(chain.request().newBuilder().url(newUrl).build());
                            }
                        }).build())
                .build();

        server.start();
    }

    @After
    public void tearDown() throws IOException {
        server.shutdown();
    }

    @NotNull
    protected String fromResource(@NotNull final String file) throws IOException {
        return Okio.buffer(Okio.source(getClass().getClassLoader().getResourceAsStream(file))).readUtf8();
    }
}

Make the project actually compile under Java 7


package com.mpalourdio.hello;

import app.config.WebSecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import java.util.Arrays;

@SpringBootApplication
@PropertySource(value = {
        "file:properties/global.properties",
        "file:properties/local.properties"
}, ignoreResourceNotFound = true)
@Import({WebSecurityConfig.class})
public class Application {

    public static void main(final String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
        final String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        Arrays.stream(beanNames).forEach(System.out::println);
    }
}

package com.mpalourdio.hello;

import app.config.WebSecurityConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

import java.util.Arrays;

@SpringBootApplication
@PropertySource(value = {
        "file:properties/global.properties",
        "file:properties/local.properties"
}, ignoreResourceNotFound = true)
@Import({WebSecurityConfig.class})
public class Application {

    public static void main(final String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
        final String[] beanNames = ctx.getBeanDefinitionNames();

        Arrays.stream(beanNames)
                .sorted()
                .forEach(System.out::println);
    }
}

Sort beans names in stream

Sort beans names in stream


/* 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.activiti.engine.impl.persistence.entity;

import java.io.Serializable;

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public class MembershipEntityImpl extends AbstractEntityNoRevision implements MembershipEntity, Serializable {

  private static final long serialVersionUID = 1L;

  protected String userId;
  protected String groupId;

  public MembershipEntityImpl() {

  }

  public Object getPersistentState() {
    // membership is not updatable
    return MembershipEntityImpl.class;
  }

  public String getId() {
    // membership doesn't have an id
    return null;
  }

  public void setId(String id) {
    // membership doesn't have an id
  }

  public String getUserId() {
    return userId;
  }

  public void setUserId(String userId) {
    this.userId = userId;
  }

  public String getGroupId() {
    return groupId;
  }

  public void setGroupId(String groupId) {
    this.groupId = groupId;
  }

}

/* 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.activiti.engine.impl.persistence.entity;

import java.io.Serializable;

/**
 * @author Tom Baeyens
 * @author Joram Barrez
 */
public class MembershipEntityImpl extends AbstractEntityNoRevision implements MembershipEntity, Serializable {

  private static final long serialVersionUID = 1L;

  protected String userId;
  protected String groupId;

  public MembershipEntityImpl() {

  }

  public Object getPersistentState() {
    // membership is not updatable
    return MembershipEntityImpl.class;
  }

  public String getUserId() {
    return userId;
  }

  public void setUserId(String userId) {
    this.userId = userId;
  }

  public String getGroupId() {
    return groupId;
  }

  public void setGroupId(String groupId) {
    this.groupId = groupId;
  }

}

Fix for create membership issue when used in TaskListener::notify()


package uk.ac.ebi.quickgo.common.loader;

import java.io.*;
import java.util.zip.GZIPOutputStream;

/**
 * To test the GZIPFiles class, create a gzip'd file with known test in a temporary location.
 * The client is expected to clean up the file after it's finished with it.
 *
 * @author Tony Wardell
 * Date: 17/05/2016
 * Time: 15:38
 * Created with IntelliJ IDEA.
 */
public class GZIPFileMocker{

    public static final String TEXT = "Mary had a little lamb, it's fleece was white as snow";

    public static final File createTestFile(){

        BufferedWriter bufferedWriter = null;
        File temp = null;
        try {

            temp = File.createTempFile("temp-file-name", "txt.gz");

            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(
                            new GZIPOutputStream(new FileOutputStream(temp))
                    ));

            // from the input file to the GZIP output file
            bufferedWriter.write(TEXT);
            bufferedWriter.newLine();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            //Close the BufferedWrter
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return temp;
    }
}

package uk.ac.ebi.quickgo.common.loader;

import java.io.*;
import java.util.zip.GZIPOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * To test the GZIPFiles class, create a gzip'd file with known test in a temporary location.
 * The client is expected to clean up the file after it's finished with it.
 *
 * @author Tony Wardell
 * Date: 17/05/2016
 * Time: 15:38
 * Created with IntelliJ IDEA.
 */
class GZIPFileMocker {
    private static final Logger logger = LoggerFactory.getLogger(GZIPFileMocker.class);

    static final String TEXT = "Mary had a little lamb, it's fleece was white as snow";

    static File createTestFile() {
        BufferedWriter bufferedWriter = null;
        File temp = null;

        try {

            temp = File.createTempFile("temp-file-name", "txt.gz");

            //Construct the BufferedWriter object
            bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(
                            new GZIPOutputStream(new FileOutputStream(temp))
                    ));

            // from the input file to the GZIP output file
            bufferedWriter.write(TEXT);
            bufferedWriter.newLine();
        } catch (IOException e) {
            logger.error("Error: ", e);
        } finally {
            //Close the BufferedWrter
            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    logger.error("Error: ", e);
                }
            }
        }

        return temp;
    }
}

Use logger to record exception instead of printStackTrace.


package info.u_team.u_team_core.block;

import java.util.function.Supplier;

import info.u_team.u_team_core.api.block.BlockItemProvider;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;

public class UBlock extends Block implements BlockItemProvider {

	protected final Supplier<Item> blockItem;

	public UBlock(Properties properties) {
		this(null, properties);
	}

	public UBlock(CreativeModeTab creativeTab, Properties properties) {
		this(creativeTab, properties, null);
	}

	public UBlock(Properties properties, Item.Properties blockItemProperties) {
		this(null, properties, blockItemProperties);
	}

	public UBlock(CreativeModeTab creativeTab, Properties properties, Item.Properties blockItemProperties) {
		super(properties);
		blockItem = () -> createBlockItem(blockItemProperties == null ? new Item.Properties().tab(creativeTab) : creativeTab == null ? blockItemProperties : blockItemProperties.tab(creativeTab));
	}

	protected Item createBlockItem(Item.Properties blockItemProperties) {
		return new BlockItem(this, blockItemProperties);
	}

	@Override
	public Item blockItem() {
		return blockItem.get();
	}
}

package info.u_team.u_team_core.block;

import java.util.function.Supplier;

import com.google.common.base.Suppliers;

import info.u_team.u_team_core.api.block.BlockItemProvider;
import net.minecraft.world.item.BlockItem;
import net.minecraft.world.item.CreativeModeTab;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.block.Block;

public class UBlock extends Block implements BlockItemProvider {

	protected final Supplier<Item> blockItem;

	public UBlock(Properties properties) {
		this(null, properties);
	}

	public UBlock(CreativeModeTab creativeTab, Properties properties) {
		this(creativeTab, properties, null);
	}

	public UBlock(Properties properties, Item.Properties blockItemProperties) {
		this(null, properties, blockItemProperties);
	}

	public UBlock(CreativeModeTab creativeTab, Properties properties, Item.Properties blockItemProperties) {
		super(properties);
		blockItem = Suppliers.memoize(() -> createBlockItem(blockItemProperties == null ? new Item.Properties().tab(creativeTab) : creativeTab == null ? blockItemProperties : blockItemProperties.tab(creativeTab)));
	}

	protected Item createBlockItem(Item.Properties blockItemProperties) {
		return new BlockItem(this, blockItemProperties);
	}

	@Override
	public Item blockItem() {
		return blockItem.get();
	}
}

Fix contract of block item provider by memoize the supplier for the block item.


/**
 * Copyright (c) 2005-2007 Intalio inc.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Intalio inc. - initial API and implementation
 */

package org.intalio.tempo.deployment;

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

/**
 * Deployed assembly.
 * <p>
 * This is an immutable data object returned when querying {@link DeploymentService#getDeployedAssemblies()}
 */
public class DeployedAssembly implements Serializable {
    private static final long serialVersionUID = 1L;

    final AssemblyId _aid;
    final File _assemblyDir;
    final List<DeployedComponent> _components;

    public DeployedAssembly(AssemblyId assemblyId, File assemblyDir, List<DeployedComponent> components)
    {
        _aid = assemblyId;
        _assemblyDir = assemblyDir;
        _components = components;
    }

    public AssemblyId getAssemblyId() {
        return _aid;
    }

    public File getAssemblyDir() {
        return _assemblyDir;
    }

    public List<DeployedComponent> getDeployedComponents() {
        return _components;
    }

    public String toString() {
        return _aid.toString();
    }
}

/**
 * Copyright (c) 2005-2007 Intalio inc.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Intalio inc. - initial API and implementation
 */

package org.intalio.tempo.deployment;

import java.io.Serializable;
import java.util.List;

/**
 * Deployed assembly.
 * <p>
 * This is an immutable data object returned when querying {@link DeploymentService#getDeployedAssemblies()}
 */
public class DeployedAssembly implements Serializable {
    private static final long serialVersionUID = 1L;

    final AssemblyId _aid;
    final String _assemblyDir;
    final List<DeployedComponent> _components;

    public DeployedAssembly(AssemblyId assemblyId, String assemblyDir, List<DeployedComponent> components)
    {
        _aid = assemblyId;
        _assemblyDir = assemblyDir;
        _components = components;
    }

    public AssemblyId getAssemblyId() {
        return _aid;
    }

    public String getAssemblyDir() {
        return _assemblyDir;
    }

    public List<DeployedComponent> getDeployedComponents() {
        return _components;
    }

    public String toString() {
        return _aid.toString();
    }
}

Change assemblyDir type from File to String since it needs to travel across the ether

git-svn-id: bf08415a33f9c0f05ac2b054c631df0aaa894ee0@245 f54485bd-ff3a-0410-97a1-83db373c2bce


/*
 * 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.google.j2cl.junit.apt;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * Utility methods for using Apache Velocity.
 */
class J2clTestingVelocityUtil {
  private static final String CLASSPATH_RESOURCE_LOADER_CLASS = "classpath.resource.loader.class";

  /**
   * Creates and returns a VelocityEngine that will find templates on the
   * classpath.
   */
  public static VelocityEngine createEngine() {
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty(
        CLASSPATH_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
    velocityEngine.init();
    return velocityEngine;
  }
}

/*
 * 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.google.j2cl.junit.apt;

import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

/**
 * Utility methods for using Apache Velocity.
 */
class J2clTestingVelocityUtil {
  private static final String CLASSPATH_RESOURCE_LOADER_CLASS = "classpath.resource.loader.class";

  /**
   * Creates and returns a VelocityEngine that will find templates on the
   * classpath.
   */
  public static VelocityEngine createEngine() {
    VelocityEngine velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngine.setProperty(
        CLASSPATH_RESOURCE_LOADER_CLASS, ClasspathResourceLoader.class.getName());
    velocityEngine.setProperty("runtime.references.strict", "true");
    velocityEngine.init();
    return velocityEngine;
  }
}

Make sure junit velocity templates fail-fast on missing references.

PiperOrigin-RevId: 296119525


package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features;

import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView;
import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline.*;

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

/**
 * @author Jan Molak
 */
public class HasHeadline implements Feature<Headline> {

    private final HeadlineConfig config;
    private JobView job;

    public HasHeadline(HeadlineConfig config) {
        this.config = config;
    }

    @Override
    public HasHeadline of(JobView jobView) {
        this.job = jobView;

        return this;
    }

    @Override
    public Headline asJson() {
        return headlineOf(job).asJson();
    }

    private CandidateHeadline headlineOf(final JobView job) {
        List<CandidateHeadline> availableHeadlines = new ArrayList<>();
        Collections.addAll(availableHeadlines,
                new HeadlineOfExecuting(job, config),
                new HeadlineOfAborted(job, config),
                new HeadlineOfFixed(job, config),
                new HeadlineOfFailing(job, config)
        );

        return availableHeadlines.stream().filter(new Predicate<CandidateHeadline>() {
            @Override
            public boolean test(CandidateHeadline candidateHeadline) {
                return candidateHeadline.isApplicableTo(job);
            }
        }).findFirst().orElse(new NoHeadline());
    }
}

package com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features;

import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.JobView;
import com.smartcodeltd.jenkinsci.plugins.buildmonitor.viewmodel.features.headline.*;

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

/**
 * @author Jan Molak
 */
public class HasHeadline implements Feature<Headline> {

    private final HeadlineConfig config;
    private JobView job;

    public HasHeadline(HeadlineConfig config) {
        this.config = config;
    }

    @Override
    public HasHeadline of(JobView jobView) {
        this.job = jobView;

        return this;
    }

    @Override
    public Headline asJson() {
        return headlineOf(job).asJson();
    }

    private CandidateHeadline headlineOf(final JobView job) {
        List<CandidateHeadline> availableHeadlines = new ArrayList<>();
        Collections.addAll(availableHeadlines,
                new HeadlineOfExecuting(job, config),
                new HeadlineOfAborted(job, config),
                new HeadlineOfFixed(job, config),
                new HeadlineOfFailing(job, config)
        );

        return availableHeadlines.stream()
                .filter(candidateHeadline -> candidateHeadline.isApplicableTo(job))
                .findFirst()
                .orElse(new NoHeadline());
    }
}

Replace anonymous type with lambda

Replace anonymous type with lambda


/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

package org.openlmis.stockmanagement.domain.reason;

import lombok.Getter;

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

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

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

/*
 * This program is part of the OpenLMIS logistics management information system platform software.
 * Copyright © 2017 VillageReach
 *
 * This program is free software: you can redistribute it and/or modify it under the terms
 * of the GNU Affero General Public License as published by the Free Software Foundation, either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details. You should have received a copy of
 * the GNU Affero General Public License along with this program. If not, see
 * http://www.gnu.org/licenses.  For additional information contact info@OpenLMIS.org.
 */

package org.openlmis.stockmanagement.domain.reason;

import lombok.Getter;

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

  @Getter
  private int priority;

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

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

This reverts commit e5ccc08d57d538b6d6a4c6a8fd099f50e3a769af.


/*
 * The command to paste text from the clip tray.
 */
package htmleditor.commands;

import htmleditor.HTMLEditor;
import javafx.event.Event;

/**
 * @author aac6012
 */
public class PasteCommand extends UndoableCommand {

    public PasteCommand(HTMLEditor e) {
        this.editor = e ;
    }

    @Override
    public void execute(Event t) {
        int pos = this.editor.getCarrotPosition() ;
        String oldBuff = this.editor.getText().getText() ;

        String newBuff = oldBuff.substring(0,pos) ;
        newBuff += this.editor.getClipboard() ;
        newBuff += oldBuff.substring(pos) ;

        this.editor.setBuffer(newBuff) ;

        this.saveState() ; //Save after state changes.
    }
}

/*
 * The command to paste text from the clip tray.
 */
package htmleditor.commands;

import htmleditor.HTMLEditor;
import javafx.event.Event;

/**
 * @author aac6012
 */
public class PasteCommand extends UndoableCommand {

    public PasteCommand(HTMLEditor e) {
        this.editor = e ;
    }

    @Override
    public void execute(Event t) {
        String oldBuff = this.editor.getText().getText() ;
        String newBuff ;

        String selection = this.editor.getBufferSelection() ;
        int pos = this.editor.getCarrotPosition() ;

        //Overwrite the selection with the pasted text.
        if (!selection.equals("")) {

            //Text is to the left of cursor
            if(pos + selection.length() <= oldBuff.length()
            &&
            selection.equals(oldBuff.substring(pos, pos+selection.length()))){
                //Remove text from right of cursor and insert pasted text
                newBuff = oldBuff.substring(0,pos) ;
                newBuff += this.editor.getClipboard() ;
                newBuff += oldBuff.substring(pos+selection.length()) ;
            }

            //Text is to the right of cursor
            else if(pos - selection.length() > 0
            &&
            selection.equals(oldBuff.substring(pos-selection.length(), pos))){
                //Remove text from left of cursor and insert pasted text
                newBuff = oldBuff.substring(0,pos-selection.length()) ;
                newBuff += this.editor.getClipboard() ;
                newBuff += oldBuff.substring(pos) ;

            }

            //Unable to find text with respect to cursor
            else {
                System.out.println("You broke it.") ;
                //Don't change the buffer if something broke (damage control)
                newBuff = oldBuff ;
            }

        }

        //No text to overwrite because no selection.
        else {
            newBuff = oldBuff.substring(0,pos) ;
            newBuff += this.editor.getClipboard() ;
            newBuff += oldBuff.substring(pos) ;
        }

        this.editor.setBuffer(newBuff) ;

        this.saveState() ; //Save after state changes.
    }
}

Paste will now override selected text.

Paste will now override selected text.


/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2018 Application Security, Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assertions.assertNull(realm.getPassword(null));
        Assertions.assertNull(realm.getPrincipal(null));
        // To support tomcat 9.0.0.M13 and lower this will still work
        Assertions.assertEquals("waffle.apache.WindowsRealm/1.0", realm.getName());
        // In tomcat 9.0.0.M15+, this is all that will now report
        Assertions.assertEquals("WindowsRealm", realm.getClass().getSimpleName());
    }
}

/**
 * Waffle (https://github.com/Waffle/waffle)
 *
 * Copyright (c) 2010-2018 Application Security, Inc.
 *
 * All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse
 * Public License v1.0 which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-v10.html.
 *
 * Contributors: Application Security, Inc.
 */
package waffle.apache;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Windows Realm Tests.
 *
 * @author dblock[at]dblock[dot]org
 */
public class WindowsRealmTests {

    /**
     * Test properties.
     */
    @Test
    public void testProperties() {
        final WindowsRealm realm = new WindowsRealm();
        Assertions.assertNull(realm.getPassword(null));
        Assertions.assertNull(realm.getPrincipal(null));
        Assertions.assertEquals("WindowsRealm", realm.getClass().getSimpleName());
    }
}

Remove legacy tomcat support from test

[test] Remove legacy tomcat support from test

This made no real sense as a test case.


package uk.ac.cam.gpe21.droidssl.analysis;

import soot.PackManager;
import soot.Transform;
import soot.options.Options;

import java.util.Arrays;

public final class StaticAnalyser {
	public static void main(String[] args) {
		Options.v().set_src_prec(Options.src_prec_apk);
		Options.v().set_output_format(Options.output_format_none);
		Options.v().set_android_jars("/opt/android/platforms");
		Options.v().set_process_dir(Arrays.asList("test-hv/build/apk/test-hv-release-unsigned.apk"));
		Options.v().set_unfriendly_mode(true);

		PackManager.v().getPack("jtp").add(new Transform("jtp.allow_all_hostname_verifier", new AllowAllHostnameVerifierTransformer()));

		soot.Main.main(new String[0]);
	}
}

package uk.ac.cam.gpe21.droidssl.analysis;

import soot.PackManager;
import soot.Transform;
import soot.options.Options;

import java.util.Arrays;

public final class StaticAnalyser {
	public static void main(String[] args) {
		Options.v().set_src_prec(Options.src_prec_apk);
		Options.v().set_output_format(Options.output_format_none);
		Options.v().set_android_jars("/opt/android/platforms");
		Options.v().set_process_dir(Arrays.asList("test-hv/build/apk/test-hv-release-unsigned.apk"));

		/*
		 * We configure Soot with the Options class and then call its main()
		 * method with an empty arguments array. Enabling unfriendly mode stops
		 * Soot from printing the help because of the empty arguments array.
		 */
		Options.v().set_unfriendly_mode(true);

		PackManager.v().getPack("jtp").add(new Transform("jtp.allow_all_hostname_verifier", new AllowAllHostnameVerifierTransformer()));

		soot.Main.main(new String[0]);
	}
}

Add comment about setting unfriendly_mode.


package de.christianscheb.partyprojector.app;

import android.os.Bundle;
import android.preference.PreferenceActivity;
import de.christianscheb.partyprojector.app.preferences.AppPreferences;

public class SettingsActivity extends PreferenceActivity {

    public static final String KEY_PREF_SERVER = "pref_server";
    private AppPreferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SettingsFragment fragment = new SettingsFragment();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, fragment)
                .commit();
    }
}

package de.christianscheb.partyprojector.app;

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

public class SettingsActivity extends Activity {

    public static final String KEY_PREF_SERVER = "pref_server";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SettingsFragment fragment = new SettingsFragment();
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, fragment)
                .commit();
    }
}

Use Activity as base class

Use Activity as base class


package com.spaceout;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

public class MainActivity extends Activity {

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

        startService(new Intent(this, NeuralAlertnessService.class));
    }

    public void setNetwork(View view) {
        startActivity(new Intent(this, NetworkActivity.class));
    }

}

package com.spaceout;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

public class MainActivity extends Activity {

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

        startService(new Intent(this, NeuralAlertnessService.class));
    }

    public void setNetwork(View view) {
        startActivity(new Intent(this, NetworkActivity.class));
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, NeuralAlertnessService.class));

        super.onDestroy();
    }

}

Stop the neural alertness service when the app is closed


package org.mym.prettylog;

import android.app.Application;

import org.mym.plog.PLog;
import org.mym.plog.config.PLogConfig;

/**
 * <p>
 * This class shows how to init PLog Library.
 * </p>
 * Created by muyangmin on 9/1/16.
 *
 * @author muyangmin
 * @since V3.94
 */
public class PLogApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        PLog.init(new PLogConfig.Builder()
                .globalTag(null)
//                .emptyMsgLevel(Log.INFO)
                .forceConcatGlobalTag(true)
                .keepInnerClass(true)
                .keepLineNumber(true)
                .useAutoTag(true)
                .maxLengthPerLine(160)
                .build());
    }
}

package org.mym.prettylog;

import android.app.Application;

import org.mym.plog.PLog;
import org.mym.plog.config.PLogConfig;

/**
 * <p>
 * This class shows how to init PLog Library.
 * </p>
 * Created by muyangmin on 9/1/16.
 *
 * @author muyangmin
 * @since V1.3.0
 */
public class PLogApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        PLog.init(new PLogConfig.Builder()
//                .emptyMsgLevel(Log.INFO)
                .forceConcatGlobalTag(true)
                .keepInnerClass(true)
                .keepLineNumber(true)
                .useAutoTag(true)
                .maxLengthPerLine(160)
                .build());
    }
}

Fix a wrong config in sample application.


package mil.nga.giat.mage.sdk.datastore.observation;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;

import mil.nga.giat.mage.sdk.datastore.Property;

@DatabaseTable(tableName = "observation_properties")
public class ObservationProperty extends Property {

	@DatabaseField(foreign = true, uniqueCombo = true)
	private ObservationForm observationForm;

	public ObservationProperty() {
		// ORMLite needs a no-arg constructor
	}

	public ObservationProperty(String pKey, Serializable pValue) {
		super(pKey, pValue);
	}

	public ObservationForm getObservation() {
		return observationForm;
	}

	public void setObservationForm(ObservationForm observationForm) {
		this.observationForm = observationForm;
	}

	public boolean isEmpty() {
		Serializable value = getValue();
		if (value instanceof String) {
			return StringUtils.isBlank(value.toString());
		} else if (value instanceof ArrayList) {
			return ((ArrayList) value).size() == 0;
		} else {
			return value != null;
		}
	}
}

package mil.nga.giat.mage.sdk.datastore.observation;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;

import mil.nga.giat.mage.sdk.datastore.Property;

@DatabaseTable(tableName = "observation_properties")
public class ObservationProperty extends Property {

	@DatabaseField(foreign = true, uniqueCombo = true)
	private ObservationForm observationForm;

	public ObservationProperty() {
		// ORMLite needs a no-arg constructor
	}

	public ObservationProperty(String pKey, Serializable pValue) {
		super(pKey, pValue);
	}

	public ObservationForm getObservation() {
		return observationForm;
	}

	public void setObservationForm(ObservationForm observationForm) {
		this.observationForm = observationForm;
	}

	public boolean isEmpty() {
		Serializable value = getValue();
		if (value instanceof String) {
			return StringUtils.isBlank(value.toString());
		} else if (value instanceof ArrayList) {
			return ((ArrayList) value).size() == 0;
		} else {
			return value == null;
		}
	}
}

Fix isEmpty bug for non string properties


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

package io.kamax.matrix.codec;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MxSha256 {

    private MessageDigest md;

    public MxSha256() {
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public String hash(String data) {
        return MxBase64.encode(md.digest(data.getBytes(StandardCharsets.UTF_8)));
    }

}

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

package io.kamax.matrix.codec;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MxSha256 {

    private MessageDigest md;

    public MxSha256() {
        try {
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public String hash(byte[] data) {
        return MxBase64.encode(md.digest(data));
    }

    public String hash(String data) {
        return hash(data.getBytes(StandardCharsets.UTF_8));
    }

}

Add ability to get SHA256 on bytes

Add ability to get SHA256 on bytes


package com.indeed.proctor.service.config;

/**
 * Context variable configuration, which also requires type conversion.
 */
public class JsonContextVarConfig extends JsonVarConfig {
    private String type;

    // If a context var is missing during extraction, we'll just use this default.
    // If null, the user did not specify a default value for this variable.
    private String defaultValue;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
}

package com.indeed.proctor.service.config;

import org.codehaus.jackson.map.annotate.JsonSerialize;

/**
 * Context variable configuration, which also requires type conversion.
 */
public class JsonContextVarConfig extends JsonVarConfig {
    private String type;

    // If a context var is missing during extraction, we'll just use this default.
    // If null, the user did not specify a default value for this variable.
    private String defaultValue;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
    public String getDefaultValue() {
        return defaultValue;
    }

    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }
}

Exclude null defaultValues from /config/context.


package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import javax.annotation.Nonnull;
import org.realityforge.arez.Arez;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context().getSpy() ).whyRun() );
  }

  static void logAllErrors( @Nonnull final ArezContext context )
  {
    context.addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

package org.realityforge.arez.gwt.examples;

import elemental2.dom.DomGlobal;
import javax.annotation.Nonnull;
import org.realityforge.arez.Arez;
import org.realityforge.arez.ArezContext;
import org.realityforge.arez.extras.WhyRun;

final class ExampleUtil
{
  private ExampleUtil()
  {
  }

  static void spyEvents()
  {
    Arez.context().getSpy().addSpyEventHandler( SpyUtil::emitEvent );
  }

  static void whyRun()
  {
    DomGlobal.console.log( new WhyRun( Arez.context().getSpy() ).whyRun() );
  }

  static void logAllErrors( @Nonnull final ArezContext context )
  {
    context.addObserverErrorHandler( ( observer, error, throwable ) -> {
      DomGlobal.console.log( "Observer error: " + error + "\nobserver: " + observer );
      if ( null != throwable )
      {
        DomGlobal.console.log( throwable );
      }
    } );
  }
}

Add utility to spy events

Add utility to spy events