<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Java &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sun, 18 Feb 2024 09:01:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>Simple algorithm for casting strings to double</title>
		<link>https://codepills.com/simple-algorithm-for-casting-strings-to-double/</link>
					<comments>https://codepills.com/simple-algorithm-for-casting-strings-to-double/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Mon, 05 Feb 2024 14:30:33 +0000</pubDate>
				<category><![CDATA[Solutions]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[CSV]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[separators]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1356</guid>

					<description><![CDATA[The article describes a method for converting incorrectly formatted numeric strings in CSV files into doubles by replacing commas with dots and handling various input errors, complemented by a Java util class implementation and tests. <a href="https://codepills.com/simple-algorithm-for-casting-strings-to-double/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article describes a method for converting incorrectly formatted numeric strings in CSV files into doubles by replacing commas with dots and handling various input errors, complemented by a Java util class implementation and tests.</p>
<p><span id="more-1356"></span></p>
<h2>Introduction</h2>
<p>Recently, I was solving a straightforward issue. The technical documentation about the input format was straightforward. A particular column in the CSV document represented numbers in double format. However, users were allowed to interact with CSV files and make manual edits. This lead to a situation where the user or the processing program changes the number to a standardized format or even to an incorrect one. In most cases, users change the dot to a comma.</p>
<p>Thus, if possible, I needed to devise a simple way to fix the incorrect input and cast the string to double.</p>
<h2>Implementation</h2>
<p>I have created a simple util class with a single static method to fix the incorrect string format.</p>
<p>The method implementation catches and solves the following cases:</p>
<ul>
<li>The method throws an exception if the input string is null or empty.</li>
<li>The method throws an exception if the input string contains more than one separator or a mix of different separators.</li>
<li>The method throws an exception if the input string is not a number.</li>
<li>Otherwise, the process replaces the comma with a dot and parses the string to double.</li>
</ul>
<p>Casting can still fail and throw <code>NumberFormatException</code> if the input string is not a number. <em>parseStringToDouble()</em> method will not handle the failure, and it will be up to the caller to catch the exception and manage it. Feel free to adjust the method according to your needs.</p>
<p>Here is a simple algorithm for how to cast string to double:</p>
<pre><code class="language-java">public static class StringUtil {
  
  private static final String DOT = ".";
  private static final String COMMA = ",";
  private static final String EMPTY = "";
  
  /**
   * Parses a string to a double.
   *
   * @param numberStr
   * @return the parsed double
   * @throws IllegalArgumentException if the input string is null or empty, or if the number is ambiguous
   */
  public static Double parseStringToDouble(final String numberStr) {
      if (numberStr == null || numberStr.isEmpty()) {
          throw new IllegalArgumentException("Input string is null or empty");
      }

      val numberStrWithReplacedCommas = numberStr.replace(COMMA, DOT);

      int dotCount = numberStr.length() - numberStr.replace(DOT, EMPTY).length();
      int commaCount = numberStr.length() - numberStrWithReplacedCommas.length();

      if (dotCount + commaCount > 1) {
          throw new IllegalArgumentException("There is more than one separator, or a mix of them, the number is ambiguous");
      }

      return Double.parseDouble(numberStrWithReplacedCommas);
  }

}</code></pre>
<p>Feel free to use this simple algorithm in your projects and extend it according to your will. You may not need to throw an exception if the input string is null or empty or if the number is ambiguous. You may want to catch <code>NumberFormatException</code> from <i>parseDouble</i> method and return 0.0 in such case. You could return empty Optional. It is up to you.</p>
<h2>Tests</h2>
<p>I also wrote a few tests to verify that the algorithm works correctly. Please check it and adjust it according to your will. Here are the tests:</p>
<pre><code class="language-java">import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import lombok.val;

class StringUtilTest {

    @Test
    public void testParseValidStringWithDot() {
        val result = StringUtil.parseStringToDouble("123.45");
        Assertions.assertEquals(123.45, result, 0.000);
    }

    @Test
    public void testParseValidStringWithComma() {
        val result = StringUtil.parseStringToDouble("123,45");
        Assertions.assertEquals(123.45, result, 0.000);
    }

    @Test
    public void testParseStringWithMultipleSeparatorsShouldThrowException() {
        Assertions.assertThrows(IllegalArgumentException.class,
            () -> StringUtil.parseStringToDouble("123,45.67"));
    }

    @Test
    public void testParseStringWithInvalidCharactersShouldThrowException() {
        Assertions.assertThrows(IllegalArgumentException.class,
            () -> StringUtil.parseStringToDouble("123..45"));
    }

    @Test
    public void testParseStringWithOtherInvalidCharactersShouldThrowException() {
        Assertions.assertThrows(IllegalArgumentException.class,
            () -> StringUtil.parseStringToDouble("123,,45"));
    }

    @Test
    public void testParseNonNumericStringShouldThrowException() {
        Assertions.assertThrows(NumberFormatException.class,
            () -> StringUtil.parseStringToDouble("not a number"));
    }

    @Test
    public void testParseEmptyStringShouldThrowException() {
        Assertions.assertThrows(IllegalArgumentException.class,
            () -> StringUtil.parseStringToDouble(""));
    }

    @Test
    public void testParseNullShouldThrowException() {
        Assertions.assertThrows(IllegalArgumentException.class,
            () -> StringUtil.parseStringToDouble(null));
    }

}</code></pre>
<h2>Conclusion</h2>
<p>In simple algorithms, we have seen how to handle multiple cases of incorrect string input and how to cast string to double.</p>
<p>But in the end, it is up to you how to handle the cases when the input string is null or empty or if the number is ambiguous. You can throw a custom exception, return 0.0, empty Optional, or do something else.</p>
<p>Did you find an algorithm for casting strings to double easily? Do you have your trick or know another way <u>how to change arbitrary string to double</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/simple-algorithm-for-casting-strings-to-double/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to make multipart requests with file and object through autogenerated code defined in OpenAPI</title>
		<link>https://codepills.com/how-to-make-multipart-requests-with-file-and-object-through-autogenerated-code-defined-in-openapi/</link>
					<comments>https://codepills.com/how-to-make-multipart-requests-with-file-and-object-through-autogenerated-code-defined-in-openapi/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 03 Feb 2024 18:08:37 +0000</pubDate>
				<category><![CDATA[Solutions]]></category>
		<category><![CDATA[Converter]]></category>
		<category><![CDATA[Deserialization]]></category>
		<category><![CDATA[Endpoint Creation]]></category>
		<category><![CDATA[File Upload]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Multipart Form Data]]></category>
		<category><![CDATA[MultipartFile]]></category>
		<category><![CDATA[Object Validation]]></category>
		<category><![CDATA[ObjectMapper]]></category>
		<category><![CDATA[OpenAPI]]></category>
		<category><![CDATA[Postman]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[Validator]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1364</guid>

					<description><![CDATA[This article explains how to create a Spring Boot endpoint using OpenAPI to receive objects and, optionally, files through multipart form data, focusing on deserialization and validation of incoming objects. <a href="https://codepills.com/how-to-make-multipart-requests-with-file-and-object-through-autogenerated-code-defined-in-openapi/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article explains creating a Spring Boot endpoint using OpenAPI to receive objects and, optionally, files through multipart form data, focusing on deserialization and validation of incoming objects.</p>
<p><span id="more-1364"></span></p>
<h2>Introduction</h2>
<p>In this article we will continue and spin from the <a href="https://codepills.com/how-to-make-multipart-requests-with-files-through-autogenerated-code-defined-in-openapi/" title="How to make multipart requests with files through autogenerated code defined in OpenAPI" target="_blank" rel="nofollow noopener">previous article</a> about generating OpenAPI with Spring Boot for multipart endpoint and uploading files through it. We strongly recommend reading the last article if you want to import more than one file. But in this article, we will focus only on the optional import of a single file.</p>
<p>But instead of multiple files, we will try to upload only one file and one serialized object, for example, the information about the new user.</p>
<p>We will also show how to handle the deserialization of the incoming object from the string at the Spring Boot backend and how to control proper deconstruction if some fields are optional or not mandatory.</p>
<h2>OpenAPI User import definition YAML</h2>
<p>So we start where we end the last time. Let&#8217;s generate the Spring Boot endpoint through the OpenAPI schema, which will be able to receive objects and, optionally, a file through multipart form data.</p>
<pre><code class="language-yaml">openapi: 3.0.2
info:
  title: User management module
  description: User management
  version: '0.1'
  contact:
  email: optional@email.com
servers:
  - url: https://localhost:8080/api/user-management

paths:
  /users/import:
    post:
      summary: Create new Users with optional attachment
      tags:
        - users
      operationId: createUserWithOptionalFile
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                createUser:
                  description: Wrapper containing information for new user creation
                  type: object
                  properties:
                    username:
                      description: Users username
                      type: string
                    age:
                      description: Users password
                      type: number
                    creationTimestamp:
                      description: Time when the user will be defined as created in the system
                      type: string
                      format: date-time
                      example: "2024-02-29T12:30:00.000Z"
                    email:
                      description: Email of the user
                      type: string
                    addressId:
                      description: ID of the users address
                      type: string
                    accessRights:
                      description: List of access rights for the user
                      type: array
                      items:
                        type: object
                        properties:
                          accessRightId:
                            description: ID of the access right
                            type: string
                          note:
                            description: Note for the access right
                            type: string
                  required:
                    - username
                    - email
                    - accessRights
                optionalFile:
                  description: Optional file attachment
                  type: string
                  format: binary
              required:
              - createUser
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateUserResponse'
        '400':
          description: Bad Request</code></pre>
<p>As you can see, we have defined the endpoint /users/import, which will be able to receive the object createUser and optionally also a single file. The createUser object is defined in the schema and is required, while the file is optional. CreateUser object also has various definitions of fields, although unimportant and displayed only for current examples.</p>
<p>You can refer to the object schema to make the YAML file more readable and concise. The object&#8217;s schema can be defined in self-standing section dedicated to components.</p>
<pre><code class="language-yaml">openapi: 3.0.2
info:
  title: User management module
  description: User management
  version: '0.1'
  contact:
  email: optional@email.com
servers:
  - url: https://localhost:8080/api/user-management

paths:
  /users/import:
    post:
      summary: Create new Users with optional attachment
      tags:
        - users
      operationId: createUserWithOptionalFile
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                createUser:
                  $ref: '#/components/schemas/CreateUser'
                optionalFile:
                  description: Optional file attachment
                  type: string
                  format: binary
              required:
              - createUser
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CreateUserResponse'
        '400':
          description: Bad Request

components:
  schemas:
    CreateUser:
      description: Wrapper containing information for new user creation
      type: object
      properties:
        username:
          description: Users username
          type: string
        age:
          description: Users password
          type: number
        creationTimestamp:
          description: Time when the user will be defined as created in the system
          type: string
          format: date-time
          example: "2024-02-29T12:30:00.000Z"
        email:
          description: Email of the user
          type: string
        addressId:
          description: ID of the users address
          type: string
        accessRights:
          description: List of access rights for the user
          type: array
          items:
            type: object
            properties:
              accessRightId:
                description: ID of the access right
                type: string
              note:
                description: Note for the access right
                type: string
      required:
        - username
        - email
        - accessRights</code></pre>
<h2>Enforcing and casting mandatory properties of multipart request</h2>
<p>Multipart file can accept only the <i>String</i>s or <i>File</i>s (better visible in <a href="#testing_with_postman">testing with Postman</a> section). So any string input &#8211; Java&#8217;s serialized object, or JSON, is at the end nothing more than just a string of bytes.</p>
<p>The problem will arise during the deserialization of autogenerated code. It does not matter if you declare the object cast as required. With proper mapping, the input will be taken as a String and not as the type you want to use from the method signature.</p>
<p>Mapper and validator factory beans can solve the issue and handle the input.</p>
<p>First, register one new bean for object Validation. Optionally, you can register the ObjectMapper with JavaTimeModule to handle the date-time format, as we will use the date-time string in ISO format (&#8220;YYYY-MM-DDTHH:MM:SS.mmmZ&#8221;). The Validator is created through LocalValidatorFactoryBean.</p>
<pre><code class="language-java">import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import jakarta.validation.Validator;
import lombok.val;

@Configuration
public class AppConfig {

  //@Bean
  //public ObjectMapper objectMapper() {
  //  val objectMapper = new ObjectMapper();
  //  objectMapper.registerModule(new JavaTimeModule());
  //  return objectMapper;
  //}

  @Bean
  public Validator validator() {
    return new LocalValidatorFactoryBean();
  }

}</code></pre>
<p>The code was written for Java 21 dependencies with Lombok.</p>
<p>To enforce the proper conversion, you must create a new Spring component to convert the incoming string to the object. The component will be able to handle the deserialization and validation of the object.</p>
<pre><code class="language-java">import java.util.Set;

import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validator;
import lombok.val;

@Component
public class StringToCreateUserDtoConverter implements Converter&lt;String, CreateUserDto> {

  private final Validator validator;
  private final ObjectMapper objectMapper;

  public StringToCreateUserDtoConverter(final Validator validator, final ObjectMapper objectMapper) {
    this.validator = validator;
    this.objectMapper = objectMapper;
  }

  @Override
  public CreateUserDto convert(final String source) {
    CreateUserDto createUserDto;
    try {
        createUserDto = objectMapper.readValue(source, CreateUserDto.class);
    } catch (JsonProcessingException e) {
        throw new CreateUserDeserializationException("Input mapping and processing error: " + e.getMessage());
    }
    val violations = validator.validate(createUserDto);
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
    return createUserDto;
  }

}</code></pre>
<p>Just for the record, I will also add here the custom exception you can throw and catch in the custom exception handler:</p>
<pre><code class="language-java">import java.io.Serial;

import lombok.Getter;

@Getter
public class CreateUserDeserializationException extends RuntimeException {

  @Serial
  private static final long serialVersionUID = 1659771269447893294L;

  public CreateUserDeserializationException(String msg) {
    super(msg);
  }

}</code></pre>
<h2>Unit tests</h2>
<p>I recommend writing the unit tests for the converter. It is a good practice to test the conversion and validation of the object. As we rely heavily upon Spring magic, a lot can unintentionally influence the component&#8217;s behaviour without us discovering it.</p>
<p>The code below is just an example of the unit tests with the usage of <i>SpringBootTest</i> and <i>LocalTestcontainers</i> which ties to get close to real-world use scenarios. We highly recommend to accommodate tests to your environment and needs.</p>
<pre><code class="language-java">
import org.testcontainers.containers.PostgreSQLContainer;

public class LocalTestcontainers {

    public static void startPostgres(){
        PostgreSQLContainer<?> postgre = new PostgreSQLContainer<>("postgres:16.0")
            .withDatabaseName("INSERT_DATABASE_NAME")
            .withUsername("INSERT_DATABASE_USERNAME")
            .withPassword("INSERT_DATABASE_PASSWORD");
        postgre.start();

        System.setProperty("spring.datasource.url", postgre.getJdbcUrl());
        System.setProperty("spring.datasource.username", postgre.getUsername());
        System.setProperty("spring.datasource.password", postgre.getPassword());
    }

}</code></pre>
<pre><code class="language-java">import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.testcontainers.junit.jupiter.Testcontainers;

import com.codepills.usermanagementmodule.api.exception.CreateUserDeserializationException;
import com.codepills.usermanagementmodule.utils.LocalTestcontainers;

import jakarta.validation.ConstraintViolationException;
import lombok.val;

@SpringBootTest
@Testcontainers
class StringToCreateUserDtoConverterTest {

    static {
        LocalTestcontainers.startPostgres();
    }

    @Autowired
    private StringToCreateUserDtoConverter stringToCreateUserDtoConverter;

    @Test
    void testConvertValidInputString() {
        // Arrange
        val username = "JohnDoe";
        val age = 25;
        val formatter = DateTimeFormatter.ISO_INSTANT;
        val now4CreationTime = Instant.now();
        val email = "john.doe@noemail.com";
        val addressId = UUID.randomUUID();
        val accessRightId1 = UUID.randomUUID();
        val accessRightId2 = UUID.randomUUID();

        val stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        stringBuilder.append("\"username\" : \"").append(username).append("\",");
        stringBuilder.append("\"age\" : ").append(age).append(",");
        stringBuilder.append("\"creationTimestamp\" : \"").append(formatter.format(now4CreationTime)).append("\",");
        stringBuilder.append("\"email\" : \"").append(email).append("\",");
        stringBuilder.append("\"addressId\" : \"").append(addressId).append("\",");
        stringBuilder.append("\"accessRights\" : [");
        stringBuilder.append("{");
        stringBuilder.append("\"accessRightId\" : \"").append(accessRightId1).append("\",");
        stringBuilder.append("}, {");
        stringBuilder.append("\"accessRightId\" : \"").append(accessRightId2).append("\"");
        stringBuilder.append("}]}");
        val validInput = stringBuilder.toString();

        // Act
        val createUserDto = stringToCreatUserDtoConverter.convert(validInput);

        // Assert
        assertNotNull(createUserDto);
        assertEquals(username, createUserDto.getUsername());
        assertEquals(age, createUserDto.getAge());
        assertEquals(now4CreationTime, createUserDto.getCreationTimestamp());
        assertEquals(email, createUserDto.getEmail());
        assertEquals(addressId.toString(), createUserDto.getAddressId());
        assertEquals(2, createUserDto.getAccessRights().size());
        assertEquals(accessRightId1.toString(), createUserDto.getAccessRights().get(0).getAccessRightId());
        assertEquals(accessRightId2.toString(), createUserDto.getAccessRights().get(1).getAccessRightId());
    }

    @Test
    void testConvertInvalidInputString() {
        // Arrange
        val invalidInput = "invalid input string";
        // Act & Assert
        try {
            stringToCreateUserDtoConverter.convert(invalidInput);
        } catch (CreateUserDeserializationException ex) {
            assertEquals("Input mapping and processing error: Unrecognized token 'invalid': was expecting (JSON String, Number, Array, "
                             + "Object or token 'null', 'true' or 'false')\n at [Source: (String)\"invalid input string\"; line: 1, "
                             + "column: 8]", ex.getMessage());
        }
    }

    @Test
    void testConvertInputWithValidationErrors() {
        // Arrange
        val username = "JohnDoe";
        val age = 25;
        val formatter = DateTimeFormatter.ISO_INSTANT;
        val now4CreationTime = Instant.now();
        val email = "john.doe@noemail.com";
        val addressId = UUID.randomUUID();
        val accessRightId1 = UUID.randomUUID();
        val accessRightId2 = UUID.randomUUID();

        val stringBuilder = new StringBuilder();
        stringBuilder.append("{");
        stringBuilder.append("\"username\" : \"").append(username).append("\",");
        stringBuilder.append("\"age\" : ").append(age).append(",");
        stringBuilder.append("\"creationTimestamp\" : \"").append(formatter.format(now4CreationTime)).append("\",");
        stringBuilder.append("\"email\" : \"").append(email).append("\",");
        // Missing addressId
        stringBuilder.append("\"addressId\" : null,");
        stringBuilder.append("\"accessRights\" : [");
        stringBuilder.append("{");
        stringBuilder.append("\"accessRightId\" : \"").append(accessRightId1).append("\",");
        stringBuilder.append("}, {");
        stringBuilder.append("\"accessRightId\" : \"").append(accessRightId2).append("\"");
        stringBuilder.append("}]}");
        val validInput = stringBuilder.toString();

        // Act & Assert
        try {
            stringToCreateUserDtoConverter.convert(inputWithValidationErrors);
        } catch (ConstraintViolationException ex) {
            assertEquals(1, ex.getConstraintViolations().size());
        }
    }

}</code></pre>
<h2>User Management Controller</h2>
<p>Now, all we need to do is create a controller to implement the OpenAPI schema.</p>
<p>Here is an example of the controller:</p>
<pre><code class="language-java">@Logger
@RestController
@RequiredArgsConstructor
public class UserManagementController implements UserManagementApi {

  @Override
  public ResponseEntity&lt;Void&gt&gt; createUserWithOptionalFile(
        @RequestPart(name = "createUser") final CreateUserDto createUserDto,
        @RequestPart(name = "optionalFile", required = false) MultipartFile optionalFile
     ) {
    if (optionalFile == null || optionalFile.isEmpty()) {
        log.info("No optionalFile uploaded.");
    } else {
        log.info("PDF optionalFile {} uploaded but not saved.", optionalFile.getOriginalFilename());
    }

    // You can work with createUserDto here

    return ResponseEntity.ok().build();
  }

}</code></pre>
<p>I will leave the implementation of <em>createUserWithOptionalFile()</em> method up to you as it is not the main focus of this article.</p>
<p>Again, notice the <i>optionalFile</i> and <i>createUser</i> keywords in the method arguments. It is the same as the keyword as defined in the OpenAPI schema.</p>
<h2 id="testing_with_postman">Testing with Postman</h2>
<p>Nothing blocks our development anymore, and we can start testing the endpoint with Postman. The endpoint will be able to receive the serialized object in the form of string and also the file. However, attaching the file to the request is, of course, optional.</p>
<p>As it might need to be stressed more, the most important thing is using the exact keywords defined in the OpenAPI schema. In our case, for importing object, it will be <i>createUser</i> and for optional file, it will be <i>optionalFile</i>.</p>
<p>Let&#8217;s run the SpringBoot app at localhost.</p>
<p>Backend should be running at localhost. And if added the necessary logic for file processing into the controller, we should be able to upload serialized objects in JSON format and optional file through the <em>/users/import</em> endpoint.</p>
<p>When using Postman, you also need to define the type of multipart key. It is either the <em>String</em> or <em>File</em>. For files, use <em>File</em>, and for the object, use <em>String</em>. Do not forget that in the <a href="https://codepills.com/how-to-make-multipart-requests-with-files-through-autogenerated-code-defined-in-openapi/" title="How to make multipart requests with files through autogenerated code defined in OpenAPI" target="_blank" rel="nofollow noopener">previous article</a> we discuss the implementation of sending multiple files through multipart request.</p>
<p>All you need to do is to define your endpoint <code>POST</code> request in Postman. Select <code>POST</code> request, add the URL, and in the body tab, select form-data and add the keywords <em>createUser</em> set as <em>String</em> and <em>optionalFile</em> as <em>File</em> .</p>
<p><img fetchpriority="high" decoding="async" src="https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_objects_and_files.png" alt="Postman multipart request with multiple objects and files" width="665" height="316" class="size-full wp-image-1373" srcset="https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_objects_and_files.png 665w, https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_objects_and_files-300x143.png 300w" sizes="(max-width: 665px) 100vw, 665px" /></p>
<p>The most important part is to really define serialized object as <em>String</em> and not <em>File</em>.</p>
<p>Here is an example of <em>createUser</em> as <em>String</em>:</p>
<pre><code class="language-text">{
	"username" : "johndoe",
	"age" : "25",
	"creationTimestamp" : "2024-02-29T12:30:00.000Z",
	"email" : "john.doe@noemail.com",
	"addressId" : "f8935f28-8d7b-40a4-96d7-a3288976617e",
	"accessRights" : [
		{
      "accessRightId" : "712d5a0a-11b5-4a44-9e92-6e67d16be2aa"
    }
	]
}</code></pre>
<h2>Conclusion</h2>
<p>This article has shown how to create a Spring Boot endpoint to receive objects and, optionally, file through multipart form data. We have also demonstrated how to handle the deserialization of the incoming object from the string at the Spring Boot backend and how to control proper deconstruction if some fields are optional or not mandatory.</p>
<p>Is it applicable to auto-generating infrastructure code through OpenAPI with Spring Boot for multipart endpoint and uploading files? Let us know in the comments below. Do you have your trick or see another way <u>how to enforce and deserialize multipart object</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-make-multipart-requests-with-file-and-object-through-autogenerated-code-defined-in-openapi/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to compile and run Java files on Windows</title>
		<link>https://codepills.com/how-to-compile-and-run-java-files-on-windows/</link>
					<comments>https://codepills.com/how-to-compile-and-run-java-files-on-windows/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 01 Jul 2023 17:04:17 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[javac]]></category>
		<guid isPermaLink="false">http://www.budystudio.com/design/?p=197</guid>

					<description><![CDATA[There are several scenarios when you need to compile and run your Java code from the terminal or command prompt on Windows. Here is a tutorial on how to do it. <a href="https://codepills.com/how-to-compile-and-run-java-files-on-windows/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>From time to time, you get into a situation you need to compile and run your Java code, and instead of using any build tool or IDE, you need to do it manually. If you are engaged in software development or writing automated script writing, compiling and executing code from the Windows console should be straightforward and effortless.</p>
<p><span id="more-197"></span></p>
<p>We will use the following simple code to print a code into the terminal or command prompt for demonstration purposes.</p>
<pre><code class="language-java">public class MyJavaApp {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

}</code></pre>
<h2>Compile and run Java code in a few steps</h2>
<p>You must follow only a few basic steps to compile and run Java code.</p>
<ol>
<li>As a precondition, ensuring the installation of Java Development Kit (JDK) on your system and the accessibility of the <code>javac</code> and <code>java</code> commands from the terminal or command prompt is important.</li>
<li>First, you <strong>have to have a Java source code in Java files</strong>. Open a text editor and write your Java code. Save the file with a <code>.java</code> file extension.</li>
<li>Then you are ready to compile the Java source file. Open a terminal or command prompt and navigate to the directory where your Java source file is placed. Utilize the <code>javac</code> command for compiling the Java source file into bytecode. For example:
<pre><code class="language-bash">javac MyJavaApp.java</code></pre>
<p>        You will generate a bytecode file named <code>MyJavaApp.java</code> if there are no compilation errors.
    </li>
<li>When you have successfully compiled the Java source file into a bytecode file, you can execute the bytecode using the <code>java</code> command. However, select the class which contains valid <code>public static void main(String args[])</code> Java method in order <strong>for JVM to have an access point to your code</strong>.
<p>        Here is an example of running MyJavaApp:</p>
<pre><code class="language-bash">java MyJavaApp</code></pre>
<p>        And here is the output:</p>
<p>        <img decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands.png" alt="javac and java commands" width="283" height="102" class="alignnone size-full wp-image-1347 aligncenter" /></p>
<p>        <code>java MyJavaApp</code> will run your Java program, and if everything is correct, you should see the output in the console.
    </li>
</ol>
<h2>Compiling and running nested classes</h2>
<p>So far, we have seen compile and run only a single class. However, running a multi-class project is no different from compiling and running a single class. Here is an example of a multi-class project we will use next.</p>
<pre><code class="language-java">public class MyJavaApp {

    public static void main(String[] args) {
        InsertedClass.printToWorld();
    }

}

public class InsertedClass {

    public static void printToWorld() {
        System.out.println("Hello World from other class!");
    }

}</code></pre>
<p>For sure, the same as in a single class, you need to pick a class for compiling the class which contains the <code>public static void main(String args[])</code>. That is the only way the compiler can reach and compile all classes in your project.</p>
<p><img decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands-compiled_files.png" alt="javac and java commands - compiled files" width="155" height="93" class="alignnone size-full wp-image-1349 aligncenter" /></p>
<p>And again, same as in the single class, you need to run the multi-class project with the <code>java</code> command on the file, which contains <code>public static void main(String args[])</code> method.</p>
<p><img loading="lazy" decoding="async" src="https://codepills.com/wp-content/uploads/2012/02/javac_and_java_commands-compile_and_run_all_files.png" alt="javac and java commands - compile and run all files" width="276" height="109" class="alignnone size-full wp-image-1348 aligncenter" /></p>
<h2>Conclusion</h2>
<p>This article has shown how to compile and run Java code on the Windows platform.</p>
<p>Did you find compiling and running your Java code easy? Do you have your trick or know another way <u>how to compile and run Java code from the terminal or command prompt</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-compile-and-run-java-files-on-windows/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>7 different ways how to get NumberFormatException in Java</title>
		<link>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/</link>
					<comments>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 05 May 2022 11:30:51 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[exception]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[NumberFormatException]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1304</guid>

					<description><![CDATA[This article will show you the NumberFormatException, how you are getting it and what you should do to handle the exception properly. <a href="https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>If you get NumberFormatException in Java, it is highly probable because of the following reasons. This article will uncover the NumberFormatException, how you are getting it and what you should do to handle the exception properly.</p>
<p><span id="more-1304"></span></p>
<h2>What is NumberFormatException</h2>
<p>The NumberFormatException is an unchecked Java exception which happens when there is incorrect string input converted to a numeric value. When the input is wrong, NumberFormatException is thrown to inform the user that the conversion requires a correct input and the transformation did not happen. For example, the NumberFormatException is thrown when a numerical string is parsed to an integer, but the string contains also space.</p>
<p>As the NumberFormatException is an unchecked exception, it does not need to be declared in the throws clause of a method or constructor. However, when in doubt of input correctness, it should be handled in code using a try-catch block.</p>
<h2>NumberFormatException Example</h2>
<p>Let&#8217;s take a look at the simple example of NumberFormatException being thrown:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {
    public static void main(String args[]) {
        int orderNumber = Integer.parseInt("Order 66");
        System.out.println(orderNumber);
    }
}</code></pre>
<p>The above code will throw NumberFormatException. While pure input of string &#8220;66&#8221; is a valid input, a string with non-numerical characters like &#8220;Order 66&#8221; is unsuitable for creating a number.</p>
<pre><code class="language-java">Exception in thread "main" java.lang.NumberFormatException: For input string: "Order 66"
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.base/java.lang.Integer.parseInt(Integer.java:652)
	at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at NumberFormatExceptionExample.main(NumberFormatExceptionExample.java:6)</code></pre>
<h2>8 Different Ways How To Get NumberFormatException</h2>
<p>There are various causes for throwing NumberFormatException, and the improper conversion of invalid input mainly causes them. Here is a list of different ways how to get NumberFormatException:</p>
<p>1. Input string is empty:</p>
<pre><code class="language-java">Integer.parseInt("");</code></pre>
<p>2. Input string is null:</p>
<pre><code class="language-java">Integer.parseInt(null);</code></pre>
<p>3. Input string with non-numeric data:</p>
<p>This case has several different options why it can happen.</p>
<p>a. Input string contains space character:</p>
<pre><code class="language-java">Integer.parseInt("66 66");</code></pre>
<p>b. Input string contains non-numeric character:</p>
<pre><code class="language-java">Integer.parseInt("Sixty");</code></pre>
<p>c. Numeric input with non-numeric character in input string</p>
<pre><code class="language-java">Integer.parseInt("Catch22");</code></pre>
<p>4. Input string with inappropriate symbols in it:</p>
<pre><code class="language-java">Double.parseDouble("66,12345");</code></pre>
<p>5. Input string with leading or tailing white space</p>
<pre><code class="language-java">Integer randomExample = new Integer("  12345  ");</code></pre>
<p><em>Integer</em>, <em>Long</em>, <em>Short</em>, <em>Byte</em> throw NumberFormatException; <em>Double</em>, <em>Float</em> does not.</p>
<p>6. Mismatch of data type between input string and the target data type</p>
<pre><code class="language-java">Integer.parseInt("12.34");</code></pre>
<p>7. Input string exceeding the range of the target data type</p>
<pre><code class="language-java">Integer.parseInt("2147483648");</code></pre>
<p>The example shown above is a case of NumberFormatException upon placing a numeric input string exceeding the range of the target data type, which is in our case <em>Integer</em> class object. The maximum range for Integer class object is from -2_147_483_648 to 2_147_483_647.</p>
<h2>How to handle NumberFormatException</h2>
<p>The NumberFormatException is an unchecked exception in Java. Therefore it can be handled as any other Java exception by wrapping critical code to try-catch block.</p>
<p>Look at the following example of catching NumberFormatException with a try-catch block:</p>
<pre><code class="language-java">public class NumberFormatExceptionExample {

    public static void main(String args[]) {
        String userInput = "Order 66";
        Optional&lt;Integer&gt; orderNumber = processOrder(userInput);
        if (orderNumber.isPresent()) {
            System.out.println("Execute order " + orderNumber.get());
        } else {
            System.out.println("Unrecognized order number. Please try again.");
        }
    }

    public static Optional&lt;Integer&gt; processOrder(String userInput) {
        try {
            int order = Integer.parseInt(userInput);
            return Optional.of(order);
        } catch (NumberFormatException ex) {
            System.out.println("Order exception: Invalid user input!");
        }
        return Optional.empty();
    }

}</code></pre>
<p>Depending on the requirements of the application, take necessary action. For example, log the exception with an appropriate message or return an empty Optional object if you are using at least Java 8. Like in the example above, wrapping the code in try-catch blocks allows the program to continue execution after the code throws the exception.</p>
<p><b>Output</b>:</p>
<pre><code class="language-bash">Order exception: Invalid user input!
Unrecognized order number. Please try again.</code></pre>
<h2>Conclusion</h2>
<p>This article led us to explain what NumberFormatException and how to handle it. It also showed over seven different ways how the NumberFormatException can occur and how we can defensively take care of it.</p>
<p>Do you know NumberFormatException? In what case did it throw to you? Do you have your trick, or do you see another way <u>how to handle NumberFormatException</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/7-different-ways-how-to-get-numberformatexception-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to figure out if a character in a string is a number</title>
		<link>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/</link>
					<comments>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 03 May 2022 13:49:33 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[char]]></category>
		<category><![CDATA[Character]]></category>
		<category><![CDATA[exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[regular expression]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1301</guid>

					<description><![CDATA[This article is about multiple ways to pull a character from a string and check if it is a number. <a href="https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show how to figure out if a character in a string is a number. You might be wondering how to do it. There are multiple ways to determine if an individual or series of characters in the string classify as a number. So let&#8217;s look at various approaches for determining if the character is a number.</p>
<p><span id="more-1301"></span></p>
<h2>Using <em>Character</em> class</h2>
<p>First option is to select a character from string with help of <em>charAt()</em> method and the character position; and use <em>Character</em> class static method <em>isDigit()</em> to return <em>boolean</em> value.</p>
<pre><code class="language-java">String movie = "101 dalmatians";
System.out.println(movie);
boolean result = Character.isDigit(movie.charAt(0));
System.out.println("Is first letter number? Answer: " + result)</code></pre>
<p>The output will be:</p>
<pre><code class="language-bash">101 dalmatians
Is first letter number? true</code></pre>
<p>If we want to check if several characters are numbers, we can place the <em>isDigit()</em> method call inside the loop.</p>
<pre><code class="language-java">String movie = "101 dalmatians";
for (int i = 0; i <= movie.length() - 1; i++) {
    System.out.println(movie.charAt(i) + " -> " + Character.isDigit(movie.charAt(i)));
}</code></pre>
<p>The output of the above code will be:</p>
<pre><code class="language-bash">1 -> true
0 -> true
1 -> true
  -> false
d -> false
a -> false
l -> false
m -> false
a -> false
t -> false
i -> false
a -> false
n -> false
s -> false</code></pre>
<h2>Using Unicode check</h2>
<p>Using <em>Character</em> class static method <em>isDigit()</em> can be used on any Unicode character, not just 0-9 number range. You can use create number check at any <b>Unicode</b> character.</p>
<p>Here is an example of checking a number through a check of Unicode characters:</p>
<pre><code class="language-java">String movie = "101 dalmatians";
System.out.println(movie);
boolean char c = word.charAt(0);
boolean isDigit = (c >= '0' && c <= '9');
System.out.println(isDigit)</code></pre>
<pre><code class="language-bash">101 dalmatians
true</code></pre>
<h2>Using Regex</h2>
<p>Alternative way to using <em>Character</em> class static method <em>isDigit()</em> is to use solution based on <i>regex</i> output. However, this will require string to be instance of <em>String</em> class as we can conduct regex pattern search only on <em>String</em>.</p>
<p>Let us show you first regex pattern for searching digit in substring of length 1 on the instance <em>String</em> class named <em>word</em>:</p>
<pre><code class="language-java">word.substring(0, 1).matches("\\d")</code></pre>
<p>The alternative and equivalent version uses the regex search pattern with the search of digit range.</p>
<pre><code class="language-java">word.substring(0, 1).matches("[0-9]")</code></pre>
<p>The regex solution should be discouraged as it is an over-engineered solution. While there might be a minor performance hit, we can argue it would not affect simple coding solutions. But be aware that regex brings complexity. A solution implementing regular expression should be used with caution and with a fair amount of tests.</p>
<p><b>Note:</b> Regular expressions are very strong, but expensive tool. It is valid to use regular expressions for character check if, e.g. the first character is a digit. But performance-wise, it is also like shooting birds with cannon.</p>
<h2>Using casting</h2>
<p>The last way to check if the character in a string is a number is to use Java casting feature. We will cast string values into one of the numerical object classes. However, this is the worst way how to do it. If you find a code using casting, you should refactor it immediately.</p>
<pre><code class="language-java">public boolean isNumber(String word) {
    boolean isNumber = true;
    try {
        Integer.valueOf(word.substring(0,1));
    } catch (Exception e) {
        isNumber = false;
    }
    return isNumber;
}</code></pre>
<p>There is a lot that can go wrong with the method above. If the entering argument word is an empty string, casting will throw <em>NumberFormatException</em> and catch it. If the first character is not a digit, e.g. letter or special symbol, casting will also throw <em>NumberFormatException</em> and catch it. But if the first character is a digit, it will return true.</p>
<p>You can place any numerical object class to the code such as <em>Integer</em>, <em>Double</em>, <em>Float</em> or <em>Long</em>. But please do not! Using casting with <em>valueOf()</em> method is wrong for two reason:</p>
<ul>
<li>In general, we want to avoid throwing <em>Exceptions</em>, checked or unchecked, as they slow the program and have tremendous performance hit.</li>
<li>Second reason, we can see above at least 3 different ways which provide shorter, more effective and readable way for solving the same problem.</li>
</ul>
<h2>Conclusion</h2>
<p>In the article, we have demonstrated four different ways to find out if the single character or characters from a string is a number or not. The solutions ranged from best to worst, from easiest to most cumbersome. Use as much as possible the first option which use <em>Character</em> class static method <em>isDigit()</em> for determining if the character is a string. Using <em>isDigit()</em> method is, without instantiation of any variables, the most effective and readable solution.</p>
<p>I hope you learned something new and had fun. Thanks for the reading. And if you have any tricks or know a better way <u>how to find out if the character is a string</u>, let us know in the comments below. We would like to hear your ideas.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-figure-out-if-a-character-in-a-string-is-a-number/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How To Turn Number To String With Padded Space or Zeroes</title>
		<link>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/</link>
					<comments>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Apr 2022 14:59:52 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[Formatter]]></category>
		<category><![CDATA[good practice]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[String]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1293</guid>

					<description><![CDATA[Article about a simple solution to turning numbers into specific length <em>String</em> with padded space. <a href="https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show us how to turn numbers into the <em>String</em> with padded space or numbers.</p>
<p><span id="more-1293"></span></p>
<h2>Introduction</h2>
<p>I have been recently doing code review on other developer pull-request when I found the piece of code below:</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    String documentVersion = "";
    if (version > 999) {
        throw new IllegalStateException("Version number " + version + " is too large.");
    } else if (version > 99) {
        documentVersion += version;
    } else if (version > 9) {
        documentVersion += "0" + version;
    } else {
        documentVersion += "00" + version;
    }

    return "DOCUMENT_VERSION_" + documentVersion;
}</code></pre>
<p>As you can immediately see, the code is bad and can be surely rewritten to something more simple. Creating a string from a number can not be so declarative, right? There needs to be a simpler way how to do it. And surely it can. Like many other general-purpose programming languages, Java has multiple libraries and functions for processing text. <em>String</em> class itself has a static method <em>format()</em> which can be fully utilized on the text changes like this.</p>
<h2>Java String format()</h2>
<p>The Java <em>String</em> class <em>format()</em> method returns the formatted string. Let&#8217;s look little bit on parameters of <em>format()</em> method.</p>
<h3>String.format() signature</h3>
<p>There are two type of <em>String format()</em> method:</p>
<pre><code class="language-java">public static String format(String format, Object... args)</code></pre>
<p>and</p>
<pre><code class="language-java">public static String format(Locale locale, String format, Object... args)  </code></pre>
<p>Therefore, method parameters are described as:</p>
<ul>
<li><b>locale</b> is specifies the locale to be applied on the format() method.</li>
<li><b>format</b> is format of the string.</li>
<li><b>args</b> represent arguments for the format string. It may be zero or more.</li>
</ul>
<p><em>format()</em> method returns new <em>String</em>. However, it is also good to be prepared for possibility of two unchecked exception:</p>
<ul>
<li><b>NullPointerException</b> is thrown if <b>format</b> is null.</li>
<li><b>IllegalFormatException</b> is thrown if <b>format</b> is illegal or incompatible.</li>
</ul>
<h3>String.format() internal implementation</h3>
<p>In reality, <em>String.format()</em> method allows usage of multiple <em>Object</em> arguments because internal implementation use nothing else than new instance of <em><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html" title="Java 8 Docs - Formatter Class" target="_blank" rel="nofollow noopener">Formatter</a></em> class.</p>
<pre><code class="language-java">public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}</code></pre>
<p>Usage of quiet <em>Formatter</em> class explains why we can take multiple arguments depending on the number of elements we want to format inside the string. <em>Formatter</em> class can use several different option of &#8220;%&#8221; character combination in order to define string formatting. In the table below are all options explained:</p>
<table>
<thead>
<tr>
<th>Formatter Argument</th>
<th>Data Type</th>
<th>Output</th>
</tr>
</thead>
<tbody>
<tr>
<td>%a %A</td>
<td>floating point (except BigDecimal)</td>
<td>Returns Hex output of floating point number.</td>
</tr>
<tr>
<td>%b</td>
<td>Any type</td>
<td>&#8220;true&#8221; if non-null, &#8220;false&#8221; if null</td>
</tr>
<tr>
<td>%c</td>
<td>character</td>
<td>Unicode character</td>
</tr>
<tr>
<td>%d</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Decimal Integer</td>
</tr>
<tr>
<td>%e</td>
<td>floating point</td>
<td>decimal number in scientific notation</td>
</tr>
<tr>
<td>%f</td>
<td>floating point</td>
<td>decimal number</td>
</tr>
<tr>
<td>%g</td>
<td>floating point</td>
<td>decimal number, possibly in scientific notation depending on the precision and value.</td>
</tr>
<tr>
<td>%h</td>
<td>any type</td>
<td>Hex String of value from hashCode() method.</td>
</tr>
<tr>
<td>%n</td>
<td>none</td>
<td>Platform-specific line separator.</td>
</tr>
<tr>
<td>%o</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Octal number</td>
</tr>
<tr>
<td>%s</td>
<td>any type</td>
<td>String value</td>
</tr>
<tr>
<td>%t</td>
<td>Date/Time (incl. long, Calendar, Date and TemporalAccessor)</td>
<td>%t is the prefix for Date/Time conversions. More formatting flags are needed after this. See Date/Time conversion below.</td>
</tr>
<tr>
<td>%x</td>
<td>integer (incl. byte, short, int, long, bigint)</td>
<td>Hex string.</td>
</tr>
</tbody>
</table>
<h2><em>format()</em> examples</h2>
<p>Let us show you few tricks with <em>format()</em></p>
<pre><code class="language-bash">System.out.println(String.format("%d", 100)); // Integer
System.out.println(String.format("%s", "Anna Smith")); // String
System.out.println(String.format("%f", 42.42)); // Float
System.out.println(String.format("%x", 100)); // Hexadecimal
System.out.println(String.format("%c", 'a')); // Char
System.out.println("-----");
System.out.println(String.format("number with text: %d", 100)); // number with other text
System.out.println(String.format("%f", 42.12345)); // prints floating number
System.out.println(String.format("%10.10f", 42.12345)); // prints 10 digits for fractions padded with 0
System.out.println("-----");
System.out.println(String.format("|<-%10d->|", 222)); // Align right, padding with empty space
System.out.println(String.format("|<-%-10d->|", 555)); // Align left, padding with empty space
System.out.println(String.format("|<-% d->|", 777)); // Single space between % and conversion type is allowed
System.out.println(String.format("|<-%010d->|", 999)); // Filling space with zeros</code></pre>
<pre><code class="language-java">100
Anna Smith
42.420000
64
a
-----
number with text: 100
42.123450
42.1234500000
-----
|<-       222->|
|<-555       ->|
|<- 777->|
|<-0000000999->|</code></pre>
<h2>Using <em>format()</em> to turn number into formatted string</h2>
<p>To take for first exemplary code from code review, all what we needed to do in <code>getDocumentVersion()</code> method was to place custom format of string into the <em>String</em> class <em>format</em> method.</p>
<pre><code class="language-java">private static final String DOCUMENT_VERSION = "document_version-";

public String getDocumentVersion(int version) {
    return String.format(DOCUMENT_VERSION + "%03d", revisionNumber);
}</code></pre>
<p>If we place number 1 into the method <code>getDocumentVersion()</code> we will get the same result as boilerplate code from code review:</p>
<p><b>Output</b></p>
<pre><code class="language-bash">document_version-001</code></pre>
<p>We can still quickly write some custom code to test our beliefs. But be thorough and do not forget edge cases as zero and negative numbers.</p>
<pre><code class="language-java">System.out.println(String.format("%03d", 999));
System.out.println(String.format("%03d", 99));
System.out.println(String.format("%03d", 9));
System.out.println(String.format("%03d", 0));
System.out.println(String.format("%03d", -9));</code></pre>
<pre><code class="language-java">999
099
009
000
-09</code></pre>
<p>As you can notice <em>format()</em> takes negative number into account its length with minus sign.</p>
<p><b>Note</b> : If you have any crazy idea how to use <em>format()</em> method, let us know in comments below.</p>
<h2>Conclusion</h2>
<p>This article showed us how to turn a number into a string with a specific length where additional space is padded.</p>
<p>Did you find the <em>String.format()</em> method useful? Do you have your trick, or do you know another way <u>how to turn a number into a string of specific length</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-turn-number-to-string-with-padded-space-or-zeroes/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Flattening Stream Collections in Java</title>
		<link>https://codepills.com/flattening-stream-collections-in-java/</link>
					<comments>https://codepills.com/flattening-stream-collections-in-java/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Tue, 01 Mar 2022 15:24:06 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[collections]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1289</guid>

					<description><![CDATA[This article is about flattening the list of element list with use of Java 8 stream feature <em>flatMap</em> and <em>forEach</em> <a href="https://codepills.com/flattening-stream-collections-in-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article is about Java 8 stream feature <em>flatMap</em>. If we have a <code>List&lt;List&lt;Object&gt;&gt;</code>, how can we turn the list of lists into a single list that contains all the elements from the lists in the same streamflow using the features of Java 8?</p>
<p><span id="more-1289"></span></p>
<h2>Introduction</h2>
<p>The answer is simply to use <em>flatMap</em> to flatten the lists of elements into one coherent list of the same elements. <code>flatMap</code> converts lists to streams in a single Stream and then collects the result into a list.</p>
<p>The best explanation will probably show the example of <em>flatMap</em> in action.</p>
<h2>Flattening the List with <em>flatMap</em> &#8211; Simple Example</h2>
<p>Let&#8217;s start with a simple example and continue with a more complex case later in the article. Our simple example will have a list of list with <em>String</em> elements. Each inner list contains a list of <em>String</em> elements which is a tuplet denoting at the first position the level of list and in the second position the overall total position of <em>String</em> element.</p>
<pre><code class="language-java">List&lt;List&lt;String&gt;&gt; nestedList = asList(
    asList("1-1", "1-2", "1-3"),
    asList("2-4", "2-5", "2-6", "2-7", "2-8"),
    asList("3-9", "3-10")
);</code></pre>
<p>We take this simple list above, and we will push it to our simple flattening method <em>flatteningTheListOfLists(List&lt;List&lt;String&gt;&gt; list)</em>.</p>
<pre><code class="language-java">public  List&lt;String&gt; flattenListOfLists(List&lt;List&lt;String&gt;&gt; list) {
    return list.stream()
               .flatMap(Collection::stream)
               .collect(Collectors.toList());
}</code></pre>
<p>As a result, we will get a list with all the <em>String</em> elements in one list.</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_simpleScenario() {
     List&lt;String&gt; flattenedList = flattenListOfLists(nestedList);

    assertNotNull(flattenedList);
    assertEquals(10, flattenedList.size());

    for (String element : flattenedList) {
        System.out.print(element);
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">1-1, 1-2, 1-3, 2-4, 2-5, 2-6, 2-7, 2-8, 3-9, 3-10, </code></pre>
<h2>Flattening the List with <em>flatMap</em> &#8211; Realistic Scenario</h2>
<p>Instead of a simple play with a happy case scenario, hypothetically, let&#8217;s have a more advanced system where we will generate the list of objects directly in the stream. We will have a list of employees with their job position. And we would like to collect all their possible career options for employees above <i>junior engineer</i> level into a single list of all career options across all employees through a department. The resulting list will give us a list of possible combinations of employee promotions above the junior level.</p>
<p>Here is an example of <em>Employee</em> class:</p>
<pre><code class="language-java">public class Employee {

    private Position position;

    public Employee(Position position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }
}</code></pre>
<p>And here is an example of <em>Employee</em> and <em>Position</em> class:</p>
<pre><code class="language-java">public class Employee {

    private final String name;
    private final Position position;

    public Employee(String name, Position position) {
        this.name = name;
        this.position = position;
    }

    public Position getPosition() {
        return position;
    }

}</code></pre>
<pre><code class="language-java">public enum Position {

    JUNIOR_ENGINEER(1),
    SENIOR_ENGINEER(2),
    SOFTWARE_ARCHITECT(3),
    ENGINEERING_MANAGER(4);

    private final int level;

    Position(int level) {
        this.level = level;
    }

    public int getLevel() {
        return this.level;
    }
}</code></pre>
<p>In order to get the list of all possible career options for all employees above <i>junior level</i> we would create for example something like <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> where class <em>employee</em> property is a list of employees of <em>Employee</em> class. <code>getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees)</code> method will go through all the employees, filter employees from the list with level above junior level and create a list of possible career options for that specific employee. All the career options should be than pushed to <code>List</code> and outputted from stream to <code>List</code> collector.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel())) // This is bad practice and will not work
                    .collect(Collectors.toList());
}</code></pre>
<p>Example of <i>createPossibleCareerOptions()</i>:</p>
<pre><code class="language-java">public List&lt;Position&gt; createPossibleCareerOptions(int level) {
    return Arrays.stream(Position.values())
                 .filter(position -> position.getLevel() > level)
                 .collect(Collectors.toList());
}</code></pre>
<p>As we can see above, we mapped an employee to the list of her/his career options. But we want to collect list of all possibilities, not list of lists. Therefore, the code above does not work while stream <code>map</code> function maps <code>employee</code> instance into the list, but stream collector can not collect list of position list into the single list.</p>
<p>To make this code work, we need to introduce a consequent function in a stream that will flatten the list&#8217;s mapping into one stream. We need to place <code>flatMap</code> function for flattening the stream of list of positions into single steam positions for our Java stream.</p>
<pre><code class="language-java">public List&lt;Position&gt; getAllCareerOptionsAboveJunior(List&lt;Employee&gt; employees) {
    return employees.stream()
                    .filter(employee -> employee.getPosition().getLevel() > Position.JUNIOR_ENGINEER.getLevel())
                    .map(employee -> createPossibleCareerOptions(employee.getPosition().getLevel()))
                    .flatMap(List::stream) // I need to flatten list streams into one stream
                    .collect(Collectors.toList());
}</code></pre>
<p>Finally, let&#8217;s put all parts together and try the solution on the list of employees.</p>
<pre><code class="language-java">List&lt;Employee&gt; employees = asList(
        new Employee("Mark", Position.JUNIOR_ENGINEER),
        new Employee("Thomas", Position.SENIOR_ENGINEER),
        new Employee("Janet", Position.SOFTWARE_ARCHITECT),
        new Employee("Percy", Position.ENGINEERING_MANAGER)
);</code></pre>
<p>We can test the result with the test written below:</p>
<pre><code class="language-java">@Test
public void testFlatteningTheListOfLists_realisticScenario() {
    List&lt;Position&gt; allPossiblePromotions = getAllCareerOptionsAboveJunior(employees);

    assertNotNull(allPossiblePromotions);
    assertEquals(3, allPossiblePromotions.size());

    for (Position position : allPossiblePromotions) {
        System.out.print(position + ", ");
    }
}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-bash">SOFTWARE_ARCHITECT, ENGINEERING_MANAGER, ENGINEERING_MANAGER, </code></pre>
<p><b>Note</b> : If you have better idea for <code>Map</code> sorting, let me know in comments below.</p>
<h2>Flattening the <em>List</em> With <em>forEach</em></h2>
<p>To flatten this nested collection into a list of the same elements, we can also use <em>forEach</em> together with a Java 8 method reference. However, the solution with <em>forEach</em> might be discouraged by some developers as it needs to create a new reference on the list with results before it returns the complete results. Thus, creating the result variable will make the code more cumbersome and brittle. And while it might be suitable for small lists and simple applications, it brings pointlessly more complexity with its wrapping code for more complex scenarios as described above. On the contrary, it provides no advantage in the form of, for example, code readability.</p>
<p>Neither to say, let&#8217;s take a look at the option of flattening the stream of element&#8217;s list with the help of <em>forEach</em> method.</p>
<pre><code class="language-java">public List&lt;String&gt; useOfForEach(Stream&lt;List&lt;String&gt;&gt; streamOfLists) {
    List&lt;String&gt; result = new ArrayList<>();
    streamOfLists.forEach(result::addAll);
    return result;
}</code></pre>
<p>If we use the same list of simple <em>String</em> elements as for happy case scenario with <em>flatMap</em> we will get the same results.</p>
<h2>Conclusion</h2>
<p>We have seen in this article how to use a Java 8 Stream method <em>flatMap</em> first on a simple example and then on a more realistic scenario. We have also seen the option of flattening the stream with <em>forEach</em>. However, use of <em>forEach</em> might be discouraged on more realistic scenario when used on stream of <i>Objects</i> which generates the lists.</p>
<p>Did you find use of <em>flatMap</em> hard? Do you have your trick or you know another way <u>how to use <em>flatMap</em></u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/java-basics/java8/" title="Tutorial JVM - Java Basics - Java 8" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/flattening-stream-collections-in-java/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Selenium &#8211; remove html element from the DOM</title>
		<link>https://codepills.com/selenium-remove-html-element-from-the-dom/</link>
					<comments>https://codepills.com/selenium-remove-html-element-from-the-dom/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Mon, 03 Jan 2022 08:58:53 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[drivers]]></category>
		<category><![CDATA[finviz.com]]></category>
		<category><![CDATA[Firefox]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[stocks]]></category>
		<category><![CDATA[time-series]]></category>
		<category><![CDATA[web-scrapper]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1280</guid>

					<description><![CDATA[This article will show you how to remove elements from <b>HTML DOM</b> (Document Object Model) when using automated web-browser framework <b>Selenium</b>. <a href="https://codepills.com/selenium-remove-html-element-from-the-dom/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show you how to remove elements from <b>HTML DOM</b> (Document Object Model) when using automated web-browser framework <b>Selenium</b>. If you want to remove anything you do not want on your site during web-scraping, you came to the right Selenium tutorial.</p>
<p><span id="more-1280"></span></p>
<h2>Introduction</h2>
<p>Let&#8217;s start with a practical example of removing elements from DOM. Imagine scrapping a website with <b>Selenium</b> and taking a screenshot of the page. However, the timed modal window will unannounced pop up when Selenium&#8217;s driver spin the browser window. So it is probably a good idea to remove the window before taking a picture in such a case.</p>
<p>When scrapping sites, removing excessive advertisement and disturbing elements is hard enough. But pop-up windows in the wrong moments are an overall user experience nowadays on many sites and blogs.</p>
<p>For example, we want to scrap stock time-series from famous sites like finviz.com. Unfortunately, after the first few seconds on the page, the cookies modal window pop-up and block the stock graph. Therefore, I will need to remove the cookie allowance modal window to take a clear screenshot.</p>
<div id="attachment_1281" style="width: 650px" class="wp-caption alignnone"><img loading="lazy" decoding="async" aria-describedby="caption-attachment-1281" src="https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-1024x768.png" alt="Finviz.com cookie popup window" width="640" height="480" class="size-large wp-image-1281" srcset="https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-1024x768.png 1024w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-300x225.png 300w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup-768x576.png 768w, https://codepills.com/wp-content/uploads/2022/01/finviz_cookie_popup.png 1098w" sizes="(max-width: 640px) 100vw, 640px" /><p id="caption-attachment-1281" class="wp-caption-text">Finviz.com cookie popup window</p></div>
<p>Let me show you two different ways to remove elements from Selenium&#8217;s HTML DOM. One way will be about eliminating parts that load with the page load and can be removed immediately. The second way will require calling <i>WebDriverWait</i> instance, and the way will be used for elements that pop up or load to page letter.</p>
<p>However, both options do not remove the element from the DOM. Instead, they hide it and make it invisible in the Selenium web driver.</p>
<h2>Remove elements from Selenium&#8217;s DOM without waiting</h2>
<pre><code class="language-java">FirefoxOptions options = new FirefoxOptions();
options.addArguments("-width=1920");
options.addArguments("-height=1080");
FirefoxDriver driver = new FirefoxDriver(options);

String stock = "T"; // AT&T Inc.
driver.get("https://finviz.com/quote.ashx?t=" + stock + "&ty=c&ta=1&p=d");

driver.executeScript("return document.getElementsByClassName('snapshot-table2')[0].remove();");</code></pre>
<p>If we look at the code, it might look straightforward. But I will go through it briefly. Initially, we set options for our Selenium Driver. Then, we pick Firefox as Selenium driver and put options (browser windows dimensions) into the driver itself.</p>
<p>After setting drivers options and instantiating Firefox drivers, we are clear to the call page in Firefox. We call finviz.com stock page for AT&#038;T Inc. company. The page which is loaded is immediately available for changes. If we want to remove any element we do not like, we can call script execution upon the loaded HTML DOM. We call executed script, which will remove the first  (0-th) element of the specific class name. It will be the first data table under the stock time-series graph.</p>
<p><b>Note</b> : If you have better idea for elements removal from Selenium&#8217;s HTML DOM, let me know in comments below.</p>
<h2>Remove elements from Selenium&#8217;s DOM with waiting</h2>
<pre><code class="language-java">FirefoxOptions options = new FirefoxOptions();
options.addArguments("-width=1920");
options.addArguments("-height=1080");
FirefoxDriver driver = new FirefoxDriver(options);

String stock = "T"; // AT&T Inc.
driver.get("https://finviz.com/quote.ashx?t=" + stock + "&ty=c&ta=1&p=d");

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement cookieWindow = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("ConsentManager__Overlay-np32r2-0")));
driver.executeScript("return arguments[0].remove();", cookieWindow);</code></pre>
<p>The code above looks straightforward also. Initially, we set options for our Selenium Driver and picked Firefox as Selenium driver.</p>
<p>After setting drivers options and instantiating Firefox driver, we are clear to the call page in Firefox. We call the finviz.com stock page for AT&#038;T Inc. company and wait for 10 seconds or until HTML DOM does not contain an element with a specific class name. If it does, we will execute the script upon it, which will remove the first (the 0-th) element when it is found. Action means removing the whole pop-up modal window that appeared in the first 10 seconds of finviz.com page duration.</p>
<p>Class name &#8220;ConsentManager__Overlay-np32r2-0&#8221; is class name of pop-up cookie modal window. However, this class name might and surely will change in the future. So I would not rely on it for 100%. But for now, it serves our purpose.</p>
<h2>Conclusion</h2>
<p>This article has shown how remove elements from <b>HTML DOM</b> when using automated web-browser framework <b>Selenium</b>. Articles provide two different ways how to remove element on the page. Elements which load with page load can be removed immediately, without calling <i>WebDriverWait</i> instance. However, elements which pop-up or load to page letter needs to be removed with help of <i>WebDriverWait</i> instance.</p>
<p>However, if you look better, code snippets in the article can help you to build your Selenium web-scrapper 😉</p>
<p>Did you find element removal easy? Do you have your trick or know another way <u>how to remove elements from HTML DOM in Selenium</u>? Let us know in the comments below the article. We would like to hear your ideas and stories, and you might help others as well.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/selenium-remove-html-element-from-the-dom/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to print current project classpath</title>
		<link>https://codepills.com/how-to-print-current-project-classpath/</link>
					<comments>https://codepills.com/how-to-print-current-project-classpath/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 03 Oct 2021 13:44:55 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[classpath]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JVM]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1259</guid>

					<description><![CDATA[This article is a short explanation of a classpath and a single line of Java code that will help you print out your classpath. <a href="https://codepills.com/how-to-print-current-project-classpath/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>Imagine you want to figure out what is the path to your Java compiled classes. For that, you will need to print the classpath. This article is a short explanation of what a classpath is and a single line of Java code that will help you print out your classpath.</p>
<p><span id="more-1259"></span></p>
<h2>What is Java classpath?</h2>
<p>If we want to be wordy, <b>classpath</b> is the path where the Java Virtual Machine looks for user-defined classes, packages, and resources in Java programs. However, plain and straightforward, <b>classpath</b> is the route where the Java Virtual Machine will know where to find your compiled class.</p>
<p>Think of classpath as Java&#8217;s version of PATH environment variables &#8211; OSes search for executable files on the system environment PATH, Java searches for classes and packages on the classpath.</p>
<p>It would generally be impractical to have the JVM look through every folder on your machine. So you have to provide the JVM with a list of places where to look. Then, when we place folders and jar files on the classpath, we can automatically look up classes.</p>
<h2>How to print classpath?</h2>
<p>In Java, we can use a single line of code to print out the current project classpath. The only issue is with the system based classpath separator. On Unix based systems (Mac OS, CentOS, etc.), the colon character <code>:</code> is the classpath separator. However, on Windows, the separator is the semicolon <code>;</code>.</p>
<p>To print classpath at Unix based systems use:</p>
<pre><code class="language-java">System.out.println(System.getProperty("java.class.path").replace(':', '\n'));</code></pre>
<p>To print classpath at Windows use:</p>
<pre><code class="language-java">System.out.println(System.getProperty("java.class.path").replace(';', '\n'));</code></pre>
<p><b>Output</b></p>
<p>The code will work like a charm in new versions of Java (8, 11, &#8230;). However, the Java code snippet will also print library dependencies.</p>
<p>On Windows, the output can look something like the following example:</p>
<pre><code class="language-bash">
C:\DEV\programming\interview-preparation\trees\target\test-classes
C:\DEV\programming\interview-preparation\trees\target\classes
C:\Users\computer_user\.m2\repository\junit\junit\4.13.1\junit-4.13.1.jar
C:\Users\computer_user\.m2\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar
C:\Users\computer_user\.m2\repository\org\projectlombok\lombok\1.18.12\lombok-1.18.12.jar
...
</code></pre>
<p><b>Note</b>: If you have a better idea for printing classpath, let us know in the comments below.</p>
<h2>Conclusion</h2>
<p>Concisely, this article summarized what the classpath is and how to print classpath in your current Java project.</p>
<p>Did you find printing classpath easy? Do you have your trick or know another way how to print classpath? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-print-current-project-classpath/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Verify method was called n-times with Mockito</title>
		<link>https://codepills.com/verify-method-was-called-n-times-with-mockito/</link>
					<comments>https://codepills.com/verify-method-was-called-n-times-with-mockito/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 03 Apr 2021 15:31:10 +0000</pubDate>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[testing]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1206</guid>

					<description><![CDATA[Mockito Verify example for n-times calls using various verification modes. <a href="https://codepills.com/verify-method-was-called-n-times-with-mockito/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This short article will explain how to <strong>verify</strong> that Mock&#8217; method was called n-times with the help of <strong>Mockito testing framework</strong>.</p>
<p><span id="more-1206"></span></p>
<h2>Introduction</h2>
<p>We often encounter the problem during testing that we do not care about the data correctness, as much as we care about correct algorithm flow. In this situations, we want to check if specific methods were hit and executed. Sometimes we need to go deeper and seek an answer on how often these methods were called or verify that the methods called at all.</p>
<p>The necessary method, which will help us in our testing quest, is called <a href="https://javadoc.io/static/org.mockito/mockito-core/3.9.0/org/mockito/Mockito.html#exact_verification" title="Mockito verify" target="_blank" rel="nofollow noopener">verify()</a> and is part of <strong>Mockito testing framework</strong>.</p>
<h2>Mockito verify verification options</h2>
<pre><code class="language-java">public static <T> T verify(T mock, VerificationMode mode)</code></pre>
<p><i>mock</i> is object of type <code>T</code> you are placing into the <code>verify()</code> method for verification. As a second method argument is <code>VerificationMode</code> <i>mode</i> variable, which describes how the <i>mock</i> should be verified. Possible verification modes are:</p>
<pre><code class="language-java">verify(mock, times(5)).someMethod("was called exactly five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeast(5)).someMethod("was called at least five times");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atMost(5)).someMethod("was called at most five times");</code></pre>
<p>There is also one special <code>VerificationMode</code> mode called <code>only()</code>. This mode verifies that no other method was called on the mock so far.</p>
<pre><code class="language-java">verify(mock, only()).someMethod("only someMethod was called");</code></pre>
<h2>Mockito verify verification modes in action </h2>
<p>In order to test individual verification modes, we will write a simple test. For testing purposes it will consist from two classes. (Both are inner private classes for <i>MockitoVerifyTest.java</i>.) First will be a fake class <code>Account</code> which trough dependency injection will use second class <code>Counter</code>. <code>Counter</code> class will be used as a <code>Mock</code> in our test.</p>
<p>Here is a <code>Counter</code> class:</p>
<pre><code class="language-java">private class Counter {

    private int counter;

    public Counter() {
        this.counter = 0;
    }

    public void increment() {
        this.counter++;
    }

    public void reset() {
        this.counter = 0;
    }

    public int getCount() {
        return this.counter;
    }
}</code></pre>
<p>And here is the <code>Account</code> class:</p>
<pre><code class="language-java">private class Account {

    private Counter counter;

    public Account(Counter counter) {
        this.counter = counter;
    }

    public void incrementCounter() {
        this.counter.increment();
    }

    public void resetCounter() {
        this.counter.reset();
    }

    public int getCounterValue() {
        return this.counter.getCount();
    }
}</code></pre>
<p>And finally, here is an exemplary test where you can see usage of individual verification modes:</p>
<pre><code class="language-java">import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@RunWith(MockitoJUnitRunner.class)
public class MockitoVerifyTest {

    @Mock
    Counter counter;

    @Test
    public void testMockitoVerifyMethodCalls() {

        Account account = new Account(counter);

        // Verification using only() and atLeastOnce()
        account.incrementCounter();
        Mockito.verify(counter, only()).increment();
        Mockito.verify(counter, atLeastOnce()).increment();

        // Verification using times(X)
        for (int i = 0; i < 4; i++) {
            account.incrementCounter();
        }
        Mockito.verify(counter, times(5)).increment();

        // Verification using atLeast(X), atMost(X), never()
        for (int i = 0; i < 5; i++) {
            account.incrementCounter();
        }
        Mockito.verify(counter, atLeast(5)).increment();
        Mockito.verify(counter, atMost(10)).increment();
        Mockito.verify(counter, never()).getCount();
    }
}</code></pre>
<p>Let's discuss little but example code.</p>
<pre><code class="language-java">Account account = new Account(counter);

// Verification using only() and atLeastOnce()
account.incrementCounter();
Mockito.verify(counter, only()).increment();
Mockito.verify(counter, atLeastOnce()).increment();</code></pre>
<p>First, we will create new instance of <code>Account</code> class which trough dependency injection is injected with Mock instance of our <code>Counter</code> class.</p>
<p>As first we verify that there was no method, except <i>increment()</i> method, has been called on our mock at all. And as second verification, we will check that it was called at least once,</p>
<pre><code class="language-java">for (int i = 0; i < 4; i++) {
    account.incrementCounter();
}
Mockito.verify(counter, times(5)).increment();</code></pre>
<p>Now we call <i>incrementCounter()</i> method four more times, remember we already called it once, and we will check that it was mock method injected to instance was called <b>exactly</b> five times.</p>
<pre><code class="language-java">for (int i = 0; i < 5; i++) {
    account.incrementCounter();
}
Mockito.verify(counter, atLeast(5)).increment();
Mockito.verify(counter, atMost(10)).increment();
Mockito.verify(counter, never()).getCount();</code></pre>
<p>In the last section, we are incrementing the counter again five more times, and now we are checking if it was called <b>at least</b> five times and <b>at most</b> ten times.</p>
<p>On the last line we are checking method call for Mock' <i>getCount()</i> method that was <b>never</b> called.</p>
<h2>Conclusion</h2>
<p>This article contains a straightforward test on which we have demonstrated how to use Mockito <code>verify</code> method for mock' method call verification.</p>
<p>As always, you can find all our examples on our <a href="https://github.com/codekopf/tutorials-jvm/tree/master/testing-modules/mockito/" title="Tutorial JVM - Testing modules - Mockito" target="_blank" rel="nofollow noopener">GitHub project</a>!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/verify-method-was-called-n-times-with-mockito/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
