Java.Spring.Logging

from docs

Since Spring Framework 5.0, Spring comes with its own Commons Logging bridge implemented in the spring-jcl module. The implementation checks for the presence of the Log4j 2.x API and the SLF4J 1.7 API in the classpath and uses the first one of those found as the logging implementation, falling back to the Java platform’s core logging facilities (also known as JUL or java.util.logging) if neither Log4j 2.x nor SLF4J is available.

Put Log4j 2.x or Logback (or another SLF4J provider) in your classpath, without any extra bridges, and let the framework auto-adapt to your choice. For further information see the Spring Boot Logging Reference Documentation.

public class MyBean {
	private final Log log = LogFactory.getLog(getClass());
    // ...
}

Posted in Без рубрики | Comments Off on Java.Spring.Logging

Java.Spring.ExternalBeanRegistration

// app

@SpringBootApplication
public class App {

	public static void main(String[] args) {

		ConfigurableApplicationContext configurableContext = SpringApplication.run(App.class, args);
		AppContext.getInstance().setContext(configurableContext);

		var beanFactory = configurableContext.getBeanFactory();
		beanFactory.registerSingleton("someSingletone", new SomeSingletonBean());

		var test  = new Test();
		test.execute();

	}

}

class Test{
	public void execute(){
		var someSingleTone = (SomeSingletonBean) AppContext.getInstance().getContext().getBean("someSingletone");
		someSingleTone.sayHello();
	}

}

// someSingletoneBean

public class SomeSingletonBean {
  public void sayHello(){
      System.out.println("hello");
  }
}

// helper singletone class

package com.example.main;

import org.springframework.context.ApplicationContext;

/**
 * @author Dinesh.Lomte
 *
 */
public enum AppContext {

    INSTANCE;

    public static AppContext getInstance() {
        return INSTANCE;
    }

    private ApplicationContext applicationContext;

    /**
     * Default constructor
     */
    private AppContext() {
    }

    /**
     *
     */
    public void setContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     *
     * @return
     */
    public ApplicationContext getContext() {
        return applicationContext;
    }
}
Posted in Без рубрики | Comments Off on Java.Spring.ExternalBeanRegistration

Docker.Postgres

met some problems (connection refused, Postgresql Docker role does not exist), following official docs, so decided to keep working example here

// works !!!
docker run --name sberHomeworkDb_5432 -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword -e POSTGRES_DB=testDb -e POSTGRES_USER=testUser postgres:13.8-alpine

// works !!!
docker run --name sberHomeworkDb_5432 -p 5432:5432 -e POSTGRES_PASSWORD=mysecretpassword postgres:13.8-alpine

// works !!!
docker run --name sberHomeworkDb -p 5433:5432 -e POSTGRES_PASSWORD=mysecretpassword postgres:13.8-alpine
Posted in Без рубрики | Comments Off on Docker.Postgres

Docker. Tips

docker pull nginx:latest
docker ps // show all containers
// creation and start of NEW container with customName: will search for image, download if will not find it, un without blocking terminal
// -d means detached mode, non blocking console
docker run -d -p:9000:80 --name customName nginx:latest 
docker stop ad40c1c66e1c // will stop container with id ad40c1c66e1c
docker start ad40c1c66e1c // will start container with id ad40c1c66e1c
docker stop containerName// will stop container with name containerName
docker start containerName // will start container with name containerName
docker stop $(docker ps -a -q) // stop all containers
docker logs containerId // will show log for container id, for ex. docker logs f716d60b98ed
docker images // hi, cap )

nehopper is devops worldwide service

from docker help

Common Commands:
  run         Create and run a new container from an image
  exec        Execute a command in a running container
  ps          List containers
  build       Build an image from a Dockerfile
  pull        Download an image from a registry
  push        Upload an image to a registry
  images      List images
  login       Log in to a registry
  logout      Log out from a registry
  search      Search Docker Hub for images
  version     Show the Docker version information
  info        Display system-wide information

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.11.2-desktop.5)
  compose*    Docker Compose (Docker Inc., v2.22.0-desktop.2)
  container   Manage containers
  context     Manage contexts
  dev*        Docker Dev Environments (Docker Inc., v0.1.0)
  extension*  Manages Docker extensions (Docker Inc., v0.2.20)
  image       Manage images
  init*       Creates Docker-related starter files for your project (Docker Inc., v0.1.0-beta.8)
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  plugin      Manage plugins
  sbom*       View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc., 0.6.0)
  scan*       Docker Scan (Docker Inc., v0.26.0)
  scout*      Docker Scout (Docker Inc., v1.0.7)
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Swarm Commands:
  swarm       Manage Swarm

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  import      Import the contents from a tarball to create a filesystem image
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  wait        Block until one or more containers stop, then print their exit codes

Global Options:
      --config string      Location of client config files (default
                           "C:\\Users\\.docker")
  -c, --context string     Name of the context to use to connect to the
                           daemon (overrides DOCKER_HOST env var and
                           default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket to connect to
  -l, --log-level string   Set the logging level ("debug", "info",
                           "warn", "error", "fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default
                           "C:\\Users\\.docker\\ca.pem")
      --tlscert string     Path to TLS certificate file (default
                           "C:\\Users\\.docker\\cert.pem")
      --tlskey string      Path to TLS key file (default
                           "C:\\Users\\.docker\\key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit
Posted in Без рубрики | Comments Off on Docker. Tips

Java.MapStruct.Tips

install

    implementation("org.mapstruct:mapstruct:1.3.1.Final")
    annotationProcessor("org.mapstruct:mapstruct-processor:1.3.1.Final")
    testAnnotationProcessor("org.mapstruct:mapstruct-processor:1.3.1.Final")
    implementation("org.projectlombok:lombok-mapstruct-binding:0.2.0")

mapper

public interface GameMapMapper {

    GameMapMapper INSTANCE = Mappers.getMapper(GameMapMapper.class);

//   add mapping if needed
//    @Mapping(target = "maxX", source = "maxX")
//    @Mapping(target = "maxY", source = "maxY")
    GameMapUi toMapDto(Map gameMap);

    GrassUi toGrassDto(Grass grass);

    AnimalUi toAnimalsDto(Animal animal);

}

example of call

        var gameMapMapper = GameMapMapper.INSTANCE;
        var map = gameMapMapper.toMapDto(gameContext.getState().getMap());

        var grass = gameContext.getState().getGrass().stream().map(
                g -> gameMapMapper.toGrassDto(g)
        ).collect(Collectors.toList());

        var animals = gameContext.getState().getAnimals().stream().map(
                animal -> gameMapMapper.toAnimalsDto(animal)
        ).collect(Collectors.toList());

        GameStateUi gameStateUi = new GameStateUi();
        gameStateUi.gameMap(map);
        gameStateUi.setGrass(grass);
        gameStateUi.setAnimals(animals);

with newer versions also faced with problems like this:

Internal error in the mapping processor: java.lang.RuntimeException: javax.annotation.processing.FilerException: Attempt to recreate a file for type com.example.main.life.mappers.GameMapMapperImpl  	at org.mapstruct.ap.internal.processor.
https://github.com/mapstruct/mapstruct/issues/1818
Posted in Без рубрики | Comments Off on Java.MapStruct.Tips

Java.SpringBoot.InjectingProperties

example

public class GreetingsServiceImpl implements GreetingsService {

    @Value("${myProperty:defaultValue}") 
    private String property;

    @Override
    public GreetingUI getGreeting() {
        // will read from resources/application.properties or will take default value
        String propValue =  property;
        return new GreetingUI().message("greeting from backend");
    }
}

/resources/application.properties

myProperty = helloThere;

Details

Posted in Без рубрики | Comments Off on Java.SpringBoot.InjectingProperties

Java.Mockito

build.gradle.kts

...
    testImplementation("org.mockito:mockito-junit-jupiter:5.7.0")
    testImplementation("org.mockito:mockito-inline:5.2.0")
...

seconnd one lib is for static methods

Examples

package com.example.main.example;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.mockito.ArgumentMatchers.anyInt;

@ExtendWith(MockitoExtension.class)
public class AppStateTestWithMockito {

    @Mock
    List virtualMockList;

    @Test
    public void mockitoVirtualObject() {
        virtualMockList.add("one");
        virtualMockList.add("two");
        Assertions.assertTrue(virtualMockList.size() == 0); // true
//        Assertions.assertTrue(virtualMockList.size() > 1); // false
        Mockito.when(virtualMockList.size()).thenReturn(10);
        Assertions.assertTrue(virtualMockList.size() > 1); // false
    }


    @Test
    public void mockitoWhenThenReturn() {
        virtualMockList.add("one");
        virtualMockList.add("two");

        // equivalent mocks
        Mockito.doReturn(10).when(virtualMockList).size();
        Mockito.when(virtualMockList.size()).thenReturn(10);

        Assertions.assertTrue(virtualMockList.size() > 1); // false
    }

    @Test
    public void throwTest() {
        // equivalents
        //        Mockito.doThrow(new RuntimeException()).when(virtualMockList).size();
        Mockito.when(virtualMockList.size()).thenThrow(new RuntimeException());
        Assertions.assertThrows(RuntimeException.class, () -> {
            virtualMockList.size();
        });
    }

    @Test
    public void callWithParams() {
        Mockito.doReturn("myValue").when(virtualMockList).get(10);
        Assertions.assertEquals("myValue", virtualMockList.get(10));
    }

    @Test
    void anyValue() {
        // equivalents
        // Mockito.doReturn("myValue").when(virtualMockList).get(any(int.class));
        Mockito.doReturn("myValue").when(virtualMockList).get(anyInt());

        Assertions.assertEquals("myValue", virtualMockList.get(10));
        Assertions.assertEquals("myValue", virtualMockList.get(11));
        Assertions.assertEquals("myValue", virtualMockList.get(12));
    }

    @Test
    void doAnswerExample() {
        Mockito.doAnswer(invocation -> {
            int arg = invocation.getArgument(0);
            return arg * arg;
        }).when(virtualMockList).get(anyInt());

        Assertions.assertEquals(100, virtualMockList.get(10));
    }

    @Test
    void verifyExample() {
        var value = virtualMockList.get(10);
        Mockito.verify(virtualMockList, Mockito.times(1)).get(10);
    }

    @Test
    void verifyNoMoreInteractions() {
        Mockito.verifyNoMoreInteractions(virtualMockList);
    }

    @Test
    void verifyOrder() {
        virtualMockList.get(10);
        virtualMockList.size();
        var inOrder = Mockito.inOrder(virtualMockList);
        inOrder.verify(virtualMockList).get(10);
        inOrder.verify(virtualMockList).size();
    }

    @Test
    public void spyRedirection() {

        List list = new LinkedList(); // works with LinkedList, but doesn't work with ArrayList
        List spy = Mockito.spy(list);

        //optionally, you can stub out some methods:
//        Mockito.when(spy.size()).thenReturn(100);

        //using the spy calls real methods
        spy.add("one");
        spy.add("two");

        //prints "one" - the first element of a list
        System.out.println(spy.get(0));

        //size() method was stubbed - 100 is printed
        System.out.println(spy.size());
    }

    @Test
    public void spyRedirection2() {

        List spyMockitoList2 = Mockito.spy(new ArrayList());

        spyMockitoList2.add("one");
        spyMockitoList2.add("two");

        Assertions.assertTrue(spyMockitoList2.size() > 0); // false
    }

    @Test
    void staticMethod() {
        try (MockedStatic<UtilsExample> utils = Mockito.mockStatic(UtilsExample.class)) {
            utils.when(UtilsExample::doSmth).thenReturn("hi, from static method");
            Assertions.assertEquals("hi, from static method", UtilsExample.doSmth());
        }
    }
}

class UtilsExample {
    static String doSmth() {
        return "static";
    }

}
Posted in Без рубрики | Comments Off on Java.Mockito

Java.MavenShadePlugin

        <!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-shade-plugin -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.4.1</version>
        </dependency>
Posted in Без рубрики | Comments Off on Java.MavenShadePlugin

Java.Servlets

all servlets were written with community verison of idea, so ome workaround was needed

myFirstServlet (need to be deployed on TomCat manually)

communityHackServlet (starts with tomcat automatically)

source for communityHackServlet

Posted in Без рубрики | Comments Off on Java.Servlets

Java.DesignPatterns.SingletonExamples

first way

package org.example;

public class SomeSingletone {

    private static SomeSingletone someSingletone;
    private SomeSingletone(){}

    static {
        synchronized (SomeSingletone.class) {
          someSingletone = new SomeSingletone();
        }
    }

    public static SomeSingletone getSomeSingletone(){
        return someSingletone;
    }

}

another way

package org.example;

public class AnotherSingletone {

    private static AnotherSingletone anotherSingletone;

    private AnotherSingletone() {
    }

    public static AnotherSingletone getAnotherSingletone() {
        if (anotherSingletone == null) {
            anotherSingletone = new AnotherSingletone();
        }

        return anotherSingletone;
    }
}
Posted in Без рубрики | Comments Off on Java.DesignPatterns.SingletonExamples