Java Bookmarks

Published: 2019-08-04, Updated: 2023-06-07

Links

Exemplos

Exemplo de anotação

@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CacheName {
}

Versões do java

Pegar a versão da JRE necessária para rodar uma classe

$ javap -v <path to class file> | grep "major"

Field Descriptors / Symbols

BaseType Character Type Interpretation
B byte signed byte
C char Unicode character code point in the Basic Multilingual Plane, encoded with UTF-16
D double double-precision floating-point value
F float single-precision floating-point value
I int integer
J long long integer
L ClassName ; reference an instance of class ClassName
S short signed short
Z boolean true or false
[ reference one array dimension

Exemplos

[Lex001/Player; // array de classes ex001.Player
Lex001/Ex01Main; // classe ex001.Ex01Main
[J // array de doubles
[I // array de int

Para buscar assinatura de uma classe existente

$ javap -v java.lang.Class | grep -A1 'forName('

  public static java.lang.Class<?> forName(java.lang.String) throws java.lang.ClassNotFoundException;
    descriptor: (Ljava/lang/String;)Ljava/lang/Class;
--
  public static java.lang.Class<?> forName(java.lang.String, boolean, java.lang.ClassLoader) throws java.lang.ClassNotFoundException;
    descriptor: (Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;
--
  public static java.lang.Class<?> forName(java.lang.Module, java.lang.String);
    descriptor: (Ljava/lang/Module;Ljava/lang/String;)Ljava/lang/Class;

Argumentos de gerenciamento de memória

# -Xmx10m
É a heap máxima que pode ser alocada para objetos que não são da young generation

# -Xmn1m
É a heap máxima que pode ser alocada para objetos acabaram ser criados, depois de algum tempo eles sao movidos para a heap do Xmx

Xmx e Xmn tem seus tamanhos somados a Heap.

Sobreposição de classes no classpath

If you load two classes with same package and name which one will be executed?

R: The one what was loaded first, it doesn't matter the class visibility, it works with public, protected, package and private? classes as well


$ ./gradlew build
$ java -cp ./build/classes/java/main/:./lib/ com.mageddo.fruitcase.FruitMain
3

$ java -cp ./lib:./build/classes/java/main/ com.mageddo.fruitcase.FruitMain
2

Mover o mouse sozinho / Pegar a posicao do mouse

https://gist.github.com/mageddo/ba7ac24e5ea6e6fd894aac9113b37f34

Carregar e rodar classes de um jar em uma JVM que já está rodando

Criar jar a partir de arquivos selecionados, programaticamente

final Manifest manifest = new Manifest();
final Attributes attributes = manifest.getMainAttributes();

attributes.put(new Attributes.Name("Agent-Class"), ClassAgent.class.getName());
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");

JarMaker.write(jarOut, new JarPath[0], "ramspider testing", manifest);

Carregar javaagent de forma programatica

Novidades nas versoes do JAVA

Java 10

Local Variable Inference

var msg = "Hello World";

Copiar maps/sets/listas de maneira funcional

Map.copyOf("name", "Elvis", "age", 21);
Set.copyOf("key1", "key2", "key3");
List.copyOf("key1", "key2", "key3");

Java 9

Interfaces agora podem ter metodos privados

interface InterfaceWithPrivateMethods {
     
    private static String staticPrivate() {
        return "static private";
    }
     
    private String instancePrivate() {
        return "instance private";
    }
     
    default void check() {
        String result = staticPrivate();
        InterfaceWithPrivateMethods pvt = new InterfaceWithPrivateMethods() {
            // anonymous class
        };
        result = pvt.instancePrivate();
    }
}}

Pacote oficial para recuperar dados de pacote

ProcessHandle self = ProcessHandle.current();
long PID = self.getPid();
ProcessHandle.Info procInfo = self.info();
  
Optional<String[]> args = procInfo.arguments();
Optional<String> cmd =  procInfo.commandLine();
Optional<Instant> startTime = procInfo.startInstant();
Optional<Duration> cpuUsage = procInfo.totalCpuDuration();

Destruir processos

childProc = ProcessHandle.current().children();
childProc.forEach(procHandle -> {
    assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy());
});

Nao precisa mais declarar a variavel dentro do try-with-resources para fechar sozinho

MyAutoCloseable mac = new MyAutoCloseable();
try (mac) {
    // do some stuff with mac
}
  
try (new MyAutoCloseable() { }.finalWrapper.finalCloseable) {
   // do some stuff with finalCloseable
} catch (Exception ex) { }

Novo pacote para trabalhar com http requests

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .GET()
  .build();
 
HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, HttpResponse.BodyHandler.asString());

Poder criar maps/sets/listas de maneira funcional

Map.of("name", "Elvis", "age", 21);
Set.of("key1", "key2", "key3");
List.of("key1", "key2", "key3");

Shell interativo para poder testar comandos

$ echo 'System.out.println("Hello World");' | jshell
|  Welcome to JShell -- Version 10.0.2
|  For an introduction type: /help intro

jshell> System.out.println("Hello World");
Hello World

Java 8

Lambda

Arrays.asList(1,2).forEach(System.out::println);

Collections Streams

Stream.of(1,2,3).map(Integer::doubleValue).collect(Collectors.toList());

Java Time

LocalDate.of(2018, 1, 25).minusDays(5);

Registrar JMX

@Bean
public FeatureSwitchJMX featureSwitchJmx(MBeanExporter mBeanExporter, FeatureManager featureManager) throws Exception {
	final FeatureSwitchJMX jmx = new FeatureSwitchJMX(featureManager);
	mBeanExporter.(jmx, new ObjectName(String.format(
		"%s:type=%s", jmx.getClass().getPackage().getName(), jmx.getClass().getSimpleName()
	)));
	return jmx;
}

Montar URL com java

UriBuilder.fromUri("http://site.mock").path("home").toTemplate();
// http://site.mock/mock

implementation group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1'

Usar Java socket para alta performance

Instalar certificado

keytool -import -noprompt -trustcacerts -alias <AliasName> -file   <certificate> -keystore <KeystoreFile> -storepass <Password>

exemplo

sudo keytool -import -noprompt -trustcacerts -alias somedomain.intranet -file  ~/Downloads/cert/certificate.cer -keystore /opt/jdk1.8.0_65/jre/lib/security/cacerts -storepass changeit

Listar certificados

keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts" | grep "pagse"

Remover certificados

keytool -delete -alias mydomain -keystore pc.keystore

Especificar opções da VM

Use a opção JAVA_TOOL_OPTIONS que é reconhecida por todas as VMs

export JAVA_TOOL_OPTIONS='-DXmx150m' && java -DXms8m Main
Picked up JAVA_TOOL_OPTIONS: -DXmx150m

As duas opções vão ser setadas

export JAVA_TOOL_OPTIONS='-DXmx150m' && java -DXmx50m Main
Picked up JAVA_TOOL_OPTIONS: -DXmx150m

A linha de comando vai sobrescrever

As seguintes opções também sao suportadas pela JVM mas não há garantia que e JVM vá suporta-las

export JAVA_OPTS="-Dcom.sun.net.ssl.checkRevocation=false"
export JAVA_OPTIONS="-Dcom.sun.net.ssl.checkRevocation=false"
export _JAVA_OPTIONS="-Dcom.sun.net.ssl.checkRevocation=false"

Controlar o volume

https://github.com/mageddo/ilarkesto/blob/master/src/main/java/ilarkesto/media/Audio.java

Escrever e ler na memória ram

http://www.mkyong.com/java/java-write-directly-to-memory/
http://robaustin.wikidot.com/how-to-write-to-direct-memory-locations-in-java

Fazer calculos com hexadecimal, passar hexadecimal para integer

Integer.parseInt("f7c0", 16) - Integer.parseInt("A", 16);

Setar proxy no java,

final String ip = "127.0.0.1";
final String porta = "8001";

System.setProperty("http.useProxy", "true");
System.setProperty("http.proxyHost", ip);
System.setProperty("http.proxyPort", porta);
System.setProperty("https.proxyHost", ip);
System.setProperty("https.proxyPort", porta);
System.setProperty("socksProxyHost", ip);
System.setProperty("socksProxyPort", porta);

Setar proxy na chamada do java

java n -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8008 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=8008

cria servidor HTTP naquela pasta

python -m SimpleHTTPServer

explicando que são POJOs

Basicamente um objeto que ao invés de implementar uma interface é anotado assim facilitando a migração para outros frameworks, para um Listener do JMS para rabbit por exemplo é mais fácil pq ele só é anotado

rodar java dentro da JVM

Object result = groovy.util.Eval.me("StringBuilder str = new StringBuilder();str.append("dasd \n");str.toString();");

Entendendo assinaturas de métodos de class quando recebe nosuchmethodException

Type Signatures - taken from this page.

The JNI uses the Java VM’s representation of type signatures. Table 3-2 shows these type signatures.

Z                               boolean
B                               byte
C                               char
S                               short
I                               int
J                               long
F                               float
D                               double
L fully-qualified-class ;       fully-qualified-class
[ type                          type[]
( arg-types ) ret-type          method type

For example, the Java method:

long f (int n, String s, int[] arr);

has the following type signature:

(ILjava/lang/String;[I)J

Concatenar variáveis dentro do properties

internal.db.source=$(user.dir)/jdbc/hsqldb-internal/hsqldb.jar

rodar um cenário específico com o cucumber no intellij

Tag the feature file with any name, you may add multiple tags separated with spaces.

Eg : @acceptance @regression

Now, add below options in the end of VM otions by editing configuration

-Dcucumber.options="--tags @acceptance"

Run the test and it will only trigger the feature files tagged with @acceptance

You can either set the configuration one for acceptance and one for regression or edit the configuration everytime you run it.

Jackson problema trazendo data 1 dia antes

Mudar o timezone para o do Brasil

@Temporal(TemporalType.DATE)
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy", locale = "pt-BR", timezone = "Brazil/East")

Pegar código de saida do ultimo programa

ls | tee stdout.atm ; echo fechou:${PIPESTATUS[0]} > exit.atm

ou

ls; echo $?

Usando labels no for

ex de label:

x:
  for(int i=0; i < 10; i++)
    for(int j=0; j < 10; j++)
        continue x;

As labels são úteis em loops quando você quer intercalar em DOIS fors, ex:

public static void main(String[] args) {
	x:
	for(int i=0; i < 3; i++){
		System.out.println("hi, i="+ i);
		for(int j=0; j < 3; j++) {
			System.out.println("\thi i=" + i + ", j=" + j);
			continue x;
		}
	}
	System.out.println("bye");
}

isso vai gerar o seguinte

hi, i=0
	hi i=0, j=0
hi, i=1
	hi i=1, j=0
hi, i=2
	hi i=2, j=0
bye

Como voce pode ver isso gera o seguinte resultado: Os dois fors vao loopar 3 vezes cada alternando entre um e outro ao inves do segundo loopar 3 vezes para cada for como seria o resultado normal

Reflection

Mudar valor de constante via reflection / mudar valor de campo static final

public class Main {
 public static void main(String args[]) throws Exception {      
    final var f = Boolean.class.getField("FALSE");
	  FieldHelper.makeNonFinal(f); // https://gist.github.com/mageddo/70ff6953b290265770811da3bd041861
		FieldUtils.writeStaticField(f, true);
		System.out.format("Everything is %s", false); // "Everything is true"
 }
}

Pegar o valor de um campo

FieldUtils.readField(object, fieldName, true);

Escrever valor em campo privado via reflection

FieldUtils.writeField(childInstance, "a_field", "Hello", true);

Loopando em campos/metodos por reflection

Sempre que for usar reflection para avaliar campos/metodos verifique se o mesmo é sintético

final java.lang.reflect.Field[] fields = Object.class.getDeclaredFields();
for (int i=0; i < fields.length; i++) {
  final java.lang.reflect.Field field = fields[i];
  if(!field.isSynthetic()){
....

Se for fazer um if do indice(como por exemplo colocar o ponto e virgula do csv) precisa entao antes remover os campos sinteticos como abaixo

List<java.lang.reflect.Field> fields = new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()));
// retirando campos que sao sinteticos
fields = fields.parallelStream().filter(e -> !e.isSynthetic()).collect(Collectors.toList());

for (int i=0; i < fields.size(); i++) {
    final java.lang.reflect.Field field = fields.get(i);
    final Field annotation = field.getAnnotation(Field.class);
    writer.write(annotation.name());
    if(i+1 != fields.size()) {
        writer.write(';');
    }
}

Pegar os classloaders

Thread.getContextClassLoader();
Class.getClassLoader();
ClassLoader.getSystemClassLoader();

Pegar todas as classes de uma pasta

File it = new File("/tmp/classes")
ClassLoader cl = new URLClassLoader([ it.toURI().toURL() ] as URL[])
if(it.isFile()){
	return
}
println("> loading ${it}")
try {
	def reflections = new Reflections(
		new ConfigurationBuilder()
			.setScanners(new SubTypesScanner(true), new TypeAnnotationsScanner())
			.addClassLoaders(cl)
			.setUrls(it.toURI().toURL())
	)
	println("> objects: ${reflections.getTypesAnnotatedWith(RuntimeReflection.class)}")
} catch(Throwable e){
	println "> failed"
	e.printStackTrace()
}

Capturar eventos globais de teclado (Nao testado)

Verificar se é 32 ou 64 bits

System.getProperty("sun.arch.data.model");

Ignorar campos adicionais no Jackson

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
    ...
}

Rodar aplicacao com limitacao de memoria

/usr/java/jre8/bin/java -Xmx512m -Xms512m -XX:MaxMetaspaceSize=128m -XX:+UseG1GC

Compilar um programa com pacote

$ javac com/mageddo/Main.java
$ java com/mageddo/Main

Você tambem pode entrar dentro da pasta e compilar mas na hora de rodar tem que rodar de fora

$ cd com/mageddo/ && javac Main.java
$ java com/mageddo/Main

Calcular intervalos com java 8

System.out.println("-----------------------------");
final Duration between = Duration.between(calendarStart.toInstant(), calendarEnd.toInstant());
final long rdays = between.toDays();
final long rhours = between.minus(Duration.ofDays(rdays)).toHours();
final long rMinutes = between.minus(Duration.ofDays(rdays)).minus(Duration.ofHours(rhours)).toMinutes();
final long rSeconds = between.minus(Duration.ofDays(rdays)).minus(Duration.ofHours(rhours))
											.minus(Duration.ofMinutes(rMinutes)).getSeconds();
// final long rdays = ChronoUnit.DAYS.between(calendarStart.toInstant(), calendarEnd.toInstant());

previnindo injecao de formulario e chamada dupla

use crsf ou crie um token na mao e sete na session ao carregat o form e valide form no submit ja deletando da session

Pegar locale

public static Locale getBrazilLocale(){
	return new Locale.Builder().setLanguage("pt").setRegion("BR").build();
}

Debugando JVM

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n myapp

ou

export JAVA_OPTIONS='-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=4000,suspend=n' && export JAVA_OPTS=$JAVA_OPTIONS

Java 11+ dentro do docker

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=*:4000,suspend=n myapp

Mudando o tmp dir da JVM

-Djava.io.tmpdir=./

Fazer o sonar ignorar

@SuppressWarnings({"squid:S2078", "squid:S2076"})

Exemplo de javadoc

/**
 * The default value is {@value com.acme.Entity#DEFAULT_ORDER} and action method is {@value com.acme.Entity#doStuff}
 */
void c

Contador de tempo

org.apache.commons.lang3.time.StopWatch watch = new org.apache.commons.lang3.time.StopWatch();
watch.start();

Thread.sleep(300);
final var first = watch.getTime();
watch.split();

Thread.sleep(400);
final var second = watch.getTime() - watch.getSplitTime();
watch.split();

Thread.sleep(100);
final var third = watch.getTime() - watch.getSplitTime();
watch.split();

System.out.printf("first=%d, second=%d, third=%d, total=%d%n", first, second, third, watch.getTime());
// first=304, second=405, third=104, total=813

Apache dados da request

HttpHeaders -> pegar os headers possiveis
ContentType -> Pegar os tipos de dado 
HttpStatus -> pegar os status possiveis

Recuperar MX Beans - pegar parametros da JVM

final HotSpotDiagnosticMXBean platformMXBean = ManagementFactory
            .getPlatformMXBean(HotSpotDiagnosticMXBean.class);
System.out.println(ManagementFactory.getRuntimeMXBean().getInputArguments());
for(VMOption vmOption: platformMXBean.getDiagnosticOptions()){
    System.out.println(vmOption.getName() + ": " + vmOption.getValue());
}

Navegar na diagonal de um array bidimensional

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt(), sumA = 0, sumB = 0;
        int a[][] = new int[n][n];
        for(int a_i=0; a_i < n; a_i++){
            for(int a_j=0; a_j < n; a_j++){
                a[a_i][a_j] = in.nextInt();
            }
        }

        for(int i=0, b = a.length-1; i < a.length; i++, b--){
            sumA +=  a[i][i];
            sumB +=  a[i][b];
        }

        System.out.println(Math.max(sumA, sumB) - Math.min(sumA, sumB));
    }
}

Extender anotação customizando a nova

@Target({ ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Transactional(transactionManager = PersistenceUnitNames.OTIS_TM)
public @interface TransactionalOtis {

    /**
     * The transaction propagation type.
     * <p>Defaults to {@link Propagation#REQUIRED}.
     * @see org.springframework.transaction.interceptor.TransactionAttribute#getPropagationBehavior()
     */
    Propagation propagation() default Propagation.REQUIRED;
}

Entendendo como funciona o generics

Pegar id do processo atual (PID) / process id

Java 8-

System.out.println(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);

Java 9+

ProcessHandle self = ProcessHandle.current();
long PID = self.getPid();

Rodar openjdk

docker run --memory 4mb --memory-swap 0 --rm -v $PWD:/opt -it openjdk:8-jdk bash

Variáveis do Java para setar parametros default

_JAVA_OPTIONS='-DXmx100m'
JAVA_OPTS='-DXmx100m'

Fazer um array com base nas posicoes de outro array

byte [] target = new byte[]{1,2,3,4};
byte[] rangeCopy = Arrays.copyOfRange(target, 1, 2);
System.out.println(Arrays.toString(rangeCopy)); // 2

Substituir algumas posicoes do array X com o array Y

byte [] source = new byte[]{1,2};
byte [] target = new byte[]{0,0,0,0,0};

System.arraycopy(source, 0, target, 3, 2);
System.out.println(Arrays.toString(target)); // [0, 0, 0, 1, 2]

Rodar projeto em java 9

Ver se uma classe implementa outra

Interface.class.isAssignableFrom(Class.class)

Fazer join de List e Array de strings

System.out.println(String.join("|", Stream.of(1,2,3).map(String::valueOf).collect(Collectors.toList())));
System.out.println(Stream.of(1,2,3).map(String::valueOf).collect(Collectors.joining(",")));

Comparacao das JDKs

(sempre buildando para a menor versao e para a versao especifica para ver se tem diferenca, geralmente nao tem grandes diferencas)

Programa simples para alocar strings

import java.util.*;

public class Main{

	public static void main(String args[]) throws Exception {
		System.out.println("is alive!!");
		StringBuilder sb = new StringBuilder();
		for(int i=0; true; i++){
			sb.append(String.valueOf(System.nanoTime()));
			sb.append('\n');

			if (i % 500000 == 0){
				System.out.println("clearing..." + new Date().toString());
				sb = new StringBuilder();
			}
		}
		// System.out.println("I'm dying...");
	}

}
JDK Xmx (minimo) RAM
5 100m 108m
8 50m 75m
9 15m 46m

Spring 5 webflux + JPA (Apenas subida)

JDK Xmx (minimo) RAM
8 50m 187m
9 50m 222m

Mudar locale da JVM

java -Duser.country=CA -Duser.language=fr ... com.x.Main
java -Duser.country=BR -Duser.language=pt ... com.x.Main

Liga/Desliga com apache commons

commons-configuration-1.2-sources.jar!/org/apache/commons/configuration/AbstractConfiguration.java:832

Deletar os caracteres sobrando da esquerda e preenche com zeros na esquerda caso nao tenha o tamanho especificado

StringUtils.leftPad(StringUtils.right(account, 8), 8, '0');

Remover acentos de palavras

final String word = "São João na roça";
final String normalizedWord = Normalizer.normalize(word, Normalizer.Form.NFKD);

System.out.printf("%s - %s - %s %n", word, normalizedWord, normalizedWord.replaceAll("\\p{M}", "").replaceAll("[^\\p{ASCII}]", ""));
System.out.printf("%s %n", StringUtils.stripAccents(word));

Collections

Usando ArrayDeque e LinkedList

final ArrayDeque<Integer> stack = new ArrayDeque<>();
stack.add(1);
stack.add(2);
stack.add(3);
stack.add(4);
stack.add(5);
System.out.println("after add: " + stack);
stack.pop();
System.out.println("after pop: " + stack);
stack.removeLast();
System.out.println("after removeLast: " + stack);

// a diferenca do pop pro poll eh que o pop estoura excecao caso nao tenha elemento para retonar 
after add: [1, 2, 3, 4, 5]
after pop: [2, 3, 4, 5]
after poll: [2, 3, 4]

Criar collection a partir de valores

Set<String> set = Stream.of("a", "b").collect(Collectors.toSet());
Set<String> set = Stream.of("a", "b").collect(Collectors.toCollection(HashSet::new));

Sort

Compara lista de listas

class ListComparator<T extends Comparable<T>> implements Comparator<List<T>> {

  @Override
  public int compare(List<T> o1, List<T> o2) {
    for (int i = 0; i < Math.min(o1.size(), o2.size()); i++) {
      int c = o1.get(i).compareTo(o2.get(i));
      if (c != 0) {
        return c;
      }
    }
    return Integer.compare(o1.size(), o2.size());
  }
}

using

List<List<Integer>> listOfLists = ...;
Collections.sort(listOfLists, new ListComparator<>());

Composite sort

Collections.sort(persons, new Comparator() {
	public int compare(Object o1, Object o2) {
	
		String x1 = ((Person) o1).getName();
		String x2 = ((Person) o2).getName();
		int sComp = x1.compareTo(x2);

		if (sComp != 0) {
			return sComp;
		}

		Integer x1 = ((Person) o1).getAge();
		Integer x2 = ((Person) o2).getAge();
		return x1.compareTo(x2);
	}
});

Limitando memoria de programa java com ulimit

ulimit
-S para voce poder mudar o limite de memoria varias vezes no mesmo bash senao vai ter que fechar e abrir outro se quiser mudar o -v
-v limite de memoria do processo em KB

Porém por algum motivo na JDK esse limite fica como se fosse em bytes, sendo assim voce precisa setar 2_000_000 para criar uma JVM de 200M de heap

ulimit -Sv 2000000 && java -Xmx200m -XX:MaxMetaspaceSize=30m Main
free memory: 192,009
allocated memory: 196,608
max memory: 196,608
total free memory: 192,009
-------------------------------------

100
free memory: 89,609
allocated memory: 196,608
max memory: 196,608
total free memory: 89,609
-------------------------------------

50 
free memory: 41,959
allocated memory: 196,608
max memory: 196,608
total free memory: 41,959
-------------------------------------

50
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at Main.main(Main.java:15)

Main.java


import java.text.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class Main {

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

		final List<byte[]> data = new LinkedList<>();
		final Scanner in = new Scanner(System.in);
		printMemory();
		while (true){
      System.out.println("How much memory to allocate in MB?");
			data.add(new byte[Integer.parseInt(in.nextLine()) * 1024 * 1024]);
			printMemory();
		}
	}

	public static void printMemory(){
		Runtime runtime = Runtime.getRuntime();
		NumberFormat format = NumberFormat.getInstance();

		long maxMemory = runtime.maxMemory();
		long allocatedMemory = runtime.totalMemory();
		long freeMemory = runtime.freeMemory();

		System.out.println("free memory: " + format.format(freeMemory / 1024));
		System.out.println("allocated memory: " + format.format(allocatedMemory / 1024));
		System.out.println("max memory: " + format.format(maxMemory / 1024));
		System.out.println("total free memory: " + format.format((freeMemory + (maxMemory - allocatedMemory)) / 1024));
		System.out.println("-------------------------------------\n");
	}
}

Servidor TCP

final ServerSocket server = new ServerSocket(3333);
while (!server.isClosed()){
	final Socket socket = server.accept();
	final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	System.out.println(br.readLine());
	socket.getOutputStream().write("Bye ;)\n ".getBytes());
	socket.getOutputStream().flush();
	socket.close();
}

Servidor UDP

final DatagramSocket server = new DatagramSocket(3333);
final byte[] buff = new byte[1024];
while (!server.isClosed()){
	final DatagramPacket packet = new DatagramPacket(buff, 0, buff.length);
	server.receive(packet);
	System.out.println(new String(packet.getData(), 0, packet.getLength()));
}

Testando

echo `date` > /dev/udp/127.0.0.1/333
nc -u 127.0.0.1 3333 < /dev/random

Pegar versao da JDK que compilou a JDK

Arquivos / Streams

Pegar dados do arquivo, owner, goup

public static PosixFileAttributes getPathAttributes(Path path){
    try {
        return Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

Acessar offsets do arquivo de forma randomica

// ab
// cd
// ef
final RandomAccessFile raf = new RandomAccessFile(new File("/tmp/x1.txt"), "r");
raf.seek(3);
System.out.println(raf.readLine());
raf.close();
// cd

Codec Commands

Bytes para HEX

Hex.encodeHexString(new byte[]{1,2,3})

Calcular hash de arquivo

DigestUtils.sha256Hex(new FileInputStream("/tmp/xyz.tmp"));

Imprimir array de bytes como hexadecimal

public static String bytesToHex(byte[] in) {
	final StringBuilder builder = new StringBuilder();
	for(byte b : in) {
	    builder.append(String.format("%02x", b));
	}
	return builder.toString();
}

BigInteger para hexadecimal

new BigInteger(99).toString(16);

Mandar email com java usando gmail

compile group: 'javax.mail', name: 'javax.mail-api', version: '1.6.1'
compile 'com.sun.mail:javax.mail:1.6.1'
package com.mageddo.core.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class SendMailSSL {
	public static void main(String[] args) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.socketFactory.port", "465");
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");

		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication("email","password");
				}
			});

		try {

			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress("from@no-spam.com"));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse("edigitalb@gmail.com"));
			message.setSubject("Testing Subject");
			message.setText("Dear Mail Crawler," +
					"\n\n No spam to my email, please!");

			Transport.send(message);

			System.out.println("Done");

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
}

Running commands inside JVM

public class ProcessUtils {

  public static ProcessBuilder run(String command){
    final StringTokenizer st = new StringTokenizer(command);
    final String[] cmdarray = new String[st.countTokens()];
    for (int i = 0; st.hasMoreTokens(); i++)
      cmdarray[i] = st.nextToken();
    return new ProcessBuilder(cmdarray).redirectErrorStream(true);
  }

  public static String run(final int waitSeconds, final String command) throws InterruptedException, IOException {
    final Process process = ProcessUtils.run(command).start();
    try {
      process.waitFor(waitSeconds, TimeUnit.SECONDS);
      return IOUtils.toString(process.getInputStream());
    } catch (InterruptedException e){
      process.destroy();
      throw e;
    }
  }
}

Mudar campo static final

final var systemClockField = Clock.class.getDeclaredField("SYSTEM_CLOCK");
FieldUtils.removeFinalModifier(systemClockField);
FieldUtils.writeStaticField(systemClockField, clock, true);

Random

Gerar random em um range

final double min = 0.10; // exclusivo
final double max = 1.0; // exclusivo
final double r = Math.random() * ((max - min)) + min;

Programa para executar comandos via SSH e transferir arquivos via sftp

Comparação de imagens docker de jdk opensource

$ docker image ls | grep openjdk
adoptopenjdk                                      12-jre-hotspot      c0fc911f0fb5        7 days ago          237MB
adoptopenjdk                                      12-hotspot          8f9c81987f14        7 days ago          443MB
openjdk                                           12                  ad1c6207e3ad        2 weeks ago         470MB
openjdk                                           12-jdk              ad1c6207e3ad        2 weeks ago         470MB
openjdk                                           12-alpine           0c68e7c5b7a0        5 months ago        339MB

Libs

Markdown Parser

Pegar ícone de um .exe e salvar no arquivo / icone

[1], [2]

final var icon = FileSystemView.getFileSystemView()
    .getSystemIcon(Paths.get("some.exe").toFile());
final var image = new BufferedImage(
    icon.getIconWidth(),
    icon.getIconHeight(),
    BufferedImage.TYPE_INT_ARGB
);
final var graphics2D = image.createGraphics();
icon.paintIcon(null, graphics2D, 0, 0);
graphics2D.dispose();

try (var out = Files.newOutputStream(Paths.get("some.png"), TRUNCATE_EXISTING, CREATE_NEW)) {
  ImageIO.write(image, "png", out);
}

Verificar se porta está em uso

boolean isPortInUse(int port) {
  try {
    new Socket("127.0.0.1", port).close();
    return true;
  } catch(SocketException e) {
    return false;
  }
}

Diretórios

Criar diretório com permissão 777

var path = Paths.get("/tmp/xpto");
Files.createDirectories(path);
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxrwxrwx"));

Adicionar itens na Map de forma idempotente

final ExecutorService pool = Executors.newFixedThreadPool(100);
final Map<String, Integer> points = new ConcurrentHashMap<>();

for (int i = 0; i < 200; i++) {
 pool.submit(() -> {
  points.compute("Elvis", (k, v) -> {
   if(v == null){
    // primeira vez vem aqui
    return 1;
   }
   // outras vezes vem aqui
   return v + 1;
  });
 });
}

pool.awaitTermination(3, TimeUnit.SECONDS);
pool.shutdown();
System.out.println(points);

Permissoes de arquivos

https://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html

  public static void main(String[] args) throws IOException {
    final var p = Paths.get("/var/run/docker.sock");
    final var permisions = Files.getPosixFilePermissions(p);
    System.out.println(permisions);

    final var attr = Files.readAttributes(p, PosixFileAttributes.class);
    System.out.println(attr.permissions());
  }

Toggle

Toggle Percentual

// calcula se retorna true ou false com base na chance percentual
public Boolean drawLottery() {
  final BigDecimal randomNumber = BigDecimal.valueOf(Math.random() * 100).setScale(2, RoundingMode.DOWN);
  final BigDecimal percentRate = BigDecimal.valueOf(10);
  return randomNumber.compareTo(percentRate) == -1;
}

Embedded Databases

Emdedded Postgres

Constantes para HTTP

JDBC

Generics

Pegar o generics de um campo:

No exemplo, como pegar Bar2?

class Foo {
  Bar<Bar2> field;
}

Classe utilitária

Pegar o tipo passado no generics de uma classe

ex:

public abstract class Transformer<T> implements SingleValueConverter {

solução

ParameterizedType ptype = (ParameterizedType) getClass().getGenericSuperclass();
Type type = ptype.getActualTypeArguments()[0];

Converter string delimitada para lista de integers

Integer[] numbers = Arrays.stream("1, 2 , 3".split("\\s*, \\s*"))
	.map(Integer::parseInt).toArray(Integer[]::new);
System.out.println(Arrays.toString(numbers));

Lidar com sinais do linux/so na mão

Checar o sistema operacional / SO

org.apache.commons.lang3.SystemUtils#IS_OS_WINDOWS

com.sun.jna.Platform#isWindows()

org.apache.commons.exec.OS#isFamilyWindows()

Garbage Collector

Para checar o garbage collector que está sendo usado

$ java -XX:+PrintCommandLineFlags -version

Forçar fechamento de socket

dep: httpclient org.apache.http.impl.BHttpConnectionBase#shutdown

 final Socket socket = this.socketHolder.getAndSet(null);
        if (socket != null) {
            // force abortive close (RST)
            try {
                socket.setSoLinger(true, 0);
            } catch (final IOException ex) {
            } finally {
                socket.close();
            }
        }

Escolhendo um garbage collector

If (a) peak application performance is the first priority and (b) there are no pause-time requirements or pauses of one second or longer are acceptable, then let the VM select the collector or select the parallel collector with -XX:+UseParallelGC.

If response time is more important than overall throughput and garbage collection pauses must be kept shorter than approximately one second, then select a mostly concurrent collector with -XX:+UseG1GC or -XX:+UseConcMarkSweepGC.

java examples, java commands, java bookmarks


Instalar nodejs em versões antigas ubuntu

Comments