Skip to content

Commit

Permalink
Added fat jar creation with new Project.
Browse files Browse the repository at this point in the history
Fixed the template to generate code correctly.
  • Loading branch information
AlexandrouR committed Dec 12, 2019
1 parent d06af17 commit 92487a1
Show file tree
Hide file tree
Showing 13 changed files with 181 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,10 @@ class InteractiveOptions {
static Scanner scanner = new Scanner(System.in);

static String getProjectName() {
print("Please enter the project name [BlockchainApp]:");
print("Please enter the project name [Web3App]:");
String projectName = getUserInput();
if (projectName.trim().isEmpty()) {
return "BlockchainApp";
return "Web3App";
}
while (!InputVerifier.classNameIsValid(projectName)) {
projectName = getUserInput();
Expand Down
71 changes: 57 additions & 14 deletions src/main/java/org/web3j/console/project/Project.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,31 @@
import java.io.IOException;

import org.web3j.commons.JavaVersion;
import org.web3j.console.Faucet;
import org.web3j.console.WalletFunder;
import org.web3j.console.project.utils.InputVerifier;
import org.web3j.console.project.utils.ProgressCounter;
import org.web3j.console.project.utils.ProjectUtils;

import static java.io.File.separator;

public class Project {
private TemplateProvider templateProvider;
private ProjectStructure projectStructure;

private Project(final Builder builder) {}
private Project(
final Builder builder,
TemplateProvider templateProvider,
ProjectStructure projectStructure) {
this.projectStructure = projectStructure;
this.templateProvider = templateProvider;
}

public TemplateProvider getTemplateProvider() {
return this.templateProvider;
}

public ProjectStructure getProjectStructure() {
return this.projectStructure;
}

public static Builder builder() {
return new Builder();
Expand All @@ -41,6 +55,8 @@ public static class Builder {
private String packageName;
private String rootDirectory;
private boolean withSampleCode = false;
private boolean withFatJar = false;
private ProgressCounter progressCounter = new ProgressCounter(true);

public Builder withSolidityFile(final File solidityImportPath) {
this.solidityImportPath = solidityImportPath;
Expand All @@ -62,6 +78,11 @@ public Builder withTests() {
return this;
}

public Builder withFatJar() {
this.withFatJar = true;
return this;
}

public Builder withProjectName(String projectName) {
this.projectName = projectName;
return this;
Expand All @@ -81,12 +102,12 @@ private void buildGradleProject(final String pathToDirectory)
throws IOException, InterruptedException {
if (!isWindows()) {
setExecutable(pathToDirectory, "gradlew");
executeCommand(
executeBuild(
new File(pathToDirectory),
new String[] {"bash", "-c", "./gradlew build -q"});
} else {
setExecutable(pathToDirectory, "gradlew.bat");
executeCommand(
executeBuild(
new File(pathToDirectory),
new String[] {"cmd.exe", "/c", "gradlew.bat build -q"});
}
Expand All @@ -101,10 +122,14 @@ private boolean isWindows() {
return System.getProperty("os.name").toLowerCase().startsWith("windows");
}

private void executeCommand(final File workingDir, final String[] command)
private void executeBuild(final File workingDir, final String[] command)
throws InterruptedException, IOException {
executeProcess(workingDir, command);
return;
}

private void executeProcess(File workingDir, String[] command)
throws InterruptedException, IOException {
ProgressCounter progressCounter = new ProgressCounter();
progressCounter.processing(true, "Creating " + projectName);
new ProcessBuilder(command)
.directory(workingDir)
.redirectOutput(ProcessBuilder.Redirect.INHERIT)
Expand All @@ -113,6 +138,18 @@ private void executeCommand(final File workingDir, final String[] command)
.waitFor();
}

private void createFatJar(String pathToDirectory) throws IOException, InterruptedException {
if (!isWindows()) {
executeProcess(
new File(pathToDirectory),
new String[] {"bash", "./gradlew", "shadowJar", "-q"});
} else {
executeProcess(
new File(pathToDirectory),
new String[] {"cmd.exe", "/c", "./gradlew.bat shadowJar", "-q"});
}
}

public Project build() throws Exception {
final ProjectStructure projectStructure =
new ProjectStructure(rootDirectory, packageName, projectName);
Expand All @@ -121,11 +158,16 @@ public Project build() throws Exception {
TemplateProvider builtTemplateProvider =
getTemplateProvider(projectStructure, projectWriter);
generateFiles(projectStructure, projectWriter, builtTemplateProvider);
progressCounter.processing("Creating " + projectName);
buildGradleProject(projectStructure.getProjectRoot());
if (withTests) {
generateTests(projectStructure);
}
return new Project(this);
if (withFatJar) {
createFatJar(projectStructure.getProjectRoot());
}
progressCounter.setLoading(false);
return new Project(this, builtTemplateProvider, projectStructure);
}

private void generateTests(ProjectStructure projectStructure) throws IOException {
Expand Down Expand Up @@ -241,17 +283,18 @@ private TemplateProvider getTemplateProvider(
.withPrivateKeyReplacement(
s ->
s.replace(
"<wallet_password_placeholder>",
projectWallet.getWalletPassword()))
"<passwod_file_name>",
projectWallet.getPasswordFileName()))
.withWalletNameReplacement(
s -> s.replace("<wallet_name>", projectWallet.getWalletName()));
projectWriter.writeResourceFile(
projectWallet.getWalletPassword(),
projectWallet.getPasswordFileName(),
projectStructure.getWalletPath());
if (JavaVersion.getJavaVersionAsDouble() < 11) {
WalletFunder.fundWallet(projectWallet.getWalletAddress(), Faucet.RINKEBY, null);
}
// if (JavaVersion.getJavaVersionAsDouble() < 11) {
// WalletFunder.fundWallet(projectWallet.getWalletAddress(),
// Faucet.RINKEBY, null);
// }
}
return templateProvider.build();
}
Expand Down
37 changes: 33 additions & 4 deletions src/main/java/org/web3j/console/project/ProjectCreator.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,16 @@
package org.web3j.console.project;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import picocli.CommandLine;

import org.web3j.console.project.utils.InputVerifier;

import static org.web3j.codegen.Console.exitError;
import static org.web3j.codegen.Console.exitSuccess;
import static org.web3j.utils.Collection.tail;
Expand Down Expand Up @@ -60,14 +64,22 @@ public static void main(String[] args) {
}

void generate() {
generate(true, Optional.empty(), false);
generate(true, Optional.empty(), false, false);
}

void generate(boolean withTests, Optional<File> solidityFile) {
generate(withTests, solidityFile, false);
generate(withTests, solidityFile, false, false);
}

void generate(boolean withTests, Optional<File> solidityFile, boolean withWallet) {
generate(withTests, solidityFile, withWallet, false);
}

void generate(
boolean withTests,
Optional<File> solidityFile,
boolean withWallet,
boolean withFatJar) {
try {
Project.Builder builder =
Project.builder()
Expand All @@ -82,14 +94,31 @@ void generate(boolean withTests, Optional<File> solidityFile, boolean withWallet
if (withTests) {
builder.withTests();
}
if (withFatJar) {
builder.withFatJar();
}
builder.build();
onSuccess();
} catch (final Exception e) {
exitError(e);
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
exitError("Could not generate project reason:" + sw.toString());
}
}

private void onSuccess() {
exitSuccess("\n" + this.projectName + " has been created in" + this.root);
exitSuccess(
"\n"
+ this.projectName
+ " has been created in "
+ this.root
+ "\n"
+ "To test your smart contracts (./src/test/java/io/web3j/generated/contracts/HelloWorldTest.java): ./gradlew test"
+ "\n"
+ "To run your Web3 app (./src/main/java/io/web3j/"
+ InputVerifier.capitalizeFirstLetter(this.projectName)
+ ".java): java -jar ./build/libs/"
+ InputVerifier.capitalizeFirstLetter(this.projectName)
+ "-0.1.0-all.jar");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public void run() {

private void createProject() {
new ProjectCreator(outputDir, packageName, projectName)
.generate(true, Optional.empty(), true);
.generate(true, Optional.empty(), true, true);
}

boolean inputIsValid(String... requiredArgs) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ TemplateProvider build() {
privateKeyReplacement.apply(
walletNameReplacement.apply(mainJavaClass)))),
solidityProject,
packageNameReplacement.apply(gradleBuild),
packageNameReplacement.apply(projectNameReplacement.apply(gradleBuild)),
projectNameReplacement.apply(gradleSettings),
gradlewWrapperSettings,
gradlewBatScript,
Expand Down
14 changes: 12 additions & 2 deletions src/main/java/org/web3j/console/project/utils/ProgressCounter.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,25 @@
import java.io.IOException;

public class ProgressCounter {
public void processing(boolean loading, String message) {
private boolean isLoading;

public ProgressCounter(boolean isLoading) {
this.isLoading = isLoading;
}

public void setLoading(boolean isLoading) {
this.isLoading = isLoading;
}

public void processing(String message) {
Thread th =
new Thread(
() -> {
String anim = "|/―\\";
try {
System.out.write("\r|".getBytes());
int current = 0;
while (loading) {
while (isLoading) {
current++;
String data =
String.format(
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/EmptyTemplate.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public class <project_name> {

public static void main(String[]args)throws Exception{
public static void main(String[]args) {

}

Expand Down
60 changes: 28 additions & 32 deletions src/main/resources/Template.java
Original file line number Diff line number Diff line change
@@ -1,61 +1,57 @@
package

<package_name>;
package <package_name>;

import <package_name>.generated.contracts.HelloWorld;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.web3j.abi.datatypes.Address;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.tx.gas.ContractGasProvider;
import org.web3j.tx.gas.DefaultGasProvider;
import org.web3j.protocol.http.HttpService;


import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class<project_name> {
public class <project_name> {

private static final Logger log=LoggerFactory.getLogger(<project_name>.class);
private static final Logger log=LoggerFactory.getLogger(<project_name>.class);


public static void main(String[]args)throws Exception{
Credentials credentials=loadCredentials("<wallet_name>","<wallet_password_placeholder>");
Web3j web3j=createWeb3jService("RINKEBY_NODE_URL");
public static void main(String[]args)throws Exception{
Credentials credentials=loadCredentials("<wallet_name>");
Web3j web3j=createWeb3jService("ETHEREUM_NODE");
HelloWorld helloWorld=deployHelloWorld(web3j,credentials,new DefaultGasProvider());
callGreetMethod(helloWorld);
}
}

private static Credentials loadCredentials(String walletName)throws CipherException,IOException,URISyntaxException{
String pathtoProjectResources=String.join(File.separator,System.getProperty("user.dir"),"src","test","resources","wallet");
String pathToWallet=String.join(File.separator,pathtoProjectResources,walletName)
String pathToWalletPasswordFile=String.join(File.separator,pathToProjectResources,)
File file=new File(pathToWallet);
private static Credentials loadCredentials(String walletName) throws IOException, CipherException {
String pathToProjectResources = String.join(File.separator, System.getProperty("user.dir"), "src", "test", "resources", "wallet");
String pathToWallet = String.join(File.separator, pathToProjectResources, walletName);
String pathToWalletPasswordFile = String.join(File.separator, pathToProjectResources, "<passwod_file_name>");
File file = new File(pathToWalletPasswordFile);
log.info("Reading wallet password from resources.");
String password=new String(Files.readAllBytes(Paths.get(file.toURI())));
log.info("Loading wallet file: "+walletName+" from resources.");
log.info("Creating credentials from from wallet.");
return WalletUtils.loadCredentials(walletPassword,new File(file));
}

String password = new String(Files.readAllBytes(Paths.get(file.toURI())));
log.info("Loading wallet file: " + walletName + " from resources.");
log.info("Creating credentials from wallet.");
return WalletUtils.loadCredentials(password, new File(pathToWallet));
}

private static Web3j createWeb3jService(String url){
private static Web3j createWeb3jService(String url){
log.info("Connecting to "+url);
return Web3j.build(new HttpService(url));
}
}

private static HelloWorld deployHelloWorld(Web3j web3j,Credentials credentials,ContractGasProvider contractGasProvider)throws Exception{
private static HelloWorld deployHelloWorld(Web3j web3j,Credentials credentials,ContractGasProvider contractGasProvider)throws Exception{
return HelloWorld.deploy(web3j,credentials,contractGasProvider,"Hello Blockchain World!").send();
}
}

private static void callGreetMethod(HelloWorld helloWorld)throws Exception{
private static void callGreetMethod(HelloWorld helloWorld)throws Exception{
log.info("Calling the greeting method of contract HelloWorld");
String response=helloWorld.greeting().send();
log.info("Contract returned: "+response);
}
}
log.info("Contract returned: "+ response);
}
}
Loading

0 comments on commit 92487a1

Please sign in to comment.