Header Ads Widget

Responsive Advertisement

Auto-Update Batch File with Latest JAR & Start App Automatically


A> Single Jar file and update single bat file

To automatically find the latest JAR file, update the batch file, and start the application using the new JAR file without manual intervention, we can follow these steps:

  1. Locate the latest JAR file: Determine the latest JAR file based on the versioning in its name.
  2. Update the batch file: Modify the batch file to reference the latest JAR file.
  3. Start the application: Run the updated batch file.

Here's how you can implement this in Java:

Java Program

  1. Locate the latest JAR file: This involves listing all JAR files in a directory and finding the one with the highest version number.
  2. Update the batch file: Modify the batch file to reference the latest JAR file.
  3. Run the batch file: Execute the updated batch file.

Code Example

java

import java.io.IOException;

import java.nio.file.*;

import java.util.List;

import java.util.Optional;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import java.util.stream.Collectors;

 

public class JarUpdater {

 

    private static final String JAR_DIRECTORY = "C:\\path\\to\\jar\\directory";

    private static final String BATCH_FILE_PATH = "C:\\path\\to\\your\\runApp.bat";

 

    public static void main(String[] args) {

        try {

            // Step 1: Locate the latest JAR file

            String latestJar = findLatestJar(JAR_DIRECTORY);

 

            if (latestJar != null) {

                // Step 2: Update the batch file with the latest JAR version

                updateBatchFile(BATCH_FILE_PATH, latestJar);

 

                // Step 3: Execute the updated batch file to start the application

                executeBatchFile(BATCH_FILE_PATH);

            } else {

                System.out.println("No JAR files found in the directory.");

            }

        } catch (IOException | InterruptedException e) {

            e.printStackTrace();

        }

    }

 

    private static String findLatestJar(String jarDirectory) throws IOException {

        Path dir = Paths.get(jarDirectory);

        Pattern jarPattern = Pattern.compile("myapp-(\\d+\\.\\d+\\.\\d+)\\.jar");

 

        Optional<String> latestJar = Files.list(dir)

                .filter(path -> path.toString().endsWith(".jar"))

                .map(Path::getFileName)

                .map(Path::toString)

                .filter(jarPattern.asPredicate())

                .sorted((a, b) -> compareVersions(extractVersion(a, jarPattern), extractVersion(b, jarPattern)))

                .findFirst();

 

        return latestJar.orElse(null);

    }

 

    private static int compareVersions(String version1, String version2) {

        String[] parts1 = version1.split("\\.");

        String[] parts2 = version2.split("\\.");

        for (int i = 0; i < parts1.length; i++) {

            int v1 = Integer.parseInt(parts1[i]);

            int v2 = Integer.parseInt(parts2[i]);

            if (v1 != v2) {

                return Integer.compare(v2, v1);

            }

        }

        return 0;

    }

 

    private static String extractVersion(String jarName, Pattern jarPattern) {

        Matcher matcher = jarPattern.matcher(jarName);

        if (matcher.matches()) {

            return matcher.group(1);

        }

        return "";

    }

 

    private static void updateBatchFile(String batchFilePath, String newJarVersion) throws IOException {

        Path batchFile = Paths.get(batchFilePath);

        List<String> lines = Files.readAllLines(batchFile);

        List<String> updatedLines = lines.stream()

                .map(line -> line.contains("myapp-") && line.endsWith(".jar") ? replaceJarVersion(line, newJarVersion) : line)

                .collect(Collectors.toList());

        Files.write(batchFile, updatedLines);

        System.out.println("Updated batch file: " + batchFilePath);

    }

 

    private static String replaceJarVersion(String line, String newJarVersion) {

        return line.replaceAll("myapp-[\\d\\.]+\\.jar", newJarVersion);

    }

 

    private static void executeBatchFile(String batchFilePath) throws IOException, InterruptedException {

        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", batchFilePath);

        processBuilder.inheritIO();

        Process process = processBuilder.start();

        process.waitFor();

        System.out.println("Executed batch file: " + batchFilePath);

    }

}

 

Explanation

  1. Locate the latest JAR file:

Ø  The findLatestJar method lists all files in the specified directory and filters for files matching the myapp-<version>.jar pattern.

Ø  The compareVersions method compares version strings numerically to determine the latest version.

Ø  The extractVersion method extracts the version number from the JAR file name.

  1. Update the batch file:

Ø  The updateBatchFile method reads the batch file, replaces any line containing an old JAR version with the new JAR version, and writes the updated content back to the file.

  1. Execute the batch file:

Ø  The executeBatchFile method uses ProcessBuilder to run the batch file, starting the application with the latest JAR version.

Batch File Example (runApp.bat)

Before updating:

batch

@echo off

java -jar myapp-1.0.0.jar

 

After running the Java program, the batch file would be updated to:

batch

@echo off

java -jar myapp-1.2.3.jar

 

Usage

  1. Set the correct paths:

Ø  Update the JAR_DIRECTORY with the path to the directory containing your JAR files.

Ø  Update the BATCH_FILE_PATH with the path to your batch file.

  1. Run the Java program:

Ø  Compile and run the Java program. It will find the latest JAR file, update the batch file, and execute it to start the application with the new JAR version.

This approach automates the process of finding the latest JAR file, updating the batch file, and starting the application, eliminating the need for manual updates.

 


B> Multiple Jar files and update multiple bat files

To automatically find the latest JAR files for multiple microservices, update their corresponding batch files, and start all the applications, you can extend the previous solution to handle multiple services.

Steps to Implement

  1. Locate the latest JAR file for each microservice: Determine the latest JAR file based on the versioning in its name for each microservice.
  2. Update the batch files: Modify each batch file to reference the latest JAR file for the corresponding microservice.
  3. Start the applications: Run each updated batch file to start the respective microservice.

Java Program to Handle Multiple Microservices

  1. Define microservices and their directories: Map each microservice to its JAR directory and batch file.
  2. Locate the latest JAR file for each microservice.
  3. Update each batch file.
  4. Run the batch files.

Code Example

java

import java.io.IOException;

import java.nio.file.*;

import java.util.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import java.util.stream.Collectors;

 

public class MultiServiceJarUpdater {

 

    private static final Map<String, String> microservices = new HashMap<>() {{

        put("service1", "C:\\path\\to\\service1\\jar\\directory");

        put("service2", "C:\\path\\to\\service2\\jar\\directory");

        put("service3", "C:\\path\\to\\service3\\jar\\directory");

    }};

   

    private static final Map<String, String> batchFiles = new HashMap<>() {{

        put("service1", "C:\\path\\to\\service1\\runService1.bat");

        put("service2", "C:\\path\\to\\service2\\runService2.bat");

        put("service3", "C:\\path\\to\\service3\\runService3.bat");

    }};

 

    public static void main(String[] args) {

        try {

            for (String service : microservices.keySet()) {

                String jarDirectory = microservices.get(service);

                String batchFilePath = batchFiles.get(service);

 

                // Step 1: Locate the latest JAR file for the microservice

                String latestJar = findLatestJar(jarDirectory);

 

                if (latestJar != null) {

                    // Step 2: Update the batch file with the latest JAR version

                    updateBatchFile(batchFilePath, latestJar);

 

                    // Step 3: Execute the updated batch file to start the application

                    executeBatchFile(batchFilePath);

                } else {

                    System.out.println("No JAR files found for " + service + " in the directory.");

                }

            }

        } catch (IOException | InterruptedException e) {

            e.printStackTrace();

        }

    }

 

    private static String findLatestJar(String jarDirectory) throws IOException {

        Path dir = Paths.get(jarDirectory);

        Pattern jarPattern = Pattern.compile("myapp-(\\d+\\.\\d+\\.\\d+)\\.jar");

 

        Optional<String> latestJar = Files.list(dir)

                .filter(path -> path.toString().endsWith(".jar"))

                .map(Path::getFileName)

                .map(Path::toString)

                .filter(jarPattern.asPredicate())

                .sorted((a, b) -> compareVersions(extractVersion(a, jarPattern), extractVersion(b, jarPattern)))

                .findFirst();

 

        return latestJar.orElse(null);

    }

 

    private static int compareVersions(String version1, String version2) {

        String[] parts1 = version1.split("\\.");

        String[] parts2 = version2.split("\\.");

        for (int i = 0; i < parts1.length; i++) {

            int v1 = Integer.parseInt(parts1[i]);

            int v2 = Integer.parseInt(parts2[i]);

            if (v1 != v2) {

                return Integer.compare(v2, v1);

            }

        }

        return 0;

    }

 

    private static String extractVersion(String jarName, Pattern jarPattern) {

        Matcher matcher = jarPattern.matcher(jarName);

        if (matcher.matches()) {

            return matcher.group(1);

        }

        return "";

    }

 

    private static void updateBatchFile(String batchFilePath, String newJarVersion) throws IOException {

        Path batchFile = Paths.get(batchFilePath);

        List<String> lines = Files.readAllLines(batchFile);

        List<String> updatedLines = lines.stream()

                .map(line -> line.contains("myapp-") && line.endsWith(".jar") ? replaceJarVersion(line, newJarVersion) : line)

                .collect(Collectors.toList());

        Files.write(batchFile, updatedLines);

        System.out.println("Updated batch file: " + batchFilePath);

    }

 

    private static String replaceJarVersion(String line, String newJarVersion) {

        return line.replaceAll("myapp-[\\d\\.]+\\.jar", newJarVersion);

    }

 

    private static void executeBatchFile(String batchFilePath) throws IOException, InterruptedException {

        ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", batchFilePath);

        processBuilder.inheritIO();

        Process process = processBuilder.start();

        process.waitFor();

        System.out.println("Executed batch file: " + batchFilePath);

    }

}

 

 

Explanation

  1. Define Microservices:

Ø  Use microservices map to store the directories where JAR files for each microservice are located.

Ø  Use batchFiles map to store the paths to the batch files for each microservice.

  1. Locate the Latest JAR File:

Ø  The findLatestJar method locates the latest JAR file in the specified directory by comparing version numbers.

  1. Update the Batch Files:

Ø  The updateBatchFile method updates the batch file to use the latest JAR version.

  1. Run the Batch Files:

Ø  The executeBatchFile method executes the batch file to start the application.

Batch File Example (runService1.bat)

Before updating:

batch

@echo off

java -jar myapp-1.0.0.jar

 

After running the Java program, the batch file would be updated to:

batch

@echo off

java -jar myapp-1.2.3.jar

 

Usage

  1. Set the Correct Paths:

Ø  Update the microservices map with paths to the directories containing JAR files for each microservice.

Ø  Update the batchFiles map with paths to the batch files for each microservice.

  1. Run the Java Program:

Ø  Compile and run the Java program. It will find the latest JAR files, update the batch files, and execute them to start each microservice with the latest JAR version.

This approach automates the process of finding the latest JAR files for multiple microservices, updating the batch files, and starting the applications, eliminating the need for manual updates

 


Real Code Example for multiple microservice jar files

To create a series of batch files that automatically update with the latest JAR files for different microservices, and manage different target paths in Java, you can use Java’s file handling and string manipulation features to generate these batch scripts dynamically.

Here’s a step-by-step breakdown:

Steps:

  1. Identify the JAR file locations and target paths for each microservice.
  2. Create a template for the batch file, with placeholders for paths.
  3. Use Java to generate the batch files by reading the latest JAR files from the respective directories and updating the paths automatically.
  4. Write the generated content into batch files.

java

package com.kartik.jar.version;

 

import java.io.File;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.net.URISyntaxException;

import java.nio.charset.Charset;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

public class JarFileVersion {

 

              public static void main(String[] args) throws IOException, URISyntaxException {

                                                         

                             JarFileVersion jfv = new JarFileVersion();

                             Map<String, String> mapInput = new LinkedHashMap<String, String>();

                             mapInput.put("CONFIG_SERVICE", "C:/Users/SG0308108/FileDetails/configuration/configuration-impl/target");

                             mapInput.put("CONFIG_PROVIDER_SERVICE", "C:/Users/SG0308108/FileDetails/configuration-provider/configuration-provider-impl/target");

                             mapInput.put("SESSION_SERVICE", "C:/Users/SG0308108/FileDetails/session/session-service/target");

                             mapInput.put("LOGIN_SERVICE", "C:/Users/SG0308108/FileDetails/login-profile/login-profile-impl/target");

                             mapInput.put("AIR_SERVICE", "C:/Users/SG0308108/FileDetails/air/air-impl/service/target");

                             mapInput.put("ANCILLARIES_SERVICE", "C:/Users/SG0308108/FileDetails/ancillaries/ancillaries-impl/target");

                             mapInput.put("BAGAGE_SERVICE", "C:/Users/SG0308108/FileDetails/baggage/baggage-impl/target");                        

                             mapInput.put("FAIR_RULE_SERVICE", "C:/Users/SG0308108/FileDetails/farerules/farerules-impl/target");

                             mapInput.put("FLIGHT_STATUS_SERVICE", "C:/Users/SG0308108/FileDetails/flight-status/flight-status-impl/target");

                             mapInput.put("INSURANCE_SERVICE", "C:/Users/SG0308108/FileDetails/insurance/insurance-impl/target");

                             mapInput.put("PASSENGER_SERVICE", "C:/Users/SG0308108/FileDetails/passenger/passenger-impl/target");

                             mapInput.put("PAYMENT_OPTION_SERVICE", "C:/Users/SG0308108/FileDetails/payment-options/payment-options-impl/target");

                             mapInput.put("PRODUCT_SERVICE", "C:/Users/SG0308108/FileDetails/products/products-impl/service/target");

                             mapInput.put("PURCHASE_SERVICE_1", "C:/Users/SG0308108/FileDetails/purchase/purchase-impl/payment-service/target");

                             mapInput.put("PURCHASE_SERVICE_2", "C:/Users/SG0308108/FileDetails/purchase/booking/booking-impl/target");

                             mapInput.put("PURCHASE_SERVICE_3", "C:/Users/SG0308108/FileDetails/purchase/purchase-impl/purchase-orchestrator/target");

                             mapInput.put("PURCHASE_SERVICE_4", "C:/Users/SG0308108/FileDetails/purchase/purchase-impl/poller-service/target");

                             mapInput.put("PURCHASE_SERVICE_5", "C:/Users/SG0308108/FileDetails/purchase/purchase-impl/fulfillment-service/target");

                             mapInput.put("PURCHASE_SERVICE_6", "C:/Users/SG0308108/FileDetails/purchase/purchase-impl/fraud-check-service/target");

                             mapInput.put("SEAT_SERVICE", "C:/Users/SG0308108/FileDetails/seats/seats-impl/target");

                             mapInput.put("PNR_SERVICE", "C:/Users/SG0308108/FileDetails/pnr/pnr-impl/target");

                            

                             Map<String, String> mapOutPut = new LinkedHashMap<String, String>();

                             for (Map.Entry<String, String> entry : mapInput.entrySet()) {

                                           System.out.println(entry.getKey() + ":" + entry.getValue());

                                           mapOutPut.put(entry.getKey(),

                                                                        jfv.getResourceListing(entry.getValue()));

                             }

                             for (Map.Entry<String, String> entry : mapOutPut.entrySet()) {

                                           jfv.searchAndUpdate(entry.getKey(), entry.getValue());

                                           // System.out.println("kkk "+entry.getValue());

                                           // jfv.runBatFile(entry.getKey()+".bat");

                             }

 

              }

 

              String getResourceListing(String path) throws URISyntaxException,

                                           UnsupportedEncodingException, IOException {

                             File folder = new File(path);

                             File[] listOfFiles = folder.listFiles();

 

                             for (int i = 0; i < listOfFiles.length; i++) {

                                           if (listOfFiles[i].isFile()) {

                                                          String fName = listOfFiles[i].getName();

                                                          if (fName.endsWith(".jar")) {

                                                                        System.out.println("File " + fName);

                                                                        return fName;

                                                          }

                                           } else if (listOfFiles[i].isDirectory()) {

                                                          // System.out.println("Directory " + listOfFiles[i].getName());

                                           }

                             }

                             return null;

              }

 

              void searchAndUpdate(String fileName, String newFileName)

                                           throws IOException {

                             String REGEX = "([^\\s]+(\\.(?i)(txt|doc|csv|pdf|jar))$)";

                             String file = "C:/DC/KartikRequired/Project/Common/FileDetails_bat/batch/"

                                                          + fileName + ".bat";

                             Path path = Paths.get(file);

                             Charset charset = StandardCharsets.UTF_8;

                             String content = new String(Files.readAllBytes(path), charset);

                             Pattern p = Pattern.compile(REGEX);

                             Matcher m = p.matcher(content);

                             content = m.replaceAll(newFileName);

                             Files.write(path, content.getBytes(charset));

              }

 

              void runBatFile(String fileName) {

                             try {

                                           Runtime.getRuntime()

                                                                        .exec("cmd /c " + fileName,

                                                                                                     null,

                                                                                                     new File(

                                                                                                                                 "C:/DC/KartikRequired/Project/Common/FileDetails_bat/batch/"));

                             } catch (IOException e) {

                                           e.printStackTrace();

                             }

              }

 

              String getVersion(String pathWithFile) {

                             File file = new File(pathWithFile);

                             String versionNumber = "";

                             String fileName = file.getName().substring(0,

                                                          file.getName().lastIndexOf("."));

                             if (fileName.contains(".")) {

                                           String majorVersion = fileName.substring(0, fileName.indexOf("."));

                                           String minorVersion = fileName.substring(fileName.indexOf("."));

                                           int delimiter = majorVersion.lastIndexOf("-");

                                           if (majorVersion.indexOf("_") > delimiter)

                                                          delimiter = majorVersion.indexOf("_");

                                           majorVersion = majorVersion.substring(delimiter + 1,

                                                                        fileName.indexOf("."));

                                           versionNumber = majorVersion + minorVersion;

                             }

                             System.out.println("Version: " + versionNumber);

                             return versionNumber;

              }

 

              String getVersionDetails(String pathWithFile) throws IOException {

                             /*java.io.File file = new java.io.File(

                                                          "C:/Users/SG0308108/FileDetails/air/air-impl/service/target/air-service-2.0.14-SNAPSHOT.jar");*/

                             java.io.File file = new java.io.File(pathWithFile);

                             java.util.jar.JarFile jar = new java.util.jar.JarFile(file);

                             java.util.jar.Manifest manifest = jar.getManifest();

                             String versionNumber = "";

                             java.util.jar.Attributes attributes = manifest.getMainAttributes();

                             if (attributes != null) {

                                           java.util.Iterator it = attributes.keySet().iterator();

                                           while (it.hasNext()) {

                                                          java.util.jar.Attributes.Name key = (java.util.jar.Attributes.Name) it

                                                                                      .next();

                                                          String keyword = key.toString();

                                                          if (keyword.equals("Implementation-Version")

                                                                                      || keyword.equals("Bundle-Version")) {

                                                                        versionNumber = (String) attributes.get(key);

                                                                        break;

                                                          }

                                           }

                             }

                             jar.close();

 

                             System.out.println("Version: " + versionNumber);

                             return versionNumber;

              }

}

 



Multiple File read from multiple places and update in multiple bat file
Multiple File read from multiple places and update in multiple bat file









Post a Comment

0 Comments