repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/007-TabuadaEmLoop/src/tabuada/TabuadaEmLoop.java
nivel3/007-TabuadaEmLoop/src/tabuada/TabuadaEmLoop.java
package tabuada; import java.util.Scanner; public class TabuadaEmLoop { public static void main(String[] args) { /** * 031. Tabuada de vários números * O usuário digita um número. * Mostre sua tabuada. * Depois pergunte se ele quer ver a de outro número. * Repita até ele digitar "n". */ Scanner scanner = new Scanner(System.in); String continuar = ""; do { System.out.print("\nInforme um número para ver a tabuada: "); int numero = scanner.nextInt(); for (int i = 1; i <= 10 ; i++) { int resultado = numero * i; System.out.printf("%d x %d = %d\n", numero, i, resultado); } System.out.print("\nDeseja ver a tabuada de outro número? [S] ou [N]: "); continuar = scanner.next().trim().toUpperCase(); } while (!continuar.equals("N")); System.out.println("\nFinalizando Tabuada..."); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel3/019-NumeroArmstrong/src/numero/armstrong/NumeroArmstrong.java
nivel3/019-NumeroArmstrong/src/numero/armstrong/NumeroArmstrong.java
package numero.armstrong; import java.util.Scanner; public class NumeroArmstrong { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Digite um numero: "); int numero = input.nextInt(); if (checkArmstrong(numero)) { System.out.println("É Armstrong!"); } else { System.out.println("Não é!"); } input.close(); } public static boolean checkArmstrong(int numero) { String string = String.valueOf(numero); int tamanho = string.length(); int soma = 0; int num; for (int i = 0; i < string.length(); i++) { num = Integer.parseInt(string.charAt(i) + ""); soma += Math.pow(num, tamanho); } if (soma == numero) { return true; } return false; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/035-JogoDeAdivinhacaoSimples/src/jogo/de/adivinhacao/JogoDeAdivinhacaoSimples.java
nivel1/035-JogoDeAdivinhacaoSimples/src/jogo/de/adivinhacao/JogoDeAdivinhacaoSimples.java
package jogo.de.adivinhacao; import java.util.Random; import java.util.Scanner; public class JogoDeAdivinhacaoSimples { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); int numeroSecreto = random.nextInt(10) + 1; System.out.println("===== Jogo da Adivinhação ====="); System.out.println("Digite seu palpipe entre 1 e 10! Você tem 5 tentativas!"); int tentativas = 0; boolean acertou = false; while (tentativas < 5) { System.out.print((tentativas + 1) + "ª tentativa: "); int palpite = scanner.nextInt(); if (palpite < 1 || palpite > 10) { System.out.println("[ERRO!] Número inválido. Informe um número entre 1 e 10!"); continue; } tentativas++; if (palpite == numeroSecreto) { System.out.printf("\nParabéns!!! Você acertou com %d tentativa(s). O número secreto é %d.\n", tentativas, numeroSecreto); acertou = true; break; } else if (palpite < numeroSecreto) { System.out.println("Errado! O número secreto é maior."); } else { System.out.println("Errado! O número secreto é menor."); } } if (!acertou) { System.out.printf("\nFim das tentativas. Você perdeu! O número secreto era %d.\n", numeroSecreto); } scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/011-CalcularAreaCirculo/src/calcular/area/circulo/CalcularAreaCirculo.java
nivel1/011-CalcularAreaCirculo/src/calcular/area/circulo/CalcularAreaCirculo.java
package calcular.area.circulo; import java.util.Scanner; public class CalcularAreaCirculo { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Digite o valor do Raio: "); double valor = input.nextDouble(); double areaCirculo = calcularArea(valor); System.out.printf("Área do Círculo: %.2f%n", areaCirculo); } public static double calcularArea(double raio) { return raio * raio * Math.PI; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/002-SomarNumerosUnicos/src/Main.java
nivel1/002-SomarNumerosUnicos/src/Main.java
import java.util.HashMap; import java.util.Map; public class Main { public static int somarNumerosUnicos(int[] numeros) { Map<Integer, Integer> frequencia = new HashMap<>(); for(int num : numeros) { frequencia.put(num, frequencia.getOrDefault(num, 0)+ 1); } int soma = 0; for (Map.Entry<Integer, Integer> entrada : frequencia.entrySet()) { if (entrada.getValue() == 1) { soma += entrada.getKey(); } } return soma; } public static void main(String[] args) { int[] numeros = {2, 3, 4, 2, 4}; int resultado = somarNumerosUnicos(numeros); System.out.println("Soma dos números únicos: " + resultado); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/021-ArrayMediaDoAluno/src/media/ArrayMediaDoAluno.java
nivel1/021-ArrayMediaDoAluno/src/media/ArrayMediaDoAluno.java
package media; import java.util.Arrays; import java.util.Scanner; public class ArrayMediaDoAluno { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double[] notas = new double[5]; System.out.println("Informe suas 5 notas e saiba sua média!"); for (int i = 0; i < notas.length; i++) { System.out.print("Informe a " + (i + 1) + "ª nota: "); while (!scanner.hasNextDouble()) { System.out.print("Entrada inválida! Digite a " + (i + 1) + "ª nota: "); scanner.next(); // descarta a entrada inválida } notas[i] = scanner.nextDouble(); } scanner.close(); System.out.println("Suas notas: " + Arrays.toString(notas)); double soma = 0; for (double nota : notas) { soma += nota; } double media = soma / notas.length; System.out.println("Sua média: " + media); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/003-ZooJavaPoo/src/services/Zoologico.java
nivel1/003-ZooJavaPoo/src/services/Zoologico.java
package services; import models.Animal; import java.util.ArrayList; import java.util.List; public class Zoologico { private List<Animal> animais; public Zoologico() { this.animais = new ArrayList<>(); } public void adicionarAnimal(Animal animal) { animais.add(animal); } public void listarAnimaisEmitirSom() { for (Animal animal : animais) { animal.emitirSom(); } } } //Cria uma lista de Animal, que pode armazenar tanto Leao quanto Macaco → polimorfismo. //adicionarAnimal(): adiciona um novo animal. //listarAnimaisEmitindoSom(): percorre a lista e chama emitirSom() (cada animal se comporta de forma diferente, mesmo método → polimorfismo na prática).
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/003-ZooJavaPoo/src/app/Main.java
nivel1/003-ZooJavaPoo/src/app/Main.java
package app; import models.Leao; import models.Macaco; import services.Zoologico; public class Main { public static void main(String[] args) { Zoologico zoo = new Zoologico(); // Criar animais Leao leao = new Leao(); Macaco macaco = new Macaco(); // Adicionar ao zoológico zoo.adicionarAnimal(leao); zoo.adicionarAnimal(macaco); // Mostrar sons zoo.listarAnimaisEmitirSom(); } } //Instancia o serviço Zoologico. //Cria os animais (Leao, Macaco). //Adiciona à lista e executa o método emitirSom() para cada um.
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/003-ZooJavaPoo/src/models/Macaco.java
nivel1/003-ZooJavaPoo/src/models/Macaco.java
package models; public class Macaco extends Animal { public Macaco() { super("Cebus apella", "Uh uh ah ah!"); } @Override public void emitirSom() { System.out.println("Macaco: " + getSom()); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/003-ZooJavaPoo/src/models/Animal.java
nivel1/003-ZooJavaPoo/src/models/Animal.java
package models; public abstract class Animal { private String nomeCientifico; private String som; //Construtor public Animal(String nomeCientifico, String som) { this.nomeCientifico = nomeCientifico; this.som = som; } //Getters public String getNomeCientifico(){ return nomeCientifico; } public String getSom(){ return som; } //Método abstrato (para ser implementado nas subclasses) public abstract void emitirSom(); } //abstract: essa classe não pode ser instanciada diretamente. //Atributos privados ➝ encapsulamento. //Construtor: obriga a passar nome e som ao criar um animal. //emitirSom() é abstrato → cada animal implementa o som do seu jeito.
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/003-ZooJavaPoo/src/models/Leao.java
nivel1/003-ZooJavaPoo/src/models/Leao.java
package models; public class Leao extends Animal { public Leao() { super("Panthera leo", "Rugido!"); } @Override public void emitirSom() { System.out.println("Leão: " + getSom()); } } //super(...) chama o construtor da classe Animal. //@Override: implementa o método abstrato da classe mãe. //Usa getSom() da superclasse (herança + encapsulamento).
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/026-ArraySomenteNegativos/src/negativos/ArraySomenteNegativos.java
nivel1/026-ArraySomenteNegativos/src/negativos/ArraySomenteNegativos.java
package negativos; import java.util.Arrays; import java.util.Scanner; public class ArraySomenteNegativos { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] numerosInformados = new int[10]; for (int i = 0; i < numerosInformados.length; i++) { System.out.print("Informe o " + (i + 1) + "° número: "); numerosInformados[i] = scanner.nextInt(); } int[] somenteNegativos = Arrays.stream(numerosInformados).filter(n -> n < 0).toArray(); System.out.println("Array de negativos: " + Arrays.toString(somenteNegativos)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/032-CalculadoraIMC/src/calculadora/imc/CalculadoraIMC.java
nivel1/032-CalculadoraIMC/src/calculadora/imc/CalculadoraIMC.java
package calculadora.imc; import java.util.Locale; import java.util.Scanner; public class CalculadoraIMC { public static void main(String[] args) { Scanner input = new Scanner(System.in); input.useLocale(Locale.forLanguageTag("pt-BR")); System.out.print("Digite seu peso: (kg) "); double peso = input.nextDouble(); System.out.print("Digite sua altura: (m) "); double altura = input.nextDouble(); double imc = calcularIMC(peso, altura); System.out.printf("Seu IMC: %.3f%n", imc); System.out.println(classificarIMC(imc)); input.close(); } public static String classificarIMC(double imc) { if(imc < 18.5){ return "Magreza"; }else if(imc < 25 ){ return "Normal"; }else if(imc < 30){ return "Sobrepeso"; }else if(imc < 40){ return "Obesidade"; }else{ return "Obesidade Grave"; } } public static double calcularIMC(double peso, double altura) { return peso / (altura * altura); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/018-ArrayNumerosPares/src/pares/ArrayNumerosPares.java
nivel1/018-ArrayNumerosPares/src/pares/ArrayNumerosPares.java
package pares; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class ArrayNumerosPares { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] elementos = new int[10]; System.out.println("========= NÚMEROS PARES ========="); System.out.println("Informe 10 valores inteiros."); // Preenchendo o array com os números informados pelo usuário for (int i = 0; i < elementos.length; i++) { System.out.print((i + 1) + "º valor: "); // Enquanto não for um inteiro válido, continue pedindo while (!scanner.hasNextInt()) { System.out.print("Entrada inválida! Digite o " + (i + 1) + "° valor: "); scanner.next(); // descarta a entrada inválida } elementos[i] = scanner.nextInt(); // Armazena se o valor for inteiro } scanner.close(); // Exibindo os números armazenados no array System.out.println("\nValores informados: " + Arrays.toString(elementos)); // Criando ArrayList de valores pares ArrayList<Integer> pares = new ArrayList<>(); // Verificando números pares e adicionando no ArrayList for (int numero : elementos){ if (numero % 2 == 0) { pares.add(numero); } } // Exibindo somente os valores pares do array original System.out.println("Valores pares: " + pares); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/041-AreaRetangulo/src/area/retangulo/CalcularAreaRetangulo.java
nivel1/041-AreaRetangulo/src/area/retangulo/CalcularAreaRetangulo.java
package area.retangulo; import java.util.InputMismatchException; import java.util.Scanner; public class CalcularAreaRetangulo { public static void main(String[] args) { //Ler valores double base = lerValor("Digite a base do retângulo:"); double altura = lerValor("Digite a altura do retângulo:"); // Calcular área double area = calcularArea(base, altura); // Exibir resultado System.out.println("A área do retângulo é: " + area); } // Método para ler um valor double do usuário public static double lerValor(String mensagem) { Scanner scanner = new Scanner(System.in); double valor = -1; while (true) { try { System.out.println(mensagem); valor = scanner.nextDouble(); if (valor < 0) { System.out.println("Erro: o valor não pode ser negativo. Tente novamente.\n"); } else { return valor; // valor válido } } catch (InputMismatchException e) { System.out.println("Entrada inválida! Digite apenas números.\n"); scanner.nextLine(); // limpa o buffer } } } // Método que recebe base e altura e devolve a área public static double calcularArea(double base, double altura) { return base * altura; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/000-HelloWorld/src/Main.java
nivel1/000-HelloWorld/src/Main.java
public class Main { public static void main(String[] args) { System.out.println("Hello World!"); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/008-SaudacaoPersonalizada/src/saudacao/personalizada/SaudacaoPersonalizada.java
nivel1/008-SaudacaoPersonalizada/src/saudacao/personalizada/SaudacaoPersonalizada.java
package saudacao.personalizada; import java.util.Scanner; public class SaudacaoPersonalizada { public static String criarSaudacao(String texto) { return "Olá, " + texto + "!"; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Digite seu nome: "); String nome = scanner.nextLine(); String resultado = criarSaudacao(nome); System.out.println(resultado); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/042-QuadradoDeUmNumero/src/calcular/quadrado/CalcularQuadrado.java
nivel1/042-QuadradoDeUmNumero/src/calcular/quadrado/CalcularQuadrado.java
package calcular.quadrado; import java.util.InputMismatchException; import java.util.Scanner; public class CalcularQuadrado { public static void main(String[] args) { // Ler valor double n = lerValor("Digite o valor que deseja elevar ao quadrado: "); // Calcular double resultado = calcularNumeroAoQuadrado(n); // Exibir resultado System.out.printf("Resultado: %.2f ao quadrado é %.2f%n", n, resultado); } // Método que lê o número public static double lerValor(String mensagem) { Scanner scanner = new Scanner(System.in); while (true) { try { System.out.print(mensagem); return scanner.nextDouble(); } catch (InputMismatchException e) { System.out.println("[ERRO!] Somente números são aceitos!"); scanner.nextLine(); // limpa o buffer } } } // Método que calcula o número ao quadrado public static double calcularNumeroAoQuadrado(double n) { return n * n; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/014-CalcularMediaLista/src/calcular/media/lista/CalcularMediaLista.java
nivel1/014-CalcularMediaLista/src/calcular/media/lista/CalcularMediaLista.java
package calcular.media.lista; import java.util.ArrayList; import java.util.Scanner; public class CalcularMediaLista { public static void main(String[] args) { ArrayList<Double> lista = new ArrayList<>(); Scanner input = new Scanner(System.in); System.out.println("Digite vários números para descobrir a média!"); System.out.println("Para parar de digitar, escreva um caractere não numérico!"); double num; while (true) { String linha = input.nextLine(); if (linha.isEmpty()) break; try { num = Double.parseDouble(linha); lista.add(num); } catch (NumberFormatException e) { System.out.println("Entrada inválida, digite um número!"); } } input.close(); double media = calcularMedia(lista); System.out.printf("Média: %.2f%n", media); } public static double calcularMedia(ArrayList<Double> lista) { if (lista.isEmpty()) return 0; double soma = lista.stream().mapToDouble(Double::doubleValue).sum(); double media = soma / lista.size(); return media; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/027-HashMapParesChaveValor/src/chave/valor/HashMapParesChaveValor.java
nivel1/027-HashMapParesChaveValor/src/chave/valor/HashMapParesChaveValor.java
package chave.valor; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class HashMapParesChaveValor { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map<String, Double> produtos = new HashMap<>(); int contador = 0; while (contador < 5) { System.out.print("\nNome do produto " + (contador + 1) + ": "); String nome = scanner.nextLine().trim(); if (nome.isEmpty()){ System.out.println("[ERRO] O nome não pode estar vazio!"); continue; // Volta para pedir de novo } if (produtos.containsKey(nome)) { System.out.println("[ERRO] Produto já informado. Digite outro nome!"); continue; // evita duplicata } System.out.print("Preço do produto: "); String entradaPreco = scanner.nextLine().trim(); double preco; try { preco = Double.parseDouble(entradaPreco); } catch (NumberFormatException e) { System.out.println("[ERRO] Informe um número válido para o preço!"); continue; // volta e pede novamente } produtos.put(nome, preco); contador++; } scanner.close(); System.out.println("\n===== Produtos Cadastrados ====="); for (Map.Entry<String, Double> entrada : produtos.entrySet()) { System.out.printf("Produto: %-15s | Preço: R$ %.2f%n", entrada.getKey(), entrada.getValue()); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/009-OperacoesAritmeticas/src/operacoes/aritmeticas/OperacoesAritmeticas.java
nivel1/009-OperacoesAritmeticas/src/operacoes/aritmeticas/OperacoesAritmeticas.java
package operacoes.aritmeticas; import java.util.Scanner; public class OperacoesAritmeticas { // Método que recebe dois números e mostra os resultados das operações public static void calcularOperacoes(double a, double b) { System.out.println("Soma: " + (a + b)); System.out.println("Subtração: " + (a - b)); System.out.println("Multiplicação: " + (a * b)); if (b != 0) { System.out.println("Divisão: " + (a / b)); } else { System.out.println("Divisão: ERRO! não é possível dividir por zero."); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("==== Calculadora ===="); System.out.print("Informe o primeiro número: "); double a = scanner.nextDouble(); System.out.print("Informe o segundo número: "); double b = scanner.nextDouble(); System.out.printf("\nResultados entre %.1f e %.1f:", a, b); System.out.println(); calcularOperacoes(a, b); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/016-ArraySomarElementosInteiros/src/somar/ArraySomarElementosInteiros.java
nivel1/016-ArraySomarElementosInteiros/src/somar/ArraySomarElementosInteiros.java
package somar; import java.util.ArrayList; import java.util.Scanner; public class ArraySomarElementosInteiros { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<Integer> elementos = new ArrayList<>(); // ArrayList para tamanho dinâmico System.out.println("========= SOMANDO NÚMEROS INTEIROS ========="); System.out.println("Digite números inteiros. Pressione ENTER sem digitar nada para parar."); while (true) { System.out.print("Informe um número inteiro: "); String entrada = scanner.nextLine().trim(); // O método trim() remove todos os espaços em branco no início e no fim da String. if (entrada.isEmpty()) { // Condição para parar (Enter) break; } try { int numero = Integer.parseInt(entrada); // Converte a entrada para inteiro elementos.add(numero); // Adiciona ao ArrayList } catch (NumberFormatException e) { System.out.println("Entrada inválida! Digite apenas números inteiros."); } } scanner.close(); // Exibindo os números armazenados no ArrayList System.out.println("\nNúmeros informados: " + elementos); // Calculando a soma int soma = 0; for (int numero : elementos) { soma += numero; } System.out.println("Soma dos números informados: " + soma); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/006-NumeroPrimo/src/numeroprimo/Main.java
nivel1/006-NumeroPrimo/src/numeroprimo/Main.java
package numeroprimo; import java.util.Scanner; public class Main { public static boolean ehPrimo(int numero) { if (numero < 1) return false; for (int i = 2; i <= Math.sqrt(numero); i++) { if (numero % i == 0) return false; } return true; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.println("==== VERIFICADOR DE NÚMERO PRIMO ===="); System.out.printf("Digite um número: "); int numero = scanner.nextInt(); System.out.print("RESULTADO: "); if (ehPrimo(numero)) { System.out.print(numero + " é primo!"); } else { System.out.print(numero + " NÃO é primo!"); } } catch (Exception e) { System.out.println("Entrada inválida! Digite apenas números inteiros."); } finally { scanner.close(); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/043-VerificarNumero/src/verificar/numero/VerificarNumero.java
nivel1/043-VerificarNumero/src/verificar/numero/VerificarNumero.java
package verificar.numero; import java.util.Scanner; public class VerificarNumero { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int numero; System.out.print("Digite um número inteiro: "); if (sc.hasNextInt()) { numero = sc.nextInt(); if (numero > 0) { System.out.println("O número é positivo."); } else if (numero < 0) { System.out.println("O número é negativo."); } else { System.out.println("O número é zero."); } } else { System.out.println("Entrada inválida. Digite apenas números inteiros."); } sc.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/001-Palindromo/src/Main.java
nivel1/001-Palindromo/src/Main.java
import java.util.Scanner; public class Main { public static boolean isPalindrome(String texto) { String textoLimpo = texto.replaceAll("[^a-zA-Z0-9]", "").toLowerCase(); String textoInvertido = new StringBuilder(textoLimpo).reverse().toString(); return textoLimpo.equals(textoInvertido); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("=== Verificador de palíndromo ==="); System.out.print("Digite uma palavra ou frase: "); String str1 = scanner.nextLine(); System.out.println(str1 + " é palíndromo? " + isPalindrome(str1)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/033-TrocarValorDuasVariaveis/src/troca/valor/duas/variaveis/Main.java
nivel1/033-TrocarValorDuasVariaveis/src/troca/valor/duas/variaveis/Main.java
package troca.valor.duas.variaveis; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.printf("Digite o valor de A: "); int a = sc.nextInt(); System.out.printf("Digite o valor de B: "); int b = sc.nextInt(); // Operador xor a = a ^ b; b = b ^ a; a = a ^ b; // XOR (ou exclusivo): // 0 ^ 0 = 0 // 1 ^ 1 = 0 // 0 ^ 1 = 1 // 1 ^ 0 = 1 System.out.println("A: " + a + " | B: " + b); sc.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/040-CondicoesBooleanas/src/condicoes/booleanas/CondicoesBooleanas.java
nivel1/040-CondicoesBooleanas/src/condicoes/booleanas/CondicoesBooleanas.java
package condicoes.booleanas; import java.util.Scanner; public class CondicoesBooleanas { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Está chovendo? (sim/não): "); String chovendo = scanner.nextLine().trim().toLowerCase(); System.out.print("Vai passear com o cachorro? (sim/não): "); String passearComOCachorro = scanner.nextLine().trim().toLowerCase(); // Normaliza "não" com acento if (chovendo.equals("não")) { chovendo = "nao"; } if (passearComOCachorro.equals("não")) { passearComOCachorro = "nao"; } // Converte respostas em booleanos boolean estaChovendo = chovendo.equals("sim") || chovendo.equals("s"); boolean vaiPassearComCachorro = passearComOCachorro.equals("sim") || passearComOCachorro.equals("s"); // Resultado usando operador ternário (&& e || ) e operadores lógicos (? :) String resultado = (estaChovendo && vaiPassearComCachorro) ? "Ambas as condições são verdadeiras." : (estaChovendo || vaiPassearComCachorro) ? "Apenas uma condição é verdadeira." : "Nenhuma das condições é verdadeira."; System.out.println(resultado); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/031-DiasSemana/src/dias/semana/DiasSemana.java
nivel1/031-DiasSemana/src/dias/semana/DiasSemana.java
package dias.semana; import java.util.Scanner; public class DiasSemana { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Digite o numero do dia da semana: "); int numero = input.nextInt(); System.out.println(obterDiaSemana(numero)); } public static String obterDiaSemana(int numero) { switch (numero) { case 1: return "Domingo"; case 2: return "Segunda-feira"; case 3: return "Terça-feira"; case 4: return "Quarta-feira"; case 5: return "Quinta-feira"; case 6: return "Sexta-feira"; case 7: return "Sábado"; default: return "Número inválido"; } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/007-InverterString/src/inverterstring/Main.java
nivel1/007-InverterString/src/inverterstring/Main.java
package inverterstring; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.println(" ===== INVERTER UMA STRING ===== "); System.out.print("Digite uma palavra ou frase: "); String texto = scanner.nextLine(); String textoInvertido = new StringBuilder(texto).reverse().toString(); String textoMinusculo = texto.toLowerCase(); String textoMaiusculo = texto.toUpperCase(); System.out.println("\n*** RESULTADOS ***"); System.out.println("Original: " + texto); System.out.println("Invertido: " + textoInvertido); System.out.println("Minúsculas: " + textoMinusculo); System.out.println("Maiúsculas: " + textoMaiusculo); } catch (Exception e) { System.out.println("Erro ao ler o texto."); } finally { scanner.close(); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/078-ClassificacaoIdade/src/classificacao/ClassificacaoIdade.java
nivel1/078-ClassificacaoIdade/src/classificacao/ClassificacaoIdade.java
package classificacao; import java.util.Scanner; public class ClassificacaoIdade { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int idade = lerIdadeValida(scanner); String classificacao; if (idade <= 12) { classificacao = "Criança"; } else if (idade <= 17) { classificacao = "Adolescente"; } else if (idade <= 64) { classificacao = "Adulto"; } else { classificacao = "Idoso"; } System.out.println("Classificação: " + classificacao); scanner.close(); } private static int lerIdadeValida(Scanner scanner) { int idade; System.out.println("==== Classificador de Idade ===="); while (true) { System.out.print("Digite a idade da pessoa (0 a 120): "); try { idade = scanner.nextInt(); if (idade < 0 || idade > 120) { System.out.println("[ERRO!] Idade fora do intervalo válido. Tente novamente."); } else { return idade; } } catch (Exception e) { System.out.println("[ERRO!] Entrada inválida. Informe um número inteiro."); scanner.nextLine(); } } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/030-ConversorHorario/src/conversor/horario/ConversorMinutosHoras.java
nivel1/030-ConversorHorario/src/conversor/horario/ConversorMinutosHoras.java
package conversor.horario; import java.util.Scanner; public class ConversorMinutosHoras { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Digite quantos minutos deseja converter: "); int minutos = input.nextInt(); System.out.println(converterHorario(minutos)); input.close(); } public static String converterHorario(int minutos) { int hora = minutos / 60; int dias = 0; if (hora > 23) { dias = hora / 24; hora = hora % 24; } int minuto = minutos % 60; if (dias > 0) { return String.format("%d %s, %02d:%02d", dias, (dias == 1 ? "dia" : "dias"), hora, minuto); } return String.format("%02d:%02d", hora, minuto); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/013-MaiorNumeroEmTres/src/maior/numero/em/tres/MaiorNumeroEmTres.java
nivel1/013-MaiorNumeroEmTres/src/maior/numero/em/tres/MaiorNumeroEmTres.java
package maior.numero.em.tres; import java.util.ArrayList; import java.util.Scanner; public class MaiorNumeroEmTres { public static void main(String[] args) { ArrayList<Double> listaNumeros = new ArrayList<>(); Scanner input = new Scanner(System.in); System.out.println("Digite 3 números:"); for (int i = 0; i < 3; i++) { try { double num = input.nextDouble(); listaNumeros.add(num); } catch (java.util.InputMismatchException e) { System.out.println("Valor inválido! Digite um número."); input.next(); i--; } } double maior = calcularMaiorNumero(listaNumeros.get(0), listaNumeros.get(1), listaNumeros.get(2)); System.out.printf("Maior: %.2f\n", maior); } public static double calcularMaiorNumero(double n1, double n2, double n3) { double maior = n1; if (n2 > maior) maior = n2; if (n3 > maior) maior = n3; return maior; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/038-MultiploDeTresOuCinco/src/multiplo/MultiploDeTresOuCinco.java
nivel1/038-MultiploDeTresOuCinco/src/multiplo/MultiploDeTresOuCinco.java
package multiplo; import java.util.Scanner; public class MultiploDeTresOuCinco { public static void main(String[] args) { Scanner scanner =new Scanner(System.in); System.out.print("Informe um número inteiro: "); int numeroInformado = scanner.nextInt(); String resultado = (numeroInformado % 3 == 0 || numeroInformado % 5 == 0) ? numeroInformado + " é múltiplo de 3 ou de 5." : numeroInformado + " não é múltiplo de 3 nem de 5."; System.out.println(resultado); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/020-ArrayNomes/src/nomes/ArrayNomes.java
nivel1/020-ArrayNomes/src/nomes/ArrayNomes.java
package nomes; import java.util.Scanner; public class ArrayNomes { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String[] nomes = new String[5]; System.out.println("Informe 5 nomes. Apenas letras são aceitas!"); for (int i = 0; i < nomes.length; i++) { System.out.print((i + 1) + "° nome: "); String entrada = scanner.nextLine().trim(); if (entrada.isEmpty() || !entrada.matches("[\\p{L} ]+")) { //usar \\p{L} representa qualquer letra Unicode, incluindo acentos System.out.println("ERRO! Informe apenas letras."); i--; // repete esta posição continue; } nomes[i] = entrada; } scanner.close(); // Imprimindo nomes System.out.println("\nNomes informados:"); for (String nome : nomes) { System.out.println(nome); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/071-ArrayTamanho/src/tamanho/ObterTamanhoDoArray.java
nivel1/071-ArrayTamanho/src/tamanho/ObterTamanhoDoArray.java
package tamanho; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ObterTamanhoDoArray { public static void main(String[] args) { // Exemplo 1: array de inteiros int[] numeros = {1, 2, 3, 4, 5, 6}; System.out.println("Array de inteiros: " + java.util.Arrays.toString(numeros)); System.out.println("Tamanho: " + numeros.length); // Exemplo 2: array de Strings String[] nomes = {"Ana", "Beatriz", "Carlos"}; System.out.println("\nArray de Strings: " + java.util.Arrays.toString(nomes)); System.out.println("Tamanho: " + nomes.length); // Exemplo 3: array vazio double[] vazios = {}; System.out.println("\nArray vazio: " + java.util.Arrays.toString(vazios)); System.out.println("Tamanho: " + vazios.length); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/005-Fatorial/src/fatorial/Main.java
nivel1/005-Fatorial/src/fatorial/Main.java
package fatorial; import java.util.Scanner; public class Main { public static long calcularFatorial(int n) { long fatorial = 1; System.out.print(n + "! = "); for (int i = n; i >= 1; i--) { fatorial *= i; System.out.print(i); if (i > 1) { System.out.print(" x "); } } System.out.print(" = "); // Parte final antes do resultado return fatorial; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.println("===== F A T O R I A L ====="); System.out.print("Digite um número inteiro positivo: "); int numero = scanner.nextInt(); if (numero < 0) { System.out.println("Não é possível calcular fatorial de número negativo."); } else { long resultado = calcularFatorial(numero); System.out.println(resultado); } } catch (Exception e) { System.out.println("Entrada inválida! Digite apenas números inteiros."); } finally { scanner.close(); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/028-HashMapNomeIdade/src/nome/idade/HashMapNomeIdade.java
nivel1/028-HashMapNomeIdade/src/nome/idade/HashMapNomeIdade.java
package nome.idade; import java.util.*; public class HashMapNomeIdade { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map<String, Integer> pessoas = new HashMap<>(); while (pessoas.size() < 5) { System.out.print("\nNome da " + (pessoas.size() + 1) + "ª pessoa: "); String nome = scanner.nextLine().trim(); if (nome.isEmpty()){ System.out.println("[ERRO] O nome não pode estar vazio!"); continue; // Se vazio pede novamente } if (pessoas.containsKey(nome)) { System.out.println("[ERRO] Essa pessoa já foi registrada! Digite outro nome!"); continue; // Evita duplicata } System.out.print("Informe a idade: "); String idadeEntrada = scanner.nextLine().trim(); if (idadeEntrada.isEmpty()) { System.out.println("[ERRO] Idade não pode estar vazia!"); continue; // Se vazio pede novamente } int idade; try { idade = Integer.parseInt(idadeEntrada); if (idade < 0 || idade > 120){ System.out.println("[ERRO] Idade não pode ser negativa ou maior que 120 anos!"); continue; } } catch (NumberFormatException e) { System.out.println("[ERRO] Informe uma idade válida!"); continue; } pessoas.put(nome, idade); } scanner.close(); // Encontrando o(s) mais velho(s) int idadeMaisAlta = Collections.max(pessoas.values()); List<String> nomesMaisVelhos = new ArrayList<>(); for (Map.Entry<String, Integer> entrada : pessoas.entrySet()) { if (entrada.getValue() == idadeMaisAlta) { nomesMaisVelhos.add(entrada.getKey()); } } // Todos Cadastrados System.out.println("\n===== Pessoas Cadastradas ====="); for (Map.Entry<String, Integer> entrada : pessoas.entrySet()){ System.out.printf("Nome: %-15s | Idade: %d%n", entrada.getKey(), entrada.getValue()); } //Resultado Final if (nomesMaisVelhos.size() == 1) { System.out.println("\nA pessoa com mais idade é " + nomesMaisVelhos.get(0) + " com " + idadeMaisAlta + " anos."); } else { System.out.println("\nOs mais velhos são: " + String.join(", ", nomesMaisVelhos) + " com " + idadeMaisAlta + " anos."); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/039-LetraVogal/src/verificador/vogal/LetraVogal.java
nivel1/039-LetraVogal/src/verificador/vogal/LetraVogal.java
package verificador.vogal; import java.util.Scanner; public class LetraVogal { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("===== Verificador de Vogal ====="); System.out.print("Informe uma letra (a-z): "); String entrada = scanner.nextLine().trim(); if (entrada.length() != 1 || !Character.isLetter(entrada.charAt(0))){ System.out.println("[ERRO] Informe apenas uma letra válida!"); } else { char letra = Character.toLowerCase(entrada.charAt(0)); String vogais = "aeiou"; String resultado = vogais.contains(String.valueOf(letra)) ? letra + " é vogal!" : letra + " não é vogal!"; System.out.println(resultado); } scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/019-ArrayNumerosImpares/src/impares/ArrayNumerosImpares.java
nivel1/019-ArrayNumerosImpares/src/impares/ArrayNumerosImpares.java
package impares; import java.util.ArrayList; import java.util.Arrays; public class ArrayNumerosImpares { public static void main(String[] args) { //Array aleatório de números entre 1 a 100 int tamanho = 10; int[] numeros = new int[tamanho]; for (int i = 0; i < tamanho; i++) { numeros[i] = (int) (Math.random() * 100) + 1; // Gera número de 1 a 100 } System.out.println("======== NÚMEROS ÍMPARES ========"); ArrayList<Integer> impares = new ArrayList<>(); int contadorImpares = 0; for (int numero : numeros) { if (numero % 2 != 0) { contadorImpares++; impares.add(numero); } } System.out.println("Array aleatório: " + Arrays.toString(numeros)); System.out.println("Quantidade: " + contadorImpares); System.out.println("Ímpares: " + impares); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/036-NumeroEntre10E20/src/verificador/NumeroEntre10E20.java
nivel1/036-NumeroEntre10E20/src/verificador/NumeroEntre10E20.java
package verificador; import java.util.Scanner; public class NumeroEntre10E20 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Digite um número: "); int numero = scanner.nextInt(); if (numero >= 10 && numero <= 20){ System.out.println("✅ O número está entre 10 e 20 (inclusive)."); } else { System.out.println("❌ O número NÃO está entre 10 e 20."); } scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/010-ApenasDigitosEmString/src/apenas/digitos/em/string/ApenasDigitosEmString.java
nivel1/010-ApenasDigitosEmString/src/apenas/digitos/em/string/ApenasDigitosEmString.java
package apenas.digitos.em.string; import java.util.Scanner; public class ApenasDigitosEmString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Informe uma string: "); String input = scanner.nextLine(); boolean somenteDigitos = true; for (int i = 0; i < input.length(); i++) { char c = input.charAt(i); if (c < '0' || c > '9') { // verifica se não é dígito somenteDigitos = false; break; // sai do laço assim que encontrar um não dígito } } if (somenteDigitos) { System.out.println("A string contém apenas dígitos."); } else { System.out.println("A string contém caracteres que não são dígitos."); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/037-VerificarVoto/src/verificacao/voto/VerificarVoto.java
nivel1/037-VerificarVoto/src/verificacao/voto/VerificarVoto.java
package verificacao.voto; import java.util.Scanner; public class VerificarVoto { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("===== Verificação de Voto ====="); System.out.print("Informe sua idade: "); int idade = scanner.nextInt(); scanner.nextLine(); // consumir quebra de linha System.out.print("Você possui título de eleitor? (sim/não): "); String resposta = scanner.nextLine().trim().toLowerCase(); if (resposta.equals("não")) { resposta = "nao"; } // Normaliza "não" (com ou sem acento) boolean temTitulo = resposta.equals("sim") || resposta.equals("s"); if (idade >= 16 && idade <= 65 && temTitulo) { System.out.println("Pode votar normalmente."); } else { System.out.println("Não pode votar."); } scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/025-ArraySomentePositivos/src/positivos/ArraySomentePositivos.java
nivel1/025-ArraySomentePositivos/src/positivos/ArraySomentePositivos.java
package positivos; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class ArraySomentePositivos { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] numerosInformados = new int[10]; for (int i = 0; i < numerosInformados.length; i++) { System.out.print("Informe o " + (i + 1) + "° número: "); numerosInformados[i] = scanner.nextInt(); } int[] numerosPositivos = Arrays.stream(numerosInformados).filter(n -> n > 0).toArray(); System.out.println("Array de positivos: " + Arrays.toString(numerosPositivos)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/023-ArrayTemONumero/src/encontrar/numero/ArrayTemONumero.java
nivel1/023-ArrayTemONumero/src/encontrar/numero/ArrayTemONumero.java
package encontrar.numero; import java.util.Arrays; import java.util.Scanner; public class ArrayTemONumero { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Verifique se um número foi sorteado (Escolha entre 1 a 50): "); int[] numerosaleatorios = new int[20]; for (int i = 0; i < numerosaleatorios.length; i++) { numerosaleatorios[i] = (int) (Math.random() * 50 ) + 1; } int palpite = scanner.nextInt(); boolean existe = Arrays.stream(numerosaleatorios).anyMatch(n -> n == palpite); if (existe) { System.out.println("O número " + palpite + " foi encontrado no array!"); } else { System.out.println("\nO número não foi encontrado!"); } System.out.println("Números sorteados: " + Arrays.toString(numerosaleatorios)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/015-ArrayImprimirCincoNumerosInteiros/src/imprimir/cinco/numeros/inteiros/ArrayImprimirCincoNumerosInteiros.java
nivel1/015-ArrayImprimirCincoNumerosInteiros/src/imprimir/cinco/numeros/inteiros/ArrayImprimirCincoNumerosInteiros.java
package imprimir.cinco.numeros.inteiros; import java.util.Arrays; import java.util.Scanner; public class ArrayImprimirCincoNumerosInteiros { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] elementos = new int[5]; // Criando array // Preenchendo o array com os números informados pelo usuário for (int i = 0; i < elementos.length; i++) { System.out.print("Informe o " + (i + 1) + "° número inteiro: "); // Enquanto não for um inteiro válido, continue pedindo while (!scanner.hasNextInt()) { System.out.print("Entrada inválida! Digite o " + (i + 1) + "° número inteiro: "); scanner.next(); // descarta a entrada inválida } elementos[i] = scanner.nextInt(); // Armazena se inteiro válido } scanner.close(); // Exibindo os números armazenados no array System.out.println("\nNúmeros informados: " + Arrays.toString(elementos)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/024-ArrayInverterOrdem/src/inverter/ArrayInverterOrdem.java
nivel1/024-ArrayInverterOrdem/src/inverter/ArrayInverterOrdem.java
package inverter; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class ArrayInverterOrdem { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Integer[] numeros = new Integer[10]; for (int i = 0; i < numeros.length; i++) { System.out.print("Informe o " + (i + 1) + "° número: "); while (!scanner.hasNextInt()) { System.out.print("Entrada inválida! Digite o " + (i + 1) + "° número inteiro: "); scanner.next(); } numeros[i] = scanner.nextInt(); } scanner.close(); System.out.println("Array Original: " + Arrays.toString(numeros)); Collections.reverse(Arrays.asList(numeros)); System.out.println("Array invertido: " + Arrays.toString(numeros)); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/034-SimuladorDado/src/simulador/dado/SimuladorDado.java
nivel1/034-SimuladorDado/src/simulador/dado/SimuladorDado.java
package simulador.dado; import java.util.Random; public class SimuladorDado { public static void main(String[] args) { System.out.println("Número do dado: " + jogarDado()); } public static int jogarDado(){ int[] dado = {1,2,3,4,5,6}; Random random = new Random(); int index = random.nextInt(dado.length); return dado[index]; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/029-SetRemoverNomesRepetidos/src/remover/repetidos/SetRemoverNomesRepetidos.java
nivel1/029-SetRemoverNomesRepetidos/src/remover/repetidos/SetRemoverNomesRepetidos.java
package remover.repetidos; import java.util.*; public class SetRemoverNomesRepetidos { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Set<String> nomes = new LinkedHashSet<>(); // LinkedHashSet<>() para manter a ordem Map<String, String> normalizados = new HashMap<>(); // Map para controlar case-insensitive e manter a primeira forma digitada System.out.println("Informe os nomes (ENTER vazio para encerrar)."); int contador = 1; while (true) { System.out.print(contador + "° nome: "); String nome = scanner.nextLine().trim(); if (nome.isEmpty()) { System.out.println("Encerrando..."); break; } String chave = nome.toLowerCase(); // normaliza para comparar sem case if (!normalizados.containsKey(chave)) { normalizados.put(chave, nome); // mantém primeira forma digitada nomes.add(nome); // adiciona no Set contador++; // incrementa só se realmente adicionou } else { System.out.println("[Aviso] Nome duplicado ignorado: " + nome); } } scanner.close(); if (!nomes.isEmpty()) { System.out.println("\n==== Lista de Nomes Sem Repetições ===="); for (String nome: nomes) { System.out.println(nome); } } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/004-ContadorDeVogais/src/contador/Main.java
nivel1/004-ContadorDeVogais/src/contador/Main.java
package contador; import java.util.Scanner; public class Main { /* Converte tudo para minúsculas para facilitar a comparação Inicializa o contador Percorre todos os caracteres da string Verifica se o caractere é uma vogal Retorna o total de vogais encontradas */ public static int contarVogais(String texto) { texto = texto.toLowerCase(); int contador = 0; for (int i = 0; i < texto.length(); i++) { char c = texto.charAt(i); if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'á' || c == 'à' || c == 'é' || c == 'í' || c == 'ó' || c == 'ú') { contador ++; } } return contador; } /* Método principal para testar o código: Cria o scanner Lê a linha inteira com espaços Mostra o resultado Fecha o scanner */ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("=== Contador de Vogais ==="); System.out.print("Digite uma palavra ou frase: "); String entrada = scanner.nextLine(); int resultado = contarVogais(entrada); System.out.println("Total de vogais: " + resultado); scanner.close(); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/022-ArrayMaiorEMenorTextos/src/maior/menor/textos/ArrayMaiorEMenorTextos.java
nivel1/022-ArrayMaiorEMenorTextos/src/maior/menor/textos/ArrayMaiorEMenorTextos.java
package maior.menor.textos; import java.util.ArrayList; import java.util.Scanner; public class ArrayMaiorEMenorTextos { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<String> frases = new ArrayList<>(); System.out.println("========== Frases Menores e Maiores =========="); System.out.println("Critérios de desempate: Tamanho e Ordem Alfabética."); while (true) { System.out.print("Informe suas frases (ENTER sem digitar nada para sair.): "); String entrada = scanner.nextLine().trim(); if (entrada.isEmpty()) { break; } frases.add(entrada); } scanner.close(); if (frases.isEmpty()) { System.out.println("\n[ERRO!] Nenhuma frase foi informada!"); return; } System.out.println("\nSuas frases:"); for (String frase : frases) { System.out.println(frase); } String menorString = frases.get(0); String maiorString = frases.get(0); for (int i = 1; i < frases.size(); i++) { String fraseAtual = frases.get(i); if (fraseAtual.length() > maiorString.length() || (fraseAtual.length() == maiorString.length() && fraseAtual.compareToIgnoreCase(maiorString) > 0)) { maiorString = fraseAtual; } if (fraseAtual.length() < menorString.length() || (fraseAtual.length() == menorString.length() && fraseAtual.compareToIgnoreCase(menorString) < 0)) { menorString = fraseAtual; } } System.out.println("\nMaior frase: " + maiorString); System.out.println("Menor frase: " + menorString); } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/012-CelsiusFahrenheit/src/celsius/fahrenheit/CelsiusFahrenheit.java
nivel1/012-CelsiusFahrenheit/src/celsius/fahrenheit/CelsiusFahrenheit.java
package celsius.fahrenheit; import java.util.Scanner; public class CelsiusFahrenheit { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("| 01 Fahrenheit para Celsius"); System.out.println("| 02 Celsius para Fahrenheit"); try { int escolha = input.nextInt(); double fahrenheit = 0; double celsius = 0; switch (escolha) { case 1: System.out.println("Digite a temperatura em Fahrenheit:"); fahrenheit = input.nextDouble(); celsius = calcularCelsius(fahrenheit); System.out.printf("%.2f°F = %.2f°C%n", fahrenheit, celsius); break; case 2: System.out.println("Digite a temperatura em Celsius:"); celsius = input.nextDouble(); fahrenheit = calcularFahrenheit(celsius); System.out.printf("%.2f°C = %.2f°F%n", celsius, fahrenheit); break; default: System.out.println("Opção Inválida!"); } } catch (java.util.InputMismatchException e) { System.out.println("Use o sistema corretamente!"); } input.close(); } public static double calcularFahrenheit(double valor) { return (valor * 1.8) + 32; } public static double calcularCelsius(double valor) { return (valor - 32) * 5 / 9; } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
pitercoding/desafios-tecnicos-java
https://github.com/pitercoding/desafios-tecnicos-java/blob/bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5/nivel1/017-ArrayMediaElementosInteiros/src/media/ArrayMediaElementosInteiros.java
nivel1/017-ArrayMediaElementosInteiros/src/media/ArrayMediaElementosInteiros.java
package media; import java.util.ArrayList; import java.util.Scanner; public class ArrayMediaElementosInteiros { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<Integer> elementos = new ArrayList<>(); // ArrayList para tamanho dinâmico System.out.println("========= CALCULANDO MÉDIA ========="); System.out.println("Digite números inteiros. Pressione ENTER sem digitar nada para parar."); while (true){ System.out.print("Informe um número inteiro: "); String entrada = scanner.nextLine().trim(); // O método trim() remove todos os espaços em branco no início e no fim da String. if (entrada.isEmpty()) { // Condição para parar (Enter) break; } try { int numero = Integer.parseInt(entrada); // Converte a entrada (String) para inteiro elementos.add(numero); } catch (NumberFormatException e) { System.out.println("Entrada inválida! Digite apenas números inteiros."); } } scanner.close(); // Exibindo os números armazenados no ArrayList System.out.println("\nNúmeros informados: " + elementos); // Calculando a soma int soma = 0; for (int numero : elementos) { soma += numero; } System.out.println("Soma: " + soma); // Calculando a média if (!elementos.isEmpty()) { // Ou seja, se o ArrayList (elementos) não estiver vazio, faça: double media = (double) soma / elementos.size(); System.out.println("Média: " + media); } else { // Se estiver vazio: System.out.println("Nenhum número foi informado, média não calculada."); } } }
java
MIT
bbcb4c3bffdb9701dd40acf7cd3e38b6c37af2a5
2026-01-05T02:38:06.070299Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/test/java/io/hyperfoil/hotrod/HotRodTest.java
hotrod/src/test/java/io/hyperfoil/hotrod/HotRodTest.java
package io.hyperfoil.hotrod; import static org.infinispan.commons.test.Exceptions.assertException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.InputStream; import java.util.Map; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.statistics.StatisticsSnapshot; public class HotRodTest extends BaseHotRodTest { @Test public void testHotRodPut() { Benchmark benchmark = loadScenario("scenarios/HotRodPutTest.hf.yaml"); Map<String, StatisticsSnapshot> stats = runScenario(benchmark); assertTrue(stats.get("example").requestCount > 0); assertEquals(0, stats.get("example").connectionErrors); } @Test public void testHotRodGet() { Benchmark benchmark = loadScenario("scenarios/HotRodTestGet.hf.yaml"); Map<String, StatisticsSnapshot> stats = runScenario(benchmark); assertTrue(stats.get("example").requestCount > 0); assertEquals(0, stats.get("example").connectionErrors); } @Test public void testUndefinedCache() throws Exception { try (InputStream is = getClass().getClassLoader().getResourceAsStream("scenarios/HotRodPutTest.hf.yaml")) { String cacheName = "something-else-undefined"; Benchmark benchmark = loadBenchmark(is, Map.of("CACHE", cacheName, "PORT", String.valueOf(hotrodServers[0].getPort()))); RuntimeException e = assertThrows(RuntimeException.class, () -> runScenario(benchmark)); assertException(RuntimeException.class, IllegalArgumentException.class, String.format("Cache '%s' is not a defined cache", cacheName), e); } } @Override protected void createCache(EmbeddedCacheManager em) { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); em.createCache("my-cache", cacheBuilder.build()); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/test/java/io/hyperfoil/hotrod/BaseHotRodTest.java
hotrod/src/test/java/io/hyperfoil/hotrod/BaseHotRodTest.java
package io.hyperfoil.hotrod; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.assertj.core.util.Files; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.commons.test.TestResourceTracker; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.core.parser.BenchmarkParser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.core.session.BaseScenarioTest; import io.hyperfoil.core.test.TestUtil; public abstract class BaseHotRodTest extends BaseScenarioTest { protected HotRodServer[] hotrodServers; private int numberServers = 1; @BeforeEach public void before() { super.before(); TestResourceTracker.setThreadTestName("hyperfoil-HotRodTest"); hotrodServers = new HotRodServer[numberServers]; for (int i = 0; i < numberServers; i++) { GlobalConfigurationBuilder globalBuilder = new GlobalConfigurationBuilder(); globalBuilder.globalState().persistentLocation(Files.temporaryFolder().getPath()); globalBuilder.globalState().enabled(true); globalBuilder.security().authorization().disable(); HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); EmbeddedCacheManager em = new DefaultCacheManager(globalBuilder.build()); createCache(em); hotrodServers[i] = HotRodClientTestingUtil.startHotRodServer(em, serverBuilder); } } protected abstract void createCache(EmbeddedCacheManager em); @AfterEach public void after() { if (hotrodServers != null) { for (HotRodServer hotRodServer : hotrodServers) { hotRodServer.stop(); } } } @Override protected Benchmark loadBenchmark(InputStream config) throws IOException, ParserException { return BenchmarkParser.instance().buildBenchmark( config, TestUtil.benchmarkData(), Map.of("PORT", String.valueOf(hotrodServers[0].getPort()))); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/test/java/io/hyperfoil/hotrod/HotRodFailuresTest.java
hotrod/src/test/java/io/hyperfoil/hotrod/HotRodFailuresTest.java
package io.hyperfoil.hotrod; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Map; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.event.CacheEntryEvent; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.statistics.StatisticsSnapshot; public class HotRodFailuresTest extends BaseHotRodTest { @Test public void testHotRodFailures() { Benchmark benchmark = loadScenario("scenarios/HotRodPutTest.hf.yaml"); Map<String, StatisticsSnapshot> stats = runScenario(benchmark); assertTrue(stats.get("example").requestCount > 0); assertTrue(stats.get("example").connectionErrors > 0); } @Override protected void createCache(EmbeddedCacheManager em) { ConfigurationBuilder cacheBuilder = new ConfigurationBuilder(); Cache<Object, Object> cache = em.createCache("my-cache", cacheBuilder.build()); cache.getAdvancedCache().withStorageMediaType().addListener(new ErrorListener()); } @Listener public static class ErrorListener { public ErrorListener() { } @CacheEntryCreated public void entryCreated(CacheEntryEvent<String, String> event) { throw new IllegalStateException("Failed intentionally"); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/HotRodRunData.java
hotrod/src/main/java/io/hyperfoil/hotrod/HotRodRunData.java
package io.hyperfoil.hotrod; import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.api.PluginRunData; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.hyperfoil.hotrod.api.HotRodRemoteCachePool; import io.hyperfoil.hotrod.config.HotRodCluster; import io.hyperfoil.hotrod.config.HotRodPluginConfig; import io.hyperfoil.hotrod.connection.HotRodRemoteCachePoolImpl; import io.netty.channel.EventLoop; import io.vertx.core.Future; public class HotRodRunData implements PluginRunData { private final HotRodPluginConfig plugin; private HotRodRemoteCachePool[] pool; public HotRodRunData(Benchmark benchmark, EventLoop[] executors, int agentId) { this.plugin = benchmark.plugin(HotRodPluginConfig.class); List<String> allCaches = new ArrayList<>(); for (HotRodCluster cluster : this.plugin.clusters()) { for (String cacheName : cluster.caches()) { // TODO: remove this limitation if (allCaches.contains(cacheName)) { throw new BenchmarkDefinitionException(String.format("Duplicated cache: %s", cacheName)); } allCaches.add(cacheName); } } this.pool = new HotRodRemoteCachePool[executors.length]; for (int i = 0; i < executors.length; i++) { this.pool[i] = new HotRodRemoteCachePoolImpl(this.plugin.clusters(), executors[i]); } } @Override public void initSession(Session session, int executorId, Scenario scenario, Clock clock) { HotRodRemoteCachePool pollById = this.pool[executorId]; session.declareSingletonResource(HotRodRemoteCachePool.KEY, pollById); } @Override public void openConnections(Function<Callable<Void>, Future<Void>> blockingHandler, Consumer<Future<Void>> promiseCollector) { for (HotRodRemoteCachePool p : this.pool) { promiseCollector.accept(blockingHandler.apply(() -> { p.start(); return null; })); } } @Override public void listConnections(Consumer<String> connectionCollector) { } @Override public void visitConnectionStats(ConnectionStatsConsumer consumer) { } @Override public void shutdown() { for (HotRodRemoteCachePool p : this.pool) { p.shutdown(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/resource/HotRodResource.java
hotrod/src/main/java/io/hyperfoil/hotrod/resource/HotRodResource.java
package io.hyperfoil.hotrod.resource; import java.util.concurrent.CompletableFuture; import io.hyperfoil.api.session.Session; public class HotRodResource implements Session.Resource { private long startTimestampNanos; private long startTimestampMillis; private CompletableFuture future; public void set(CompletableFuture future, long startTimestampNanos, long startTimestampMillis) { this.future = future; this.startTimestampNanos = startTimestampNanos; this.startTimestampMillis = startTimestampMillis; } public boolean isComplete() { return this.future.isDone(); } public long getStartTimestampMillis() { return startTimestampMillis; } public long getStartTimestampNanos() { return startTimestampNanos; } public static class Key implements Session.ResourceKey<HotRodResource> { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/connection/HotRodRemoteCachePoolImpl.java
hotrod/src/main/java/io/hyperfoil/hotrod/connection/HotRodRemoteCachePoolImpl.java
package io.hyperfoil.hotrod.connection; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.TransportFactory; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.client.hotrod.impl.HotRodURI; import org.infinispan.client.hotrod.impl.transport.netty.OperationDispatcher; import io.hyperfoil.hotrod.api.HotRodRemoteCachePool; import io.hyperfoil.hotrod.config.HotRodCluster; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.netty.channel.socket.SocketChannel; public class HotRodRemoteCachePoolImpl implements HotRodRemoteCachePool { private final HotRodCluster[] clusters; private final EventLoop eventLoop; private final Map<String, RemoteCacheManager> remoteCacheManagers = new HashMap<>(); private final Map<String, RemoteCache<?, ?>> remoteCaches = new HashMap<>(); public HotRodRemoteCachePoolImpl(HotRodCluster[] clusters, EventLoop eventLoop) { this.clusters = clusters; this.eventLoop = eventLoop; } @Override public void start() { for (HotRodCluster cluster : clusters) { ConfigurationBuilder cb = HotRodURI.create(cluster.uri()).toConfigurationBuilder(); Properties properties = new Properties(); properties.setProperty(ConfigurationProperties.DEFAULT_EXECUTOR_FACTORY_POOL_SIZE, "1"); cb.asyncExecutorFactory().withExecutorProperties(properties); // We must use the same event loop group for every execution as expected by validateEventLoop. cb.asyncExecutorFactory().factory(p -> eventLoop); cb.transportFactory(new FixedEventLoopGroupTransportFactory(eventLoop)); RemoteCacheManager remoteCacheManager = new RemoteCacheManager(cb.build()); this.remoteCacheManagers.put(cluster.uri(), remoteCacheManager); validateEventLoop(remoteCacheManager); for (String cache : cluster.caches()) { remoteCaches.put(cache, remoteCacheManager.getCache(cache)); } } } private void validateEventLoop(RemoteCacheManager remoteCacheManager) { try { Field dispatcherField = RemoteCacheManager.class.getDeclaredField("dispatcher"); dispatcherField.setAccessible(true); OperationDispatcher dispatcher = (OperationDispatcher) dispatcherField.get(remoteCacheManager); EventLoopGroup actualEventLoop = dispatcher.getChannelHandler().getEventLoopGroup(); if (actualEventLoop != eventLoop) { throw new IllegalStateException("Event loop was not injected correctly. This is a classpath issue."); } } catch (NoSuchFieldException | IllegalAccessException e) { throw new IllegalStateException(e); } ExecutorService asyncExecutorService = remoteCacheManager.getAsyncExecutorService(); if (asyncExecutorService != eventLoop) { throw new IllegalStateException("Event loop was not configured correctly."); } } @Override public void shutdown() { this.remoteCacheManagers.values().forEach(RemoteCacheManager::stop); } @Override public RemoteCacheWithoutToString<?, ?> getRemoteCache(String cacheName) { RemoteCache<?, ?> cache = this.remoteCaches.get(cacheName); if (cache == null) { throw new IllegalArgumentException(String.format("Cache '%s' is not a defined cache", cacheName)); } return new RemoteCacheWithoutToString<>(cache); } /* * While debugging, the toString method of RemoteCache will do a block call * at org.infinispan.client.hotrod.impl.RemoteCacheSupport.size(RemoteCacheSupport.java:397) * at org.infinispan.client.hotrod.impl.RemoteCacheImpl.isEmpty(RemoteCacheImpl.java:275) * This prevent us of configuring each IDE in order to debug a code */ public static class RemoteCacheWithoutToString<K, V> { private final RemoteCache<K, V> remoteCache; public RemoteCacheWithoutToString(RemoteCache<K, V> remoteCache) { this.remoteCache = remoteCache; } public CompletableFuture<V> putAsync(K key, V value) { return remoteCache.putAsync(key, value); } public CompletableFuture<V> getAsync(K key) { return remoteCache.getAsync(key); } } /** * {@link FixedEventLoopGroupTransportFactory} is a {@link TransportFactory} that always provides the same given * event loop. */ private static class FixedEventLoopGroupTransportFactory implements TransportFactory { private final EventLoopGroup eventLoop; private FixedEventLoopGroupTransportFactory(final EventLoopGroup eventLoop) { this.eventLoop = eventLoop; } @Override public Class<? extends SocketChannel> socketChannelClass() { return TransportFactory.DEFAULT.socketChannelClass(); } @Override public EventLoopGroup createEventLoopGroup(final int maxExecutors, final ExecutorService executorService) { return eventLoop; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/api/HotRodOperation.java
hotrod/src/main/java/io/hyperfoil/hotrod/api/HotRodOperation.java
package io.hyperfoil.hotrod.api; public enum HotRodOperation { /** * Adds or overrides each specified entry in the remote cache. */ PUT, /** * Get specified entry in the remote cache. */ GET }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/api/HotRodRemoteCachePool.java
hotrod/src/main/java/io/hyperfoil/hotrod/api/HotRodRemoteCachePool.java
package io.hyperfoil.hotrod.api; import io.hyperfoil.api.session.Session; import io.hyperfoil.hotrod.connection.HotRodRemoteCachePoolImpl; public interface HotRodRemoteCachePool extends Session.Resource { Session.ResourceKey<HotRodRemoteCachePool> KEY = new Session.ResourceKey<>() { }; static HotRodRemoteCachePool get(Session session) { return session.getResource(KEY); } void start(); void shutdown(); HotRodRemoteCachePoolImpl.RemoteCacheWithoutToString getRemoteCache(String cacheName); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodErgonomics.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodErgonomics.java
package io.hyperfoil.hotrod.config; public class HotRodErgonomics { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPlugin.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPlugin.java
package io.hyperfoil.hotrod.config; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.PluginConfig; import io.hyperfoil.core.api.Plugin; import io.hyperfoil.core.api.PluginRunData; import io.hyperfoil.core.parser.ErgonomicsParser; import io.hyperfoil.core.parser.Parser; import io.hyperfoil.hotrod.HotRodRunData; import io.hyperfoil.hotrod.parser.HotRodParser; import io.netty.channel.EventLoop; @MetaInfServices(Plugin.class) public class HotRodPlugin implements Plugin { @Override public Class<? extends PluginConfig> configClass() { return HotRodPluginConfig.class; } @Override public String name() { return "hotrod"; } @Override public Parser<BenchmarkBuilder> parser() { return new HotRodParser(); } @Override public void enhanceErgonomics(ErgonomicsParser ergonomicsParser) { } @Override public PluginRunData createRunData(Benchmark benchmark, EventLoop[] executors, int agentId) { return new HotRodRunData(benchmark, executors, agentId); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPluginBuilder.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPluginBuilder.java
package io.hyperfoil.hotrod.config; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.PluginBuilder; import io.hyperfoil.api.config.PluginConfig; public class HotRodPluginBuilder extends PluginBuilder<HotRodErgonomics> { private final List<HotRodClusterBuilder> clusters = new ArrayList<>(); public HotRodPluginBuilder(BenchmarkBuilder parent) { super(parent); } @Override public HotRodErgonomics ergonomics() { return null; } @Override public void prepareBuild() { } @Override public PluginConfig build() { HotRodCluster[] clusters = this.clusters.stream().map(HotRodClusterBuilder::build).toArray(HotRodCluster[]::new); if (clusters.length == 0) { throw new BenchmarkDefinitionException("No clusters set!"); } else if (Stream.of(clusters).map(HotRodCluster::uri).distinct().count() != clusters.length) { throw new BenchmarkDefinitionException("Cluster definition with duplicate uris!"); } return new HotRodPluginConfig(clusters); } public HotRodClusterBuilder addCluster() { HotRodClusterBuilder builder = new HotRodClusterBuilder(); clusters.add(builder); return builder; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodCluster.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodCluster.java
package io.hyperfoil.hotrod.config; import java.io.Serializable; import org.infinispan.client.hotrod.impl.HotRodURI; public class HotRodCluster implements Serializable { // https://infinispan.org/blog/2020/05/26/hotrod-uri private final String uri; private final String[] caches; public HotRodCluster(String uri, String[] caches) { // used to validate the uri HotRodURI.create(uri); this.uri = uri; this.caches = caches; } public String uri() { return this.uri; } public String[] caches() { return this.caches; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodClusterBuilder.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodClusterBuilder.java
package io.hyperfoil.hotrod.config; import java.util.ArrayList; import java.util.List; public class HotRodClusterBuilder { private String uri; private List<String> caches = new ArrayList<>(); public HotRodClusterBuilder uri(String uri) { this.uri = uri; return this; } public HotRodClusterBuilder addCache(String cache) { this.caches.add(cache); return this; } public HotRodCluster build() { return new HotRodCluster(uri, caches.toArray(String[]::new)); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPluginConfig.java
hotrod/src/main/java/io/hyperfoil/hotrod/config/HotRodPluginConfig.java
package io.hyperfoil.hotrod.config; import io.hyperfoil.api.config.PluginConfig; public class HotRodPluginConfig implements PluginConfig { private final HotRodCluster[] clusters; public HotRodPluginConfig(HotRodCluster[] clusters) { this.clusters = clusters; } public HotRodCluster[] clusters() { return clusters; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodResponseStep.java
hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodResponseStep.java
package io.hyperfoil.hotrod.steps; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.session.Session; import io.hyperfoil.hotrod.resource.HotRodResource; public class HotRodResponseStep implements Step { final HotRodResource.Key futureWrapperKey; protected HotRodResponseStep(HotRodResource.Key futureWrapperKey) { this.futureWrapperKey = futureWrapperKey; } @Override public boolean invoke(Session session) { HotRodResource resource = session.getResource(futureWrapperKey); boolean complete = resource.isComplete(); return complete; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodRequestStep.java
hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodRequestStep.java
package io.hyperfoil.hotrod.steps; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeoutException; import org.infinispan.client.hotrod.exceptions.HotRodTimeoutException; import io.hyperfoil.api.config.SLA; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.core.metric.MetricSelector; import io.hyperfoil.core.steps.StatisticsStep; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.hotrod.api.HotRodOperation; import io.hyperfoil.hotrod.api.HotRodRemoteCachePool; import io.hyperfoil.hotrod.connection.HotRodRemoteCachePoolImpl; import io.hyperfoil.hotrod.resource.HotRodResource; public class HotRodRequestStep extends StatisticsStep implements ResourceUtilizer, SLA.Provider { final HotRodResource.Key futureWrapperKey; final SerializableFunction<Session, HotRodOperation> operation; final SerializableFunction<Session, String> cacheName; final MetricSelector metricSelector; final SerializableFunction<Session, String> keyGenerator; final SerializableFunction<Session, String> valueGenerator; protected HotRodRequestStep(int id, HotRodResource.Key futureWrapperKey, SerializableFunction<Session, HotRodOperation> operation, SerializableFunction<Session, String> cacheName, MetricSelector metricSelector, SerializableFunction<Session, String> keyGenerator, SerializableFunction<Session, String> valueGenerator) { super(id); this.futureWrapperKey = futureWrapperKey; this.operation = operation; this.cacheName = cacheName; this.metricSelector = metricSelector; this.keyGenerator = keyGenerator; this.valueGenerator = valueGenerator; } @Override public SLA[] sla() { return new SLA[0]; } @Override public boolean invoke(Session session) { String cacheName = this.cacheName.apply(session); HotRodOperation operation = this.operation.apply(session); Object key = keyGenerator.apply(session); Object value = null; if (valueGenerator != null) { value = valueGenerator.apply(session); } HotRodRemoteCachePool pool = HotRodRemoteCachePool.get(session); HotRodRemoteCachePoolImpl.RemoteCacheWithoutToString remoteCache = pool.getRemoteCache(cacheName); String metric = metricSelector.apply(null, cacheName); Statistics statistics = session.statistics(id(), metric); long startTimestampMs = System.currentTimeMillis(); long startTimestampNanos = System.nanoTime(); CompletableFuture future; if (HotRodOperation.PUT.equals(operation)) { future = remoteCache.putAsync(key, value); } else if (HotRodOperation.GET.equals(operation)) { future = remoteCache.getAsync(key); } else { throw new IllegalArgumentException(String.format("HotRodOperation %s not implemented", operation)); } statistics.incrementRequests(startTimestampMs); future.exceptionally(t -> { trackResponseError(session, metric, t); return null; }); future.thenRun(() -> { trackResponseSuccess(session, metric); assert session.executor().inEventLoop(); session.proceed(); }); session.getResource(futureWrapperKey).set(future, startTimestampNanos, startTimestampMs); return true; } @Override public void reserve(Session session) { session.declareResource(futureWrapperKey, HotRodResource::new); } private void trackResponseError(Session session, String metric, Object ex) { Statistics statistics = session.statistics(id(), metric); if (ex instanceof TimeoutException || ex instanceof HotRodTimeoutException) { statistics.incrementTimeouts(System.currentTimeMillis()); } else { statistics.incrementConnectionErrors(System.currentTimeMillis()); } session.stop(); } private void trackResponseSuccess(Session session, String metric) { HotRodResource resource = session.getResource(futureWrapperKey); long startTimestampMillis = resource.getStartTimestampMillis(); long startTimestampNanos = resource.getStartTimestampNanos(); long endTimestampNanos = System.nanoTime(); Statistics statistics = session.statistics(id(), metric); statistics.recordResponse(startTimestampMillis, endTimestampNanos - startTimestampNanos); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodRequestBuilder.java
hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodRequestBuilder.java
package io.hyperfoil.hotrod.steps; import java.util.Arrays; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.generators.StringGeneratorBuilder; import io.hyperfoil.core.generators.StringGeneratorImplBuilder; import io.hyperfoil.core.metric.MetricSelector; import io.hyperfoil.core.metric.PathMetricSelector; import io.hyperfoil.core.metric.ProvidedMetricSelector; import io.hyperfoil.core.steps.StatisticsStep; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.hotrod.api.HotRodOperation; import io.hyperfoil.hotrod.resource.HotRodResource; /** * Issues a HotRod request and registers handlers for the response. */ @MetaInfServices(StepBuilder.class) @Name("hotrodRequest") public class HotRodRequestBuilder extends BaseStepBuilder<HotRodRequestBuilder> { private HotRodOperationBuilder operation; private StringGeneratorBuilder cacheName; private MetricSelector metricSelector; private StringGeneratorBuilder key; private StringGeneratorBuilder value; @Override public void prepareBuild() { if (metricSelector == null) { String sequenceName = Locator.current().sequence().name(); metricSelector = new ProvidedMetricSelector(sequenceName); } } @Override public List<Step> build() { int stepId = StatisticsStep.nextId(); HotRodResource.Key key = new HotRodResource.Key(); SerializableFunction<Session, String> keyGenerator = this.key != null ? this.key.build() : null; SerializableFunction<Session, String> valueGenerator = this.value != null ? this.value.build() : null; HotRodRequestStep step = new HotRodRequestStep(stepId, key, operation.build(), cacheName.build(), metricSelector, keyGenerator, valueGenerator); HotRodResponseStep secondHotRodStep = new HotRodResponseStep(key); return Arrays.asList(step, secondHotRodStep); } /** * Requests statistics will use this metric name. * * @param name Metric name. * @return Self. */ public HotRodRequestBuilder metric(String name) { return metric(new ProvidedMetricSelector(name)); } public HotRodRequestBuilder metric(ProvidedMetricSelector selector) { this.metricSelector = selector; return this; } /** * Allows categorizing request statistics into metrics based on the request path. * * @return Builder. */ public PathMetricSelector metric() { PathMetricSelector selector = new PathMetricSelector(); this.metricSelector = selector; return selector; } public StringGeneratorImplBuilder<HotRodRequestBuilder> cacheName() { StringGeneratorImplBuilder<HotRodRequestBuilder> builder = new StringGeneratorImplBuilder<>(this); cacheName(builder); return builder; } public HotRodRequestBuilder cacheName(StringGeneratorBuilder builder) { if (this.cacheName != null) { throw new BenchmarkDefinitionException("CacheName generator already set."); } this.cacheName = builder; return this; } /** * Name of the cache used for the operation. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param pattern Cache name (<code>my-cache</code>) or a pattern (<code>cache-${index}</code>). * @return Self. */ public HotRodRequestBuilder cacheName(String pattern) { return cacheName().pattern(pattern).end(); } public HotRodRequestBuilder operation(HotRodOperation operation) { return operation(() -> new HotRodOperationBuilder.Provided(operation)); } public HotRodRequestBuilder operation(HotRodOperationBuilder operation) { this.operation = operation; return this; } public StringGeneratorImplBuilder<HotRodRequestBuilder> key() { StringGeneratorImplBuilder<HotRodRequestBuilder> builder = new StringGeneratorImplBuilder<>(this); key(builder); return builder; } public HotRodRequestBuilder key(StringGeneratorBuilder builder) { if (this.key != null) { throw new BenchmarkDefinitionException("Key generator already set."); } this.key = builder; return this; } /** * Key used for the operation. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param pattern The key. * @return Self. */ public HotRodRequestBuilder key(String pattern) { return key().pattern(pattern).end(); } public StringGeneratorImplBuilder<HotRodRequestBuilder> value() { StringGeneratorImplBuilder<HotRodRequestBuilder> builder = new StringGeneratorImplBuilder<>(this); value(builder); return builder; } public HotRodRequestBuilder value(StringGeneratorBuilder builder) { if (this.value != null) { throw new BenchmarkDefinitionException("Value generator already set."); } this.value = builder; return this; } /** * Value for the operation. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * * @param pattern The value. * @return Self. */ public HotRodRequestBuilder value(String pattern) { return value().pattern(pattern).end(); } /** * Adds or overrides each specified entry in the remote cache. * * @param cacheName Name of cache to put data. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * @return */ public HotRodRequestBuilder put(String cacheName) { return operation(HotRodOperation.PUT).cacheName(cacheName); } /** * Get specified entry in the remote cache. * * @param cacheName Name of cache to put data. This can be a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * @return */ public HotRodRequestBuilder get(String cacheName) { return operation(HotRodOperation.GET).cacheName(cacheName); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodOperationBuilder.java
hotrod/src/main/java/io/hyperfoil/hotrod/steps/HotRodOperationBuilder.java
package io.hyperfoil.hotrod.steps; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.session.Session; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.hotrod.api.HotRodOperation; @FunctionalInterface public interface HotRodOperationBuilder extends BuilderBase<HotRodOperationBuilder> { SerializableFunction<Session, HotRodOperation> build(); class Provided implements SerializableFunction<Session, HotRodOperation> { private final HotRodOperation operation; public Provided(HotRodOperation operation) { this.operation = operation; } @Override public HotRodOperation apply(Session o) { return operation; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/parser/HotRodClusterParser.java
hotrod/src/main/java/io/hyperfoil/hotrod/parser/HotRodClusterParser.java
package io.hyperfoil.hotrod.parser; import org.yaml.snakeyaml.events.ScalarEvent; import io.hyperfoil.core.parser.AbstractParser; import io.hyperfoil.core.parser.Context; import io.hyperfoil.core.parser.Parser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.core.parser.PropertyParser; import io.hyperfoil.hotrod.config.HotRodClusterBuilder; public class HotRodClusterParser extends AbstractParser<HotRodClusterBuilder, HotRodClusterBuilder> { static HotRodClusterParser INSTANCE = new HotRodClusterParser(); public HotRodClusterParser() { register("uri", new PropertyParser.String<>(HotRodClusterBuilder::uri)); register("caches", new CachesParser()); } @Override public void parse(Context ctx, HotRodClusterBuilder target) throws ParserException { callSubBuilders(ctx, target); } private static class CachesParser implements Parser<HotRodClusterBuilder> { @Override public void parse(Context ctx, HotRodClusterBuilder target) throws ParserException { ctx.parseList(target, this::parseItem); } private void parseItem(Context context, HotRodClusterBuilder builder) throws ParserException { ScalarEvent event = context.expectEvent(ScalarEvent.class); builder.addCache(event.getValue()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/hotrod/src/main/java/io/hyperfoil/hotrod/parser/HotRodParser.java
hotrod/src/main/java/io/hyperfoil/hotrod/parser/HotRodParser.java
package io.hyperfoil.hotrod.parser; import org.yaml.snakeyaml.events.SequenceStartEvent; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.core.parser.Context; import io.hyperfoil.core.parser.Parser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.hotrod.config.HotRodClusterBuilder; import io.hyperfoil.hotrod.config.HotRodPluginBuilder; public class HotRodParser implements Parser<BenchmarkBuilder> { @Override public void parse(Context ctx, BenchmarkBuilder target) throws ParserException { HotRodPluginBuilder plugin = target.addPlugin(HotRodPluginBuilder::new); if (ctx.peek() instanceof SequenceStartEvent) { ctx.parseList(plugin, (ctx1, builder) -> { HotRodClusterBuilder hotRod = builder.addCluster(); HotRodClusterParser.INSTANCE.parse(ctx1, hotRod); }); } else { HotRodClusterParser.INSTANCE.parse(ctx, plugin.addCluster()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/counters/CountersScalability.java
benchmarks/src/main/java/io/hyperfoil/core/counters/CountersScalability.java
package io.hyperfoil.core.counters; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.BenchmarkParams; @State(Scope.Benchmark) @Fork(value = 2) @Warmup(iterations = 5, time = 1) @Measurement(iterations = 5, time = 1) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class CountersScalability { @State(Scope.Thread) public static class ThreadLocalCounter { private static final AtomicIntegerFieldUpdater<ThreadLocalCounter> COUNTER_UPDATER = AtomicIntegerFieldUpdater .newUpdater(ThreadLocalCounter.class, "counter"); private volatile int counter; private int counterId; @Setup public void setup(CountersScalability countersScalability) { counterId = countersScalability.registerThreadState(this); } public int weakIncrementAndGet() { int nextValue = counter + 1; COUNTER_UPDATER.lazySet(this, nextValue); return nextValue; } public int atomicIncrementAndGet() { return COUNTER_UPDATER.incrementAndGet(this); } public int getCounter() { return counter; } public int atomicDecrementAndGet() { return COUNTER_UPDATER.decrementAndGet(this); } public int weakDecrementAndGet() { int nextValue = counter - 1; COUNTER_UPDATER.lazySet(this, nextValue); return nextValue; } } private static final AtomicIntegerFieldUpdater<CountersScalability> MIN_UPDATER = AtomicIntegerFieldUpdater .newUpdater(CountersScalability.class, "min"); private static final AtomicIntegerFieldUpdater<CountersScalability> MAX_UPDATER = AtomicIntegerFieldUpdater .newUpdater(CountersScalability.class, "max"); private static final AtomicIntegerFieldUpdater<CountersScalability> SHARED_COUNTER_UPDATER = AtomicIntegerFieldUpdater .newUpdater(CountersScalability.class, "sharedCounter"); private AtomicInteger nextCounter; private ThreadLocalCounter[] counters; private int threads; private volatile int min; private volatile int max; private volatile int sharedCounter; @Setup public void setup(BenchmarkParams params) { threads = params.getThreads(); nextCounter = new AtomicInteger(); counters = new ThreadLocalCounter[threads]; } private int registerThreadState(ThreadLocalCounter threadLocalCounter) { int counterId = nextCounter.getAndIncrement(); counters[counterId] = threadLocalCounter; return counterId; } private int atomicIncrement(ThreadLocalCounter counter) { var counters = this.counters; int indexToSkip = counter.counterId; int threads = this.threads; int usage = counter.atomicIncrementAndGet(); for (int i = 0; i < threads; i++) { if (i != indexToSkip) { usage += counters[i].getCounter(); } } if (usage > max) { MAX_UPDATER.lazySet(this, usage); } return usage; } private int atomicDecrement(ThreadLocalCounter counter) { var counters = this.counters; int indexToSkip = counter.counterId; int threads = this.threads; int usage = counter.atomicDecrementAndGet(); for (int i = 0; i < threads; i++) { if (i != indexToSkip) { usage += counters[i].getCounter(); } } if (usage < min) { MIN_UPDATER.lazySet(this, usage); } return usage; } private int weakIncrement(ThreadLocalCounter counter) { var counters = this.counters; int indexToSkip = counter.counterId; int threads = this.threads; int usage = counter.weakIncrementAndGet(); for (int i = 0; i < threads; i++) { if (i != indexToSkip) { usage += counters[i].getCounter(); } } if (usage > max) { MAX_UPDATER.lazySet(this, usage); } return usage; } private int weakDecrement(ThreadLocalCounter counter) { var counters = this.counters; int indexToSkip = counter.counterId; int threads = this.threads; int usage = counter.weakDecrementAndGet(); for (int i = 0; i < threads; i++) { if (i != indexToSkip) { usage += counters[i].getCounter(); } } if (usage < min) { MIN_UPDATER.lazySet(this, usage); } return usage; } @Benchmark public int atomicUsage(ThreadLocalCounter counter) { int up = atomicIncrement(counter); int down = atomicDecrement(counter); return up + down; } @Benchmark public int weakUsage(ThreadLocalCounter counter) { int up = weakIncrement(counter); int down = weakDecrement(counter); return up + down; } @Benchmark public int sharedUsage() { int up = sharedIncrement(); int down = sharedDecrement(); return up + down; } private int sharedDecrement() { int value = SHARED_COUNTER_UPDATER.decrementAndGet(this); int min = this.min; if (min > 0 && value < min) { MIN_UPDATER.lazySet(this, value); } return value; } private int sharedIncrement() { int value = SHARED_COUNTER_UPDATER.incrementAndGet(this); if (value > max) { MAX_UPDATER.lazySet(this, value); } return value; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/impl/FakeSession.java
benchmarks/src/main/java/io/hyperfoil/core/impl/FakeSession.java
package io.hyperfoil.core.impl; import java.util.function.Supplier; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.session.AgentData; import io.hyperfoil.api.session.GlobalData; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.ThreadData; import io.hyperfoil.api.statistics.SessionStatistics; import io.hyperfoil.api.statistics.Statistics; import io.netty.util.concurrent.EventExecutor; public class FakeSession implements Session { private final EventExecutor executor; private final int agentThreadId; public FakeSession(EventExecutor executor, int agentThreadId) { this.executor = executor; this.agentThreadId = agentThreadId; } @Override public Runnable runTask() { return null; } @Override public void reserve(Scenario scenario) { } @Override public int uniqueId() { return 0; } @Override public int agentThreadId() { return agentThreadId; } @Override public int agentThreads() { return 0; } @Override public int globalThreadId() { return 0; } @Override public int globalThreads() { return 0; } @Override public int agentId() { return 0; } @Override public int agents() { return 0; } @Override public String runId() { return ""; } @Override public EventExecutor executor() { return executor; } @Override public ThreadData threadData() { return null; } @Override public AgentData agentData() { return null; } @Override public GlobalData globalData() { return null; } @Override public PhaseInstance phase() { return null; } @Override public long phaseStartTimestamp() { return 0; } @Override public Statistics statistics(int stepId, String name) { return null; } @Override public void pruneStats(Phase phase) { } @Override public <R extends Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier) { } @Override public <R extends Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier, boolean singleton) { } @Override public <R extends Resource> void declareSingletonResource(ResourceKey<R> key, R resource) { } @Override public <R extends Resource> R getResource(ResourceKey<R> key) { return null; } @Override public void currentSequence(SequenceInstance current) { } @Override public SequenceInstance currentSequence() { return null; } @Override public void attach(EventExecutor executor, ThreadData threadData, AgentData agentData, GlobalData globalData, SessionStatistics statistics) { } @Override public void start(PhaseInstance phase) { } @Override public void proceed() { } @Override public void reset() { } @Override public SequenceInstance startSequence(String name, boolean forceSameIndex, ConcurrencyPolicy policy) { return null; } @Override public void stop() { } @Override public void fail(Throwable t) { } @Override public boolean isActive() { return false; } @Override public Request currentRequest() { return null; } @Override public void currentRequest(Request request) { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/impl/FakeEventExecutor.java
benchmarks/src/main/java/io/hyperfoil/core/impl/FakeEventExecutor.java
package io.hyperfoil.core.impl; import java.util.concurrent.TimeUnit; import io.netty.util.concurrent.AbstractEventExecutor; import io.netty.util.concurrent.Future; public class FakeEventExecutor extends AbstractEventExecutor { @Override public boolean isShuttingDown() { return false; } @Override public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { return null; } @Override public Future<?> terminationFuture() { return null; } @Override public void shutdown() { } @Override public boolean isShutdown() { return false; } @Override public boolean isTerminated() { return false; } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return false; } @Override public boolean inEventLoop(Thread thread) { return false; } @Override public void execute(Runnable command) { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/impl/PoolReserveBenchmark.java
benchmarks/src/main/java/io/hyperfoil/core/impl/PoolReserveBenchmark.java
package io.hyperfoil.core.impl; import java.util.ArrayDeque; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.session.Session; import io.netty.util.concurrent.EventExecutor; @State(Scope.Benchmark) @Fork(value = 2) @BenchmarkMode(Mode.SingleShotTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class PoolReserveBenchmark { @Param({ "128", "1024", "131072" }) private int capacity; @Param({ "0", "1", "2", "4" }) private int eventExecutors; private ElasticPool<Session> pool; @Setup public void setup() { var eventExecutors = new EventExecutor[this.eventExecutors]; for (int i = 0; i < eventExecutors.length; i++) { eventExecutors[i] = new FakeEventExecutor(); } var sessions = new ArrayDeque<Session>(capacity); long executorSequence = 0; for (int i = 0; i < capacity; i++) { Session session; if (eventExecutors.length > 0) { int agentThreadId = (int) (executorSequence++ % eventExecutors.length); session = new FakeSession(eventExecutors[agentThreadId], agentThreadId); } else { session = new FakeSession(null, 0); } sessions.add(session); } // this is just to have some class loading done, really // but need to be careful to not trigger too much JIT! var sessionsCopy = new ArrayDeque<>(sessions); if (eventExecutors.length > 0) { pool = new AffinityAwareSessionPool(eventExecutors, sessionsCopy::poll); } else { pool = new LockBasedElasticPool<>(sessionsCopy::poll, () -> { System.exit(1); return null; }); } if (eventExecutors.length > 0) { pool.reserve(eventExecutors.length); pool = new AffinityAwareSessionPool(eventExecutors, sessions::poll); } else { pool.reserve(1); pool = new LockBasedElasticPool<>(sessions::poll, () -> { System.exit(1); return null; }); } } @Benchmark public void reserve() { pool.reserve(capacity); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/impl/PoolBenchmark.java
benchmarks/src/main/java/io/hyperfoil/core/impl/PoolBenchmark.java
package io.hyperfoil.core.impl; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.concurrent.TimeUnit; import java.util.stream.StreamSupport; import org.openjdk.jmh.annotations.AuxCounters; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.BenchmarkParams; import org.openjdk.jmh.infra.Blackhole; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.harness.EventLoopGroupHarnessExecutor; import io.netty.util.concurrent.EventExecutor; @State(Scope.Benchmark) @Fork(value = 2, jvmArgs = { "-Djmh.executor=CUSTOM", "-Djmh.executor.class=io.hyperfoil.core.harness.EventLoopGroupHarnessExecutor" }) @Warmup(iterations = 5, time = 1) @Measurement(iterations = 5, time = 1) @OutputTimeUnit(TimeUnit.MICROSECONDS) public class PoolBenchmark { @Param({ "0" }) private int work; @Param({ "1024" }) private int capacity; @Param({ "1" }) private int burst; @Param({ "true" }) private boolean workStealingPool; @Param({ "0", "16" }) private int fakeEventExecutors; private ElasticPool<Session> pool; @Setup public void setup(BenchmarkParams params) { if (EventLoopGroupHarnessExecutor.TOTAL_EVENT_EXECUTORS.size() != 1) { throw new IllegalStateException("Expected exactly one EventLoopExecutor"); } var executorGroup = EventLoopGroupHarnessExecutor.TOTAL_EVENT_EXECUTORS.iterator().next(); var executors = StreamSupport.stream(executorGroup.spliterator(), false) .map(EventExecutor.class::cast).toArray(EventExecutor[]::new); if (executors.length != params.getThreads()) { throw new IllegalStateException("Expected " + params.getThreads() + " executors, got " + executors.length); } executors = Arrays.copyOf(executors, executors.length + fakeEventExecutors); // create some fake EventExecutors here, if needed for (int i = executors.length - fakeEventExecutors; i < executors.length; i++) { executors[i] = new FakeEventExecutor(); } // sessions are distributed among the perceived event executors, in round-robin var sessions = createSessions(executors, capacity); if (!workStealingPool) { pool = new LockBasedElasticPool<>(sessions::poll, () -> { System.exit(1); return null; }); } else { pool = new AffinityAwareSessionPool(executors, sessions::poll); } pool.reserve(capacity); } protected static Queue<Session> createSessions(EventExecutor[] executors, int sessions) { var queue = new ArrayDeque<Session>(sessions); for (int i = 0; i < sessions; i++) { int agentThreadId = i % executors.length; final var eventExecutor = executors[agentThreadId]; final Session session = new FakeSession(eventExecutor, agentThreadId); queue.add(session); } return queue; } @AuxCounters @State(Scope.Thread) public static class Counters { public long acquired; public long released; private ArrayDeque<Session> pooledAcquired; @Setup public void setup(PoolBenchmark benchmark) { pooledAcquired = new ArrayDeque<>(benchmark.burst); } } @Benchmark public int acquireAndRelease(Counters counters) { var pool = this.pool; int acquired = 0; var pooledAcquired = counters.pooledAcquired; for (int i = 0; i < burst; ++i) { var pooledObject = pool.acquire(); pooledAcquired.add(pooledObject); } counters.acquired += burst; int work = this.work; if (work > 0) { Blackhole.consumeCPU(work); } for (int i = 0; i < burst; ++i) { pool.release(pooledAcquired.poll()); } counters.released += burst; return acquired; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/core/harness/EventLoopGroupHarnessExecutor.java
benchmarks/src/main/java/io/hyperfoil/core/harness/EventLoopGroupHarnessExecutor.java
package io.hyperfoil.core.harness; import java.util.concurrent.CopyOnWriteArraySet; import io.netty.util.concurrent.DefaultEventExecutorGroup; public class EventLoopGroupHarnessExecutor extends DefaultEventExecutorGroup { public static final CopyOnWriteArraySet<EventLoopGroupHarnessExecutor> TOTAL_EVENT_EXECUTORS = new CopyOnWriteArraySet<>(); public EventLoopGroupHarnessExecutor(int nThreads, String ignored) { super(nThreads); TOTAL_EVENT_EXECUTORS.add(this); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/benchmarks/src/main/java/io/hyperfoil/http/ParseDateBenchmark.java
benchmarks/src/main/java/io/hyperfoil/http/ParseDateBenchmark.java
package io.hyperfoil.http; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; @State(Scope.Thread) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) @Fork(2) @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) public class ParseDateBenchmark { private String[] sequences; @Setup public void setup() { sequences = new String[] { "Tue, 29 Oct 2024 16:56:32 UTC", "Tue, 29 Oct 2024 16:56:32 GMT", "Tue, 29 Oct 2024 16:56:32 CET" }; } @Benchmark public void parseDates(Blackhole bh) { for (String seq : sequences) { bh.consume(HttpUtil.parseDate(seq)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/controller-api/src/main/java/io/hyperfoil/controller/Client.java
controller-api/src/main/java/io/hyperfoil/controller/Client.java
package io.hyperfoil.controller; import java.io.File; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Map; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.statistics.StatisticsSummary; import io.hyperfoil.controller.model.Histogram; import io.hyperfoil.controller.model.RequestStatisticsResponse; import io.hyperfoil.controller.model.Run; import io.hyperfoil.controller.model.Version; /** * API for server control */ public interface Client { BenchmarkRef register(Benchmark benchmark, String prevVersion); BenchmarkRef register(String yaml, Map<String, byte[]> otherFiles, String prevVersion, String storedFilesBenchmark); BenchmarkRef register(Path benchmarkFile, Map<String, Path> otherFiles, String prevVersion, String storedFilesBenchmark); BenchmarkRef registerLocal(String benchmarkUri, String prevVersion, String storedFilesBenchmark); List<String> benchmarks(); List<String> templates(); BenchmarkRef benchmark(String name); List<Run> runs(boolean details); RunRef run(String id); long ping(); Version version(); Collection<String> agents(); String downloadLog(String node, String logId, long offset, long maxLength, File destinationFile); void shutdown(boolean force); interface BenchmarkRef { String name(); BenchmarkSource source(); Benchmark get(); RunRef start(String description, Map<String, String> templateParams); RunRef start(String description, Map<String, String> templateParams, Boolean validate); BenchmarkStructure structure(Integer maxCollectionSize, Map<String, String> templateParams); Map<String, byte[]> files(); boolean exists(); boolean forget(); } class BenchmarkSource { public final String source; public final String version; public final Collection<String> files; public BenchmarkSource(String source, String version, Collection<String> files) { this.source = source; this.version = version; this.files = files; } } class BenchmarkStructure { public final Map<String, String> params; public final String content; @JsonCreator public BenchmarkStructure(@JsonProperty("params") Map<String, String> params, @JsonProperty("content") String content) { this.params = params; this.content = content; } } interface RunRef { String id(); Run get(); RunRef kill(); Benchmark benchmark(); Map<String, Map<String, MinMax>> sessionStatsRecent(); Map<String, Map<String, MinMax>> sessionStatsTotal(); // TODO: server should expose JSON-formatted variants Collection<String> sessions(); Collection<String> connections(); Map<String, Map<String, MinMax>> connectionStatsRecent(); Map<String, Map<String, MinMax>> connectionStatsTotal(); RequestStatisticsResponse statsRecent(); RequestStatisticsResponse statsTotal(); byte[] statsAll(String format); Histogram histogram(String phase, int stepId, String metric); List<StatisticsSummary> series(String phase, int stepId, String metric); byte[] file(String filename); byte[] report(String source); Map<String, Map<String, String>> agentCpu(); } class MinMax { public final int min; public final int max; @JsonCreator public MinMax(@JsonProperty("min") int min, @JsonProperty("max") int max) { this.min = min; this.max = max; } } class EditConflictException extends RuntimeException { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/controller-api/src/main/java/io/hyperfoil/controller/HistogramConverter.java
controller-api/src/main/java/io/hyperfoil/controller/HistogramConverter.java
package io.hyperfoil.controller; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.charset.StandardCharsets; import org.HdrHistogram.AbstractHistogram; import org.HdrHistogram.EncodableHistogram; import org.HdrHistogram.HistogramLogReader; import org.HdrHistogram.HistogramLogWriter; import io.hyperfoil.controller.model.Histogram; public final class HistogramConverter { private HistogramConverter() { } public static Histogram convert(String phase, String metric, AbstractHistogram source) { ByteArrayOutputStream bos = new ByteArrayOutputStream(source.getNeededByteBufferCapacity() + 100); HistogramLogWriter writer = new HistogramLogWriter(bos); writer.outputIntervalHistogram(source); writer.close(); return new Histogram(phase, metric, source.getStartTimeStamp(), source.getEndTimeStamp(), bos.toString(StandardCharsets.UTF_8)); } public static AbstractHistogram convert(Histogram source) { ByteArrayInputStream bis = new ByteArrayInputStream(source.data.getBytes(StandardCharsets.UTF_8)); EncodableHistogram histogram = new HistogramLogReader(bis).nextIntervalHistogram(); if (histogram == null) { return null; } histogram.setStartTimeStamp(source.startTime); histogram.setEndTimeStamp(source.endTime); return (AbstractHistogram) histogram; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/BaseBenchmarkTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/BaseBenchmarkTest.java
package io.hyperfoil.benchmark; import java.io.File; import java.net.URL; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServer; import io.vertx.core.http.HttpServerRequest; import io.vertx.junit5.VertxExtension; import io.vertx.junit5.VertxTestContext; @ExtendWith(VertxExtension.class) public abstract class BaseBenchmarkTest { protected Vertx vertx; protected HttpServer httpServer; @BeforeEach public void before(Vertx vertx, VertxTestContext ctx) { this.vertx = vertx; setupHttpServer(ctx, getRequestHandler()); } protected Handler<HttpServerRequest> getRequestHandler() { return req -> req.response().end(); } private void setupHttpServer(VertxTestContext ctx, Handler<HttpServerRequest> handler) { httpServer = vertx.createHttpServer().requestHandler(handler).listen(0, "localhost", ctx.succeedingThenComplete()); } protected String getBenchmarkPath(String name) { URL resource = getClass().getClassLoader().getResource(name); if (resource == null) { throw new AssertionError("Resource named: " + name + " not found"); } File benchmark = new File(resource.getFile()); return benchmark.getAbsolutePath(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/clustering/ClusterTestCase.java
test-suite/src/test/java/io/hyperfoil/benchmark/clustering/ClusterTestCase.java
package io.hyperfoil.benchmark.clustering; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTimeout; import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.time.Duration; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.vertx.core.Handler; import io.vertx.core.Promise; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.http.HttpHeaders; import io.vertx.core.http.HttpServerRequest; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.client.HttpResponse; import io.vertx.ext.web.client.WebClient; import io.vertx.ext.web.client.WebClientOptions; import io.vertx.junit5.Checkpoint; import io.vertx.junit5.VertxTestContext; // Note: this test won't run from IDE (probably) as SshDeployer copies just .jar files for the agents; // since it inspects classpath for .jars it won't copy the class files in the hyperfoil-clustering module. // It runs from Maven just fine. @Tag("io.hyperfoil.test.Benchmark") public class ClusterTestCase extends BaseClusteredTest { private static final int AGENTS = 2; public static io.hyperfoil.api.config.Benchmark testBenchmark(int agents, int port) { BenchmarkBuilder benchmarkBuilder = BenchmarkBuilder.builder().name("test"); for (int i = 0; i < agents; ++i) { benchmarkBuilder.addAgent("agent" + i, "localhost", null); } // @formatter:off benchmarkBuilder .addPlugin(HttpPluginBuilder::new) .http() .host("localhost").port(port) .sharedConnections(10) .endHttp() .endPlugin() .addPhase("test").always(agents) .duration(5000) .scenario() .initialSequence("test") .step(SC).httpRequest(HttpMethod.GET) .path("test") .sla().addItem() .meanResponseTime(10, TimeUnit.MILLISECONDS) .limits().add(0.99, TimeUnit.MILLISECONDS.toNanos(100)).end() .errorRatio(0.02) .window(3000, TimeUnit.MILLISECONDS) .endSLA().endList() .endStep() .endSequence() .endScenario() .endPhase(); // @formatter:on return benchmarkBuilder.build(); } @Override protected Handler<HttpServerRequest> getRequestHandler() { return req -> { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); // TODO: Customise this generated block } req.response().end("test"); }; } @BeforeEach public void before(Vertx vertx, VertxTestContext ctx) { super.before(vertx, ctx); startController(ctx); } @Test public void startClusteredBenchmarkTest(VertxTestContext ctx) { assertTimeout(Duration.ofSeconds(120), () -> { WebClientOptions options = new WebClientOptions().setDefaultHost("localhost").setDefaultPort(controllerPort); WebClient client = WebClient.create(this.vertx, options.setFollowRedirects(false)); var termination = ctx.checkpoint(); // upload benchmark Promise<HttpResponse<Buffer>> uploadPromise = Promise.promise(); client.post("/benchmark") .putHeader(HttpHeaders.CONTENT_TYPE.toString(), "application/java-serialized-object") .sendBuffer(Buffer.buffer(serialize(testBenchmark(AGENTS, httpServer.actualPort()))), ctx.succeeding(uploadPromise::complete)); Promise<HttpResponse<Buffer>> benchmarkPromise = Promise.promise(); uploadPromise.future().onSuccess(response -> { assertEquals(response.statusCode(), 204); assertEquals(response.getHeader(HttpHeaders.LOCATION.toString()), "http://localhost:" + controllerPort + "/benchmark/test"); // list benchmarks client.get("/benchmark").send(ctx.succeeding(benchmarkPromise::complete)); }); Promise<HttpResponse<Buffer>> startPromise = Promise.promise(); benchmarkPromise.future().onSuccess(response -> { assertEquals(response.statusCode(), 200); assertTrue(new JsonArray(response.bodyAsString()).contains("test")); //start benchmark running client.get("/benchmark/test/start").send(ctx.succeeding(startPromise::complete)); }); startPromise.future().onSuccess(response -> { assertEquals(response.statusCode(), 202); String location = response.getHeader(HttpHeaders.LOCATION.toString()); getStatus(ctx, client, location, termination); }); }); } private void getStatus(VertxTestContext ctx, WebClient client, String location, Checkpoint termination) { client.get(location).send(ctx.succeeding(response -> { assertEquals(response.statusCode(), 200); try { JsonObject status = new JsonObject(response.bodyAsString()); assertThat(status.getString("benchmark")).isEqualTo("test"); if (status.getString("terminated") != null) { JsonArray errors = status.getJsonArray("errors"); assertThat(errors).isNotNull(); assertThat(errors.size()).withFailMessage("Found errors: %s", errors).isEqualTo(0); assertThat(status.getString("started")).isNotNull(); JsonArray agents = status.getJsonArray("agents"); for (int i = 0; i < agents.size(); ++i) { assertThat(agents.getJsonObject(i).getString("status")).isNotEqualTo("STARTING"); } termination.flag(); } else { vertx.setTimer(100, id -> { getStatus(ctx, client, location, termination); }); } } catch (Throwable t) { ctx.failNow(t); throw t; } })); } private byte[] serialize(Serializable object) { try { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) { objectOutputStream.writeObject(object); } byteArrayOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } catch (IOException e) { throw new AssertionError(e); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/clustering/MoreAgentsThanUsersTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/clustering/MoreAgentsThanUsersTest.java
package io.hyperfoil.benchmark.clustering; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.client.RestClient; import io.hyperfoil.controller.Client; import io.hyperfoil.controller.model.Run; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.http.steps.HttpStepCatalog; import io.vertx.core.Vertx; import io.vertx.junit5.VertxTestContext; @Tag("io.hyperfoil.test.Benchmark") public class MoreAgentsThanUsersTest extends BaseClusteredTest { private static final String TRACE_CONFIG = "-Dlog4j.configurationFile=file://" + MoreAgentsThanUsersTest.class.getProtectionDomain().getCodeSource().getLocation().getPath() + "/../../src/test/resources/log4j2.xml"; @BeforeEach public void before(Vertx vertx, VertxTestContext ctx) { super.before(vertx, ctx); startController(ctx); } @Test public void test() throws InterruptedException { Map<String, String> agentOptions = System.getProperty("agent.log.trace") != null ? Map.of("extras", TRACE_CONFIG) : null; //@formatter:off BenchmarkBuilder benchmark = BenchmarkBuilder.builder() .name("test") .addAgent("a1", "localhost", agentOptions) .addAgent("a2", "localhost", agentOptions) .threads(2) .addPlugin(HttpPluginBuilder::new) .http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(4) .endHttp() .endPlugin() .addPhase("test").always(1) .duration(1000) .scenario() .initialSequence("test") .step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET).path("/").endStep() .endSequence() .endScenario() .endPhase(); //@formatter:on try (RestClient client = new RestClient(vertx, "localhost", controllerPort, false, false, null)) { Client.BenchmarkRef ref = client.register(benchmark.build(), null); Client.RunRef run = ref.start(null, Collections.emptyMap()); Run info; do { info = run.get(); Thread.sleep(100); } while (!info.completed); assertThat(info.errors).isEmpty(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/clustering/BaseClusteredTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/clustering/BaseClusteredTest.java
package io.hyperfoil.benchmark.clustering; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import io.hyperfoil.Hyperfoil; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.clustering.ControllerVerticle; import io.hyperfoil.internal.Properties; import io.vertx.core.DeploymentOptions; import io.vertx.core.Verticle; import io.vertx.core.Vertx; import io.vertx.core.impl.VertxInternal; import io.vertx.junit5.VertxTestContext; public abstract class BaseClusteredTest extends BaseBenchmarkTest { protected List<Vertx> servers = new ArrayList<>(); protected volatile int controllerPort; @AfterEach public void tearDown(VertxTestContext ctx) { servers.forEach(vertx -> Hyperfoil.shutdownVertx(vertx).onComplete(ctx.succeedingThenComplete())); } protected void startController(VertxTestContext ctx) { // Some clustered tests time out in GitHub Actions because the agents don't cluster soon enough. System.setProperty("jgroups.join_timeout", "15000"); //configure multi node vert.x cluster System.setProperty(Properties.CONTROLLER_HOST, "localhost"); System.setProperty(Properties.CONTROLLER_PORT, "0"); System.setProperty(Properties.CONTROLLER_CLUSTER_IP, "localhost"); // latch used to ensure we wait for controller startup before starting the test var countDownLatch = new CountDownLatch(1); Hyperfoil.clusteredVertx(true).onSuccess(vertx -> { servers.add(vertx); vertx.deployVerticle(ControllerVerticle.class, new DeploymentOptions()) .onSuccess(deploymentId -> { Set<Verticle> verticles = ((VertxInternal) vertx).getDeployment(deploymentId).getVerticles(); ControllerVerticle controller = (ControllerVerticle) verticles.iterator().next(); controllerPort = controller.actualPort(); countDownLatch.countDown(); ctx.completeNow(); }).onFailure(ctx::failNow); }).onFailure(cause -> ctx.failNow("Failed to start clustered Vert.x, see log for details")); try { if (!countDownLatch.await(10, TimeUnit.SECONDS)) { ctx.failNow("Expected 0 latch, controller did not start in time"); } } catch (InterruptedException e) { ctx.failNow(e); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/clustering/AgentSSHKeyTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/clustering/AgentSSHKeyTest.java
package io.hyperfoil.benchmark.clustering; import static org.assertj.core.api.Assertions.assertThat; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.client.RestClient; import io.hyperfoil.controller.Client; import io.hyperfoil.controller.model.Run; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.http.steps.HttpStepCatalog; import io.vertx.core.Vertx; import io.vertx.junit5.VertxTestContext; @Tag("io.hyperfoil.test.Benchmark") public class AgentSSHKeyTest extends BaseClusteredTest { @BeforeEach public void before(Vertx vertx, VertxTestContext ctx) { super.before(vertx, ctx); startController(ctx); } /** * This test passes an sshKey that doesn't exist to verify it is attempted to be used. We do not verify the key is * used in a non error test to not mess with users ssh keys. */ @Test public void testSshKeyNotPresent() throws InterruptedException { String keyName = "not-present-#@!l"; Map<String, String> agentOptions = Map.of("sshKey", keyName); //@formatter:off BenchmarkBuilder benchmark = BenchmarkBuilder.builder() .name("test") .addAgent("agent", "localhost", agentOptions) .threads(2) .addPlugin(HttpPluginBuilder::new) .http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(4) .endHttp() .endPlugin() .addPhase("test").always(1) .duration(1000) .scenario() .initialSequence("test") .step(HttpStepCatalog.SC).httpRequest(HttpMethod.GET).path("/").endStep() .endSequence() .endScenario() .endPhase(); //@formatter:on try (RestClient client = new RestClient(vertx, "localhost", controllerPort, false, false, null)) { Client.BenchmarkRef ref = client.register(benchmark.build(), null); Client.RunRef run = ref.start(null, Collections.emptyMap()); Run info; do { info = run.get(); Thread.sleep(100); } while (!info.completed); assertThat(info.errors).isNotEmpty(); String errorString = info.errors.get(0); assertThat(errorString).containsSubsequence(keyName, "No such file or directory"); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/RequestResponseCounterTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/RequestResponseCounterTest.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.hyperfoil.benchmark.standalone; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.junit.jupiter.api.Assertions.assertEquals; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.core.handlers.TransferSizeRecorder; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.impl.statistics.StatisticsCollector; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.http.HttpServerRequest; import io.vertx.junit5.VertxTestContext; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ @Tag("io.hyperfoil.test.Benchmark") public class RequestResponseCounterTest extends BaseBenchmarkTest { private AtomicLong counter; @BeforeEach public void before(Vertx vertx, VertxTestContext ctx) { super.before(vertx, ctx); counter = new AtomicLong(); } @Override protected Handler<HttpServerRequest> getRequestHandler() { return req -> { counter.getAndIncrement(); req.response().end("hello from server"); }; } @Test public void testNumberOfRequestsAndResponsesMatch() { // @formatter:off BenchmarkBuilder builder = BenchmarkBuilder.builder() .name("requestResponseCounter " + new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date())) .addPlugin(HttpPluginBuilder::new).http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(50) .endHttp().endPlugin() .threads(2); builder.addPhase("run").constantRate(500) .duration(5000) .maxSessions(500 * 15) .scenario() .initialSequence("request") .step(SC).httpRequest(HttpMethod.GET) .path("/") .timeout("60s") .handler() .rawBytes(new TransferSizeRecorder("transfer")) .endHandler() .endStep() .endSequence(); // @formatter:on Benchmark benchmark = builder.build(); AtomicLong actualNumberOfRequests = new AtomicLong(0); StatisticsCollector.StatisticsConsumer statisticsConsumer = (phase, stepId, metric, snapshot, countDown) -> actualNumberOfRequests.addAndGet(snapshot.histogram.getTotalCount()); LocalSimulationRunner runner = new LocalSimulationRunner(benchmark, statisticsConsumer, null, null); runner.run(); assertEquals(counter.get(), actualNumberOfRequests.get()); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/IterationsTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/IterationsTest.java
package io.hyperfoil.benchmark.standalone; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkData; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.parser.BenchmarkParser; import io.hyperfoil.core.parser.ParserException; @Tag("io.hyperfoil.test.Benchmark") public class IterationsTest extends BaseBenchmarkTest { @Test public void test() throws IOException, ParserException { try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("IterationsTest.hf.yaml")) { Benchmark benchmark = BenchmarkParser.instance().buildBenchmark( inputStream, BenchmarkData.EMPTY, Map.of("PORT", String.valueOf(httpServer.actualPort()))); new LocalSimulationRunner(benchmark).run(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/RunTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/RunTest.java
package io.hyperfoil.benchmark.standalone; import static org.junit.jupiter.api.Assertions.assertEquals; import org.aesh.command.CommandResult; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.cli.commands.LoadAndRun; @Tag("io.hyperfoil.test.Benchmark") public class RunTest extends BaseBenchmarkTest { @Test public void testRunMain() { String benchmark = getBenchmarkPath("scenarios/httpRequestParameterized.hf.yaml"); LoadAndRun.main(new String[] { "-PSERVER_PORT=" + httpServer.actualPort(), benchmark }); } @Test public void testRun() { String benchmark = getBenchmarkPath("scenarios/httpRequestParameterized.hf.yaml"); LoadAndRun cmd = new LoadAndRun(); int result = cmd.exec(new String[] { benchmark, "-PSERVER_PORT=" + httpServer.actualPort() }); assertEquals(CommandResult.SUCCESS.getResultValue(), result); } @Test public void testRunMissingBenchmarkArg() { LoadAndRun cmd = new LoadAndRun(); int result = cmd.exec(new String[] {}); assertEquals(CommandResult.FAILURE.getResultValue(), result); } @Test public void testRunBenchmarkNotFound() { LoadAndRun cmd = new LoadAndRun(); int result = cmd.exec(new String[] { "not-found.hf.yaml" }); assertEquals(CommandResult.FAILURE.getResultValue(), result); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/ThinkTimeTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/ThinkTimeTest.java
package io.hyperfoil.benchmark.standalone; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.core.handlers.TransferSizeRecorder; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.impl.statistics.StatisticsCollector; import io.hyperfoil.core.util.CountDown; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.vertx.core.Handler; import io.vertx.core.http.HttpServerRequest; @Tag("io.hyperfoil.test.Benchmark") public class ThinkTimeTest extends BaseBenchmarkTest { private static final Logger log = LogManager.getLogger(ThinkTimeTest.class); private static final long benchmarkDuration = 1000; // parameters source private static Stream<Arguments> thinkTimesConfigs() { return Stream.of( Arguments.of("phase a", 1), Arguments.of("phase a", TimeUnit.MILLISECONDS.toNanos(50)), Arguments.of("phase b", TimeUnit.MILLISECONDS.toNanos(500)), Arguments.of("phase c", TimeUnit.MILLISECONDS.toNanos(1000))); } @Override protected Handler<HttpServerRequest> getRequestHandler() { return req -> { req.response().end("hello from server"); }; } @ParameterizedTest @MethodSource("thinkTimesConfigs") public void testThinkTime(String phase1, long delayNs) { BenchmarkBuilder builder = createBuilder(phase1, delayNs); Benchmark benchmark = builder.build(); // check think time is correctly setup Phase mainPhase = benchmark.phases().stream().filter(p -> p.name.equals(phase1)).findAny().orElseThrow(); // beforeSync, prepareHttpReq, sendHttpReq, afterSync, scheduleDelay, awaitDelay assertEquals(6, mainPhase.scenario().sequences()[0].steps().length); TestStatistics statisticsConsumer = new TestStatistics(); LocalSimulationRunner runner = new LocalSimulationRunner(benchmark, statisticsConsumer, null, null); runner.run(); long now = System.currentTimeMillis(); // check start time PhaseInstance phase = runner.instances().get(phase1); long expectedDuration = phase.definition().duration(); long remaining = expectedDuration - (now - phase.absoluteStartTime()); log.debug("Remaining = {}", remaining); StatisticsSnapshot stats = statisticsConsumer.stats().get("request"); assertEquals(0, stats.invalid); // the thinkTime starts just after the request is completed assertTrue(remaining < 0); } /** * create a builder with two phases where the first one should start with the second one after a provided delay */ private BenchmarkBuilder createBuilder(String firstPhase, long thinkTime) { // @formatter:off BenchmarkBuilder builder = BenchmarkBuilder.builder() .name("thinkTime " + new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date())) .addPlugin(HttpPluginBuilder::new).http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(50) .endHttp().endPlugin() .threads(1); builder.addPhase(firstPhase).constantRate(50) .duration(benchmarkDuration) .maxSessions(50) .scenario() .initialSequence("request") .step(SC).httpRequest(HttpMethod.GET) .path("/") .timeout("60s") .handler() .rawBytes(new TransferSizeRecorder("transfer")) .endHandler() .endStep() .step(SC) .thinkTime(thinkTime, TimeUnit.NANOSECONDS) .endStep() .endSequence(); // @formatter:on return builder; } public static class TestStatistics implements StatisticsCollector.StatisticsConsumer { private final Map<String, StatisticsSnapshot> stats = new HashMap<>(); @Override public void accept(Phase phase, int stepId, String metric, StatisticsSnapshot snapshot, CountDown countDown) { log.debug("Adding stats for {}/{}/{} - #{}: {} requests {} responses", phase, stepId, metric, snapshot.sequenceId, snapshot.requestCount, snapshot.responseCount); stats.computeIfAbsent(metric, n -> new StatisticsSnapshot()).add(snapshot); } public Map<String, StatisticsSnapshot> stats() { return stats; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/WrkTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/WrkTest.java
package io.hyperfoil.benchmark.standalone; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.ThreadLocalRandom; import org.aesh.command.CommandResult; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.cli.commands.Wrk; import io.hyperfoil.cli.commands.Wrk2; import io.vertx.core.Handler; import io.vertx.core.http.HttpServerRequest; @Tag("io.hyperfoil.test.Benchmark") public class WrkTest extends BaseBenchmarkTest { protected long unservedDelay = 2000; protected double servedRatio = 0.9; public WrkTest() { } @Override protected Handler<HttpServerRequest> getRequestHandler() { return this::serveOrClose; } private void serveOrClose(HttpServerRequest req) { if (servedRatio >= 1.0 || ThreadLocalRandom.current().nextDouble() < servedRatio) { req.response().end(); } else { if (unservedDelay > 0) { vertx.setTimer(unservedDelay, timer -> req.connection().close()); } else { req.connection().close(); } } } @Test public void testWrk() { Wrk.main(new String[] { "-c", "10", "-d", "5s", "--latency", "--timeout", "1s", "localhost:" + httpServer.actualPort() + "/foo/bar" }); } @Test public void testFailFastWrk() { Wrk cmd = new Wrk(); int result = cmd.exec(new String[] { "-c", "10", "-d", "5s", "--latency", "--timeout", "1s", "nonExistentHost:" + httpServer.actualPort() + "/foo/bar" }); ; assertEquals(CommandResult.FAILURE.getResultValue(), result); } @Test public void testWrk2() { Wrk2.main(new String[] { "-c", "10", "-d", "5s", "-R", "20", "--latency", "--timeout", "1s", "localhost:" + httpServer.actualPort() + "/foo/bar" }); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/StartWithDelayTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/StartWithDelayTest.java
package io.hyperfoil.benchmark.standalone; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.text.SimpleDateFormat; import java.util.Date; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.jupiter.api.Tag; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.PhaseReferenceDelay; import io.hyperfoil.api.config.RelativeIteration; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.core.handlers.TransferSizeRecorder; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.impl.statistics.StatisticsCollector; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.vertx.core.Handler; import io.vertx.core.http.HttpServerRequest; @Tag("io.hyperfoil.test.Benchmark") public class StartWithDelayTest extends BaseBenchmarkTest { private static final Logger log = LogManager.getLogger(StartWithDelayTest.class); private static final long epsilonMs = 50; // parameters source private static Stream<Arguments> delaysConfigs() { return Stream.of( Arguments.of("additional", "steady", 0), Arguments.of("additional", "steady", 2000)); } @Override protected Handler<HttpServerRequest> getRequestHandler() { return req -> { req.response().end("hello from server"); }; } @ParameterizedTest @MethodSource("delaysConfigs") public void testStartWithDifferentDelay(String phase1, String phase2, long delay) { BenchmarkBuilder builder = createBuilder(phase1, phase2, delay); Benchmark benchmark = builder.build(); // check startWithDelay is correctly setup Phase additionalPhase = benchmark.phases().stream().filter(p -> p.name.equals("additional")).findAny().orElseThrow(); assertNotNull(additionalPhase.startWithDelay()); assertEquals("steady", additionalPhase.startWithDelay().phase); assertEquals(delay, additionalPhase.startWithDelay().delay); StatisticsCollector.StatisticsConsumer statisticsConsumer = (phase, stepId, metric, snapshot, countDown) -> log.debug( "Adding stats for {}/{}/{} - #{}: {} requests {} responses", phase, stepId, metric, snapshot.sequenceId, snapshot.requestCount, snapshot.responseCount); LocalSimulationRunner runner = new LocalSimulationRunner(benchmark, statisticsConsumer, null, null); runner.run(); // check start time long startTimeDiff = runner.instances().get(phase1).absoluteStartTime() - runner.instances().get(phase2).absoluteStartTime(); log.debug("Absolute start time diff = {}", startTimeDiff); assertTrue(startTimeDiff >= delay); // assertTrue(startTimeDiff <= delay + epsilon); } /** * create a builder with two phases where the first one should start with the second one after a provided delay */ private BenchmarkBuilder createBuilder(String firstPhase, String secondPhase, long startWithDelay) { // @formatter:off BenchmarkBuilder builder = BenchmarkBuilder.builder() .name("startWithDelay " + new SimpleDateFormat("yy/MM/dd HH:mm:ss").format(new Date())) .addPlugin(HttpPluginBuilder::new).http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(50) .endHttp().endPlugin() .threads(2); builder.addPhase(firstPhase).constantRate(200) .duration(3000) .maxSessions(200 * 15) .startWith(new PhaseReferenceDelay(secondPhase, RelativeIteration.NONE, null, startWithDelay)) .scenario() .initialSequence("request") .step(SC).httpRequest(HttpMethod.GET) .path("/") .timeout("60s") .handler() .rawBytes(new TransferSizeRecorder("transfer")) .endHandler() .endStep() .endSequence(); builder.addPhase(secondPhase).constantRate(200) .duration(3000) .maxSessions(200 * 15) .scenario() .initialSequence("request") .step(SC).httpRequest(HttpMethod.GET) .path("/") .timeout("60s") .handler() .rawBytes(new TransferSizeRecorder("transfer")) .endHandler() .endStep() .endSequence(); // @formatter:on return builder; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/benchmark/standalone/TwoScenariosTest.java
test-suite/src/test/java/io/hyperfoil/benchmark/standalone/TwoScenariosTest.java
package io.hyperfoil.benchmark.standalone; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.benchmark.BaseBenchmarkTest; import io.hyperfoil.core.handlers.NewSequenceAction; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.test.TestUtil; import io.hyperfoil.core.util.RandomConcurrentSet; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.http.config.HttpPluginBuilder; import io.vertx.core.Handler; import io.vertx.core.http.HttpServerRequest; import io.vertx.ext.web.Router; @Tag("io.hyperfoil.test.Benchmark") public class TwoScenariosTest extends BaseBenchmarkTest { protected Router router; private final ConcurrentMap<String, SailsState> serverState = new ConcurrentHashMap<>(); @Override protected Handler<HttpServerRequest> getRequestHandler() { if (router == null) { router = Router.router(vertx); initRouter(); } return router; } protected void initRouter() { router.route("/board").handler(ctx -> ctx.response().end("Ahoy!")); router.route("/rig").handler(ctx -> { String ship = ctx.queryParam("ship").stream().findFirst().orElse(null); if (ship != null && serverState.replace(ship, SailsState.FURLED, SailsState.RIGGED)) { ctx.response().end("Rigged!"); } else { ctx.response().setStatusCode(409).end(); } }); router.route("/furl").handler(ctx -> { String ship = ctx.queryParam("ship").stream().findFirst().orElse(null); if (ship != null && serverState.replace(ship, SailsState.RIGGED, SailsState.FURLED)) { ctx.response().end("Furled!"); } else { ctx.response().setStatusCode(409).end(); } }); router.route("/disembark").handler(ctx -> ctx.response().end("Bye!")); } @Test public void testTwoScenarios() { // We have two options when simulating 'some users rigging and sailing ships' // * shared state of all ships (requires synchronization) // ** one option is to pick id from pool at the beginning // ** we should measure the contention there // * indexing users/sessions by uniqueId and keeping state per active user // ** however sessions for different phases have always different uniqueId() // When we can't find a suitable ship, we can // * try to pick another scenario - not possible because phases are fully isolated // * loop until we find suitable ship - do some yielding/backoff // * declare failure in stats (and retry later) RandomConcurrentSet<ShipInfo> ships = new RandomConcurrentSet<>(16); ships.put(new ShipInfo("Niña", SailsState.FURLED)); ships.put(new ShipInfo("Pinta", SailsState.FURLED)); ships.put(new ShipInfo("Santa María", SailsState.RIGGED)); ships.put(new ShipInfo("Trinidad", SailsState.RIGGED)); ships.put(new ShipInfo("Antonio", SailsState.FURLED)); ships.put(new ShipInfo("Concepción", SailsState.RIGGED)); ships.put(new ShipInfo("Santiago", SailsState.FURLED)); ships.put(new ShipInfo("Victoria", SailsState.FURLED)); Locator.push(TestUtil.locator()); // We need a different accessor per phase because the indices are assigned per scenario ReadAccess rigShip = SessionFactory.readAccess("ship"); ReadAccess furlShip = SessionFactory.readAccess("ship"); Locator.pop(); // @formatter:off BenchmarkBuilder benchmark = BenchmarkBuilder.builder() .name("Test Benchmark") .addPlugin(HttpPluginBuilder::new) .ergonomics() .stopOnInvalid(false) .endErgonomics() .http() .host("localhost").port(httpServer.actualPort()) .sharedConnections(10) .endHttp() .endPlugin() .addPhase("rig").constantRate(3) .duration(5000) .maxDuration(10000) .scenario() .initialSequence("select-ship") .step(SC).stopwatch() .step(SC).poll(ships::fetch, "ship") .filter(shipInfo -> shipInfo.sailsState == SailsState.FURLED, ships::put) .endStep() .end() .step(SC).action(new NewSequenceAction.Builder().sequence("board")) .endSequence() .sequence("board") .step(SC).httpRequest(HttpMethod.GET).path("/board").endStep() .step(SC).action(new NewSequenceAction.Builder().sequence("rig")) .endSequence() .sequence("rig") .step(SC).httpRequest(HttpMethod.GET) .path(s -> "/rig?ship=" + encode(((ShipInfo) rigShip.getObject(s)).name)) .handler().status(((request, status) -> { if (status == 200) { ((ShipInfo) rigShip.getObject(request.session)).sailsState = SailsState.RIGGED; } else { request.markInvalid(); } })).endHandler() .endStep() .step(SC).action(new NewSequenceAction.Builder().sequence("disembark")) .endSequence() .sequence("disembark") .step(SC).httpRequest(HttpMethod.GET).path("/disembark").endStep() .step(s -> { ships.put((ShipInfo) rigShip.getObject(s)); return true; }) .endSequence() .endScenario() .endPhase() .addPhase("furl").constantRate(2) // intentionally less to trigger maxDuration .duration(5000) // no max duration, should not need it .scenario() .initialSequence("select-ship") .step(SC).stopwatch() .step(SC).poll(ships::fetch, "ship") .filter(shipInfo -> shipInfo.sailsState == SailsState.RIGGED, ships::put) .endStep() .end() .step(SC).action(new NewSequenceAction.Builder().sequence("board")) .endSequence() .sequence("board") .step(SC).httpRequest(HttpMethod.GET).path("/board").endStep() .step(SC).action(new NewSequenceAction.Builder().sequence("furl")) .endSequence() .sequence("furl") .step(SC).httpRequest(HttpMethod.GET) .path(s -> "/furl?ship=" + encode(((ShipInfo) furlShip.getObject(s)).name)) .handler().status((request, status) -> { if (status == 200) { ((ShipInfo) furlShip.getObject(request.session)).sailsState = SailsState.RIGGED; } else { request.markInvalid(); } }).endHandler() .endStep() .step(SC).action(new NewSequenceAction.Builder().sequence("disembark")) .endSequence() .sequence("disembark") .step(SC).httpRequest(HttpMethod.GET).path("/disembark").endStep() .step(s -> { ships.put((ShipInfo) furlShip.getObject(s)); return true; }) .endSequence() .endScenario() .endPhase(); // @formatter:on new LocalSimulationRunner(benchmark.build()).run(); } private static String encode(String string) { return URLEncoder.encode(string, StandardCharsets.UTF_8); } enum SailsState { FURLED, RIGGED } static class ShipInfo { String name; SailsState sailsState; ShipInfo(String name, SailsState sailsState) { this.name = name; this.sailsState = sailsState; } @Override public String toString() { return "ShipInfo{" + "name='" + name + '\'' + ", sailsState=" + sailsState + '}'; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/JsonReplaceTest.java
test-suite/src/test/java/io/hyperfoil/test/JsonReplaceTest.java
package io.hyperfoil.test; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.http.BaseHttpScenarioTest; import io.vertx.core.json.JsonObject; import io.vertx.ext.web.handler.BodyHandler; import io.vertx.junit5.VertxExtension; @ExtendWith(VertxExtension.class) public class JsonReplaceTest extends BaseHttpScenarioTest { @Override protected void initRouter() { router.get("/get").handler(ctx -> { ctx.response().end(new JsonObject().put("name", "John Doe").put("age", 33).encode()); }); router.post("/post").handler(BodyHandler.create()).handler(ctx -> { try { JsonObject person = ctx.getBodyAsJson(); assertThat(person.getInteger("age")).isEqualTo(34); ctx.response().end(); } catch (Throwable t) { log.error("Assertion failed", t); ctx.response().setStatusCode(400).end(); } }); } @Test public void test() { Benchmark benchmark = loadScenario("scenarios/JsonReplaceTest.hf.yaml"); Map<String, StatisticsSnapshot> stats = runScenario(benchmark); stats.values().forEach(s -> assertThat(s.errors()).isEqualTo(0)); assertThat(stats.values().stream().mapToInt(s -> s.responseCount).sum()).isEqualTo(2); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/SessionStopTest.java
test-suite/src/test/java/io/hyperfoil/test/SessionStopTest.java
package io.hyperfoil.test; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.assertj.core.api.Assertions.assertThat; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.hyperfoil.api.session.Session; import io.hyperfoil.http.BaseHttpScenarioTest; import io.hyperfoil.http.api.HttpMethod; import io.vertx.junit5.VertxExtension; @ExtendWith(VertxExtension.class) public class SessionStopTest extends BaseHttpScenarioTest { @Override protected void initRouter() { router.get("/test").handler(ctx -> ctx.response().end("OK")); } @Test public void testStopAsStep() { AtomicInteger counter = new AtomicInteger(); parallelScenario(1).initialSequence("test") .step(SC).stop() .step(s -> { counter.incrementAndGet(); return true; }); runScenario(); assertThat(counter.get()).isEqualTo(0); } @Test public void testStopAsHandler() { AtomicInteger counter = new AtomicInteger(); parallelScenario(1).initialSequence("test") .step(SC).httpRequest(HttpMethod.GET).path("/test") .handler().onCompletion(Session::stop).endHandler() .endStep() .step(s -> { counter.incrementAndGet(); return true; }); runScenario(); assertThat(counter.get()).isEqualTo(0); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/PacingTest.java
test-suite/src/test/java/io/hyperfoil/test/PacingTest.java
package io.hyperfoil.test; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import static org.assertj.core.api.Assertions.assertThat; import java.util.Map; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.http.BaseHttpScenarioTest; import io.hyperfoil.http.api.HttpMethod; import io.vertx.junit5.VertxExtension; @ExtendWith(VertxExtension.class) public class PacingTest extends BaseHttpScenarioTest { @Override protected void initRouter() { router.route("/test").handler(ctx -> { try { Thread.sleep(500); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } ctx.response().end("Hello!"); }); } @Test public void testThinkTimes() { scenario().initialSequence("loop") .step(SC).loop("counter", 5) .steps() .step(SC).httpRequest(HttpMethod.GET).path("/test").endStep() .step(SC).clearHttpCache() .step(SC).thinkTime(500, TimeUnit.MILLISECONDS).endStep() .end() .endSequence(); Map<String, StatisticsSnapshot> stats = runScenario(); assertRequests(stats, 5); } @Test public void testSmallThinkTimes() { scenario().initialSequence("loop") .step(SC).loop("counter", 5) .steps() .step(SC).httpRequest(HttpMethod.GET).path("/test").endStep() .step(SC).clearHttpCache() .step(SC).thinkTime(1, TimeUnit.NANOSECONDS).endStep() .end() .endSequence(); Map<String, StatisticsSnapshot> stats = runScenario(); assertRequests(stats, 5); } @Test public void testCycleTimes() { scenario().initialSequence("loop") .step(SC).loop("counter", 5) .steps() // Delaying from now accumulates time skew as it always plans from this timestamp .step(SC).scheduleDelay("foo", 1, TimeUnit.SECONDS).fromNow().endStep() .step(SC).httpRequest(HttpMethod.GET).path("/test").endStep() .step(SC).clearHttpCache() .step(SC).awaitDelay("foo") .end() .step(SC).log("Final value: ${counter}") .endSequence(); Map<String, StatisticsSnapshot> stats = runScenario(); assertRequests(stats, 5); } @Test public void testCycleTimesPrecise() { scenario().initialSequence("loop") .step(SC).loop("counter", 5) .steps() // Delaying from last does not accumulate time skew as it bases the delay on previous iteration .step(SC).scheduleDelay("foo", 1, TimeUnit.SECONDS).fromLast().endStep() .step(SC).httpRequest(HttpMethod.GET).path("/test").endStep() .step(SC).clearHttpCache() .step(SC).awaitDelay("foo") .end() .endSequence(); Map<String, StatisticsSnapshot> stats = runScenario(); assertRequests(stats, 5); } @Test public void testSmallCycleTimesPrecise() { scenario().initialSequence("loop") .step(SC).loop("counter", 5) .steps() // Delaying from last does not accumulate time skew as it bases the delay on previous iteration .step(SC).scheduleDelay("bar", 500, TimeUnit.NANOSECONDS).fromLast().endStep() .step(SC).httpRequest(HttpMethod.GET).path("/test").endStep() .step(SC).clearHttpCache() .step(SC).awaitDelay("bar") .end() .endSequence(); Map<String, StatisticsSnapshot> stats = runScenario(); assertRequests(stats, 5); } private void assertRequests(Map<String, StatisticsSnapshot> stats, int expected) { assertThat(stats.size()).isEqualTo(1); StatisticsSnapshot snapshot = stats.values().iterator().next(); assertThat(snapshot.requestCount).isEqualTo(expected); assertThat(snapshot.responseCount).isEqualTo(expected); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/Benchmark.java
test-suite/src/test/java/io/hyperfoil/test/Benchmark.java
package io.hyperfoil.test; /** * JUnit category marker */ public interface Benchmark { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/YamlParserTest.java
test-suite/src/test/java/io/hyperfoil/test/YamlParserTest.java
/* * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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.hyperfoil.test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.data.Percentage.withPercentage; import static org.junit.jupiter.api.Assertions.assertThrows; import java.util.Arrays; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.Predicate; import org.assertj.core.api.Condition; import org.junit.jupiter.api.Test; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Model; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.SLA; import io.hyperfoil.api.config.Sequence; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.core.session.BaseBenchmarkParserTest; import io.hyperfoil.core.steps.AwaitIntStep; import io.hyperfoil.core.steps.NoopStep; import io.hyperfoil.core.steps.ScheduleDelayStep; import io.hyperfoil.http.api.StatusHandler; import io.hyperfoil.http.config.HttpPluginConfig; import io.hyperfoil.http.handlers.RangeStatusValidator; import io.hyperfoil.http.steps.HttpRequestStepUtil; import io.hyperfoil.http.steps.PrepareHttpRequestStep; import io.hyperfoil.http.steps.SendHttpRequestStep; public class YamlParserTest extends BaseBenchmarkParserTest { @Test public void testSimpleYaml() { Benchmark benchmark = loadScenario("scenarios/simple.hf.yaml"); assertThat(benchmark.name()).isEqualTo("simple benchmark"); Phase[] phases = benchmark.phases().toArray(new Phase[0]); assertThat(phases.length).isEqualTo(3); @SuppressWarnings("unchecked") Class<? extends Step>[] expectedSteps = new Class[] { PrepareHttpRequestStep.class, SendHttpRequestStep.class, StepBuilder.ActionStep.class, PrepareHttpRequestStep.class, SendHttpRequestStep.class, NoopStep.class, AwaitIntStep.class, ScheduleDelayStep.class }; for (Phase p : phases) { Sequence[] sequences = p.scenario().sequences(); assertThat(sequences.length).isEqualTo(1); Step[] steps = sequences[0].steps(); assertThat(steps.length).isEqualTo(expectedSteps.length); for (int i = 0; i < steps.length; ++i) { assertThat(steps[i]).as("step %d: %s", i, steps[i]).isInstanceOf(expectedSteps[i]); } } } @Test public void testComplexYaml() { Benchmark benchmark = loadScenario("scenarios/complex.hf.yaml"); assertThat(benchmark.name()).isEqualTo("complex benchmark"); assertThat(benchmark.agents().length).isEqualTo(3); double sumWeights = 0.2 + 0.8 + 0.1 + 1; assertThat(model(benchmark, "steadyState/invalidRegistration", Model.ConstantRate.class).usersPerSec) .isCloseTo(100.0 / sumWeights * 0.2, withPercentage(1)); assertThat(model(benchmark, "steadyState/validRegistration", Model.ConstantRate.class).usersPerSec) .isCloseTo(100.0 / sumWeights * 0.8, withPercentage(1)); assertThat(model(benchmark, "steadyState/unregister", Model.ConstantRate.class).usersPerSec) .isCloseTo(100.0 / sumWeights * 0.1, withPercentage(1)); assertThat(model(benchmark, "steadyState/viewUser", Model.ConstantRate.class).usersPerSec) .isCloseTo(100.0 / sumWeights, withPercentage(1)); assertThat(benchmark.phases().stream() .filter(p -> p.model instanceof Model.ConstantRate) .mapToDouble(p -> ((Model.ConstantRate) p.model).usersPerSec) .sum()).isCloseTo(100.0, withPercentage(1)); } private <M extends Model> M model(Benchmark benchmark, String name, Class<M> type) { Model model = benchmark.phases().stream() .filter(p -> p.name().equals(name)).map(p -> p.model).findFirst().orElseThrow(AssertionError::new); assertThat(model).isInstanceOf(type); return type.cast(model); } @Test public void testShortcutYaml() { Benchmark benchmark = loadScenario("scenarios/shortcut.hf.yaml"); assertThat(benchmark.name()).isEqualTo("shortcut benchmark"); assertThat(benchmark.phases().size()).isEqualTo(1); Phase phase = benchmark.phases().stream().findFirst().orElseThrow(AssertionError::new); assertThat(phase.name()).isEqualTo("main"); assertThat(phase.duration()).isEqualTo(3000); assertThat(phase.maxDuration()).isEqualTo(5000); assertThat(((Model.ConstantRate) phase.model).usersPerSec).isEqualTo(100); assertThat(((Model.ConstantRate) phase.model).maxSessions).isEqualTo(1234); assertThat(phase.scenario().initialSequences().length).isEqualTo(1); } @Test public void testIterationYaml() { Benchmark benchmark = loadScenario("scenarios/iteration.hf.yaml"); assertThat(benchmark.name()).isEqualTo("iteration benchmark"); } @Test public void testAwaitDelayYaml() { Benchmark benchmark = loadScenario("scenarios/awaitDelay.hf.yaml"); assertThat(benchmark.name()).isEqualTo("await delay benchmark"); } @Test public void testGeneratorsYaml() { loadScenario("scenarios/generators.hf.yaml"); } @Test public void testHttpRequestYaml() { Benchmark benchmark = loadScenario("scenarios/httpRequest.hf.yaml"); Phase testPhase = benchmark.phases().iterator().next(); Sequence testSequence = testPhase.scenario().sequences()[0]; Iterator<Step> iterator = Arrays.asList(testSequence.steps()).iterator(); PrepareHttpRequestStep request1 = next(PrepareHttpRequestStep.class, iterator); StatusHandler[] statusHandlers1 = HttpRequestStepUtil.statusHandlers(request1); assertThat(statusHandlers1).isNotNull().hasSize(1); assertCondition((RangeStatusValidator) statusHandlers1[0], v -> v.min == 200); assertCondition((RangeStatusValidator) statusHandlers1[0], v -> v.max == 299); PrepareHttpRequestStep request2 = next(PrepareHttpRequestStep.class, iterator); StatusHandler[] statusHandlers2 = HttpRequestStepUtil.statusHandlers(request2); assertThat(statusHandlers2).isNotNull().hasSize(2); assertCondition((RangeStatusValidator) statusHandlers2[0], v -> v.min == 201); assertCondition((RangeStatusValidator) statusHandlers2[0], v -> v.max == 259); assertCondition((RangeStatusValidator) statusHandlers2[1], v -> v.min == 200); assertCondition((RangeStatusValidator) statusHandlers2[1], v -> v.max == 210); } @Test public void testAgents1() { Benchmark benchmark = loadScenario("scenarios/agents1.hf.yaml"); assertThat(benchmark.agents().length).isEqualTo(2); } @Test public void testAgents2() { Benchmark benchmark = loadScenario("scenarios/agents2.hf.yaml"); assertThat(benchmark.agents().length).isEqualTo(3); } @Test public void testValidAuthorities() { Benchmark benchmark = loadScenario("scenarios/valid-authorities.hf.yaml"); assertThat(benchmark.plugin(HttpPluginConfig.class).http()).hasSize(4); } @Test public void testWrongAuthorities() { assertThrows(BenchmarkDefinitionException.class, () -> loadScenario("scenarios/wrong-authority.hf.yaml")); } @Test public void testAmbiguousAuthorities() { assertThrows(BenchmarkDefinitionException.class, () -> loadScenario("scenarios/ambiguous-authority.hf.yaml")); } @Test public void testStaircase() { Benchmark benchmark = loadScenario("scenarios/staircase.hf.yaml"); assertThat(benchmark.phases().stream().map(p -> p.model).filter(Model.RampRate.class::isInstance).count()).isEqualTo(3); assertThat(benchmark.phases().stream().map(p -> p.model).filter(Model.ConstantRate.class::isInstance).count()) .isEqualTo(3); for (Phase phase : benchmark.phases()) { if (phase.model instanceof Model.Noop) { continue; } assertThat(phase.scenario.initialSequences().length).isEqualTo(1); } } @Test public void testMutualTls() { Benchmark benchmark = loadScenario("scenarios/mutualTls.hf.yaml"); assertThat(benchmark.plugin(HttpPluginConfig.class).defaultHttp().keyManager().password()).isEqualTo("foobar"); assertThat(benchmark.plugin(HttpPluginConfig.class).defaultHttp().trustManager().storeType()).isEqualTo("FOO"); } @Test public void testHooks() { Benchmark benchmark = loadScenario("scenarios/hooks.hf.yaml"); assertThat(benchmark.preHooks().size()).isEqualTo(2); assertThat(benchmark.postHooks().size()).isEqualTo(1); } @Test public void testSpecialVars() { Benchmark benchmark = loadScenario("scenarios/specialvars.hf.yaml"); assertThat(benchmark.phases().size()).isEqualTo(10 + 1 /* one noop */); } @Test public void testLoop() { loadScenario("scenarios/loop.hf.yaml"); } @Test public void testCustomSla() { Benchmark benchmark = loadScenario("scenarios/customSla.hf.yaml"); assertThat(benchmark.phases().size()).isEqualTo(1); Phase phase = benchmark.phases().iterator().next(); assertThat(phase.customSlas.size()).isEqualTo(2); SLA[] foo = phase.customSlas.get("foo"); SLA[] bar = phase.customSlas.get("bar"); assertThat(foo.length).isEqualTo(1); assertThat(bar.length).isEqualTo(2); } @Test public void testStartWithDelayYaml() { Benchmark benchmark = loadScenario("scenarios/start-with-delay.hf.yaml"); assertThat(benchmark.name()).isEqualTo("benchmark using start with delay"); Phase[] phases = benchmark.phases().toArray(new Phase[0]); assertThat(phases.length).isEqualTo(2); @SuppressWarnings("unchecked") Class<? extends Step>[] expectedSteps = new Class[] { PrepareHttpRequestStep.class, SendHttpRequestStep.class, StepBuilder.ActionStep.class, PrepareHttpRequestStep.class, SendHttpRequestStep.class, NoopStep.class, AwaitIntStep.class, ScheduleDelayStep.class }; for (Phase p : phases) { Sequence[] sequences = p.scenario().sequences(); assertThat(sequences.length).isEqualTo(1); Step[] steps = sequences[0].steps(); assertThat(steps.length).isEqualTo(expectedSteps.length); for (int i = 0; i < steps.length; ++i) { assertThat(steps[i]).as("step %d: %s", i, steps[i]).isInstanceOf(expectedSteps[i]); } } } private <T extends Step> T next(Class<T> stepClass, Iterator<Step> iterator) { while (iterator.hasNext()) { Step step = iterator.next(); if (stepClass.isInstance(step)) { return stepClass.cast(step); } } throw new NoSuchElementException(); } private <T> void assertCondition(T object, Predicate<T> predicate) { assertThat(object).has(new Condition<>(predicate, "")); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/FleetTest.java
test-suite/src/test/java/io/hyperfoil/test/FleetTest.java
package io.hyperfoil.test; import static io.hyperfoil.http.steps.HttpStepCatalog.SC; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Optional; import org.junit.jupiter.api.Test; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.handlers.ArrayRecorder; import io.hyperfoil.core.handlers.ProcessorAssertion; import io.hyperfoil.core.handlers.json.JsonHandler; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.steps.AddToIntAction; import io.hyperfoil.core.steps.AwaitConditionStep; import io.hyperfoil.core.steps.SetAction; import io.hyperfoil.core.steps.SetIntAction; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.http.BaseHttpScenarioTest; import io.hyperfoil.http.api.HttpMethod; import io.hyperfoil.test.entity.CrewMember; import io.hyperfoil.test.entity.Fleet; import io.hyperfoil.test.entity.Ship; import io.vertx.core.http.HttpServerResponse; import io.vertx.core.json.Json; import io.vertx.junit5.VertxTestContext; public class FleetTest extends BaseHttpScenarioTest { private static final Fleet FLEET = new Fleet("Československá námořní flotila") .addBase("Hamburg") .addShip(new Ship("Republika") .dwt(10500) .addCrew(new CrewMember("Captain", "Adam", "Korkorán")) .addCrew(new CrewMember("Cabin boy", "Pepek", "Novák"))) .addShip(new Ship("Julius Fučík").dwt(7100)) .addShip(new Ship("Lidice").dwt(8500)); private static final int MAX_SHIPS = 16; private static final String NUMBER_OF_SHIPS = "numberOfShips"; private static final String NUMBER_OF_SUNK_SHIPS = "numberOfSunkShips"; @Override protected void initRouter() { router.route("/fleet").handler(routingContext -> { HttpServerResponse response = routingContext.response(); response.end(Json.encodePrettily(FLEET)); }); router.route("/ship").handler(routingContext -> { String shipName = routingContext.queryParam("name").stream().findFirst().orElse(""); Optional<Ship> ship = FLEET.getShips().stream().filter(s -> s.getName().equals(shipName)).findFirst(); if (ship.isEmpty()) { routingContext.response().setStatusCode(404).end(); return; } switch (routingContext.request().method().name()) { case "GET": routingContext.response().end(Json.encodePrettily(ship.get())); break; case "DELETE": routingContext.response().setStatusCode(204).setStatusMessage("Ship sunk.").end(); break; } }); } /** * Fetch a fleet (list of ships), then fetch each ship separately and if it has no crew, sink the ship. */ @Test public void testSinkEmptyShips(VertxTestContext ctx) { // We need to call async() to prevent termination when the test method completes var checkpoint = ctx.checkpoint(2); ProcessorAssertion shipAssertion = new ProcessorAssertion(3, true); ProcessorAssertion crewAssertion = new ProcessorAssertion(2, true); // @formatter:off scenario(2) .initialSequence("fleet") .step(SC).action(new SetIntAction.Builder().var(NUMBER_OF_SUNK_SHIPS).value(0)) .step(SC).httpRequest(HttpMethod.GET) .path("/fleet") .sync(false) .handler() .body(new JsonHandler.Builder() .query(".ships[].name") .processors().processor(shipAssertion.processor(new ArrayRecorder.Builder() .toVar("shipNames") .format(DataFormat.STRING) .maxSize(MAX_SHIPS))).end()) .endHandler() .endStep() .step(SC).action(new SetAction.Builder().var("crewCount").intArray().size(MAX_SHIPS).end()) .step(SC).foreach() .fromVar("shipNames") .counterVar(NUMBER_OF_SHIPS) .sequence("ship") .endStep() .endSequence() .sequence("ship") .concurrency(3) .step(SC).httpRequest(HttpMethod.GET) .path(this::currentShipQuery) .sync(false) .handler() .body(new JsonHandler.Builder() .query(".crew[]") .processors().processor(crewAssertion.processor( Processor.adapt(new AddToIntAction.Builder() .var("crewCount[.]") .value(1) .orElseSetTo(1)))).end()) // We need to make sure crewCount is set even if there's no crew .onCompletion(new SetIntAction.Builder().var("crewCount[.]").value(0).onlyIfNotSet(true)) .endHandler() .endStep() .step(SC).breakSequence() .dependency("crewCount[.]") // TODO: since previous step is async we might observe a situation when crewCount[.] // is lower than the size of crew. It doesn't matter here as we're just comparing > 0. // We could use separate variable (array) for body processing completion. .condition().intCondition().fromVar("crewCount[.]").greaterThan().value(0).end().end() .onBreak(new AddToIntAction.Builder().var(NUMBER_OF_SHIPS).value(-1)) .endStep() .step(SC).httpRequest(HttpMethod.DELETE) .path(this::currentShipQuery) .sync(false) .handler() .status(() -> { IntAccess numberOfSunkShips = SessionFactory.intAccess(NUMBER_OF_SUNK_SHIPS); return (request, status) -> { if (status == 204) { numberOfSunkShips.addToInt(request.session, -1); } else { ctx.failNow("Unexpected status " + status); } }; }) .endHandler() .endStep() .step(SC).action(new AddToIntAction.Builder().var(NUMBER_OF_SUNK_SHIPS).value(1)) .step(SC).action(new AddToIntAction.Builder().var(NUMBER_OF_SHIPS).value(-1)) .endSequence() .initialSequence("final") .stepBuilder(new AwaitConditionStep.Builder(NUMBER_OF_SHIPS, (s, numberOfShips) -> numberOfShips.isSet(s) && numberOfShips.getInt(s) <= 0)) .stepBuilder(new AwaitConditionStep.Builder(NUMBER_OF_SUNK_SHIPS, (s, numberOfSunkShips) -> numberOfSunkShips.getInt(s) <= 0)) .step(s -> { log.info("Test completed"); shipAssertion.runAssertions(ctx); crewAssertion.runAssertions(ctx); checkpoint.flag(); return true; }) .endSequence(); // @formatter:on runScenario(); } private SerializableFunction<Session, String> currentShipQuery() { ReadAccess shipName = SessionFactory.readAccess("shipNames[.]"); return s1 -> "/ship?name=" + encode((String) shipName.getObject(s1)); } private static String encode(String string) { return URLEncoder.encode(string, StandardCharsets.UTF_8); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/entity/CrewMember.java
test-suite/src/test/java/io/hyperfoil/test/entity/CrewMember.java
package io.hyperfoil.test.entity; public class CrewMember { private String title; private String firstName; private String lastName; public CrewMember() { } public CrewMember(String title, String firstName, String lastName) { this.title = title; this.firstName = firstName; this.lastName = lastName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false