Java - zacisco/notes GitHub Wiki

Info

Free and Open Source

  • AdoptOpenJDK
  • Amazon Corretto
  • Azul Zulu
  • Bck2Brwsr
  • CACAO
  • Codename One
  • DoppioJVM
  • Eclipse OpenJ9
  • GraalVM CE
  • HaikuVM
  • HotSpot
  • Jamiga
  • JamVM
  • Jelatine JVM
  • Jikes RVM (Jikes Research Virtual Machine)
  • JVM.go
  • Liberica JDK
  • leJOS
  • Maxine
  • Multi-OS Engine
  • RopeVM
  • uJVM

Proprietary Implementations

  • Azul Zing JVM
  • CEE-J
  • Excelsior JET
  • GraalVM EE
  • Imsys AB
  • JamaicaVM (aicas)
  • JBlend (Aplix)
  • MicroJvm (IS2T – Industrial Smart Software Technology)
  • OJVM
  • PTC Perc
  • SAP JVM
  • Waratek CloudVM for Java

Distr


SOME USEFULL CODE IN JAVA

What XML Parser is using?

do you have exception: AbstractMethodError: javax.xml.parsers.DocumentBuilderFactory.setFeature(L/java.lang.String;Z)V

SOLVE:

private static void OutputJaxpImplementationInfo() {
   System.out.println(getJaxpImplementationInfo("DocumentBuilderFactory", DocumentBuilderFactory.newInstance().getClass()));
   System.out.println(getJaxpImplementationInfo("XPathFactory", XPathFactory.newInstance().getClass()));
   System.out.println(getJaxpImplementationInfo("TransformerFactory", TransformerFactory.newInstance().getClass()));
   System.out.println(getJaxpImplementationInfo("SAXParserFactory", SAXParserFactory.newInstance().getClass()));
   System.out.println(getJaxpImplementationInfo("SchemaFactory", SchemaFactory.newInstance().getClass())); // TODO: don't correct for Java 8+
}

private static String getJaxpImplementationInfo(String componentName, Class componentClass) {
   CodeSource source = componentClass.getProtectionDomain().getCodeSource();
   return MessageFormat.format(
      "{0} implementation: {1} loaded from: {2}",
      componentName,
      componentClass.getName(),
      source == null ? "Java Runtime" : source.getLocation());
}

iText + custom fonts

  1. Font static class:
public static final String SOME_FONT = pathToFont("SomeFont");

private static String pathToFont(String fontName) {
  try {
    return FontUtils.class.getClassLoader().getResource("").toURI().toString() + _path to font with fontName_ + ".ttf";
  } catch (URISyntaxException e) {
    e.printStackTrace();
    return null;
  }
}
  1. (a) if using flying saucer:
ITextRenderer renderer = new ITextRenderer();
if (FontsUtils.SEGOE_UI_FONT_PATH != null)
  renderer.getFontResolver().addFont(FontsUtils.SOME_FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  1. (b) if pure:
CSSResolver cssResolver = new StyleAttrCSSResolver();

// FOR FONT(s)
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontProvider.register(FontUtils.SOME_FONT);
CssAppliersImpl cssAppliers = new CssAppliersImpl(fontProvider);

// HTML
HtmlPipelineContext htmlContext = new HtmlPipelineContext(cssAppliers);
htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

// Pipelines
ElementList elements = new ElementList();
ElementHandlerPipeline pdf = new ElementHandlerPipeline(elements, null);
HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

// XML Worker
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);

Report Libraries/Frameworks

ETL/OLAP/Reports

Compare


Spring / Spring Boot

Microservice Architecture

Best Practices

Spring Boot REST

  • Spring Boot REST + Vue есть много разных нюансов,один из них,как один DTO выгружать через разные View - разные поля скрывать/показывать

Spring Boot Exceptions

Spring Security

Spring Boot + Keycloak

Security + Exceptions

  1. w/o Exception Handler (with ErrorController) > response.sendError in some filter/handler then you need implements ErrorController in @Advice handler
  2. with Exception Handler > response.setStatus and HandlerExceptionResolver with resolveException(request, response, null, exception)
  3. or send response as is through writer or stream

source

Spring Cloud

Security + OAuth2 Client + OpenFeign

Very help:

Config for optional OAuth2 token header in some feign clients
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.cloud.openfeign.security.OAuth2AccessTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;

/**
 *  Config for optional OAuth2 token header in some feign clients.<br/>
 *  Get <b><u>first</u></b> registration from properties by default for configuration.
 */
@RequiredArgsConstructor
public class OAuthFeignConfig {
    private final OAuth2ClientProperties oAuth2ClientProperties;

    @Bean
    @ConditionalOnBean({OAuth2AuthorizedClientService.class, ClientRegistrationRepository.class})
    @ConditionalOnMissingBean
    public OAuth2AuthorizedClientManager feignOAuth2AuthorizedClientManager(ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientService oAuth2AuthorizedClientService) {
        return new AuthorizedClientServiceOAuth2AuthorizedClientManager(clientRegistrationRepository, oAuth2AuthorizedClientService);
    }

    @Bean
    @ConditionalOnBean(OAuth2AuthorizedClientManager.class)
    public OAuth2AccessTokenInterceptor defaultOAuth2AccessTokenInterceptor(OAuth2AuthorizedClientManager oAuth2AuthorizedClientManager) {
        return new OAuth2AccessTokenInterceptor(oAuth2ClientProperties.getRegistration().keySet().iterator().next(), oAuth2AuthorizedClientManager);
    }
}

Troubleshooting

don't see tables in not default schema

if you are using @Query annotation in repository and using hikari, add

spring.datasource.hikari.schema: other_services

additional to

spring.jpa.properties.hibernate.default_schema: other_services

[451 Unsupported Media Type] with multipart/form-data (FeignClient optional?)

  1. client send only @RequestPart
  2. server receive only @RequestPart then change on server @RequestPart to @RequestParam

if on server used @PathVariable with @RequestPart - all will work as you expect

Helpful info


Certificates

Утилита для проверки сертификата - keytool.

Обратите внимание что openssl может показывать поле street, вместо STREET. Также openssl "переворачивает" поля сертификата, отображая их в зеркальном порядке. При проверке штатными средствами Windows также могут быть недостатки: поле ST=Moscow отображается как S=Moscow. Выполните проверку своего DN сертификата несколькими инструментами, кафка требует полного соответствия полей, их порядка и регистра всех букв

Certificates in JAVA

Way to add certificates

  • add without explicit indication of trust
  • add with explicit indication of trust

1st way example

#It will check the chain and if it doesn't like it, java will throw an error

keytool -import -alias CHOOSE-AN-ALIAS -file certificate.pem -keystore /path/to/your/truststore

2nd way example

#In the second case, you say to explicitly trust this certificate, even if there is something wrong with the chain

keytool -trustcacerts -keystore /path/to/your/truststore -storepass changeit -importcert -alias <your_alias> -file <path_to_file>

Where’s the Java truststore?

OPERATING SYSTEM DEFAULT TRUSTSTORE LOCATION
General $JAVA_HOME/lib/security/cacerts
Linux (RHEL and related distros, including the OpenJDK docker image) /etc/pki/java/cacerts †
Linux (Ubuntu) /etc/ssl/certs/java/cacerts ‡
Mac (with JRE installed only) $(/usr/libexec/java_home)/lib/security/cacerts
Mac (with JDK installed) $(/usr/libexec/java_home)/jre/lib/security/cacerts
Windows C:\Program Files (x86)\Java\jre\lib\security\cacerts

† On RHEL, update your truststore using the update-ca-trust command.

‡ On Ubuntu, update your truststore using the update-ca-certificates command.

How to grab all certificates from site

From terminal

REMOTE_HOST=untrusted-root.badssl.com

echo | openssl s_client -showcerts -partial_chain \
    -servername ${REMOTE_HOST} -connect ${REMOTE_HOST}:443 \
    | awk '/BEGIN/,/END/{ if(/BEGIN/){a++}; out="cert"a".pem"; print >out}'

If you want use it from script

REMOTE_HOST=$1

echo \
    | openssl s_client -showcerts -partial_chain \
    -servername ${REMOTE_HOST} -connect ${REMOTE_HOST}:443 \
    | awk '/BEGIN/,/END/{ if(/BEGIN/){a++}; out="'"${remote_host}"'"a".pem"; print >out}'

JMIX

Links:

Samples

Logging

Loggers

  • logging (pure Java)
  • log4j > log4j2
  • Logback (used with SLF4J)
  • SLF4J (simple logging facade for java)

<img src="https://user-images.githubusercontent.com/2534400/208764178-421678ee-0ab0-46fa-b7dd-5f50b3e4e5c9.png" width="500px">

With libs:

  • SLF4J → Logback
  • SLF4J → slf4j-log4j12 → Log4j
  • SLF4J → log4j-slf4j-impl → Log4j 2
  • SLF4J → slf4j-jdk14 → JUL
  • SLF4J → slf4j-jcl → JCL
  • JCL → JUL
  • JCL → Log4j
  • log4j2-api → log4j2-cor
  • log4j2-api → log4j-to-slf4j → SLF4J

<img src="https://github.com/zacisco/notes/assets/2534400/2d201fd8-1ecc-470b-9e3c-b16daa13de33.png" width="500px">

Levels

<img src="https://user-images.githubusercontent.com/2534400/208762216-826d41d4-a96d-488f-a15d-2e175a9082a9.png" width="500px">

  • ALL – The ALL has the lowest possible rank and is intended to turn on all logging. => All logging.
  • TRACE – The TRACE Level designates finer-grained informational events than the DEBUG => Fine.
  • DEBUG – The DEBUG Level designates fine-grained informational events that are most useful to debug an application. => Debugging.
  • INFO – The INFO level designates informational messages that highlight the progress of the application at coarse-grained level. => Highlight information.
  • WARN – The WARN level designates potentially harmful situations. => Warning.
  • ERROR – The ERROR level designates error events that might still allow the application to continue running. => Error.
  • FATAL – The FATAL level designates very severe error events that will presumably lead the application to abort. => Critical error.
  • OFF – The OFF has the highest possible rank and is intended to turn off logging. => Disable logging.

Setting the output pattern

%m: Outputs log contents
%p: Outputs priority such as debug, info, warn, error, fatal, etc.
%r: Outputs elapsed time in milliseconds from application start to event occurrence
%c: Outputs package
%c{ n}: Reversely output as many packages as n (number) from the bottom.
Example) When %c{2}, abc is output as bc.
%n: Output newline character. Output \r\n or \n depending on platform.
%d: Event occurrence date output (It slows down the execution speed of the program.)
Ex) %d{HH:mm:ss} or %d{dd MMMM yyyy HH:mm:ss}
%C: Caller's class name output
example ) When %C{2}, abcTestClass is output as c.TestClass.
%M: method name.
%F: Program file name.
%l: information of caller
%L: number of lines of caller
%x: Nested diagnostic context (NDC)
associated with the thread %X: Mapped diagnostic context (MDC) associated with the thread
%%: Display
%t: Thread name

Hibernate

Useful links

Properties

Performance

For debug performance

jpa.show-sql: true
hibernate:
  generate_statistics: true # enable statistics
  format_sql: true
  use_sql_comments: true

# more info
logging.level:
  org.hibernate: INFO
  org.hibernate.SQL: DEBUG
  org.hibernate.type: TRACE
  org.hibernate.hql.ast.AST: INFO
  org.hibernate.tool.hbm2ddl: WARN
  org.hibernate.hql: DEBUG
  org.hibernate.cache: INFO
  org.hibernate.jdbc: DEBUG
  org.hibernate.stat: DEBUG
  • hibernate.jdbc.fetch_size - how much batch rows need read from DB. Only for Oracle, you might want to set it since the default fetchSize is just 10.

  • hibernate.jdbc.batch_size - how much operation in batch multiple INSERT, UPDATE, and DELETE statements can be set in a single database call.

    • hibernate.order_inserts -
    • hibernate.order_updates -

Sequence Optimization


Helpful links

⚠️ **GitHub.com Fallback** ⚠️