@Qualifier
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface CacheName {
}
Pegar a versão da JRE necessária para rodar uma classe
$ javap -v <path to class file> | grep "major"
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;
# -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.
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
https://gist.github.com/mageddo/ba7ac24e5ea6e6fd894aac9113b37f34
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);
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");
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
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);
@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;
}
UriBuilder.fromUri("http://site.mock").path("home").toTemplate();
// http://site.mock/mock
implementation group: 'javax.ws.rs', name: 'jsr311-api', version: '1.1.1'
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
keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts" | grep "pagse"
keytool -delete -alias mydomain -keystore pc.keystore
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"
https://github.com/mageddo/ilarkesto/blob/master/src/main/java/ilarkesto/media/Audio.java
http://www.mkyong.com/java/java-write-directly-to-memory/
http://robaustin.wikidot.com/how-to-write-to-direct-memory-locations-in-java
Integer.parseInt("f7c0", 16) - Integer.parseInt("A", 16);
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);
java n -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=8008 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=8008
python -m SimpleHTTPServer
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
Object result = groovy.util.Eval.me("StringBuilder str = new StringBuilder();str.append("dasd \n");str.toString();");
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
internal.db.source=$(user.dir)/jdbc/hsqldb-internal/hsqldb.jar
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.
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")
ls | tee stdout.atm ; echo fechou:${PIPESTATUS[0]} > exit.atm
ou
ls; echo $?
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
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"
}
}
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(';');
}
}
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()
}
System.getProperty("sun.arch.data.model");
@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
...
}
/usr/java/jre8/bin/java -Xmx512m -Xms512m -XX:MaxMetaspaceSize=128m -XX:+UseG1GC
$ 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
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());
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
public static Locale getBrazilLocale(){
return new Locale.Builder().setLanguage("pt").setRegion("BR").build();
}
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
-Djava.io.tmpdir=./
@SuppressWarnings({"squid:S2078", "squid:S2076"})
/**
* The default value is {@value com.acme.Entity#DEFAULT_ORDER} and action method is {@value com.acme.Entity#doStuff}
*/
void c
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
HttpHeaders -> pegar os headers possiveis
ContentType -> Pegar os tipos de dado
HttpStatus -> pegar os status possiveis
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());
}
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));
}
}
@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;
}
->
Qualquer coisa que estenda de T
->
Qualquer coisa que seja pai de T
Java 8-
System.out.println(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]);
Java 9+
ProcessHandle self = ProcessHandle.current();
long PID = self.getPid();
docker run --memory 4mb --memory-swap 0 --rm -v $PWD:/opt -it openjdk:8-jdk bash
_JAVA_OPTIONS='-DXmx100m'
JAVA_OPTS='-DXmx100m'
byte [] target = new byte[]{1,2,3,4};
byte[] rangeCopy = Arrays.copyOfRange(target, 1, 2);
System.out.println(Arrays.toString(rangeCopy)); // 2
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]
Interface.class.isAssignableFrom(Class.class)
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(",")));
(sempre buildando para a menor versao e para a versao especifica para ver se tem diferenca, geralmente nao tem grandes diferencas)
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 |
JDK | Xmx (minimo) | RAM |
---|---|---|
8 | 50m | 187m |
9 | 50m | 222m |
java -Duser.country=CA -Duser.language=fr ... com.x.Main
java -Duser.country=BR -Duser.language=pt ... com.x.Main
commons-configuration-1.2-sources.jar!/org/apache/commons/configuration/AbstractConfiguration.java:832
StringUtils.leftPad(StringUtils.right(account, 8), 8, '0');
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));
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));
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);
}
});
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");
}
}
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();
}
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
https://en.wikipedia.org/wiki/Java_class_file#General_layout
javap -verbose Main.class | grep "major"
Java 1.2 uses major version 46
Java 1.3 uses major version 47
Java 1.4 uses major version 48
Java 5 uses major version 49
Java 6 uses major version 50
Java 7 uses major version 51
Java 8 uses major version 52
Java 9 uses major version 53
Java 10 uses major version 54
Java 11 uses major version 55
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
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();
}
new BigInteger(99).toString(16);
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);
}
}
}
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;
}
}
}
final var systemClockField = Clock.class.getDeclaredField("SYSTEM_CLOCK");
FieldUtils.removeFinalModifier(systemClockField);
FieldUtils.writeStaticField(systemClockField, clock, true);
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;
$ 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
Markdown Parser
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);
}
boolean isPortInUse(int port) {
try {
new Socket("127.0.0.1", port).close();
return true;
} catch(SocketException e) {
return false;
}
}
Criar diretório com permissão 777
var path = Paths.get("/tmp/xpto");
Files.createDirectories(path);
Files.setPosixFilePermissions(path, PosixFilePermissions.fromString("rwxrwxrwx"));
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);
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());
}
// 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;
}
No exemplo, como pegar Bar2?
class Foo {
Bar<Bar2> field;
}
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));
org.apache.commons.lang3.SystemUtils#IS_OS_WINDOWS
com.sun.jna.Platform#isWindows()
org.apache.commons.exec.OS#isFamilyWindows()
$ java -XX:+PrintCommandLineFlags -version
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();
}
}
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