java.lang.ClassNotFoundException: org.junit.Assert / Working with docising API - java

I have encountered these errors when trying to implement the docusing embedded signature into my web app (java -eclipse).
java.lang.ClassNotFoundException: org.junit.Assert
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1412)
org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1220)
com.uniquedeveloper.registration.test2.EmbeddedSigningTest(test2.java:94)
com.uniquedeveloper.registration.test2.doPost(test2.java:79)
javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Here is my code for the test2 class:
package com.uniquedeveloper.registration;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import javax.servlet.jsp.PageContext;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import com.docusign.esign.api.EnvelopesApi;
import com.docusign.esign.client.ApiClient;
import com.docusign.esign.client.ApiException;
import com.docusign.esign.model.Document;
import com.docusign.esign.model.EnvelopeDefinition;
import com.docusign.esign.model.EnvelopeSummary;
import com.docusign.esign.model.RecipientViewRequest;
import com.docusign.esign.model.Recipients;
import com.docusign.esign.model.SignHere;
import com.docusign.esign.model.Signer;
import com.docusign.esign.model.Tabs;
import com.docusign.esign.model.ViewUrl;
/**
* Servlet implementation class test2
*/
#WebServlet("/test2")
public class test2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String rEmail = request.getParameter("recipientem");
String rName = request.getParameter("recipientname");
/*Part file = request.getPart("file_upload");
*/
/* String filePath = (String)request.getServletContext().getInitParameter("file_upload");*/
/*Part filePart = request.getPart("file_upload");
String fileName=filePart.getSubmittedFileName();
for(Part part : request.getParts()) {
part.write("C:\\Bureau\\"+ fileName);
*/
/*Part filePart = request.getPart("file_upload");
InputStream filecontent = filePart.getInputStream();
if (filePart != null) {
filecontent = filePart.getInputStream();
}
else {
System.out.println("KHAWI");
}*/
String filePath = (String)request.getServletContext().getInitParameter("file_upload");
System.out.println("ZWIN1");
EmbeddedSigningTest(rEmail, rName, filePath);
}
#Test
public void EmbeddedSigningTest(String rEmail, String rName, String filePath ) {
String AccountId = "16501888";
System.out.println("\nEmbeddedSigningTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + filePath);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertNull(ioExcp);
}
System.out.println("ZWIN2");
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope (Embedded Signer)");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.getEncoder().encodeToString(fileBytes);
doc.setDocumentBase64(base64Doc);
doc.setName(filePath);
doc.setDocumentId("1");
List<Document> docs = new ArrayList<>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(rEmail);
String name = "Pat Developer";
signer.setName(rName);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2adce842-15eb-4744-9807-5a82020cc313 ";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
try {
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(AccountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
String returnUrl = "http://localhost:8080/index/";
RecipientViewRequest recipientView = new RecipientViewRequest();
recipientView.setReturnUrl(returnUrl);
recipientView.setClientUserId(clientUserId);
recipientView.setAuthenticationMethod("email");
recipientView.setUserName(name);
recipientView.setEmail(rEmail);
ViewUrl viewUrl = envelopesApi.createRecipientView(AccountId,
envelopeSummary.getEnvelopeId(), recipientView);
Assert.assertNotNull(viewUrl);
Assert.assertNotNull(viewUrl.getUrl());
// This Url should work in an Iframe or browser to allow signing
System.out.println("ViewUrl is " + viewUrl);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
}
I (pretty sure ) think it has something to do with the file not being uplaoded properly ( null).
Please help !

The error is telling you that the class org.junit.Assert is not on the classpath. Meaning that the JUnit library is missing or it has the wrong scope (if you are using a building tool like Maven or Gradle).
The whole class has several problems, I suspect you are trying to deploy the servlet on Tomcat and there the JUnit dependency is missing. You should redesign it and keep the test separated from the servlet.

Related

Call REST Api from VB.Net WPF application

I have this sample code written in Java that explains how to call a method of a REST Api:
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apac he.commons.io.FileUtils;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
public class Test {
public static void main(String[] args) {
String alias = "ABCD";
String pin = "012345";
String originFileName = "C:\file.pdf";
String destinationFilename = "C:\file2.pdf";
String urlService = "https://serviceUrl";
Client client = ClientBuilder.newBuilder().register(MultiPartFeature.class).build();
FormDataMultiPart form = new FormDataMultiPart();
form.field("pin", pin);
form.bodyPart(new FileDataBodyPart("content", new File(originFileName)));
Response response = client.target(urlService).path("/auto/action/name/" + alias).request(MediaType.MULTIPART_FORM_DATA).post(Entity.entity(form, form.getMediaType()));
if (response.getStatus() == 200) {
InputStream file = response.readEntity(InputStream.class);
File targetFile = new File(destinationFilename);
try {
FileUtils.copyInputStreamToFile(file, targetFile);
System.out.print("Success");
} catch (IOException e) {
e.printStackTrace();
System.out.print("Error");
}
} else {
System.out.print("Error:" + response.readEntity(String.class));
}
}
}
In my application I've converted it to something like this:
Dim userAlias As String = "ABCD"
Dim pin As HttpContent = New StringContent("012345")
Dim content As HttpContent = New StreamContent(File.OpenRead(originFileName))
Using client = New HttpClient()
client.BaseAddress = New Uri(urlService)
Using formData = New MultipartFormDataContent()
formData.Add(pinCode, "pin", "pin")
formData.Add(content, "test", "test")
Dim response = client.PostAsync("/auto/sign/pades/" + userAlias, formData).Result
If response.StatusCode = 200 Then
Return response.Content.ReadAsStreamAsync().Result
Else
MessageBox.Show(response.ReasonPhrase)
Return Nothing
End If
End Using
End Using
As a result I get a 500 Internal Server Error.
I checked the service url and it's correct, so I guess I'm doing something wrong in the MultipartFormDataContent creation.
I found out that the error was caused by a typo in the name of the parameter I was uploading.
The way I created the MultipartFormDataContent was actually correct.
Thanks to #Chillzy for the suggestion that made me rewrite my code finding the typo.

Facebook4j authentication issue

I am trying to make a java app which makes connection with facebook.I am using facebok4j to achieve this,I made an app in fb devolopers and got the key annd id for it.But when i am passing it to get an access token its returning an exception error.Please help me
java code
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.Post;
import facebook4j.ResponseList;
import facebook4j.auth.AccessToken;
import facebook4j.auth.OAuthAuthorization;
import facebook4j.auth.OAuthSupport;
import facebook4j.conf.Configuration;
import facebook4j.conf.ConfigurationBuilder;
public class Fbsample {
public static Configuration createConfiguration()
{
ConfigurationBuilder confBuilder = new ConfigurationBuilder();
confBuilder.setDebugEnabled(true);
confBuilder.setOAuthAppId("*****");
confBuilder.setOAuthAppSecret("*****");
confBuilder.setUseSSL(true);
confBuilder.setJSONStoreEnabled(true);
Configuration configuration = confBuilder.build();
return configuration;
}
public static void main(String[] argv) throws FacebookException {
Configuration configuration = createConfiguration();
FacebookFactory facebookFactory = new FacebookFactory(configuration );
Facebook facebookClient = facebookFactory.getInstance();
AccessToken accessToken = null;
try{
OAuthSupport oAuthSupport = new OAuthAuthorization(configuration );
accessToken = oAuthSupport.getOAuthAppAccessToken();
}catch (FacebookException e) {
System.err.println("Error while creating access token " + e.getLocalizedMessage());
}
facebookClient.setOAuthAccessToken(accessToken);
//results in an error says {An active access token must be used to query information about the current user}
}
}
For now i specified my token and id as *.When running its returning 'Error while creating access token graph.facebook.com'.Thanks in advance.

Exception thrown when trying to load Pentaho report through java program

This code was mostly taken from Pentaho's website on sample programs. The goal is to use their API to generate HTML output with a Pentaho report.
The report was created with Pentaho 3.5.0-RC2
The version of jars I am using are the following:
pentaho-reporting-engine-classic-core-3.5.0-RC2.jar
libloader-1.1.1.jar
libbase-1.1.1.jar
The exception I am getting is the following:
org.pentaho.reporting.libraries.resourceloader.ContentNotRecognizedException: None of the selected factories was able to handle the given data: ResourceKey{schema=org.pentaho.reporting.libraries.resourceloader.loader.URLResourceLoader, identifier=file:/C:/Users/elias.kopsiaftis/workspace_experimental/TestPentahoReport/bin/Test.prpt, factoryParameters={}, parent=null}
at org.pentaho.reporting.libraries.resourceloader.DefaultResourceManagerBackend.create(DefaultResourceManagerBackend.java:295)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:387)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.create(ResourceManager.java:342)
at org.pentaho.reporting.libraries.resourceloader.ResourceManager.createDirectly(ResourceManager.java:205)
at ReportTester.getReportDefinition(ReportTester.java:74)
at ReportTester.getReport(ReportTester.java:25)
at ReportTester.main(ReportTester.java:84)
java.lang.NullPointerException
at ReportTester.getReport(ReportTester.java:26)
at ReportTester.main(ReportTester.java:84)
And finally, the code snippet!
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.HashMap;
import java.io.*;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlReportUtil;
import org.pentaho.reporting.libraries.resourceloader.Resource;
import org.pentaho.reporting.libraries.base.util.StackableException;
import org.pentaho.reporting.libraries.resourceloader.ResourceException;
import org.pentaho.reporting.libraries.resourceloader.ResourceManager;
public class ReportTester {
private String reportName = "FormCompleteUsagePerPartnerByMonth.prpt";
private String reportPath = "";
public void getReport() {
try {
final MasterReport report = getReportDefinition();
report.getParameterValues().put("partner", "");
report.getParameterValues().put("startingdate", "2015-03-01");
report.getParameterValues().put("endingdate", "2015-03-05");
HtmlReportUtil.createStreamHTML(report, System.out);
} catch(Exception e) {
e.printStackTrace();
}
}
private MasterReport getReportDefinition() {
try {
// Using the classloader, get the URL to the reportDefinition file
final ClassLoader classloader = this.getClass().getClassLoader();
final URL reportDefinitionURL = classloader.getResource(reportPath + reportName);
if(reportDefinitionURL == null) {
System.out.println("URL was null");
}
// Parse the report file
final ResourceManager resourceManager = new ResourceManager();
resourceManager.registerDefaults();
final Resource directly = resourceManager.createDirectly(reportDefinitionURL, MasterReport.class);
return (MasterReport) directly.getResource();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
ReportTester rt = new ReportTester();
rt.getReport();
}
}
Any advice on this would be much appreciated as I have been scratching my head on this all day. Thanks in advance!

Adding methodName to selenium failed screenshot name using Java

I am trying to add the failed methodName to the screenshot that is taken when a failure occurs while running selenium using java. Ive tried multiple solutions around the net but they all wind up returning the methodName of the rule class or methodName. I am not sure how to make it so the screenshot file name returns 'shouldFail_date.png'.
package test;
import org.apache.commons.io.FileUtils;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ScreenShotRule extends TestWatcher {
private WebDriver browser;
public ScreenShotRule(WebDriver browser) {
this.browser = browser;
}
#Override
protected void failed(Throwable e, Description description) {
TakesScreenshot takesScreenshot = (TakesScreenshot) browser;
File scrFile = takesScreenshot.getScreenshotAs(OutputType.FILE);
File destFile = getDestinationFile();
try {
FileUtils.copyFile(scrFile, destFile);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
#Override
protected void finished(Description description) {
browser.close();
}
private File getDestinationFile() {
Throwable t = new Throwable();
String callerMethodName = t.getStackTrace()[1].getMethodName();
DateFormat dateFormat = new SimpleDateFormat("dd_MMM_yyyy");
String userDirectory = "screenshots/" + dateFormat.format(new Date()) + "/";
new File(userDirectory).mkdirs();
String absoluteFileName = userDirectory callerMethodName + dateFormat.format(new Date()) + ".png";
return new File(absoluteFileName);
}
}
package test;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ScreenShotTest {
private WebDriver browser = new FirefoxDriver();
#Rule
public ScreenShotRule screenShootRule = new ScreenShotRule(browser);
#Test
public void shouldFail() {
browser.get("http://www.google.com");
By link = By.partialLinkText("I do not expect to find a link with this text");
browser.findElement(link);
}
}
You can use one of the efficient selenium testing-frameworks - ISFW that is based on testng and provides descriptive reporting with the need you have. Here are some of the snapshots
Overview
Detail Report

How to use log4j to save the output to a file

I have downloaded the log4j jar.
But dont know how to use it to save the output to a text file.
My code is:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
public class ShowHeaders extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
String headerName;
String headerValue;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
String method= request.getMethod();
out.println("Request Method: " +method);
out.println("-----------------------");
String uri= request.getRequestURI();
out.println("URI: " +uri);
out.println("-----------------------");
out.println("Request Headers");
Enumeration<?> Enumeration = (java.util.Enumeration<?>) request.getHeaderNames();
while (Enumeration.hasMoreElements()) {
String headerName = (String) Enumeration.nextElement();
String headerValue = request.getHeader(headerName);
out.print(""+headerName + ": ");
out.println(headerValue + "");
}
}
Kindly tell me where to describe the file location & what to use instead of out.println(); to display it that text file
Well, you should take a look at the log4j tutorial. It is really good !
this code should give you a headstart :
public static void main(String[] args) {
Logger X = Logger.getLogger("com.foo");
try {
X.addAppender(new FileAppender(new PatternLayout("%d %-5p [%c{1}] %m%n"),"src/test.log"));
} catch (IOException e) {
e.printStackTrace();
}
X.debug("Hello World debug message");
}
The log4j tutorial explains how to configure logging, and includes example configs that log to a file. (Search for where it says "Here is another configuration file that uses multiple appenders". That "config" includes file appenders.)

Categories

Resources