Send Template as Envelop Docusign Java - java

I have create Template on my docusign account. I want to use this template to send to recipients in my application using Docusign-Java-Client Program.
Right now I am reading .pdf from my local machine but i don't want to use local document, i want to use Template on docusign.
How can i read that Template in java?
i will do same in scala.
Code in Scala :
val loginInfo = authApi.login()
val loginAccounts: java.util.List[LoginAccount] = loginInfo.getLoginAccounts
val SignTest1File = "/TermsnConditions.pdf"
var fileBytes: Array[Byte] = null
try {
val currentDir = System.getProperty("user.dir")
val path = Paths.get(currentDir + SignTest1File)
fileBytes = Files.readAllBytes(path)
} catch {
case ioExcp: IOException =>
System.out.println("Exception: " + ioExcp)
}

Please check https://github.com/docusign/docusign-java-client/blob/master/src/test/java/SdkUnitTests.java SDK, and it has a sample method RequestSignatureFromTemplate() to request signature using templates.

Related

trying to convert java file to bytestring for using in stream

Im creating an api to send me files and I will upload them to S3, and im using akka-stream-alpakka-s3 library to do it using streams.
my issue is that in my controller I can convert the file to Jave file:
def uploadToS3() = Action(parse.multipartFormData) { request =>
request.body.file("file").map { filePart =>
val filename = Paths.get(filePart.filename).getFileName
val file = Paths.get(s"/tmp/$filename").toFile // this is java file
saveToS3(file, filename)
}
...
}
and in my s3 service func I counld only use scala file since it have a "toByteArray" func and I need it for the source, it looks like this:
import scala.reflect.io.File
class S3Service #Inject()(mys3Client: S3Client,
configuration: Configuration,
implicit val executionContext: ExecutionContext,
implicit val actorSystem: ActorSystem) {
implicit val materializer: ActorMaterializer = ActorMaterializer()
val bucket: String = configuration.get[String]("my.aws.s3.bucket")
// func to save to s3
def saveToS3(file: File, fileName: String): Future[AWSLocation] = {
// here im creating uuid so i to pass as directory so it will be possible to have files with the same name
val fileNameUUID: String = s"${UUID.randomUUID()}-$fileName"
// this will be my sinc for the stream
val s3Sink: Sink[ByteString, Future[MultipartUploadResult]] = mys3Client.multipartUpload(s"$bucket/$fileNameUUID", fileName)
// here is my issue: i need to transform the file to bytstring so I can creat it as the source but the file im getting from the controller is Java file and the function to create byteString is of Scala file so had to use scala file in this func.
Future.fromTry( Try{
ByteString(file.toByteArray())
}).flatMap { byteString =>
Source.single(byteString).runWith(s3Sink) map { res =>
AWSLocation(s"$bucket/$fileNameUUID", res.key)
}
}.recover {
case ex: S3Exception =>
logger.error("some message", ex)
throw ex
case ex: Throwable =>
logger.error("some message", ex)
throw ex
}
}
}
what would be the best way to align the file types so I will be able to pass bytestring file to my Source?
Take a look at FileIO.fromPath which will give you Source[ByteString, ...] from java.nio.file.Path.

AWS Creating new files from an s3 object using JAVA getting error

I have a shape file and i need to read the shape file from my java code. I used below code for reading shape file.
public class App {
public static void main(String[] args) {
File file = new File("C:\\Test\\sample.shp");
Map<String, Object> map = new HashMap<>();//
try {
map.put("url", URLs.fileToUrl(file));
DataStore dataStore = DataStoreFinder.getDataStore(map);
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource source = dataStore.getFeatureSource(typeName);
SimpleFeatureCollection collection = source.getFeatures();
try (FeatureIterator<SimpleFeature> features = collection.features()) {
while (features.hasNext()) {
SimpleFeature feature = features.next();
SimpleFeatureType schema = feature.getFeatureType();
Class<?> geomType = schema.getGeometryDescriptor().getType().getBinding();
String type = "";
if (Polygon.class.isAssignableFrom(geomType) || MultiPolygon.class.isAssignableFrom(geomType)) {
MultiPolygon geom = (MultiPolygon) feature.getDefaultGeometry();
type = "Polygon";
if (geom.getNumGeometries() > 1) {
type = "MultiPolygon";
}
} else if (LineString.class.isAssignableFrom(geomType)
|| MultiLineString.class.isAssignableFrom(geomType)) {
} else {
}
System.out.println(feature.getDefaultGeometryProperty().getValue().toString());
}
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
I got the desired output. But my requirement is write an aws lambda function to read shape file. For this
1. I created a Lambda java project of s3 event. I wrote the same code inside the handleRequest. I uploaded the java lambda project as a lanbda function and added one trigger. When I am uploading a .shp file to as s3 bucket lmbda function will automatically invoked. But I am getting an error like below
java.lang.RuntimeException: java.io.FileNotFoundException: /sample.shp (No such file or directory)
I have sample.shp file inside my s3 bucket. I go through below link.
How to write an S3 object to a file?
I am getting the same error. I tried to change my code like below
S3Object object = s3.getObject(new GetObjectRequest(bucket, key));
InputStream objectData = object.getObjectContent();
map.put("url", objectData );
instead of
File file = new File("C:\\Test\\sample.shp");
map.put("url", URLs.fileToUrl(file));
:-( Now i am getting an error like below
java.lang.NullPointerException
Also I tried the below code
DataStore dataStore = DataStoreFinder.getDataStore(objectData);
instead of
DataStore dataStore = DataStoreFinder.getDataStore(map);
the error was like below
java.lang.ClassCastException:
com.amazonaws.services.s3.model.S3ObjectInputStream cannot be cast to
java.util.Map
Also I tried to add key directly to the map and also as DataStore object. Everything went wrong..:-(
Is there anyone who can help me?
It will be very helpful if someone can do it for me...
The DataStoreFinder.getDataStore method in geotools requires you to provide a map containing a key/value pair with key "url". The value associated with that "url" key needs to be a file URL like "file://host/path/my.shp".
You're trying to insert a Java input stream into the map. That won't work, because it's not a file URL.
The geotools library does not accept http/https URLs (see the geotools code here and here), so you need a file:// URL. That means you will need to download the file from S3 to the local Lambda filesystem and then provide a file:// URL pointing to that local file. To do that, here's Java code that should work:
// get the shape file from S3 to local filesystem
File localshp = new File("/tmp/download.shp");
s3.getObject(new GetObjectRequest(bucket, key), localshp);
// now store file:// URL in the map
map.put("url", localshp.getURI().getURL().toString());
If the geotools library had accepted real URLs (not just file:// URLs) then you could have avoided the download and simply created a time-limited, pre-signed URL for the S3 object and put that URL into the map.
Here's an example of how to do that:
// get current time and add one hour
java.util.Date expiration = new java.util.Date();
long msec = expiration.getTime();
msec += 1000 * 60 * 60;
expiration.setTime(msec);
// request pre-signed URL that will allow bearer to GET the object
GeneratePresignedUrlRequest gpur = new GeneratePresignedUrlRequest(bucket, key);
gpur.setMethod(HttpMethod.GET);
gpur.setExpiration(expiration);
// get URL that will expire in one hour
URL url = s3.generatePresignedUrl(gpur);

How to convert Scala FilePart as File (Java) to use in multipart-form data?

I have a method that already have an FilePart[TemporaryFile] and i will call another method to send a multi-part form data. This method is using scala play 2.4.X and i have to send it using ning method below:
def sendFile(file: FilePart[TemporaryFile]): Option[Future[Unit]] = {
val asyncHttpClient:AsyncHttpClient = WS.client.underlying
val postBuilder = asyncHttpClient.preparePost(s"${config.ocrProvider.host}")
val multiPartPost = postBuilder
.addBodyPart(new StringPart("access_token",s"${config.ocrProvider.accessToken}"))
.addBodyPart(new StringPart("typename",s"${config.ocrProvider.typeName}"))
.addBodyPart(new StringPart("action",s"${config.ocrProvider.actionUpload}"))
.addBodyPart(new FilePart(**expects java.io.File not FilePart**)
}
How can i take advantage of this parameter and send as java.io.File?
You need to write the content of file: FilePart[TemporaryFile] to disk and then use that file for constructing the new multipart request. You can see this example Scala File Upload
val tempFile = new File("/tmp/some/path")
file.ref.moveTo(tempFile)
val filePart = new FilePart(tempFile)

Access GoogleCloudStorage using GoogleCloudEndpoints

I'm working on this project in which I'm using a Google-App-Engine backend connected to an Android app via Google-Cloud-Endpoints. For Google-Cloud-Datastore access I'm using Objectify and everything works fine.
Now I decided to add the functionality to upload images to Google-Cloud-Storage but I couldn't find a clear explanation on how to do this using the Google-Cloud-Endpoints setup.
I found the following explanation how to use Google-Cloud-Storage with Google-App-Engine:
https://cloud.google.com/appengine/docs/java/googlecloudstorageclient/app-engine-cloud-storage-sample
but instead of adding it to the Endpoints Api the article writes an additional servlet.
Furthermore I found this example of upload/download for Android:
github.com /thorrism/GoogleCloudExample
Sadly this is using the Google Cloud Storage API for direct access to the Google-Cloud-Storage and you need to add a P12-file to the asset folder, which seems unsecure.
My Google-App-Engine code looks like that:
#Api(
name = "example",
version = "v1",
scopes = { Constants.EMAIL_SCOPE },
clientIds = { Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID, Constants.API_EXPLORER_CLIENT_ID },
audiences = {Constants.ANDROID_AUDIENCE},
description = "API for the Example Backend application."
)
public class ExampleApi{
#ApiMethod(name = "doSomething", path = "dosomething", httpMethod = HttpMethod.POST)
public String doSomething(#Named("text") String text){
TestEntity test = new TestEntity(text);
ofy().save().entity(test).now();
return test;
}
After I uploaded it I generated the Endpoints Client Library and imported it into my android project.
Then I'm calling Endpoints from Android like explained here:
https://cloud.google.com/appengine/docs/java/endpoints/calling-from-android#creating_the_service_object
public static com.appspot.******.example.Example buildServiceHandler(Context context, String email) {
GoogleAccountCredential credential = GoogleAccountCredential.usingAudience(
context, AppConstants.AUDIENCE);
credential.setSelectedAccountName(email);
com.appspot.******.example.Example.Builder builder = new com.appspot.******.example.Example.Builder(
AppConstants.HTTP_TRANSPORT,
AppConstants.JSON_FACTORY, null);
builder.setApplicationName("example-server");
return builder.build();
}
sApiServiceHandler = buildServiceHandlerWithAuth(context,email);
And each Api-Method I call like this:
com.appspot.******.example.Example.DoSomething doSomething = sApiServiceHandler.doSomething(someString);
doSomething.execute();
All of this works fine, but only for storing/receiving Datastore Entities. How would I go about uploading/downloading files to Google Cloud Storage using the Google Cloud Endpoints setup?
Is it somehow possible to send a POST with my image data via Endpoints to the UploadServlet using the already build ServiceHandler ?
Is it possible to call a servlet from an Endpoints Method? How am I supposed to send the Post to the Servlet and how would I go about the authentication?
Any help or advice would be greatly appreciated!
There are different ways to do this, but the most recommended way is to use Signed URLs, so that your Android app can upload the file securely to Google Cloud Storage directly, without going through your Endpoints backend. The basic process is:
1) Create an Endpoints method that creates a new signed URL and returns it to the Android client. Signing the URL on the server still requires a P12 key but is stored on App Engine, not on the client, so is secure. Try to use a short expiration for the URL, for example no more than 5 minutes.
2) Have the Android client upload the file directly to the signed URL, as you would doing a normal HTTP PUT to the Cloud Storage XML API to upload a file (resumable uploads with the JSON API are also supported, but not covered here).
Your Endpoints method might look like this:
#ApiMethod(name = "getUploadUrl", path = "getuploadurl", httpMethod = HttpMethod.GET)
public MyApiResponse getUploadUrl(#Named("fileName") String fileName
#Named("contentType" String contentType)
{
String stringToSign
= "PUT\n" + contentType
+ "\n" + EXPIRATION_TIMESTAMP_EPOCH_SECONDS + "\n"
+ YOUR_GCS_BUCKET + "/" + fileName;
// Load P12 key
FileInputStream fileInputStream = new FileInputStream(PATH_TO_P12_KEY);
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(fileInputStream, password);
PrivateKey key = keyStore.getKey(privatekey", YOUR_P12_KEY_PASSWORD);
// Get signature
Signature signer = Signature.getInstance("SHA256withRSA");
signer.initSign(key);
signer.update(stringToSign.getBytes("UTF-8"));
byte[] rawSignature = signer.sign();
String signature = new String(Base64.encodeBase64(rawSignature, false), "UTF-8");
// Construct signed url
String url
= "http://storage.googleapis.com/" + YOUR_GCS_BUCKET + fileName
+ "?GoogleAccessId=" + P12_KEY_SERVICE_ACCOUNT_CLIENT_ID
+ "&Expires=" + EXPIRATION_TIMESTAMP_EPOCH_SECONDS
+ "&Signature=" + URLEncoder.encode(signature, "UTF-8");
// Endpoints doesn't let you return 'String' directly
MyApiResponse response = new MyApiResponse();
response.setString(url);
return response;
}
On the Android side, you might use the method like this:
// Get the upload URL from the API
getUploadUrl = sApiServiceHandler.getUploadUrl(fileName, contentType);
MyApiResponse response = getUploadUrl.execute();
String uploadUrl = response.getString();
// Open connection to GCS
URL url = new URL(uploadUrl);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("PUT");
httpConnection.setRequestProperty("Content-Type", contentType);
// Write file data
OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
out.write(fileData);
out.flush();
// Get response, check status code etc.
InputStreamReader in = new InputStreamReader(httpConnection.getInputStream());
// ...
(Disclaimer: I'm just typing code freely into a text editor but not actually testing it, but it should be enough to give you a general idea.)

upload a file to salesforce using connector

i builded a flow in mule which create a case in Salesforce using 'Salesforce' connector. now i need to upload a file to that case using the same mule flow. This can be done programatically by the following code:
try {
File f = new File("c:\java\test.docx");
InputStream is = new FileInputStream(f);
byte[] inbuff = new byte[(int)f.length()];
is.read(inbuff);
Attachment attach = new Attachment();
attach.setBody(inbuff);
attach.setName("test.docx");
attach.setIsPrivate(false);
// attach to an object in SFDC
attach.setParentId("a0f600000008Q4f");
SaveResult sr = binding.create(new com.sforce.soap.enterprise.sobject.SObject[] {attach})[0];
if (sr.isSuccess()) {
System.out.println("Successfully added attachment.");
} else {
System.out.println("Error adding attachment: " + sr.getErrors(0).getMessage());
}
} catch (FileNotFoundException fnf) {
System.out.println("File Not Found: " +fnf.getMessage());
} catch (IOException io) {
System.out.println("IO: " +io.getMessage());
}
But to make it simple, does there is any mule connector which automatically done all this and attach a file to the particular created case.
Yes you can use the Salesforce Cloud Connector for that. Example:
<file:file-to-byte-array-transformer />
<sfdc:create type="Attachment">
<sfdc:objects>
<sfdc:object>
<body>#[payload]</body>
<name>test.docx</name>
<parentid>#[message.inboundProperties['mysfdcparentid']]</parentid>
</sfdc:object>
</sfdc:objects>
</sfdc:create>
In the example, I am setting the sobject type to 'Attachment'.
The body element is the file itself. Note that the connector will handle the base64 encoding for you, you just need to provide it with a byte array. If you're using File, you can use file:file-to-byte-array-transformer for example.
The parentid is set using MEL to get the value from a message property. So if you have a previous SFDC operation you can use MEL to extract the value of the previous sobject.

Categories