Skip to content

Commit

Permalink
Refactoring the code examples after adding linter to CI/CD (#118)
Browse files Browse the repository at this point in the history
* added a linter run command to CI/CD

* set failOnViolation property to true

* refactoring the code to ensure the build runs smoothly

* fixes after merge

* fixed build failure

* fixed build failure

* removing extra catches

* changed system.out.printLn to logger calls

* renamed static final variable

* fixing build issues

* fix for linter

* fixed build issue

* fixes for codestyle

---------

Signed-off-by: Anna Hileta <[email protected]>
  • Loading branch information
annahileta authored Nov 14, 2023
1 parent 5b868f7 commit ac45bcd
Show file tree
Hide file tree
Showing 164 changed files with 2,003 additions and 1,733 deletions.
2 changes: 2 additions & 0 deletions .github/workflows/maven.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ jobs:
java-version: '11'
distribution: 'temurin'
cache: maven
- name: Check code with linters
run: mvn -U checkstyle:check
- name: Download dependancies
env:
CLIENT_ID: ${{ secrets.CLIENT_ID }}
Expand Down
10 changes: 0 additions & 10 deletions checkstyle.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,13 @@
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://www.puppycrawl.com/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="JavadocPackage"/>
<module name="TreeWalker">
<!-- Code convention checking -->
<!-- One statement per line, one declaration per line -->
<module name="OneStatementPerLine">
<property name="treatTryResourcesAsStatement" value="true"/>
</module>

<!-- If continuation lines are not indented automatically, indent them one tab stop -->
<module name="JavadocTagContinuationIndentation">
<property name="offset" value="2"/>
<property name="violateExecutionOnNonTightHtml" value="true"/>
</module>

<!-- Add at least one blank line between method definitions and property definitions -->
<module name="EmptyLineSeparator">
<property name="tokens" value="VARIABLE_DEF, METHOD_DEF"/>
Expand All @@ -32,9 +25,6 @@
<!-- Avoid Redundant Initializations -->
<module name="ExplicitInitialization"/>

<!-- Check using catch -->
<module name="IllegalCatch"/>

<!-- Other checking -->

<!-- Loops need braces except they are a single line statement -->
Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@
<configuration>
<configLocation>checkstyle.xml</configLocation>
<violationSeverity>warning</violationSeverity>
<failOnViolation>false</failOnViolation>
<failOnViolation>true</failOnViolation>
</configuration>
</plugin>
</plugins>
Expand Down
39 changes: 20 additions & 19 deletions src/main/java/com/docusign/App.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
package com.docusign;

import java.io.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
Expand All @@ -10,17 +20,8 @@
import java.nio.file.Path;
import java.util.Collections;

import java.awt.Desktop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

@Slf4j
@SpringBootApplication(exclude={JmxAutoConfiguration.class})
@SpringBootApplication(exclude = {JmxAutoConfiguration.class})
@ComponentScan(basePackages = "com.docusign")
@Import(WebSecurityConfig.class)

Expand All @@ -32,7 +33,7 @@ public static void main(String[] args) throws IOException, URISyntaxException {
ClassLoader classLoader = App.class.getClassLoader();
URL applicationJsonURL = classLoader.getResource("application.json");

if (applicationJsonURL != null){
if (applicationJsonURL != null) {
SpringApplication.run(App.class, args);
openHomePage();
} else {
Expand All @@ -46,16 +47,16 @@ public static void main(String[] args) throws IOException, URISyntaxException {
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
} catch (Exception e) {
System.out.println("File applicationJsonMissingError.html could not be accessed.");
} catch (IOException e) {
log.error("File applicationJsonMissingError.html could not be accessed.");
}

Desktop.getDesktop().browse(path.toUri());
}

System.out.println("");
System.out.println("Please, add the application.json file to the resources folder.");
System.out.println("");
log.info("");
log.info("Please, add the application.json file to the resources folder.");
log.info("");
}
}

Expand All @@ -64,15 +65,15 @@ private static void openHomePage() throws IOException {
try {
Desktop.getDesktop().browse(new URI("http://localhost:8080"));
} catch (URISyntaxException use) {
System.err.println("Invalid URI in App.openHomePage()");
log.error("Invalid URI in App.openHomePage()");
}
}

private static void initFileSystem() {
try {
FileSystems.newFileSystem(new URI(""), Collections.emptyMap());
log.info("FileSystem initialized successfully");
} catch (Exception e) {
} catch (FileSystemAlreadyExistsException | URISyntaxException | IOException e) {
if (e instanceof FileSystemAlreadyExistsException) {
log.info("FileSystem is already initialized");
} else {
Expand Down
26 changes: 13 additions & 13 deletions src/main/java/com/docusign/DSConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@
import com.docusign.core.model.manifestModels.ManifestStructure;
import com.docusign.esign.client.auth.OAuth;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.core.HttpHeaders;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import jakarta.ws.rs.HttpMethod;
import jakarta.ws.rs.core.HttpHeaders;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
Expand All @@ -23,6 +23,10 @@
@Setter
public class DSConfiguration {

public Boolean isConsentRedirectActivated = false;

public String apiTypeHeader = "ApiType";

@Value("${com.docusign.github.example-uri}")
private String exampleUrl;

Expand All @@ -33,8 +37,6 @@ public class DSConfiguration {

private ManifestStructure codeExamplesText;

public Boolean isConsentRedirectActivated = false;

private boolean additionalRedirect;

private boolean shareAccessExampleScenario;
Expand Down Expand Up @@ -104,8 +106,6 @@ public class DSConfiguration {
@Value("${CodeExamplesManifest}")
private String codeExamplesManifest;

public String apiTypeHeader = "ApiType";

public String getDsReturnUrl() {
return appUrl + "/ds-return";
}
Expand All @@ -115,37 +115,37 @@ public String getDsPingUrl() {
}

public String getBaseUrl(ApiIndex apiIndex, OAuth.Account oauthAccount) {
if (apiIndex.equals(ApiIndex.ROOMS)) {
if (ApiIndex.ROOMS.equals(apiIndex)) {
return roomsBasePath;
} else if (apiIndex.equals(ApiIndex.CLICK)) {
} else if (ApiIndex.CLICK.equals(apiIndex)) {
return clickBasePath;
} else if (apiIndex.equals(ApiIndex.MONITOR)) {
} else if (ApiIndex.MONITOR.equals(apiIndex)) {
return monitorBasePath;
} else if (apiIndex.equals(ApiIndex.ADMIN)) {
} else if (ApiIndex.ADMIN.equals(apiIndex)) {
return adminBasePath;
}

return oauthAccount.getBaseUri();
}

public ApiType getSelectedApiType() {
if (selectedApiType == null){
if (selectedApiType == null) {
return ApiType.ESIGNATURE;
}

return ApiType.valueOf(selectedApiType);
}

public ApiIndex getSelectedApiIndex() {
if (selectedApiType == null){
if (selectedApiType == null) {
return ApiIndex.ESIGNATURE;
}

return ApiIndex.valueOf(selectedApiType);
}

public ManifestStructure getCodeExamplesText() {
if (codeExamplesText != null){
if (codeExamplesText != null) {
return codeExamplesText;
}

Expand Down
27 changes: 14 additions & 13 deletions src/main/java/com/docusign/EG001ControllerEmbeddedSigning.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,14 @@

import com.docusign.common.WorkArguments;
import com.docusign.controller.eSignature.examples.AbstractEsignatureController;
import com.docusign.controller.eSignature.services.EmbeddedSigningService;
import com.docusign.core.common.Utils;
import com.docusign.core.model.Session;
import com.docusign.core.model.User;
import com.docusign.esign.api.EnvelopesApi;
import com.docusign.esign.client.ApiClient;
import com.docusign.esign.model.EnvelopeDefinition;
import com.docusign.esign.model.EnvelopeSummary;
import com.docusign.esign.model.RecipientViewRequest;
import com.docusign.esign.model.ViewUrl;

import com.docusign.controller.eSignature.services.EmbeddedSigningService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
Expand All @@ -33,26 +30,30 @@
public class EG001ControllerEmbeddedSigning extends AbstractEsignatureController {

private static final String DOCUMENT_FILE_NAME = "World_Wide_Corp_lorem.pdf";

private static final String DOCUMENT_NAME = "Lorem Ipsum";

private static final int ANCHOR_OFFSET_Y = 20;

private static final int ANCHOR_OFFSET_X = 10;

private static final String SIGNER_CLIENT_ID = "1000";

@Autowired
public EG001ControllerEmbeddedSigning(DSConfiguration config, Session session, User user){
public EG001ControllerEmbeddedSigning(DSConfiguration config, Session session, User user) {
super(config, Boolean.valueOf(config.getQuickACG()) ? "quickEmbeddedSigning" : "eg001", session, user);
}

@Override
protected void onInitModel(WorkArguments args, ModelMap model) throws Exception {
super.onInitModel(args, model);
if(Utils.isCfr(session.getBasePath(), user.getAccessToken(), session.getAccountId())){
session.setStatusCFR("enabled");
throw new Exception(config.getCodeExamplesText().getSupportingTexts().getCFRError());
}
if(config.getQuickstart().equals("true")){
config.setQuickstart("false");
}
super.onInitModel(args, model);
if (Utils.isCfr(session.getBasePath(), user.getAccessToken(), session.getAccountId())) {
session.setStatusCFR("enabled");
throw new Exception(config.getCodeExamplesText().getSupportingTexts().getCFRError());
}
if (config.getQuickstart().equals("true")) {
config.setQuickstart("false");
}
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
package com.docusign;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class httpsconnectwebhookhmacvalidation {
public class HttpsConnectWebhookhMacValidation {

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

/*
* Useful reference:
* https://docs.oracle.com/javase/10/docs/api/javax/crypto/Mac.html
Expand All @@ -29,28 +37,22 @@ private static String ComputeHash(String secret, byte[] payload)
public static boolean HashIsValid(String secret, byte[] payload, String verify)
throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
String computedHash = ComputeHash(secret, payload);
boolean isEqual = MessageDigest.isEqual(computedHash.getBytes("UTF-8"),
verify.getBytes("UTF-8"));
boolean isEqual = MessageDigest.isEqual(computedHash.getBytes(StandardCharsets.UTF_8),
verify.getBytes(StandardCharsets.UTF_8));
return isEqual;
}

public static void main(String[] args) {

System.out.println("DocuSign HMAC Tester");
LOGGER.info("DocuSign HMAC Tester");
try {

Boolean response = httpsconnectwebhookhmacvalidation.HashIsValid("{DocuSign HMAC private key}",
Boolean response = HttpsConnectWebhookhMacValidation.HashIsValid("{DocuSign HMAC private key}",
Files.readAllBytes(Paths.get("payload.txt")), "{JSON response Signature}");
System.out.printf("is this HMAC Valid? ");
System.out.println(response);

LOGGER.info("is this HMAC Valid? ");
LOGGER.info(String.valueOf(response));
} catch (Exception e) {

System.out.print("Error!!! ");
System.out.print(e.getMessage());

LOGGER.error("Error!!! ");
LOGGER.error(e.getMessage());
}

}

}
2 changes: 1 addition & 1 deletion src/main/java/com/docusign/JsonPropertySourceLoader.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

public class JsonPropertySourceLoader extends YamlPropertySourceLoader {
@Override
public String[] getFileExtensions () {
public String[] getFileExtensions() {
return new String[]{"json"};
}
}
25 changes: 0 additions & 25 deletions src/main/java/com/docusign/OSDetector.java

This file was deleted.

2 changes: 1 addition & 1 deletion src/main/java/com/docusign/WebSecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,6 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
)
.csrf().disable();

return http.build();
return http.build();
}
}
Loading

0 comments on commit ac45bcd

Please sign in to comment.