<?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>CodePills.com</title>
	<atom:link href="https://codepills.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sat, 23 Mar 2024 12:23:55 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to connect to an EC2 instance over SSH</title>
		<link>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/</link>
					<comments>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 01 Mar 2024 09:10:48 +0000</pubDate>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Amazon Web Services]]></category>
		<category><![CDATA[AWS]]></category>
		<category><![CDATA[EC2]]></category>
		<category><![CDATA[EC2 instance]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[PuTTY]]></category>
		<category><![CDATA[PuTTYgen]]></category>
		<category><![CDATA[remote access]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[SSH]]></category>
		<category><![CDATA[SSH client]]></category>
		<category><![CDATA[windows]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1412</guid>

					<description><![CDATA[The article outlines connecting to an Amazon EC2 instance via SSH, detailing prerequisites and steps for Unix-based systems as well as Windows users, including PuTTY private key conversion. <a href="https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article is a simple guide detailing the prerequisites and step-by-step procedures for connecting to EC2 instances via SSH. It covers Unix-based systems and Windows users, including the conversion of private key files for PuTTY.</p>
<p><span id="more-1412"></span></p>
<h2>Introduction</h2>
<p>SSH (Secure Shell) is a popular, secure protocol for remote access to servers and other network devices. When you launch an EC2 instance, you can connect to it using SSH to manage the server, install and update software, configure settings, and perform other administrative tasks.</p>
<ul>
<li id="prerequisites">Prerequisites</li>
<li id="connecting-over-unix-based-systems">Connecting over Unix-based systems</li>
<li id="connecting-over-windows">Connecting over Windows</li>
</ul>
<h2 id="prerequisites">Prerequisites</h2>
<p>Before you can connect to an EC2 instance over SSH, you need the following:</p>
<ul>
<li>Running EC2 instance and accessible over the network.</li>
<li>The EC2 instance&#8217;s IP address or public DNS.</li>
<li>The appropriate security group configured to allow SSH access (port 22) from your IP address or network.</li>
<li>The private key file (.pem) corresponding to the key pair used when launching the instance.</li>
</ul>
<p>Remember to keep your private key file secure and not share it with anyone. It is the key to accessing your EC2 instance.</p>
<p>If you encounter any issues while connecting, double-check that your instance is running, that the security group allows SSH access from your IP address, or that you are using the correct private key file.</p>
<h2 id="connecting-over-unix-based-systems">Connecting over Unix-based systems</h2>
<p>To connect to your EC2 instance via SSH at Unix-based systems like Linux, macOS, or others, follow these steps:</p>
<h3>Locate the private key file</h3>
<p>Find the private key file (.pem) you downloaded when you created the EC2 instance.</p>
<p>Make sure you have the correct permissions to use the private key file. On Linux or macOS, you can set the permissions using the command:</p>
<pre><code class="language-bash">chmod 400 /path/to/your/private-key.pem</code></pre>
<h3>Connect to the EC2 instance using SSH</h3>
<p>Open a terminal or command prompt and use the `ssh` command to connect to your EC2 instance:</p>
<pre><code class="language-bash">ssh -i /path/to/your/private-key.pem ec2-user@&lt;public-dns-or-ip&gt;</code></pre>
<ul>
<li>Replace <code>/path/to/your/private-key.pem</code> with the real path to your private key file.</li>
<li>Replace <code>&lt;public-dns-or-ip&gt;</code> with the public DNS or IP address of your EC2 instance.</li>
<li>If you&#8217;re using a different username than <b>ec2-user</b> (e.g., for Ubuntu instances, it&#8217;s usually <b>ubuntu</b>), modify the command accordingly.</li>
</ul>
<p>Here&#8217;s an example of the SSH command:</p>
<pre><code class="language-bash"> ssh -i ~/Downloads/my-key-pair.pem ec2-user@ec2-1-25-67-980.us-west-2.compute.amazonaws.com</code></pre>
<h3>Accept the server&#8217;s host key</h3>
<p>If it&#8217;s your first time connecting to the instance, the server may prompt you to accept its host key. Type <i>yes</i> and press Enter to continue.</p>
<h3>Connection to EC2 instance</h3>
<p>Success! You should now have successfully connected to your EC2 instance via SSH.</p>
<h2 id="connecting-over-windows">Connecting over Windows</h2>
<p>If you&#8217;re using Windows and don&#8217;t have the <code>ssh</code> command available, you can use an SSH client like PuTTY:</p>
<ul>
<li>First, convert your private key file (.pem) to a format compatible with PuTTY (.ppk) using PuTTYgen. If you do not know how, just <a href="#generating_a_ppk_file_from_a_pem_file">check the section below</a>.</li>
<li>Open PuTTY and enter the public IPv4 DNS or IP address of your EC2 instance in the <i>&#8220;Host Name (or IP address)&#8221;</i> field. Keep <i>&#8220;Connection type&#8221;</i> as <i>&#8220;SSH&#8221;</i>.</li>
<li>From the <i>&#8220;Connection&#8221;</i> category in left tree navigation, select <i>&#8220;SSH -> Auth&#8221;</i> and click on <i>&#8220;Credentials&#8221;</i>.</li>
<li>For <i>&#8220;Private key file for authentication&#8221;</i> click on <i>&#8220;Browse&#8221;</i> and select the private key file (.ppk).</li>
<li>Click on <i>&#8220;Open&#8221;</i> to initiate the SSH connection. At <i>&#8220;Putty Security Alert&#8221;</i>, click <i>&#8220;Yes&#8221;</i> to accept the server&#8217;s host key.</li>
</ul>
<h3 id="generating_a_ppk_file_from_a_pem_file">Generating a .ppk file from a .pem file</h3>
<p>To convert your private key file (.pem) to a .ppk file for use with PuTTY, follow these steps:</p>
<ul>
<li>Open PuTTY Key Generator (PuTTYgen) and click on <i>&#8220;Load&#8221;</i> to select your private key file (.pem).</li>
<li>Click on <i>&#8220;Save private key&#8221;</i> to convert the key to PuTTY&#8217;s .ppk format and save it to a location of your choice.</li>
<li>You can now connect the converted .ppk file with PuTTY to your EC2 instance.</li>
</ul>
<h2>Conclusion</h2>
<p>This article has shown how to connect to an Amazon EC2 instance over SSH. Following the steps outlined above, you can securely access your EC2 instance and manage it remotely using SSH.</p>
<p>Be sure to store your private key file securely and avoid sharing it with others, as it serves as the gateway to accessing your Amazon EC2 instance.</p>
<p>If you face any connection issues, verify that your instance is operational, that your security group permits SSH access from your IP address, and that you employ the correct private key file.</p>
<p>Did you find connecting to your EC2 instance over SSH easy? Do you have tips or another way to connect to an EC2 instance? Let us know in the comments below. We&#8217;d love to hear your ideas and experiences.</p>
<p>Thanks for reading!</p>
<p>Like this article? Please share it with your friends and help us grow. Happy coding! 😊</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-connect-to-an-ec2-instance-over-ssh/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<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 make multipart requests with files through autogenerated code defined in OpenAPI</title>
		<link>https://codepills.com/how-to-make-multipart-requests-with-files-through-autogenerated-code-defined-in-openapi/</link>
					<comments>https://codepills.com/how-to-make-multipart-requests-with-files-through-autogenerated-code-defined-in-openapi/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 01 Feb 2024 15:55:58 +0000</pubDate>
				<category><![CDATA[Solutions]]></category>
		<category><![CDATA[Auto-generated Code]]></category>
		<category><![CDATA[Maven Plugin]]></category>
		<category><![CDATA[Multipart File Uploads]]></category>
		<category><![CDATA[OpenAPI Schema]]></category>
		<category><![CDATA[Postman Testing]]></category>
		<category><![CDATA[REST Endpoint]]></category>
		<category><![CDATA[Spring Boot]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1360</guid>

					<description><![CDATA[This article provides a clear tutorial on generating infrastructure code defined in OpenAPI schema for your custom Spring Boot application and handling multipart file uploads through an autogenerated REST endpoint. <a href="https://codepills.com/how-to-make-multipart-requests-with-files-through-autogenerated-code-defined-in-openapi/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article provides a clear tutorial on generating code infrastructure defined OpenAPI schema for your custom Spring Boot application and handling multipart file uploads through an autogenerated REST endpoint.</p>
<p><span id="more-1360"></span></p>
<h2>Introduction</h2>
<p>Let&#8217;s imagine we want to build some simple user management app separated frontend with which we will communicate through REST.</p>
<p>Also, let&#8217;s add some limitations and requirements for our user management project. We will need to use the OpenAPI schema to generate the code infrastructure, as it can help us speed up interface development between the frontend and backend. We will focus on the implementation of code infrastructure on the backend side.</p>
<p>We generally want to receive and process multiple user files through multipart form data in Spring Boot.</p>
<h2>Maven OpenAPI plugin</h2>
<p>First, we must define a plugin in the pom.xml file to generate the code infrastructure from the OpenAPI schema.</p>
<p>Here is an example of the <em>pom.xml</em> file with the plugin definition:</p>
<pre><code class="language-xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"&gt;
  &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;

  &lt;parent&gt;
    &lt;groupId&gt;com.codepills.openapi&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-parent&lt;/artifactId&gt;
    &lt;version&gt;1.1.0&lt;/version&gt;
  &lt;/parent&gt;

  &lt;groupId&gt;com.codepills.openapi&lt;/groupId&gt;
  &lt;artifactId&gt;user-management-module&lt;/artifactId&gt;
  &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt;
  &lt;name&gt;user-management-module&lt;/name&gt;
  &lt;description&gt;User management module&lt;/description&gt;

  &lt;properties&gt;
    &lt;java.version&gt;21&lt;/java.version&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;
    &lt;version.swagger.codegen&gt;3.0.50&lt;/version.swagger.codegen&gt;
    &lt;open.api.file&gt;${project.basedir}/src/main/api-specification/OpenApi-UserManagement.yaml&lt;/open.api.file&gt;
    &lt;open.api.base&gt;com.codepills.openapi.usermanagementmodule&lt;/open.api.base&gt;
    &lt;generated-sources-path&gt;${project.build.directory}/generated-sources&lt;/generated-sources-path&gt;
    &lt;generated-sources-java-path&gt;main/java&lt;/generated-sources-java-path&gt;
  &lt;/properties&gt;

  &lt;dependencies&gt;...&lt;/dependencies&gt;

  &lt;build&gt;
    &lt;finalName&gt;${project.name}&lt;/finalName&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;io.swagger.codegen.v3&lt;/groupId&gt;
        &lt;artifactId&gt;swagger-codegen-maven-plugin&lt;/artifactId&gt;
        &lt;version&gt;${version.swagger.codegen}&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;generate-the-stuff&lt;/id&gt;
            &lt;phase&gt;generate-sources&lt;/phase&gt;
            &lt;goals&gt;
              &lt;goal&gt;generate&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
        &lt;configuration&gt;
          &lt;inputSpec&gt;${open.api.file}&lt;/inputSpec&gt;
          &lt;language&gt;spring&lt;/language&gt;
          &lt;modelNameSuffix&gt;Dto&lt;/modelNameSuffix&gt;
          &lt;configOptions&gt;
            &lt;sourceFolder&gt;${generated-sources-java-path}&lt;/sourceFolder&gt;
            &lt;basePackage&gt;${open.api.base}&lt;/basePackage&gt;
            &lt;modelPackage&gt;${open.api.base}.api.model&lt;/modelPackage&gt;
            &lt;apiPackage&gt;${open.api.base}.api&lt;/apiPackage&gt;
            &lt;interfaceOnly&gt;true&lt;/interfaceOnly&gt;
            &lt;useBeanValidation&gt;true&lt;/useBeanValidation&gt;
            &lt;library&gt;spring-boot3&lt;/library&gt;
            &lt;dateLibrary&gt;custom&lt;/dateLibrary&gt;
            &lt;jakarta&gt;true&lt;/jakarta&gt;
          &lt;/configOptions&gt;
          &lt;typeMappings&gt;
            &lt;typeMapping&gt;DateTime=Instant&lt;/typeMapping&gt;
            &lt;typeMapping&gt;multipartFile=org.springframework.web.multipart.MultipartFile&lt;/typeMapping&gt;
          &lt;/typeMappings&gt;
          &lt;importMappings&gt;
            &lt;importMapping&gt;Instant=java.time.Instant&lt;/importMapping&gt;
          &lt;/importMappings&gt;
          &lt;output&gt;${generated-sources-path}&lt;/output&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;

  &lt;repositories&gt;...&lt;/repositories&gt;

&lt;/project&gt;</code></pre>
<p>As you can see, we have defined the SpringBoot module, and in it, the OpenAPI file is located at <i>/src/main/API-specification/OpenApi-UserManagement.yaml</i>. The <em>OpenApi-UserManagement.yaml</em> file will also be responsible for defining generated code infrastructure.</p>
<h2>OpenAPI User management definition YAML</h2>
<p>Let&#8217;s create the <em>OpenApi-UserManagement.yaml</em> file at <i>/src/main/api-specification/</i> relative to the location of <i>pom.xml</i></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: Import User files
      tags:
        - UserManagement
      operationId: importFiles
      requestBody:
        content:
          multipart/form-data:
            schema:
              properties:
                userFiles:
                  type: array
                  items:
                    type: multipartFile
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                type: object
                additionalProperties:
                  type: array
                  items:
                    type: string
        '400':
          description: Bad Request</code></pre>
<p>As you can see, we have defined a simple endpoint for importing user files. The endpoint is defined as a <code>POST</code> request with a summary, tags, operationId, requestBody and responses.</p>
<p>It is essential to define the keywords for user files well. I picked up the <i>userFiles</i>, but you can use whatever you like. For example &#8211; simply <i>files</i>. The keyword will be used for the protocol to tie the files during transmission.</p>
<h2>User Management Controller</h2>
<p>Now, all we need to do is create a controller to implement the OpenAPI schema. User management schema name will be generated based on the tags in the OpenAPI schema.</p>
<p>Here is an example of the controller:</p>
<pre><code class="language-java">@RestController
@RequiredArgsConstructor
public class UserManagementController implements UserManagementApi {

  @Override
  public ResponseEntity&lt;Map&lt;&lt;tring, List<String&gt;&gt;&gt; importFiles(@RequestPart("userFiles") List&lt;MultipartFile> userFiles) {
    // ... your logic here ...
  }

}</code></pre>
<p>I will leave the implementation up to you as it is not the main focus of this article.</p>
<p>Again, notice the <i>userFiles</i> keyword in the method argument. It is the same as the keyword as defined in the OpenAPI schema.</p>
<h2>Testing with Postman</h2>
<p>Let&#8217;s run the app; the last thing will be testing the endpoint with Postman.</p>
<p>As it might not be stressed enough so far, the most important thing is to use the same keyword as defined in the OpenAPI schema. In our case, it is <i>userFiles</i>.</p>
<p><img decoding="async" src="https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_files.png" alt="Postman - Multipart request with multiple files" width="665" height="319" class="size-full wp-image-1361" srcset="https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_files.png 665w, https://codepills.com/wp-content/uploads/2024/02/postman_multipart_request_with_multiple_files-300x144.png 300w" sizes="(max-width: 665px) 100vw, 665px" /></p>
<p>And now, if the backend is running at localhost, and we added the necessary logic for file processing into the controller, we should be able to upload multiple files through the 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>. The following article will discuss the <a href="https://codepills.com/how-to-make-multipart-requests-with-file-and-object-through-autogenerated-code-defined-in-openapi/" title="How to make multipart requests with file and object through autogenerated code defined in OpenAPI" target="_blank" rel="nofollow noopener">implementation and use of mixed input</a>.</p>
<p>Otherwise, all you need to do is to define your endpoint <code>POST</code> request as everything else. Select <code>POST</code> request, add the URL, and in the body tab, select form-data and add the keyword and the file.</p>
<p>Add multiple files with the same key &#8220;userFiles&#8221; and send the request.</p>
<h2>Conclusion</h2>
<p>This article has shown how to implement autogenerate of code from OpenAPI schema, how to define the schema for multiple file uploads and how to implement the endpoint at the Spring Boot backend. All you need to do is run your application and use the same keyword defined in the OpenAPI schema for the file upload.</p>
<p>Did you find autogenerate OpenAPI implementation and sending files through multipart requests easy? Do you have your trick or know another way <u> to send effectively multipart requests with files</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-files-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 loading="lazy" 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>Java concurrency interview conversation about passing shared variables to threads</title>
		<link>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/</link>
					<comments>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Thu, 01 Jun 2023 08:00:03 +0000</pubDate>
				<category><![CDATA[Java Concurrency]]></category>
		<category><![CDATA[Java concurrency]]></category>
		<category><![CDATA[Java interview]]></category>
		<category><![CDATA[Java threads]]></category>
		<guid isPermaLink="false">http://codekopf.com/?p=1</guid>

					<description><![CDATA[During one interview, I talked with the interviewer about how Java handles Threads and passed references to threads and pitfalls of concurrency in general. <a href="https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>During one interview, I got a pretty nice Java concurrency interview question. It was more or less a conversation between me and the interviewer about how Java handles Threads and passing references, plus ideas on solving concurrency pitfalls.</p>
<p>Let&#8217;s take a while and simulate such a conversation so you can be prepared for your next Java concurrency interview.</p>
<p><span id="more-854"></span></p>
<p>The whole ping-pong between interviewer and candidate is to test the candidate&#8217;s ability and knowledge of Java concurrency and way of handling access to shared variables.</p>
<h2>Two threads with the same primitive int as argument</h2>
<p>So, the narrative of the conversation goes like this:</p>
<blockquote><p>Create two Java Threads. Each Thread takes the same single <i>primitive int</i> as an argument to its constructor. Let the first thread increment <i>primitive int</i> to 100 million. Let the second Thread increment the same shared variable to 20 million. How will look the output of both threads at the end of the incrementation?</p></blockquote>
<p>So as you might guess already, this example will go in the way of figuring out if incrementing <i>primitive int</i> will be <strong>concurrent safe</strong>. What is meant by that, it incrementing the <i>primitive int</i> in one Thread will not influence the shared variable in the other Thread and vice versa.</p>
<p>Should both threads print 20 million, 100 million or one print count of 20 million and the second 100 million?</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) {
        int sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private int sharedInt;

    public TOne(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared primitive int is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private int sharedInt;

    public TTwo(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared primitive int is: " + this.sharedInt);
    }
}</code></pre>
<p>Let's put the code to the file name <i>Main.java</i>, compile it and run it. As you can see, the <i>tTwo</i> execute immediately as it increments much lower than <i>tOne</i>. Both threads show the results as expected, although <i>tTwo</i> finished before <i>tOne</i>, which does not look correct.</p>
<pre><code class="language-bash">tTwo: The shared primitive int is: 20000000
tOne: The shared primitive int is: 100000000</code></pre>
<p>Would there be a way for <i>tTwo</i> to wait for <i>tOne</i>? What will be the output? We still do not know if they share the variable <i>sharedInt</i> of primitive <i>int</i>, if to <i>tTwo</i> takes a shorter time to execute as to <i>tOne</i>.</p>
<h2>One Thread waits for another one to finish</h2>
<p>We need to adjust our code slightly. We need to use <i>Thread</i> class <i>join()</i> method.</p>
<p>The whole premise of calling <i>join()</i> method upon calling Thread is for calling Thread to stop and go to a waiting state. <strong>Calling Thread will remain to wait until the referenced Thread upon which the <i>join()</i> method was called terminates.</strong> This way we block <i>tTwo</i> before executing.</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        int sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tOne.join();
        tTwo.start();
    }
}

class TOne extends Thread {
    private int sharedInt;

    public TOne(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared primitive int is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private int sharedInt;

    public TTwo(int sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared primitive int is: " + this.sharedInt);
    }
}</code></pre>
<p>Let's compile and run the code above:</p>
<pre><code class="language-bash">tOne: The shared primitive int is: 100000000
tTwo: The shared primitive int is: 20000000</code></pre>
<p>When we run the code, we conclude that even though the variable is shared, it is isolated in the threads. <strong>The reason is that each Java Thread on its creation allocates and creates resources. And primitive types make their copies; they do not pass as a reference on the new threads.</strong> However, will this rule apply to object-type variables?</p>
<h2>Two threads with the same Integer variable as argument</h2>
<p>But what if we will use <i>Object</i> variable instead <i>primitive int</i> type? Will it be the same? Will the instance of the object also be isolated?</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        Integer sharedInt = 0;
        TOne tOne = new TOne(sharedInt);
        TTwo tTwo = new TTwo(sharedInt);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private Integer sharedInt;

    public TOne(Integer sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 100_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tOne: The shared object Integer is: " + this.sharedInt);
    }
}

class TTwo extends Thread {
    private Integer sharedInt;

    public TTwo(Integer sharedInt) {
        this.sharedInt = sharedInt;
    }

    public void run() {
        for (int i = 0; i < 20_000_000; i++) {
            this.sharedInt += 1;
        }
        System.out.println("tTwo: The shared object Integer is: " + this.sharedInt);
    }
}</code></pre>
<p>The output of the code above is surprisingly correct:</p>
<pre><code class="language-bash">tTwo: The shared object Integer is: 20000000
tOne: The shared object Integer is: 100000000</code></pre>
<p>Both threads are doing relatively well. However, with a close inspection under the hood, we find out something fishy is happening. If we look better at the assigned references to <i>sharedInt</i>, both threads have assigned the same reference before the thread executions. However, after the run, the <i>sharedInt</i> in <i>tOne</i> had assigned a different reference. Thus, while the output is correct, each Thread's referenced object changes. Therefore, each Thread on every iteration assigns a new object to <i>sharedInt</i>. Consequently, at the end of execution, the different object is printed.</p>
<p>Rather than using the object variable of <i>Integer</i> class, let's make a wrapping class around the <i>count</i> so the passed object variable will not change. What will change will be its internal state. Here is a code with <i>Wrapper</i> class:</p>
<pre><code class="language-java">public class Main {
    public static void main(String[] args) throws InterruptedException {
        Wrapper wrapper = new Wrapper(0);
        TOne tOne = new TOne(wrapper);
        TTwo tTwo = new TTwo(wrapper);
        tOne.start();
        tTwo.start();
    }
}

class TOne extends Thread {
    private Wrapper wrapper;

    public TOne(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        synchronize {
            for (int i = 0; i < 100_000_000; i++) {
                this.wrapper.increment();
            }
            System.out.println("tOne: Count is " + this.wrapper.printCount());
        }
    }
}

class TTwo extends Thread {
    private Wrapper wrapper;

    public TTwo(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        synchronize {
            for (int i = 0; i < 20_000_000; i++) {
                this.wrapper.increment();
            }
            System.out.println("tTwo: Count is " + this.wrapper.printCount());
        }
    }
}

class Wrapper {
    private Integer count;

    public Wrapper(Integer count) {
        this.count = count;
    }

    public void increment() {
        this.count++;
    }

    public Integer printCount() {
        return this.count;
    }
}</code></pre>
<p><strong>Result is shocking!</strong> More and more you try, you will get slightly different numbers every time. The result is not 20 million, nor 100, or 120. Why?! As you can see, there is clearly a problem with synchronization and keeping the isolated internal state of the wrapper from one Thread to another.</p>
<pre><code class="language-bash">tTwo: Count is 22095354
tOne: Count is 104408141</code></pre>
<p>The whole concurrency is about keeping the data isolated from one Thread to another. We ended the interview section as the conversation showed several vital elements of your concurrency knowledge. You successfully demonstrated mastery of the difference between passing reference for primitive and object variables, ways for synchronizing threads and how to show and estimate concurrent output.</p>
<p>The interview might continue, and the interviewer might challenge you to fix the issues. So formalize the problem with the current solution and figure out how to fix the current situation and isolate the internal state of the wrapper.</p>
<h2>Passing object and isolating its internal state</h2>
<p>How can we isolate the internal state? How to secure the synchronization of internal variables?</p>
<p>The question is now, thus, how we can fix the current situation. There are several mechanisms in Java to keep the inner state concurrent. It would be worth telling about each of them in a separate article. But you might start discussing each Java concurrency mechanism with the interviewer, how it can fix the code, and what the output will be.</p>
<p>Let's show one way to fix the issue, which will be through the use of <b>Locks</b>.</p>
<pre><code class="language-java">import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Wrapper wrapper = new Wrapper(0);
        TOne tOne = new TOne(wrapper);
        TTwo tTwo = new TTwo(wrapper);
        tOne.start();
        tTwo.start();
        // tOne.join();
        // tTwo.join();
        System.out.println("Final count: " + wrapper.printCount());
    }
}

class TOne extends Thread {
    private Wrapper wrapper;

    public TOne(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        this.wrapper.getLock();
        try {
            for (int i = 0; i < 100_000_000; i++) {
                this.wrapper.increment();
            }
        } finally {
            this.wrapper.unlock();
        }
        System.out.println("tOne: Count is " + this.wrapper.printCount());
    }
}

class TTwo extends Thread {
    private Wrapper wrapper;

    public TTwo(Wrapper wrapper) {
        this.wrapper = wrapper;
    }

    public void run() {
        this.wrapper.getLock();
        try {
            for (int i = 0; i < 20_000_000; i++) {
                this.wrapper.increment();
            }
        } finally {
            this.wrapper.unlock();
        }
        System.out.println("tTwo: Count is " + this.wrapper.printCount());
    }
}

class Wrapper {
    private Integer count;
    private Lock lock;

    public Wrapper(Integer count) {
        this.count = count;
        this.lock = new ReentrantLock();
    }

    public void getLock() {
        lock.lock();
    }

    public void unlock() {
        lock.unlock();
    }

    public void increment() {
        this.count++;
    }

    public Integer printCount() {
        return this.count;
    }
}</code></pre>
<p>If you choose not to use <i>join()</i> methods for both threads, the main Java thread will execute first and will leave the two other threads running in parallel. The output will be like this:</p>
<pre><code class="language-bash">Final count: 0
tOne: Count is 100000000
tTwo: Count is 120000000</code></pre>
<p>However, if you decide to use <i>join()</i> method, the output will be as follows:</p>
<pre><code class="language-bash">tOne: Count is 100000000
tTwo: Count is 120000000
Final count: 120000000</code></pre>
<h2>Conclusion</h2>
<p>As said before, the whole concept of concurrency is about keeping the data isolated from one Thread to another. You can use this conversation to prepare for an interview for your understanding of concurrent mechanisms. But the successful demonstration of concepts demonstrated your knowledge of the difference between passing reference for primitive variables and object variables, ways for synchronizing threads and how to show and estimate concurrent output.</p>
<p>Don't come only with answers to the interviewers' questions. Try to come also with solutions to problems and pitfalls of concurrency.</p>
<p>And for interviewers, there are several alternatives of how the interview conversation might go between you and the candidate. Suppose this conversation about concurrency inspires you. In that case, you might challenge the candidate to come up with different solutions, can for example, obey using a wrapper and instead focus on handling the situation with <b>volatile</b> or <b>synchronization</b> keyword.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/java-concurrency-interview-conversation-about-passing-shared-variables-to-threads/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>Developer Notes 001</title>
		<link>https://codepills.com/developer-notes-001/</link>
					<comments>https://codepills.com/developer-notes-001/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sun, 01 May 2022 13:34:28 +0000</pubDate>
				<category><![CDATA[Tips & tricks]]></category>
		<category><![CDATA[curl]]></category>
		<category><![CDATA[Enum]]></category>
		<category><![CDATA[interpunct]]></category>
		<category><![CDATA[Jackson]]></category>
		<category><![CDATA[Java 8]]></category>
		<category><![CDATA[Lombok]]></category>
		<category><![CDATA[NUMBER]]></category>
		<category><![CDATA[Oracle DB]]></category>
		<category><![CDATA[Postman]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[String]]></category>
		<category><![CDATA[Switch]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1298</guid>

					<description><![CDATA[The list of a few developer notes collected during the software development which were not enough for a self-standing article. <a href="https://codepills.com/developer-notes-001/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article selects a few developer notes collected during the software development, which were unfortunately not enough for a self-standing article.</p>
<p><span id="more-1298"></span></p>
<p>Developer notes will be an irregular series of articles where I will briefly go through some of my notes to make notes for posterity. The notes themself can be pretty long, yet their length is not enough for writing a meaningful article.</p>
<p>Let&#8217;s take a look at a list of content:</p>
<ul>
<li><a href="#oracle_error" title="Oracle Error: Value Larger Than Specified Precision Allowed For This Column">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</a></li>
<li><a href="#switch_on_string_with_enum_name_in_java_8" title="Switch on String in Java">Switch on String with Enum Name in Java 8</a></li>
<li><a href="#lomboks_serialization_error_for_jackson" title="Lombok's serialization error for Jackson">Lombok&#8217;s serialization error for Jackson</a></li>
<li><a href="#interpunct" title="Interpunct">Interpunct</a></li>
<li><a href="#how_to_do_curl_in_postman" title="How To Do CURL in Postman">How To Do <em>curl</em> in Postman</a></li>
</ul>
<h2 id="oracle_error">Oracle Error: Value Larger Than Specified Precision Allowed For This Column</h2>
<p>I was getting errors on inserting data into the Oracle database &#8220;ORA-01438: value larger than specified precision allowed for this column.&#8221;</p>
<p>The reason why I was getting an error was a too big number. When I looked over UI to database column definition, I saw something like this NUMBER(15,2).</p>
<p>Official Oracle documentation, as for <a href="https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/Data-Types.html#GUID-75209AF6-476D-4C44-A5DC-5FA70D701B78" title="Number datatype" target="_blank" rel="nofollow noopener">Oracle database v21</a>, depicts <code>NUMBER</code> datatype defined as <code>NUMBER (precision,scale)</code>.</p>
<p><code>NUMBER</code> datatype notation can be rather rewritten to <i>NUMBER (size,precision)</i>) where the first number depicts the total size of the digits in a number, and the second means the decimal point scale.</p>
<p>In other words, for example, for <code>NUMBER(2,2)</code>, we can place the column number consisting of 2 digits, both of which will be decimals. i.e. 0.15, 0.45 etc. But if we would like to have a bigger number in the column, we need to upgrade the size of the column reserved for the whole number &#8211; <code>NUMBER(5,2)</code> will get us five digits, of which 2 are decimals. i.e 125.40, 18.00.</p>
<h2 id="switch_on_string_with_enum_name_in_java_8">Switch on String with Enum Name in Java 8</h2>
<p>Here is an example of how to use <em>Enum</em> values as strings in a <code>switch</code> case. You can only use the strings which are known at compile time. The compiler cannot determine the result of expression. However, in Java <em>Enum</em> case <code>VALUE1, VALUE2</code> are static.</p>
<pre><code class="language-java">String name = ...
switch(CustomEnum.valueOf(name)) {
   case VALUE1:
        ...
        break;
   case VALUE2:
        ...
        break;
    ...
}</code></pre>
<h2 id="lomboks_serialization_error_for_jackson">Lombok&#8217;s serialization error for Jackson</h2>
<p>When I created a new aggregated DTO class on my REST output, I got the following error:</p>
<pre><code class="language-bash">Type definition error: [simple type, class CUSTOM_DTO_CLASS_NAME]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class CUSTOM_DTO_CLASS_NAME and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: CUSTOM_DTO_CLASS_NAME[\"aggregation-class-property\"]->java.util.ArrayList[0])</code></pre>
<p>I am sure this error will be thrown quiet often as the solution on it is very simple. All I was missing on my <i>Custom DTO</i> class was <strong>Lombok&#8217;s</strong> <code>@Getters</code> annotation for serialization. So fix consisted on adding missing <code>@Getters</code> annotation on the top of my custom class for Lombok generating getter methods at compile time.</p>
<h2 id="interpunct">Interpunct</h2>
<p>I was editing my resume this month and wanted to create a nice date range in positions I held in the past. I got this from my LinkedIn profile, where LinkedIn use dates in the form as <em>Jan 2020 – Feb 2020 · 2 mos</em>. But I could not figure out where to take the dot sign as it was an image. However, the character for such sign as little black dot <strong>·</strong> really exists and its name is <strong>Interpunct</strong>,  or <strong>middle dot</strong>. So every time you would like to create a nice division of text with the help of <strong>·</strong>, think about the <strong>Interpunct</strong>.</p>
<h2 id="how_to_do_curl_in_postman">How To Do <em>curl</em> in Postman</h2>
<p>Is there a way hot to make a <em>curl</em> command in Postman? What if we would like to import the <em>curl</em> command easily into Postman and make a Postman GUI request from it.<br />
Is it even possible to easily translate all the <em>curl</em> command parameters into the Postman request?</p>
<p>Surely it is. Postman request are eventually nothing else than more fancy <em>curl</em> requests and Postman supports the <em>curl</em> import feature. Importing <em>curl</em> is very simple. Here is simple list of steps which will lead you to success:</p>
<ol>
<li>Open Postman.</li>
<li>Go to navigation menu, click File and Import option</li>
<li>In <i>Import</i> window select the raw text tab.</li>
<li>Paste the raw text e.g. <code>curl --location --request GET "https://www.google.com/"</code>, then click continue.</li>
<li>Check the name, format and import as.</li>
<li>If everything is correct, click <i>Import</i> button.</li>
</ol>
<p>Following the steps will automatically import the <em>curl</em> command into the Postman on the new tab.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/developer-notes-001/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>
	</channel>
</rss>
