Friday, 1 December 2023

virtual environment-like setup for Java

 

1. Download All Required Dependencies

Use Apache Maven to download and cache all dependencies.

  1. Open the terminal and navigate to your project directory.
  2. Run the following command:

bash

mvn dependency:go-offline

This command will pre-download all the dependencies required by your project and cache them locally in the .m2 directory (default Maven repository location).


2. Package the Application into a JAR

  1. Build a fat (or "uber") JAR that bundles your project code and all dependencies into a single file.

Add the Maven Shade plugin to your pom.xml to create this fat JAR:

xml

 

<build>

    <plugins>

        <plugin>

            <groupId>org.apache.maven.plugins</groupId>

            <artifactId>maven-shade-plugin</artifactId>

            <version>3.4.0</version>

            <executions>

                <execution>

                    <phase>package</phase>

                    <goals>

                        <goal>shade</goal>

                    </goals>

                </execution>

            </executions>

        </plugin>

    </plugins>

</build>

  1. Build the fat JAR:

bash

mvn clean package

The resulting JAR will be located in the target directory (e.g., target/kafka-consumer-1.0-SNAPSHOT.jar).


3. Prepare the Offline Virtual Environment

To simulate a virtual environment, package the JAR file along with the required tools for offline execution:

  1. Create a directory to store everything:

bash

 

mkdir kafka-consumer-offline

cd kafka-consumer-offline

  1. Copy the JAR file:

bash

 

cp path/to/target/kafka-consumer-1.0-SNAPSHOT.jar kafka-consumer-offline/

  1. Copy the .m2 Maven repository (contains all dependencies):

bash

 

cp -r ~/.m2/repository kafka-consumer-offline/m2-repository

  1. Create a run.sh script to execute the project in this self-contained environment:

bash

 

echo '#!/bin/bash

export MAVEN_OPTS="-Dmaven.repo.local=$(pwd)/m2-repository" java -jar kafka-consumer-1.0-SNAPSHOT.jar ' > run.sh chmod +x run.sh

yaml

 

 

---

 

## **4. Transfer and Execute the Project in an Offline Environment**

 

1. Transfer the `kafka-consumer-offline` directory to the offline machine.

 

2. On the offline machine, navigate to the directory:

```bash

cd kafka-consumer-offline

  1. Execute the project using the run.sh script:

bash

 

./run.sh


5. Testing the Environment

Before transferring the environment to the offline machine:

  • Disconnect your internet or simulate the offline environment.
  • Test the run.sh script locally to ensure all dependencies are properly bundled.

 

No comments:

Post a Comment