Dropbox java api get file details - java

I am java developer.I need to get file information from dropbox using java api.
I tried with metadata class.Here i am getting only id,name,path,size of the file.
But i need to get other information like owner name,mimetype,Createddate
ListFolderResult result = client.files().listFolderBuilder("")
.withIncludeDeleted(false)
.withRecursive(true)
.withIncludeMediaInfo(true)
.start();
while (true) {
List<Metadata> entries = result.getEntries();
int idx = 0;
for (Metadata metadata : entries) {
if (metadata instanceof FolderMetadata) {
System.out.println("" + ++idx + ": FOLDER [" + metadata.getPathDisplay() + "], [" + metadata.getName() + "]");
} else if (metadata instanceof FileMetadata) {
System.out.println("" + ++idx + ": File [" + metadata.getPathDisplay() + "], [" + metadata.getName() + "]");
String filePath = metadata.getPathLower().replace(metadata.getName().toLowerCase(), "");
System.out.println(metadata.getPathLower());
System.out.println("FILE PATH"+filePath);
System.out.println("Dropbox"+((FileMetadata) metadata).getRev());
System.out.println("Dropbox"+((FileMetadata) metadata).getClientModified());
System.out.println("Dropbox"+((FileMetadata) metadata).getMediaInfo());
System.out.println("Dropbox"+((FileMetadata) metadata).getMediaInfo().getMetadataValue());
System.out.println("Dropbox"+((FileMetadata) metadata).getSharingInfo());
..
Thanks advance

The FileMetadata object that you get back is documented here:
https://dropbox.github.io/dropbox-sdk-java/api-docs/v2.0.x/com/dropbox/core/v2/files/FileMetadata.html
It doesn't offer the additional information you're looking for, and there isn't another way to get it via the API, but we'll consider this a feature request.
You can keep your own file extension to mime type mapping if you'd like though. For example, you can find our groupings for some file types permission here:
https://www.dropbox.com/developers-v1/reference/devguide

Related

Problem with getting list of names of attached files in NotesDocument

I am getting sometimes problems with creating a list of names of the attached files in a NotesDocument. The custom message looks as followed:
AttachmentDominoDAO - General problem during reading attachment from
entry 39E411CEC4AD22F3C1258821003399EF in database mail.nsf.
fileObject.getName() returns null. Files found in document
[contract.pdf]
Here is the method that I am calling:
private Attachment loadFromEntry(ViewEntry entry) {
utils.printToConsole(this.getClass().getSimpleName().toString() + " - loadFromEntry(...) unid=" + entry.getUniversalID());
Attachment attachment = new Attachment();
try{
attachment.setUnid(entry.getUniversalID());
Document doc = entry.getDocument();
if (null != doc){
attachment.setCreated(doc.getCreated().toJavaDate());
if(doc.hasItem("$FILE")){
List<String> files = doc.getAttachmentNames();
for (int j = 0; j < files.size(); ++j) {
EmbeddedObject fileObject = doc.getAttachment(files.get(j));
if(null != fileObject.getName()) {
if(null != fileObject.getName()) {
attachment.setFile(fileObject.getName());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", fileName.getName() returns " + fileObject.getName(), Level.SEVERE, null);
}
if(null != fileObject.getName() && !utils.Right(fileObject.getName(),".").isEmpty()) {
attachment.setExtension(utils.Right(fileObject.getName(),"."));
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", extension is empty for file " + fileObject.getName(), Level.SEVERE, null);
}
attachment.setSizeHuman(FileUtils.byteCountToDisplaySize(fileObject.getFileSize()));
if(fileObject.getFileSize() > 0) {
attachment.setSize(fileObject.getFileSize());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", fileName.size() returns " + fileObject.getFileSize(), Level.SEVERE, null);
}
if(null != doc.getAuthors() && null != doc.getAuthors().firstElement()) {
attachment.setCreator(doc.getAuthors().firstElement());
} else {
XspOpenLogUtil.logEvent(null, "Problem with reading attachment from entry " + entry.getUniversalID() + ", doc.getAuthors().firstElement() returns " + doc.getAuthors().firstElement(), Level.SEVERE, null);
}
String fieldName = "type";
if (doc.hasItem(fieldName)) {
attachment.setType(fieldName);
}
}else {
XspOpenLogUtil.logEvent(null, "AttachmentDominoDAO - General problem during reading attachment from entry " + entry.getUniversalID() + " in database " + entry.getDocument().getParentDatabase().getFileName() + ". fileObject.getName() returns null. Files found in document " + doc.getAttachmentNames().toString(), Level.SEVERE, null);
}
}
}
}
}catch (Exception e) {
XspOpenLogUtil.logEvent(e, "General problem with reading attachment from entry " + entry.getUniversalID() + " in database " + entry.getDocument().getParentDatabase().getFileName(), Level.SEVERE, null);
}
return attachment;
}
One document can only contain one file. When I check the document there is only one attachment and the attachment mentioned in the error message.
Anyone has a suggestion how to fix this issue?
Note: in 99% of the cases the error does not occur.
If getName() returns null for an attachment, try using getSource() instead. As long as it's an actual attachment (as opposed to an OLE embedded object), then getSource() always returns the original file name.
NotesDocument.getAttachment does not find attachments that were created in rich text fields. It only finds attachments that were created directly in the document itself.
We used to call an attachment that is directly acceessed through the document a "V2 attachment" because that's the way things worked in Notes V2 -- over 30 years ago. Objects created through OLE launch properties on the form can also attach objects that are directly in the document instead of inside rich text. Since OLE and V2 are both relics of the deep, dark past, almost all attachments are created inside rich text fields these days.
Attachments that are inside rich text fields are accessed through the getEmbeddedObject method of the RichTextItem class.

Randomly changing the JSON Values for every "Post" Request Body using Java

This could be a duplicate question, but I couldn't find my solution anywhere. Hence, posting it.
I am trying to simply POST a request for a Student account Creation Scenario. I do have a JSON file which comprises all the "Keys:Values", required for Student account creation.
This is how the file student_Profile.json looks like:
{
"FirstName":"APi1-Stud-FN",
"MiddleInitial":"Q",
"LastName":"APi1-Stud-LN",
"UserAlternateEmail":"",
"SecretQuestionId":12,
"SecretQuestionAnswer":"Scot",
"UserName":"APi1-stud#xyz.com",
"VerifyUserName":"APi1-stud#xyz.com",
"Password":"A123456",
"VerifyPassword":"A123456",
"YKey":"123xyz",
"YId":6,
"Status":false,
"KeyCode":"",
"SsoUserName":"APi1-stud#xyz.com",
"SsoPassword":"",
"BirthYear":2001
}
So everything on Posting the request from "Rest Assured" point of view looks fine, it's just that I want to update a few values from the above JSON body using JAVA so that I can create a new Student profile every time I run my function and don't have to manually change the Body.
For Every POST Student Account Creation scenario, I need to update the value for
the following keys so that a new test student user account can be created:
First Name
Last Name and
Username // "VerifyUserName" and "SSO UserName" will remain same as user name
I modified the answer to get random values and pass them to json body. random value generation was taken from the accepted answer of this question.
public void testMethod() {
List<String> randomValueList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
StringBuilder salt = new StringBuilder();
Random rnd = new Random();
while (salt.length() < 18) { // length of the random string.
int index = (int) (rnd.nextFloat() * SALTCHARS.length());
salt.append(SALTCHARS.charAt(index));
}
randomValueList.add(salt.toString());
}
String jsonBody = "{\n" +
" \"FirstName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"" + randomValueList.remove(0) + "\",\n" +
" \"UserAlternateEmail\":\"\",\n" +
" \"SecretQuestionId\":12,\n" +
" \"SecretQuestionAnswer\":\"Scot\",\n" +
" \"UserName\":\"" + randomValueList.remove(0) + " \",\n" +
" \"VerifyUserName\":\"APi1-stud#xyz.com\",\n" +
" \"Password\":\"A123456\",\n" +
" \"VerifyPassword\":\"A123456\",\n" +
" \"YKey\":\"123xyz\",\n" +
" \"YId\":6,\n" +
" \"Status\":false,\n" +
" \"KeyCode\":\"\",\n" +
" \"SsoUserName\":\"APi1-stud#xyz.com\",\n" +
" \"SsoPassword\":\"\",\n" +
" \"BirthYear\":2001\n" +
"}";
Response response = RestAssured
.given()
.body(jsonBody)
.when()
.post("api_url")
.then()
.extract()
.response();
// Do what you need to do with the response body
}
We can used pojo based approach to do certain things very easily . No matter how complex is the payload , serialization and dieselization is the best answer . I have created a framework template for api automation that can we used by putting required POJO's in path :
https://github.com/tanuj-vishnoi/pojo_api_automation
To create pojo, I also have ready to eat food for you :
https://github.com/tanuj-vishnoi/pojo_generator_using_jsonschema2pojo
for the above problem you can refer to the JsonPath lib https://github.com/json-path/JsonPath and use this code:
String mypayload = "{\n" +
" \"FirstName\":\"APi1-Stud-FN\",\n" +
" \"MiddleInitial\":\"Q\",\n" +
" \"LastName\":\"APi1-Stud-LN\"}";
Map map = JsonPath.parse(mypayload).read("$",Map.class);
System.out.println(list);
once the payload converted into map you can change only required values as per the requirement
To generate random strings you can refer to lib org.apache.commons.lang3.RandomStringUtils;
public static String generateUniqueString(int lenghtOfString){
return
RandomStringUtils.randomAlphabetic(lenghtOfString).toLowerCase();
}
I recommend to store payload in a separate file and load it at runtime.

Convert Loadrunner File Parameter to Java string for payload

I have a java virtual user script that is sending a payload request. I am trying to use values from a file to send via a loadrunner file parameter.
here is the payload:
private static final String PAYLOAD =
"<ips_cad_mdt>\n" +
" <SignOnRequest>\n" +
" <DestApplication>hhhh</DestApplication>\n" +
" <OrigApplication>hhh</OrigApplication>\n" +
" <SessionRef>3</SessionRef>\n" +
" <Aliasing>1234</Aliasing>\n" +
" </SignOnRequest>\n" +
"</ips_cad_mdt>";
I would like to use something like the following:
private static final String PAYLOAD =
"<ips_cad_mdt>\n" +
" <SignOnRequest>\n" +
" <DestApplication>hhh</DestApplication>\n" +
" <OrigApplication>hhh</OrigApplication>\n" +
" <SessionRef>3</SessionRef>\n" +
" <Aliasing>”+lr.eval_string(“{AliasId}”)+”</Aliasing>\n" +
" </SignOnRequest>\n" +
"</ips_cad_mdt>";
for some reason i cant see any output for this value. do i need to declare a variable: e.g. lr.save_string("AliasId", "{AliasId}");
an example of this would help loads. Many Thanks
There seems to be an error in the code completion in VuGen. The parameters should be reversed and without the {} in save_string.
lr.save_string("1234","myId");
lr.message(lr.eval_string("{myId}"));
In the documentation it is correct - https://admhelp.microfocus.com/lr/en/12.55/help/function_reference/FuncRef.htm#FuncRef/c_vuser/lrFr_lr_save_string.htm?Highlight=lr_save_string
I asked the responsible team to fix the code completion in VuGen so you will be able to see this change in one of the future releases.

java.lang.IllegalArgumentException - 'other' has different root

I am writing a java application using Vertx. I am trying to deploy one of my modules using the following code. But I am facing IllegalArgumentException, which I am not able to solve.
Part of my main class:
System.out.println(System.getProperty("user.dir")
+ File.separator + "modules" + File.separator
+ "agents-0.0.1-SNAPSHOT-mod.zip");
InputStream agf = new FileInputStream(System.getProperty("user.dir")
+ File.separator + "conf" + File.separator
+ "dbproperties1.json");
String json = IOUtils.toString( agf );
LOGGER.debug("db json:::"+json);
JsonObject configprop = new JsonObject(json);
pm.deployModuleFromZip(System.getProperty("user.dir")
+ File.separator + "modules" + File.separator
+ "agents-0.0.1-SNAPSHOT-mod.zip", configprop, 1,
new AsyncResultHandler<String>() {
public void handle(AsyncResult<String> asyncResult) {
LOGGER.debug("Deployment agnet ID dddd");
if (asyncResult.succeeded()) {
LOGGER.debug("Deployment agnet ID is "
+ asyncResult.result());
} else {
LOGGER.debug("Deployment agnet ID is null "
+ asyncResult.result());
asyncResult.cause().printStackTrace();
}
}
});
agf.close();
The error in the console is as follows:
java.lang.IllegalArgumentException: 'other' has different root
at sun.nio.fs.WindowsPath.relativize(WindowsPath.java:392)
at sun.nio.fs.WindowsPath.relativize(WindowsPath.java:44)
at org.vertx.java.platform.impl.DefaultPlatformManager.setPathResolver(DefaultPlatformManager.java:1128)
at org.vertx.java.platform.impl.DefaultPlatformManager.access$2000(DefaultPlatformManager.java:55)
at org.vertx.java.platform.impl.DefaultPlatformManager$18.run(DefaultPlatformManager.java:1276)
at org.vertx.java.core.impl.DefaultContext$3.run(DefaultContext.java:171)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:353)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:366)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:101)
at java.lang.Thread.run(Thread.java:745)
Any help in this regard will be appreciated.
I found the solution for my case.
For a vertx project, there will be mod.json file in the project. It should have the following json.
{
"main": "com.company.agent.Manager",
"preserve-cwd": true
}
"preserve-cwd": true does the help.

java metadata-extractor tag description

I am using the Java library Metadata-extractor and cannot extract the tag
description correctly using the getUserCommentDescription method code below,
although the tag.getDescription does work:
String exif = "File: " + file;
File jpgFile = new File(file);
Metadata metadata = ImageMetadataReader.readMetadata(jpgFile);
for (Directory directory : metadata.getDirectories()) {
String directoryName = directory.getName();
for (Tag tag : directory.getTags()) {
String tagName = tag.getTagName();
String description = tag.getDescription();
if (tagName.toLowerCase().contains("comment")) {
Log.d("DEBUG", description);
}
exif += "\n " + tagName + ": " + description; //Returns the correct values.
Log.d("DEBUG", directoryName + " " + tagName + " " + description);
}
if (directoryName.equals("Exif IFD0")) {
// create a descriptor
ExifSubIFDDirectory exifDirectory = metadata.getDirectory(ExifSubIFDDirectory.class);
ExifSubIFDDescriptor descriptor = new ExifSubIFDDescriptor(exifDirectory);
Log.d("DEBUG","Comments: " + descriptor.getUserCommentDescription()); //Always null.
}
Am I missing something here?
You are checking for the directory name Exif IFD0 and then accessing the ExifSubIFDDirectory.
Try this code outside the loop:
Metadata metadata = ImageMetadataReader.readMetadata(jpgFile);
ExifSubIFDDirectory exifDirectory = metadata.getDirectory(ExifSubIFDDirectory.class);
ExifSubIFDDescriptor descriptor = new ExifSubIFDDescriptor(exifDirectory);
String comment = descriptor.getUserCommentDescription();
If this returns null then it may be an encoding issue or bug. If you run this code:
byte[] commentBytes =
exifDirectory.getByteArray(ExifSubIFDDirectory.TAG_USER_COMMENT);
Do you have bytes in the array?
If so then please open an issue in the issue tracker and include a sample image that can be used to reproduce the problem. You must authorise any image you provide for use in the public domain.

Categories