Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, September 10, 2024

Create Pdf with ITEXT

 ITEXT is one of the most common libraries used to create pdf files. you can get the library from the maven repository. below is the latest version as of now.

<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.4</version>
</dependency>

If you have fair knowledge in java, it is more than enough to create a use Itext and generate a PDF file.

you can create a java project, mostly a springboot project via https://start.spring.io/

Then you can add the maven dependency. Here i use maven, but you can use anything eg:gradle

In this example i have added

1. plain text

2. some Alignment with text

3. insert an image ( keep image in classpath)

package com.example.poc.pdf.itext.sample;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;

public class ExperienceLetter {

private static String FILE = "C:\\Project\\PoC\\docs\\Experience.pdf";

private static Font TO = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);
private static Font TO_DATA = new Font(Font.FontFamily.TIMES_ROMAN, 12);
private static Font TITLE = new Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD | Font.UNDERLINE);

private static Font BODY = new Font(Font.FontFamily.TIMES_ROMAN, 11);

public static void main(String[] args) {
try {
//create Doc
Document document = new Document();
// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));
//open doc
document.open();
// add each section
// add metadata
addMetaData(document);
//
addParaTo(document);
addTitle(document);

addBody(document, "EMPLYEE NAME", "DESIGNATION", "2022-01-01", "2024-02-01", 2);

addSignature(document);
// close doc
document.close();
} catch (DocumentException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Amal Prasad");
document.addCreator("Amal Prasad");
}

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

public static void addTitle(Document document)
throws DocumentException {
// create Para
Paragraph title = new Paragraph();
title.setAlignment(Element.ALIGN_CENTER);
addEmptyLine(title, 2);
title.add(new Paragraph("TO WHOM IT MAY CONCERN", TITLE));
title.setAlignment(Element.ALIGN_CENTER);

//add para to doc
document.add(title);
}

public static void addBody(Document document, String employeeName, String designation, String workStartDate, String workEndDate, int yearsOfExperience)
throws DocumentException {
StringBuilder experience = new StringBuilder("This letter is to certify that ");
experience.append(employeeName);
experience.append(" has worked in our organisation as ");
experience.append(designation);
experience.append(".");

experience.append("He had started working here on dated ");
experience.append(workStartDate);
experience.append(" and worked till dated ");
experience.append(workEndDate);
experience.append(".");


experience.append("He had served the company for about ");
experience.append(yearsOfExperience);
experience.append(" years.");
// create Para
Paragraph body = new Paragraph();

addEmptyLine(body, 2);
body.add(new Paragraph(experience.toString(), BODY));

//add para to doc
document.add(body);

// create Para
Paragraph bodyPart2 = new Paragraph();
addEmptyLine(bodyPart2, 1);
StringBuilder expereincePart2 = new StringBuilder("Until the day he joined, he had been quite responsible.");
expereincePart2.append("To date, he has accumulated a diverse set of talents and job experiences");
expereincePart2.append("His mind blowing abilities include: Team work,Management skills and Analytical skills");
expereincePart2.append("");

bodyPart2.add(new Paragraph(expereincePart2.toString(), BODY));
document.add(bodyPart2);

Paragraph bodyPart3 = new Paragraph();
addEmptyLine(bodyPart3, 1);

StringBuilder expereincePart3 = new StringBuilder("We wish him all the best for his future endeavours.");

bodyPart3.add(new Paragraph(expereincePart3.toString(), BODY));

addEmptyLine(bodyPart3, 1);
document.add(bodyPart3);
}

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
// System.out.println(path.toAbsolutePath());
// String classpath = System.getProperty("java.class.path");
// String[] classpathEntries = classpath.split(File.pathSeparator);
// System.out.println(Arrays.toString(classpathEntries));
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
// signImage.setAlignment(Image.LEFT | Image.TEXTWRAP);
signImage.setAlignment(Image.ALIGN_CENTER);
// signImage.setBorder(Image.BOX);
// signImage.setBorderWidth(15);
signImage.scaleToFit(100, 100);

document.add(signImage);

//////
// create Para
Paragraph afterSignature = new Paragraph();
// addEmptyLine(afterSignature, 3);
afterSignature.add(new Paragraph("Authorized Signatory", BODY));
document.add(afterSignature);
}


}


Explaining the main functionalities

1. Create a Document

//create Doc
Document document = new Document();

2. Create PDF writer instance to write input to generating pdf.

// pdf file
PdfWriter.getInstance(document, new FileOutputStream(FILE));

3. As we have added writer, Now let's open doc.

//open doc
document.open();

4. Do the functionalities/ or operations you need.

eg: add Meta data for the pdf. This also not need. BUt you can add , if you need.

public static void addMetaData(Document document) {
document.addTitle("Sample Pdf");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Alex Crow");
document.addCreator("Alex Crow");
}

you can add Text as Paragraph. Below example will help. Here we create a Paragraph. add content as Paragraphs.  After that add the Paragraph to the document, you already opened.

public static void addParaTo(Document document)
throws DocumentException {
Paragraph toPara = new Paragraph();
addEmptyLine(toPara, 1);
// Lets write a big header
toPara.add(new Paragraph("TO:", TO));

addEmptyLine(toPara, 1);
toPara.add(new Paragraph("Employee Name", TO_DATA));
toPara.add(new Paragraph("Employee ID:", TO_DATA));
toPara.add(new Paragraph("Address Line 1", TO_DATA));
toPara.add(new Paragraph("Address Line 2", TO_DATA));
toPara.add(new Paragraph("City", TO_DATA));
toPara.add(new Paragraph("Country", TO_DATA));

document.add(toPara);
}

you can use below functionality to add some empty lines

public static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}

Add Image

    public static void addSignature(Document document) throws URISyntaxException, DocumentException, IOException {
String imagePath = "signature.jpg";
Path path = Paths.get(ClassLoader.getSystemResource(imagePath).toURI());
Image signImage = Image.getInstance(path.toAbsolutePath().toString());
signImage.setAlignment(Image.ALIGN_CENTER);
signImage.scaleToFit(100, 100);

document.add(signImage);
}

Here we have added an image of an signature.

5. Finally Close the doc.

// close doc
document.close();


Wednesday, January 10, 2024

Sample Word to PDF convert with docx4j

Below is sample application to convert Word file to Pdf using dox4j

<?xml version="1.0" encoding="UTF-8"?>
<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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.poc.convert</groupId>
<artifactId>convert</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>convert</name>
<description>Poc Project to convert word to pdf</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- dox4j -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-Internal</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-ReferenceImpl</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-JAXB-MOXy</artifactId>
<version>8.3.9</version>
</dependency>
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.3.9</version>
</dependency>

<!--- ****** -->
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException -->
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/activation/DataSource -->
<!-- Caused by: java.lang.ClassNotFoundException: javax.activation.DataSource-->
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>

<!-- java.lang.NoClassDefFoundError: javax/mail/internet/MimeMultipart-->
<!-- Caused by: java.lang.ClassNotFoundException: javax.mail.internet.MimeMultipart-->

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>

<!-- Documents4jLocalServices-->
<!-- https://mvnrepository.com/artifact/org.docx4j/docx4j-documents4j-local -->
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-documents4j-local</artifactId>
<version>11.4.9</version>
</dependency>

<!-- https://mvnrepository.com/artifact/ch.qos.logback/logback-classic -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.5</version>
</dependency>


<!-- https://mvnrepository.com/artifact/org.testng/testng -->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.4.0</version>
</dependency>



<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


Above POM all dependencies 

Below Convert Class contains the Logic

--------------------------------------------------------------------------------------------------------


package com.poc.convert.convert;


import com.documents4j.api.DocumentType;

import org.docx4j.Docx4J;

import org.docx4j.documents4j.local.Documents4jLocalServices;

import org.docx4j.openpackaging.exceptions.Docx4JException;

import org.docx4j.openpackaging.packages.WordprocessingMLPackage;

import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;


import java.io.*;


public class Convert {

    private static final Logger LOGGER = LoggerFactory.getLogger(Convert.class);


    public static Documents4jLocalServices exporter = new Documents4jLocalServices();


    private static volatile Convert instance;


    private Convert() {

    }


    public static Convert getInstance() {

        if (instance == null) {

            synchronized (Convert.class) {

                if (instance == null) {

                    instance = new Convert();

                }

            }

        }

        return instance;

    }


    /**

     * Convert word .docx format file to pdf file.

     *

     * @param inputWordFile Input word .docx file.

     * @param outputPdfFile Converted .pdf file.

     * @throws IOException     Exception when reading input word ,docx file or writing to .pdf output file

     * @throws Docx4JException Excpetion occcuring during converting word file to Pdf file.

     */

    public void convertWordDocxtoPdf(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {

        LOGGER.info("Start Converting Word {} file to {}", inputWordFile, outputPdfFile);

        InputStream templateInputStream = new FileInputStream(inputWordFile);

        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);

        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();


        FileOutputStream os = new FileOutputStream(outputPdfFile);

        Docx4J.toPDF(wordMLPackage, os);

        os.flush();

        os.close();

        LOGGER.info("Successfully converted {} to {}", inputWordFile, outputPdfFile);

    }


    public void convertWordDocxtoPdfWithLocalServer(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {

        LOGGER.info("Start Converting with local server Word {} file to {}", inputWordFile, outputPdfFile);

        try (FileOutputStream fos = new FileOutputStream(outputPdfFile)) {

            if (inputWordFile.toLowerCase().endsWith(".docx")) {

                exporter.export(new File(inputWordFile), fos, DocumentType.MS_WORD);

            }

            LOGGER.info("Start Flushing ***********");

            fos.flush();

            fos.close();

            LOGGER.info("End Flushing ***********");

//            System.exit(0);

        }

        LOGGER.info("Successfully converted with local server {} to {}", inputWordFile, outputPdfFile);

    }


    public void convertWordDocxtoPdfWithLibre(String inputWordFile, String outputPdfFile) throws IOException {

        LOGGER.info("Start Converting Word with Libre {} file to {}", inputWordFile, outputPdfFile);


        String command = "libreoffice --headless --convert-to pdf " + inputWordFile + " --outdir " + outputPdfFile;

        Runtime.getRuntime().exec(command);


        LOGGER.info("Successfully converted with Libre {} to {}", inputWordFile, outputPdfFile);

    }

}

----------------------------------------------------------------------------------------------------------------


package com.poc.convert.convert;

import com.documents4j.api.DocumentType;
import org.docx4j.Docx4J;
import org.docx4j.documents4j.local.Documents4jLocalServices;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class Convert {
private static final Logger LOGGER = LoggerFactory.getLogger(Convert.class);

public static Documents4jLocalServices exporter = new Documents4jLocalServices();

private static volatile Convert instance;

private Convert() {
}

public static Convert getInstance() {
if (instance == null) {
synchronized (Convert.class) {
if (instance == null) {
instance = new Convert();
}
}
}
return instance;
}

/**
* Convert word .docx format file to pdf file.
*
* @param inputWordFile Input word .docx file.
* @param outputPdfFile Converted .pdf file.
* @throws IOException Exception when reading input word ,docx file or writing to .pdf output file
* @throws Docx4JException Excpetion occcuring during converting word file to Pdf file.
*/
public void convertWordDocxtoPdf(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {
LOGGER.info("Start Converting Word {} file to {}", inputWordFile, outputPdfFile);
InputStream templateInputStream = new FileInputStream(inputWordFile);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateInputStream);
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

FileOutputStream os = new FileOutputStream(outputPdfFile);
Docx4J.toPDF(wordMLPackage, os);
os.flush();
os.close();
LOGGER.info("Successfully converted {} to {}", inputWordFile, outputPdfFile);
}

public void convertWordDocxtoPdfWithLocalServer(String inputWordFile, String outputPdfFile) throws IOException, Docx4JException {
LOGGER.info("Start Converting with local server Word {} file to {}", inputWordFile, outputPdfFile);
try (FileOutputStream fos = new FileOutputStream(outputPdfFile)) {
if (inputWordFile.toLowerCase().endsWith(".docx")) {
exporter.export(new File(inputWordFile), fos, DocumentType.MS_WORD);
}
LOGGER.info("Start Flushing ***********");
fos.flush();
fos.close();
LOGGER.info("End Flushing ***********");
// System.exit(0);
}
LOGGER.info("Successfully converted with local server {} to {}", inputWordFile, outputPdfFile);
}

public void convertWordDocxtoPdfWithLibre(String inputWordFile, String outputPdfFile) throws IOException {
LOGGER.info("Start Converting Word with Libre {} file to {}", inputWordFile, outputPdfFile);

String command = "libreoffice --headless --convert-to pdf " + inputWordFile + " --outdir " + outputPdfFile;
Runtime.getRuntime().exec(command);

LOGGER.info("Successfully converted with Libre {} to {}", inputWordFile, outputPdfFile);
}
}


3. This is the default Springboot main classs
This class simply call the logic of the Convert class where takes InputFilePath and OutputFilePath as arguments

package com.poc.convert.convert;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.io.IOException;

@SpringBootApplication
public class ConvertApplication {

private static final Logger LOGGER = LoggerFactory.getLogger(ConvertApplication.class);

public static void main(String[] args) {
SpringApplication.run(ConvertApplication.class, args);

String inputWordFile = "";
String outputPdfFile = "";

if (args[0].length() > 0) {
inputWordFile = args[0];
} else {
LOGGER.info("Please define Input file");
}

if (args[1].length() > 0) {
outputPdfFile = args[1];
} else {
LOGGER.info("Please define Output file");
}


try {
Convert.getInstance().convertWordDocxtoPdf(inputWordFile, outputPdfFile);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (Docx4JException e) {
throw new RuntimeException(e);
}

}

}


With this you can execute Jar file with below command.
{space} --> empty space character, separate parts of the commands

1. command to execute jar
java {space} -jar {space} {name of the jar file} {space} {input file path} {output file path}

java -jar convert-0.0.1-SNAPSHOT.jar D:/sample.docx D:/sample.pdf






Wednesday, January 3, 2024

Samplelog back xml

<configuration>

<property name="LOGS" value="./logs" />

<appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%black(%d{ISO8601}) %highlight(%-5level) [%blue(%t)] %yellow(%C): %msg%n%throwable
</Pattern>
</layout>
</appender>

<appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${LOGS}/test-automation-poc-logger.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d %p %C [%t] %m%n</Pattern>
</encoder>

<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- rollover daily and when the file reaches 10 MegaBytes -->
<fileNamePattern>${LOGS}/archived/test-runner-logger-%d{yyyy-MM-dd}.%i.log
</fileNamePattern>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>

<!-- LOG everything at INFO level -->
<root level="info">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</root>

<logger name="com.example.test.runner" level="trace" additivity="false">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</logger>

<logger name="com.example.test.framework" level="trace" additivity="false">
<appender-ref ref="RollingFile" />
<appender-ref ref="Console" />
</logger>


</configuration>

Sample Custom Exception class

package com.example.test.framework.exception;

/**
* Handle exception when element is not available.
*/
public class ElementNotFoundException extends RuntimeException {
/**
* Instantiates a new {@link ElementNotFoundException}.
*
* @param message the exception message,
*/
public ElementNotFoundException(String message) {
super(message);
}
}

Sample Enum

package com.example.test.framework.enums;

/**
* Message matching type
*/
public enum MessageMatchType {
/** The exact message will be checked. */
EXACT(0),

/** The partial of the original message text is matched. */
PARTIAL(1);

/** The key. */
private int key;

private MessageMatchType(int key) {
this.key = key;

}

public int getKey() {
return key;
}

}

Thursday, November 23, 2023

Java 9 : JShell

 1. How to run Jshell

    get a command prompt windows key + R --> type cmd

2. Check java version, should be higher than 9

    java -version

3. type "jshell"

4. Now you can write syntax and check validity , edit and play on with this

5. /help --> help command

6. /list   --> will list the command typed/executed

7. edit use edit command with command number, number you can select using /list . Once you use edit, it will prompt with shell to edit.

    /edit 2


Below you I have attached series of commands i tried with all mistakes

----------------------------------------------------------------------------------------------------------------------

Microsoft Windows [Version 10.0.22621.2715]

(c) Microsoft Corporation. All rights reserved.


C:\Users\USR>java -version

openjdk version "21" 2023-09-19

OpenJDK Runtime Environment Zulu21.28+85-CA (build 21+35)

OpenJDK 64-Bit Server VM Zulu21.28+85-CA (build 21+35, mixed mode, sharing)


C:\Users\USR>jshell

|  Welcome to JShell -- Version 21

|  For an introduction type: /help intro


jshell> System.out.println("Hello");

Hello


jshell> /help

|  Type a Java language expression, statement, or declaration.

|  Or type one of the following commands:

|  /list [<name or id>|-all|-start]

|       list the source you have typed

|  /edit <name or id>

|       edit a source entry

|  /drop <name or id>

|       delete a source entry

|  /save [-all|-history|-start] <file>

|       Save snippet source to a file

|  /open <file>

|       open a file as source input

|  /vars [<name or id>|-all|-start]

|       list the declared variables and their values

|  /methods [<name or id>|-all|-start]

|       list the declared methods and their signatures

|  /types [<name or id>|-all|-start]

|       list the type declarations

|  /imports

|       list the imported items

|  /exit [<integer-expression-snippet>]

|       exit the jshell tool

|  /env [-class-path <path>] [-module-path <path>] [-add-modules <modules>] ...

|       view or change the evaluation context

|  /reset [-class-path <path>] [-module-path <path>] [-add-modules <modules>]...

|       reset the jshell tool

|  /reload [-restore] [-quiet] [-class-path <path>] [-module-path <path>]...

|       reset and replay relevant history -- current or previous (-restore)

|  /history [-all]

|       history of what you have typed

|  /help [<command>|<subject>]

|       get information about using the jshell tool

|  /set editor|start|feedback|mode|prompt|truncation|format ...

|       set configuration information

|  /? [<command>|<subject>]

|       get information about using the jshell tool

|  /!

|       rerun last snippet -- see /help rerun

|  /<id>

|       rerun snippets by ID or ID range -- see /help rerun

|  /-<n>

|       rerun n-th previous snippet -- see /help rerun

|

|  For more information type '/help' followed by the name of a

|  command or a subject.

|  For example '/help /list' or '/help intro'.

|

|  Subjects:

|

|  intro

|       an introduction to the jshell tool

|  keys

|       a description of readline-like input editing

|  id

|       a description of snippet IDs and how use them

|  shortcuts

|       a description of keystrokes for snippet and command completion,

|       information access, and automatic code generation

|  context

|       a description of the evaluation context options for /env /reload and /reset

|  rerun

|       a description of ways to re-evaluate previously entered snippets


jshell>

/list


   1 : System.out.println("Hello");


jshell> void printMessage(){

   ...>     System.out.print;n("Hello")

   ...> }

|  Error:

|  not a statement

|      System.out.print;n("Hello")

|      ^--------------^

|  Error:

|  ';' expected

|      System.out.print;n("Hello")

|                                 ^


jshell> printMessage()

|  Error:

|  cannot find symbol

|    symbol:   method printMessage()

|  printMessage()

|  ^----------^


jshell> /lsit

|  Invalid command: /lsit

|  Type /help for help.


jshell> /list


   1 : System.out.println("Hello");


jshell>

        void printMessage(){

   ...>     System.out.print;n("Hello");

   ...> }

|  Error:

|  not a statement

|      System.out.print;n("Hello");

|      ^--------------^

|  Error:

|  cannot find symbol

|    symbol:   method n(java.lang.String)

|      System.out.print;n("Hello");

|                       ^


jshell> void printMessage(){

   ...>     System.out.println("Hello");

   ...> }

|  created method printMessage()


jshell> printMessage

|  Error:

|  cannot find symbol

|    symbol:   variable printMessage

|  printMessage

|  ^----------^


jshell> printMessage()

Hello


jshell> /list


   1 : System.out.println("Hello");

   2 : void printMessage(){

           System.out.println("Hello");

       }

   3 : printMessage()


jshell> edit 2

|  Error:

|  ';' expected

|  edit 2

|      ^

|  Error:

|  cannot find symbol

|    symbol:   variable edit

|  edit 2

|  ^--^


jshell> /edit 2

|  modified method printMessage()


jshell> printMessage()

Hello Edited


jshell>


Java 9

1. REPL Jshell

2.    Collection Factory Method

3. HTTP/2 Client

4. Jigsaw Project /Modularity

5. Other features


https://www.youtube.com/watch?v=NJY-D9JLLdQ


1. Test Jshell

Take a command prompt wind + R -> type "cmd"

2. Check java version, must be above 9

java -version 

3. type "jshell" in command prompt

4. This will help you to test simple syntax

-------------------------------------------------------------------------------------------------

C:\Users\USR>java -version

openjdk version "21" 2023-09-19

OpenJDK Runtime Environment Zulu21.28+85-CA (build 21+35)

OpenJDK 64-Bit Server VM Zulu21.28+85-CA (build 21+35, mixed mode, sharing)


C:\Users\USR>jshell

|  Welcome to JShell -- Version 21

|  For an introduction type: /help intro

jshell> System.out.println("Hello");

Hello

jshell>

Saturday, July 8, 2023

Springboot 3.1 - Spring security - Create Basic Oauth2 client - Continue

 Let's continue add security features for the basic application we have built. As you can see, we have used the basic inbuild features of the spring security where default username=user and with generated password.

So let's start configuring.

1. we will create class "SecurityConfig" and let's put that inside "config" package

2. Annotate with @Configuration and @EnableWebSecurity

import org.springframework.context.annotation.Configuration;

import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

3. create new bean with "SecurityFilterChain" with "HttpSecurity"

below is the sample

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.build();
}

So up to now, the full continue code of the "SecurityConfig" class would looks like below.

Note: we need to add Exception

package com.example.danwega.outh2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.build();
}
}

4. Now let's start adding security features or configure Spring security environment. We will start modifying bean we created "SecurityFilterChain"

let's authorize http requests.

  • we use authorizeHttpRequests
  • with this we use matchers requestMatchers
  •     For home anybody can go -> auth.requestMatchers("/").permitAll()
  •     For any other request use authentication --> auth.anyRequest().authenticated()

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/").permitAll();
auth.anyRequest().authenticated();
})
.build();
}

5. Now how are you going to login. So for now, let's give a formLogin with defaults

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/").permitAll();
auth.anyRequest().authenticated();
})
.formLogin(Customizer.withDefaults())
.build();
}

let's change the code to static import for "withDefaults"

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/").permitAll();
auth.anyRequest().authenticated();
})
.formLogin(withDefaults())
.build();
}

Now user have to log with user name and password to login

6. without just providing a formLogin, we need to provide a oauth2 login as we are using oauth2.

we add auth2Login with defaults for now.

.oauth2Login(withDefaults())
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> {
auth.requestMatchers("/").permitAll();
auth.anyRequest().authenticated();
})
.oauth2Login(withDefaults())
.formLogin(withDefaults())
.build();
}

That's it for now

7. configure properties to say what oauth2 client, providers we provide.

let's use log level just to what's happening inside when we running the code

logging:
level:
org:
springframework:
security: TRACE

here we will try to configure for GitHub and Google. 

let's first try with GitHub

Github

click your top right corner icon showing you --> go to "settings" --> left side go to "developer settings" in left bottom corner --> select "OAuth2 app" in left panel

8. Let's Register new application. you can give your details as needed, below is sample set

Application name: Spring Security OAuth2 client

Homepage url : localhost:8210

Application description : optional for now

Authorization callback url : localhost:8210/login/oauth2/code/github

call back url is set according to documentation. when it is google  final part will be "google", instead of "github"

 localhost:8210/login/oauth2/code/google

Click Register Application to finish the process. This will go to page and show you "client secret" and some other information

9.