Skip to content

Commit

Permalink
Merge pull request #37 from AlexandrouR/online-services-integration
Browse files Browse the repository at this point in the history
Online services integration
  • Loading branch information
AlexandrouR authored Mar 6, 2020
2 parents b454c6d + b86a987 commit d2dff4b
Show file tree
Hide file tree
Showing 11 changed files with 286 additions and 23 deletions.
2 changes: 2 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ apply {
}

repositories {

maven { url "https://dl.bintray.com/ethereum/maven/" }
}

Expand Down Expand Up @@ -83,4 +84,5 @@ dependencies {
testImplementation "org.junit.jupiter:junit-jupiter:$junitVersion",
"org.mockito:mockito-core:$mockitoVersion",
"com.github.tomakehurst:wiremock-jre8:$wireMockVersion"
testImplementation 'org.mockito:mockito-inline:3.3.0'
}
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1 +1 @@
version=4.6.0-SNAPSHOT
version=4.6.0-SNAPSHOT
9 changes: 6 additions & 3 deletions src/main/java/org/web3j/console/Runner.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import org.web3j.codegen.Console;
import org.web3j.codegen.SolidityFunctionWrapperGenerator;
import org.web3j.codegen.TruffleJsonFunctionWrapperGenerator;
import org.web3j.console.account.AccountManager;
import org.web3j.console.config.CliConfig;
import org.web3j.console.project.ProjectCreator;
import org.web3j.console.project.ProjectImporter;
Expand All @@ -32,7 +33,7 @@
public class Runner {

private static final String USAGE =
"Usage: web3j version|wallet|solidity|new|import|generate-tests|audit ...";
"Usage: web3j version|wallet|solidity|new|import|generate-tests|audit|account ...";

private static final String LOGO =
"\n" // generated at http://patorjk.com/software/taag
Expand All @@ -47,7 +48,6 @@ public class Runner {

public static void main(String[] args) throws Exception {
System.out.println(LOGO);

CliConfig config = CliConfig.getConfig(CliConfig.getWeb3jConfigPath().toFile());
Updater updater = new Updater(config);
updater.promptIfUpdateAvailable();
Expand Down Expand Up @@ -85,14 +85,17 @@ public static void main(String[] args) throws Exception {
case "audit":
ContractAuditor.main(tail(args));
break;
case "account":
AccountManager.main(config, tail(args));
break;
case COMMAND_GENERATE_TESTS:
UnitTestCreator.main(tail(args));
break;
default:
Console.exitError(USAGE);
}
}

config.save();
Console.exitSuccess();
}
}
113 changes: 113 additions & 0 deletions src/main/java/org/web3j/console/account/AccountManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
/*
* Copyright 2020 Web3 Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package org.web3j.console.account;

import java.io.Closeable;
import java.io.IOException;
import java.util.Scanner;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

import org.web3j.console.config.CliConfig;

import static org.web3j.codegen.Console.exitError;

public class AccountManager implements Closeable {
private static final String USAGE = "account login|logout|create";
private static final String CLOUD_URL = "https://auth.epirus.io";
private OkHttpClient client;
CliConfig config;

public AccountManager(final CliConfig cliConfig, OkHttpClient client) {
this.client = client;
this.config = cliConfig;
}

public static void main(final CliConfig config, final String[] args) throws IOException {

Scanner console = new Scanner(System.in);
if ("create".equals(args[0])) {
System.out.println("Please enter your email address: ");
String email = console.nextLine().trim();
AccountManager accountManager = new AccountManager(config, new OkHttpClient());
accountManager.createAccount(email);
accountManager.close();
} else {
exitError(USAGE);
}
}

public void createAccount(String email) throws IOException {
RequestBody requestBody = createRequestBody(email);
Request newAccountRequest = createRequest(requestBody);

try {
Response sendRawResponse = executeClientCall(newAccountRequest);
ResponseBody body;
if (sendRawResponse.code() == 200 && (body = sendRawResponse.body()) != null) {
String rawResponse = body.string();
JsonObject responseJsonObj = JsonParser.parseString(rawResponse).getAsJsonObject();

if (responseJsonObj.get("token") == null) {

String tokenError = responseJsonObj.get("tokenError").getAsString();
if (tokenError == null || tokenError.isEmpty()) {
System.out.println("Could not retrieve token. Try again later.");
} else {
System.out.println(tokenError);
}
return;
}
String token = responseJsonObj.get("token").getAsString();
config.setLoginToken(token);
System.out.println(
"Account created successfully. You can now use Web3j Cloud. Please confirm your e-mail within 24 hours to continue using all features without interruption.");
} else {
System.out.println("Account creation failed. Please try again later.");
}

} catch (IOException e) {
System.out.println("Could not connect to the server.\nReason:" + e.getMessage());
}
}

protected final Response executeClientCall(Request newAccountRequest) throws IOException {
return client.newCall(newAccountRequest).execute();
}

protected final RequestBody createRequestBody(String email) {

return new FormBody.Builder().add("email", email).build();
}

protected final Request createRequest(RequestBody accountBody) {

return new Request.Builder()
.url(String.format("%s/auth/realms/EpirusPortal/web3j-token/create", CLOUD_URL))
.post(accountBody)
.build();
}

@Override
public void close() throws IOException {
this.client.dispatcher().executorService().shutdown();
this.client.connectionPool().evictAll();
}
}
40 changes: 26 additions & 14 deletions src/main/java/org/web3j/console/config/CliConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
public class CliConfig {
private static final Path web3jConfigPath =
Paths.get(System.getProperty("user.home"), ".web3j", ".config");
private static final String defaultServicesUrl = "https://internal.services.web3labs.com";
private static final String defaultServicesUrl = "https://auth.epirus.io";

public static Path getWeb3jConfigPath() {
return web3jConfigPath;
Expand All @@ -42,6 +42,7 @@ private static CliConfig initializeDefaultConfig(File configFile) throws IOExcep
defaultServicesUrl,
UUID.randomUUID().toString(),
Version.getVersion(),
null,
null);
}

Expand All @@ -60,18 +61,6 @@ public static CliConfig getConfig(File configFile) throws IOException {
}
}

public String getLatestVersion() {
return latestVersion;
}

public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}

public boolean isUpdateAvailable() {
return !version.equals(latestVersion);
}

public enum OS {
DARWIN,
FREEBSD,
Expand Down Expand Up @@ -109,6 +98,26 @@ public static OS determineOS() {
}
}

public String getLatestVersion() {
return latestVersion;
}

public void setLatestVersion(String latestVersion) {
this.latestVersion = latestVersion;
}

public boolean isUpdateAvailable() {
return !version.equals(latestVersion);
}

public String getLoginToken() {
return loginToken;
}

public void setLoginToken(final String loginToken) {
this.loginToken = loginToken;
}

public void setVersion(final String version) {
this.version = version;
}
Expand All @@ -118,18 +127,21 @@ public void setVersion(final String version) {
private String clientId;
private String latestVersion;
private String updatePrompt;
private String loginToken;

public CliConfig(
String version,
String servicesUrl,
String clientId,
String latestVersion,
String updatePrompt) {
String updatePrompt,
String loginToken) {
this.version = version;
this.servicesUrl = servicesUrl;
this.clientId = clientId;
this.latestVersion = latestVersion;
this.updatePrompt = updatePrompt;
this.loginToken = loginToken;
}

public String getVersion() {
Expand Down
25 changes: 24 additions & 1 deletion src/main/java/org/web3j/console/project/InteractiveOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,14 @@
package org.web3j.console.project;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.Scanner;

import com.fasterxml.jackson.databind.node.ObjectNode;

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

import static java.io.File.separator;
Expand Down Expand Up @@ -137,7 +141,6 @@ public static String getSolidityProjectPath() {
}

static String getUserInput() {

return scanner.nextLine();
}

Expand All @@ -150,4 +153,24 @@ public static boolean overrideExistingProject() {
String userAnswer = getUserInput();
return userAnswer.toLowerCase().equals("y");
}

public static boolean userHasWeb3jAccount() throws IOException {
if (LocalWeb3jAccount.configExists()) {
ObjectNode objectNode = LocalWeb3jAccount.readConfigAsJson();
return LocalWeb3jAccount.loginTokenExists(objectNode);
}
return false;
}

public static boolean configFileExists() {
return LocalWeb3jAccount.configExists();
}

public static boolean userWantsWeb3jAccount() throws IOException {

print("It looks like you don’t have a Web3j account, would you like to create one?");
print("This will provide free access to the Ethereum network [Y/n]");
String userAnswer = getUserInput();
return userAnswer.toLowerCase().equals("y") || userAnswer.trim().equals("");
}
}
24 changes: 22 additions & 2 deletions src/main/java/org/web3j/console/project/ProjectCreator.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
package org.web3j.console.project;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
Expand All @@ -22,6 +23,8 @@
import org.jetbrains.annotations.NotNull;
import picocli.CommandLine;

import org.web3j.console.account.AccountManager;
import org.web3j.console.config.CliConfig;
import org.web3j.console.project.java.JavaBuilder;
import org.web3j.console.project.java.JavaProjectCreatorCLIRunner;
import org.web3j.console.project.kotlin.KotlinBuilder;
Expand All @@ -48,7 +51,7 @@ public ProjectCreator(final String root, final String packageName, final String
this.root = root;
}

public static void main(String[] args) {
public static void main(String[] args) throws IOException {
final List<String> stringOptions = new ArrayList<>();
if (args.length > 0 && args[0].toLowerCase().equals(COMMAND_JAVA)) {
args = tail(args);
Expand All @@ -61,7 +64,8 @@ public static void main(String[] args) {
}

@NotNull
private static String[] getValues(String[] args, List<String> stringOptions) {
private static String[] getValues(String[] args, List<String> stringOptions)
throws IOException {
String projectName;
if (args.length == 0) {
stringOptions.add("-n");
Expand All @@ -75,6 +79,22 @@ private static String[] getValues(String[] args, List<String> stringOptions) {
stringOptions.add("-o");
stringOptions.add(projectDest);
});
if (InteractiveOptions.configFileExists()) {
if (!InteractiveOptions.userHasWeb3jAccount()) {
if (InteractiveOptions.userWantsWeb3jAccount()) {
AccountManager.main(
CliConfig.getConfig(CliConfig.getWeb3jConfigPath().toFile()),
new String[] {"create"});
}
}
} else {
if (InteractiveOptions.userWantsWeb3jAccount()) {
AccountManager.main(
CliConfig.getConfig(CliConfig.getWeb3jConfigPath().toFile()),
new String[] {"create"});
}
}

args = stringOptions.toArray(new String[0]);
}
return args;
Expand Down
1 change: 1 addition & 0 deletions src/main/java/org/web3j/console/update/Updater.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public Updater(CliConfig config) {
}

public void promptIfUpdateAvailable() {

if (config.isUpdateAvailable()) {
System.out.println(
String.format(
Expand Down
Loading

0 comments on commit d2dff4b

Please sign in to comment.