Java - zacisco/notes GitHub Wiki
- 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
- 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
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());
}
- 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;
}
}
- (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);
- (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);
-
Jasper Reports
- Alternative Links
- Birt
- Yet Another Report Generator/YARG (CUBA/JMIX Platform)
- Spring Boot Rest Project Structure
- Микросервисная архитектура на современном стеке Java-технологий
- Переписываем домашний проект на микросервисы (Java, Spring Boot, Gradle)
- Микросервисы
- Разработка двух микросервисов на Java Spring Boot OTUS
- Микросервисы со Spring Boot & Spring Cloud (Александр Бармин)
- Spring Boot микросервис для получения акций с Tinkoff API
- Пишем Spring Boot микросервис для деплоя в kubernetes с нуля!
- Открытый проект BootJava
- REST API Design Best Practices
- Best Practices for Building Rest Microservices with Spring Boot (REST Api, Exceptions, Models/DTOs, Swagger Design, Status/App monitoring)
- Spring Boot REST + Vue есть много разных нюансов,один из них,как один DTO выгружать через разные View - разные поля скрывать/показывать
- CUSTOM Spring Boot error handling LIB
- Guide to Spring Boot REST API Error Handling
- Strictly REST — API Exception and Error Handling — A Spring @RestControllerAdvice Approach (NEED ACCOUNT) source
- @RestControllerAdvice example in Spring Boot
- Spring Boot @ControllerAdvice & @ExceptionHandler example
- Get Started with Custom Error Handling in Spring Boot
- Custom Error Messages in Spring REST API
- Основы работы с Spring Security
- Создание Spring Security REST API с использованием JWT токена
- Security микросервисов с помощью Spring, OAuth2, JWT и Service Account
- Современная JWT-авторизация для веб-приложений на клиенте и сервере
- Пять простых шагов для понимания JSON Web Tokens (JWT)
- Spring Security – Map Authorities from JWT
- Keycloak + Spring Boot полное копирование статьи на версиях спирга 5.4.5+/бута 2.4.4+ не работает
- OAuth2 Redirect (medium)
- ResourceService (medium)
- OAuth2 (baeldung)
- Spring Boot Keycloak (baeldung)
- w/o Exception Handler (with ErrorController) >
response.sendError
in some filter/handler then you need implementsErrorController
in @Advice handler - with Exception Handler >
response.setStatus
andHandlerExceptionResolver
withresolveException(request, response, null, exception)
- or send response as is through writer or stream
- Spring Cloud OpenFeign и авторизация (OAuth2). Ещё проще (моя статья)
- Spring Cloud OpenFeign и авторизация
- Provide an OAuth2 Token to a Feign Client tutorial's src was very helpfully
- spring-security-openfeign source (custom)
- Spring Cloud: Feign OAuth2 authentication
- Microservices with Spring Boot and Spring Cloud. From config server to OAuth2 server (without inMemory things) — Part 3
Very help:
- source code
-
FeignAutoConfiguration
fromorg.springframework.cloud.openfeign
-
OAuth2AccessTokenInterceptor
fromorg.springframework.cloud.openfeign.security
-
- docs
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);
}
}
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
- client send only
@RequestPart
- server receive only
@RequestPart
then change on server@RequestPart
to@RequestParam
if on server used @PathVariable
with @RequestPart
- all will work as you expect
- @ConfigurationProperties vs. @Value
- Валидация данных при помощи Bean Validation API
- Injecting HTTP Headers in Spring Rest Controller
- Spring @Transactional — ошибки, которые совершали все
Утилита для проверки сертификата - keytool.
Обратите внимание что openssl может показывать поле street, вместо STREET. Также openssl "переворачивает" поля сертификата, отображая их в зеркальном порядке. При проверке штатными средствами Windows также могут быть недостатки: поле ST=Moscow отображается как S=Moscow. Выполните проверку своего DN сертификата несколькими инструментами, кафка требует полного соответствия полей, их порядка и регистра всех букв
- add without explicit indication of trust
- add with explicit indication of trust
#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
#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>
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.
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}'
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}'
- logging (pure Java)
- log4j > log4j2
- Logback (used with SLF4J)
- SLF4J (simple logging facade for java)
- 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
- 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.
%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
- Datasource Proxy
- Queries counting interceptor
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
-
-
- Hibernate pooled and pooled-lo identifier generators
- Hibernate's table generator optimizers
-
spring.jpa.properties.hibernate.id.optimizer.pooled.preferred: pooled-lo
orhibernate.id.optimizer.pooled.preferred: pooled-lo