Saturday, 7 January 2023

Get POSIX file attributes in Java

POSIX stands for Portable Operating System Interface, it is a set of standard operating system interfaces based on the Unix operating system. POSIX standardizes set of guidelines to ease the task of cross-platform software development. You can refer this link for more information on POSIX.

 

How to get POSIX file attributes in Java?

Below snippet return the POSIX attributes in Java.

filePath
.getFileSystem()
.provider()
.getFileAttributeView(filePath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
.readAttributes();

 

Find the below working application.


PosixFileAttributesDemo.java

package com.sample.app.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.attribute.FileTime;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.util.Objects;
import java.util.Set;

public class PosixFileAttributesDemo {

	public static final PosixFileAttributes getPosixAttributes(final String filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");
		return getPosixAttributes(new File(filePath));
	}

	public static final PosixFileAttributes getPosixAttributes(final File filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");
		return getPosixAttributes(filePath.toPath());

	}

	public static final PosixFileAttributes getPosixAttributes(final Path filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");

		return filePath.getFileSystem().provider()
				.getFileAttributeView(filePath, PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS)
				.readAttributes();
	}

	public static void main(String[] args) throws IOException {
		final String filePath = "/Users/Shared/filePrograms/a.txt";

		final PosixFileAttributes posixFileAttributes = getPosixAttributes(filePath);

		final FileTime creationTime = posixFileAttributes.creationTime();
		final Object fileKey = posixFileAttributes.fileKey();
		final boolean isDirectiory = posixFileAttributes.isDirectory();
		final boolean isRegularFile = posixFileAttributes.isRegularFile();
		final boolean isSymbolicLink = posixFileAttributes.isSymbolicLink();
		final FileTime lastAccessTime = posixFileAttributes.lastAccessTime();
		final FileTime lastModifiedTime = posixFileAttributes.lastModifiedTime();
		final UserPrincipal owner = posixFileAttributes.owner();
		final Set<PosixFilePermission> permissions = posixFileAttributes.permissions();
		final long fileSizeInBytes = posixFileAttributes.size();

		System.out.println("creationTime : " + creationTime);
		System.out.println("fileKey : " + fileKey);
		System.out.println("isDirectiory : " + isDirectiory);
		System.out.println("isRegularFile : " + isRegularFile);
		System.out.println("isSymbolicLink : " + isSymbolicLink);
		System.out.println("lastAccessTime : " + lastAccessTime);
		System.out.println("lastModifiedTime : " + lastModifiedTime);
		System.out.println("owner : " + owner);
		System.out.println("fileSizeInBytes : " + fileSizeInBytes);

		System.out.println("File permissions : ");
		for (final PosixFilePermission permission : permissions) {
			System.out.println("  " + permission);
		}

	}

}

 

Output

creationTime : 2023-01-07T15:41:28Z
fileKey : (dev=1000004,ino=37049869)
isDirectiory : false
isRegularFile : true
isSymbolicLink : false
lastAccessTime : 2023-01-07T15:41:30Z
lastModifiedTime : 2023-01-07T15:41:28Z
owner : krishna
fileSizeInBytes : 12
File permissions : 
  OWNER_WRITE
  OTHERS_READ
  OWNER_READ
  GROUP_READ

 

 

You may like

file and stream programs in Java

How to get the directory size in Java?

Convert string to InputStream in Java

Read the data from BufferedReader in Java

Read file content using BufferedReader in Java

Touch the file in Java (Update the file timestamp)

Touch the file in Java (Update the file timestamp)

If you are from Linux background, you might have seen ‘touch’ command, which sets the modification and access times of files. 

 

Touch command address following both scenarios

Scenario 1: Update the timestamp when the file exits.

Scenario 2: Create an empty file when the file is not exists.

 

We can achieve the same kind of behavior using ‘Files.setLastModifiedTime’ method. ‘Files.setLastModifiedTime’ method update the file's last modified time attribute.

 

Example

Files.setLastModifiedTime(filePath, FileTime.from(Instant.now()));

 


Let’s experiment it with below example.

$ls -lart
total 0
drwxrwxrwt  16 root     wheel  512 Jan  7 19:03 ..
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:03 a.txt
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:03 b.txt
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:03 c.txt
drwxr-xr-x   5 krishna  wheel  160 Jan  7 19:03 .

 

As you see above example, files a.txt, b.txt, c.txt are updated 19:03. Let’s run below application and confirm the touch functionality.

 

package com.sample.app.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.time.Instant;
import java.util.Objects;

public class FileTouchDemo {

	public static void touch(String filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");
		touch(Paths.get(filePath));
	}

	public static void touch(final File filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");
		touch(filePath.toPath());
	}

	public static void touch(final Path filePath) throws IOException {
		Objects.requireNonNull(filePath, "filePath is null");
		if (Files.exists(filePath)) {
			Files.setLastModifiedTime(filePath, FileTime.from(Instant.now()));
		} else {
			Files.createFile(filePath);
		}
	}

	public static void main(String[] args) throws IOException {
		final String filePath1 = "/Users/Shared/filePrograms/a.txt";
		final String filePath2 = "/Users/Shared/filePrograms/b.txt";
		final String filePath3 = "/Users/Shared/filePrograms/c.txt";
		final String filePath4 = "/Users/Shared/filePrograms/d.txt";

		touch(filePath1);
		touch(new File(filePath2));
		touch(Paths.get(filePath3));
		touch(Paths.get(filePath4));

		System.out.println("Files last modification time is updated");
	}

}

 

Output from Linux terminal.

$ls -lart
total 0
drwxrwxrwt  16 root     wheel  512 Jan  7 19:03 ..
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:23 a.txt
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:23 c.txt
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:23 b.txt
-rw-r--r--   1 krishna  wheel    0 Jan  7 19:23 d.txt
drwxr-xr-x   6 krishna  wheel  192 Jan  7 19:23 .

From the output, you can confirm d.txt is created as it wasn't exists already and last modified time of a.txt, b.txt and c.txt is updated to current time.

 

You may like

file and stream programs in Java

How to process a huge file line by line in Java?

How to get the directory size in Java?

Convert string to InputStream in Java

Read the data from BufferedReader in Java

Read file content using BufferedReader in Java

Friday, 6 January 2023

Micronaut: Qualifying a bean By Annotation

  In my previous post, I explained how to qualify a bean by name. In this post, I am going to explain how to qualify a bean by building your own qualifiers using the Qualifier annotation. 

@Qualifier
@Retention(RUNTIME)
public @interface Bull {

}

@Qualifier
@Retention(RUNTIME)
public @interface Poodle {

}

@Singleton
public class DogService {

	private Dog dog1;
	private Dog dog2;

	public DogService(@Bull Dog dog1, @Poodle Dog dog2) {
		this.dog1 = dog1;
		this.dog2 = dog2;
	}

}

 

public DogService(@Bull Dog dog1, @Poodle Dog dog2)

dog1 is injected with an instance of BullDog and dog2 is injected with an instance of PoodleDog.

 

How is this injection possible?

@Bull Dog dog1;

Annotation value (Bull) + type being injected simple name (Dog) == (case-insensitive) == The simple name of a bean of type Engine (BullDog).

 

Find the below working application.

 

Step 1: Create new maven project ‘micronaut-qualify-by-annotation’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<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">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample.app</groupId>
	<artifactId>micronaut-qualify-by-annotation</artifactId>
	<version>1</version>

	<properties>
		<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
		<micronaut.version>3.7.1</micronaut.version>

		<maven.compiler.target>15</maven.compiler.target>
		<maven.compiler.source>15</maven.compiler.source>
	</properties>

	<dependencies>

		<dependency>
			<groupId>io.micronaut</groupId>
			<artifactId>micronaut-inject-java</artifactId>
			<version>${micronaut.version}</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>com.sample.app.App</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>

				<executions>
					<execution>
						<id>make-assembly</id>
						<phase>package</phase>
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>

 

Step 3: Define Dog interface.

 

Dog.java

package com.sample.app.interfaces;

public interface Dog {

	String aboutMe();
}

Step 4: Define BullDog and PoodleDog classes.

 

BullDog.java

package com.sample.app.models;

import com.sample.app.interfaces.Dog;

import jakarta.inject.Singleton;

@Singleton
public class BullDog implements Dog {

	@Override
	public String aboutMe() {
		return "I am Bull Dog";
	}

}

PoodleDog.java

package com.sample.app.models;

import com.sample.app.interfaces.Dog;

import jakarta.inject.Singleton;

@Singleton
public class PoodleDog implements Dog {

	@Override
	public String aboutMe() {
		return "I am Poodle Dog";
	}

}

Step 5: Define annotations.

 

Bull.java

package com.sample.app.annotations;

import jakarta.inject.Qualifier;
import java.lang.annotation.Retention;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier
@Retention(RUNTIME)
public @interface Bull {

}

Poodle.java

package com.sample.app.annotations;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Retention;

import jakarta.inject.Qualifier;

@Qualifier
@Retention(RUNTIME)
public @interface Poodle {

}

Step 6: Define DogService class.

 

DogService.java

package com.sample.app.util;

import com.sample.app.annotations.Bull;
import com.sample.app.annotations.Poodle;
import com.sample.app.interfaces.Dog;

import jakarta.inject.Singleton;

@Singleton
public class DogService {

	private Dog dog1;
	private Dog dog2;

	public DogService(@Bull Dog dog1, @Poodle Dog dog2) {
		this.dog1 = dog1;
		this.dog2 = dog2;
	}

	public void aboutMe() {

		System.out.println(dog1.aboutMe());
		System.out.println(dog2.aboutMe());

	}

}

Step 7: Define main application class.

 

App.java

package com.sample.app;

import com.sample.app.util.DogService;

import io.micronaut.context.ApplicationContext;

public class App {

	public static void main(String[] args) {
		try (ApplicationContext context = ApplicationContext.run()) {
			DogService animalUtil = context.getBean(DogService.class);
			animalUtil.aboutMe();
		}
	}
}

Total project structure looks like below.




Build the project using mvn package command.

Navigate to the folder where pom.xml is located and execute the command ‘mvn package’.

 

Upon command successful execution, you can see the jar file ‘micronaut-qualify-by-annotation-1-jar-with-dependencies.jar’ in project target folder.


$ls ./target/
archive-tmp
classes
generated-sources
maven-archiver
maven-status
micronaut-qualify-by-annotation-1-jar-with-dependencies.jar
micronaut-qualify-by-annotation-1.jar
test-classes

Execute below command to run the application.

java -jar ./target/micronaut-qualify-by-annotation-1-jar-with-dependencies.jar

$java -jar ./target/micronaut-qualify-by-annotation-1-jar-with-dependencies.jar
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
I am Bull Dog
I am Poodle Dog

You can download this application from this link.


Previous                                                    Next                                                    Home

PlantUML: Reverse arrows to improve readability in sequence diagram

We can also use the reverse arrows (<-, <--) to improve the readability of interactions in the diagram.

 

For example, Following two snippets convey the same interaction.

 

Snippet 1

ADServer -> LoginServer: Login Successful
LoginServer -> Client: Login Successful

 

Snippet 2

LoginServer <- ADServer: Login Successful
Client <- LoginServer: Login Successful

 

Find the below complete snippet.

reverseArrow.txt

@startuml
Client -> LoginServer: Enter user name
Client -> LoginServer: Enter password
Client -> LoginServer: Submit the form 
LoginServer -> ADServer: Check the credentials
LoginServer <- ADServer: Login Successful
Client <- LoginServer: Login Successful

 

Above snippet generates below diagram.

 


 

 

 

Previous                                                    Next                                                    Home

Thursday, 5 January 2023

PlantUML: how to use dotted arrow in the sequence diagram?

Using -->, we can draw a dotted arrow to connect the entities.

 

dottedArrow.txt 

@startuml
Client --> LoginServer: Enter user name
Client --> LoginServer: Enter password
Client --> LoginServer: Submit the form 
LoginServer --> ADServer: Check the credentials
ADServer --> LoginServer: Login Successful
LoginServer --> Client: Login Successful
@enduml

 

Above snippet generate following diagram.

 


  

Previous                                                    Next                                                    Home