Have tried to search for this almost 'everywhere', but couldn't find a pointer as to how to implement this. Please kindly review my code and offer suggestions on how to set/update ALL documents properties in SharePoint using OpenCMIS. Have created the documents successfully using CMIS, however I'm not able to populate different values for different documents.
For example, a.pdf, b.pdf have different properties. So when I update them, i expect the value to be mapped from array of values assigned to them but at the moment, the same value are being append to all the documents...
Please see my code below, hopefully it will make things clearer:
try {
String [] nextLine =null;
CSVReader reader = new CSVReader(new FileReader(indexFileLocation));
List content = reader.readAll();
for (Object o : content) {
nextLine = (String[]) o;
System.out.println("\n"+ nextLine[2] + "\n"+nextLine[7] + "\n"+ nextLine[6]);
}
//reader.close();
Map <String, Object> newDocProps = new HashMap<String, Object>();
newDocProps.put(PropertyIds.OBJECT_TYPE_ID, "cmis:document");
newDocProps.put(PropertyIds.NAME, ff.getName());
Document doc = newFolder.createDocument(newDocProps, contentStream, VersioningState.NONE);
CmisObject cmisobject = (Document) session.getObject(doc.getId());
Map<String, Object> pp = new HashMap<String, Object>();
//pp.put(PropertyIds.OBJECT_ID, "Name");
pp.put("WorkflowNumber", nextLine[7]);
pp.put("InvoiceDate", nextLine[2]);
cmisobject.updateProperties(pp);
Any help is appreciated.
#Albert, How are you creating session? It could be an issue with session creation. Please paste your code here to create session.
Related
Im trying to get a key:value pair from a simple jsonString to add it after into a memory tab. If facing an issue cause my input is a string. and it looks like my loop isnot able to read the key value pair.
I read many topics about it, and im still in trouble with it. As you can see below
{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}
and my method, find only on object... the result is the same in my loop
public static ArrayHandler jsonSimpleObjectToTab(String data) throws ParseException {
if( data instanceof String) {
final var jsonParser = new JSONParser();
final var object = jsonParser.parse(data);
final var array = new JSONArray();
array.put(object);
final var handler = new ArrayHandler("BW_funct_Struct");
for( KeyValuePair element : array) {
handler.addCell(element);
Log.warn(handler);
}
return handler;
} else {
throw new IllegalArgumentException("jsonSimpleObjectToTab: do not support complex object" + data + "to Tab");
}
}
i also tryed before to type my array as a List, Object etc, without the keyValuePair object, i would appreciate some help.
Thanks again dear StackOverFlowers ;)
You can try this :
const json = '{"nom":"BRUN","prenom":"Albert","date_naiss":"10-10-1960","adr_email":"abrun#gmail.com","titre":"Mr","sexe":"F"}';
map = new Map();
const obj = JSON.parse(json,(key,value) => {
map.set(key,value)
});
and you'll have every pair stored in map
Simply split the whole line at the commas and then split the resulting parts at the colon. This should give you the individual parts for your names and values.
Try:
supposing
String input = "\"nom\":\"BRUN\",\"prenom\":\"Albert\"";
then
String[] nameValuePairs = input.split(",");
for(String pair : nameValuePairs)
{
String[] nameValue = pair.split(":");
String name = nameValue[0]; // use it as you need it ...
String value = nameValue[1]; // use it as you need it ...
}
You can use TypeReference to convert to Map<String,String> so that you have key value pair.
String json = "{\"nom\":\"BRUN\",\"prenom\":\"Albert\",\"date_naiss\":\"10-10-1960\",\"adr_email\":\"abrun#gmail.com\",\"titre\":\"Mr\",\"sexe\":\"F\"}";
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<Map<String,String>> typeReference = new TypeReference<Map<String, String>>() {
};
Map<String,String> map = objectMapper.readValue(json, typeReference);
I just answered a very similar question. The gist of it is that you need to parse your Json String into some Object. In your case you can parse it to Map. Here is the link to the question with my answer. But here is a short version: you can use any Json library but the recommended ones would be Jackson Json (also known as faster XML) or Gson(by Google) Here is their user guide site. To parse your Json text to a class instance you can use ObjectMapper class which is part of Jackson-Json library. For example
public <T> T readValue(String content,
TypeReference valueTypeRef)
throws IOException,
JsonParseException,
JsonMappingException
See Javadoc. But also I may suggest a very simple JsonUtils class which is a thin wrapper over ObjectMapper class. Your code could be as simple as this:
Map<String, Object> map;
try {
map = JsonUtils.readObjectFromJsonString(input , Map.class);
} catch(IOException ioe) {
....
}
Here is a Javadoc for JsonUtils class. This class is a part of MgntUtils open source library written and maintained by me. You can get it as Maven artifacts or from the Github
Consider the following code:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
Yaml yaml = new Yaml();
FileWriter writer = new FileWriter("/path/to/file.yaml");
for (Map.Entry m : data.entrySet()) {
String temp = new StringBuilder().append(m.getKey()).append(": ").append(m.getValue()).toString();
yaml.dump(temp, file);
}
}
The output of the above code is
'NAME1: Raj'
'NAME2: Kumar'
But i want the output without the single quotes like
NAME1: Raj
NAME2: Kumar
This thing is very comfortable for parsing the file.
If anyone have solution, please help me to fix. Thanks in advance
Well SnakeYaml does exactly what you tell it to: For each entry in the Map, it dumps the concatenation of the key, the String ": ", and the value as YAML document. A String maps to a Scalar in YAML, and since the scalar contains a : followed by space, it must be quoted (else it would be a key-value pair).
What you actually want to do is to dump the Map as YAML mapping. You can do it like this:
public void testDumpWriter() {
Map<String, Object> data = new HashMap<String, Object>();
data.put("NAME1", "Raj");
data.put("NAME2", "Kumar");
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(options);
FileWriter writer = new FileWriter("/path/to/file.yaml");
yaml.dump(data, writer);
}
I have the Yaml file:
#Define CDN domains
---
CDN:
quality: 200..300
cost: low
Video-type: mp4
and with this Java code, I retrieve sub values of CDN:
// The path of your YAML file.
Yaml yaml = new Yaml();
Map<String, Map<String, String>> values =
(Map<String, Map<String, String>>) yaml
.load(new FileInputStream(new File("/workspace/servlet-yaml/src/test.yaml")));
for (String key : values.keySet()) {
Map<String, String> subValues = values.get(key);
for (String subValueKey : subValues.keySet()) {
System.out.println(values);
}
}
The output is:
{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
{CDN={quality=200..300, cost=low, Video-type=mp4}}
First of all, I don't know why it repeats three times?
Secondly, I want to write a code that
if cost = low , then do somthing.
First of all, I dont know whay it reapets three times?
Because you tell it to. For each subValueKey, print the whole value set. There are three sub-keys, so the complete value set gets printed three times.
Secondly, I want to write a code that if cost = low , then do somthing.
Yaml yaml = new Yaml();
Map<String, Map<String, String>> values =
(Map<String, Map<String, String>>) yaml.load(
new FileInputStream(new File(
"/workspace/servlet-yaml/src/test.yaml")));
final Map<String, String> cdn = values.get("CDN");
// or iterate over all keys like you currently do
final String cost = cdn.get("cost");
// or iterate over all subkeys and compare them to "cost".
// that way, it's easier to handle missing keys.
if ("low".equals(cost)) {
// do something
}
I'm new about NOSQL. I use couchDB and ektrop Java API. I tried these code but it gives HTTP 405 error.
protected CouchDbInstance _db;
{
String dbname = "my_database";
try {
//creates a database with the specified name
CouchDbConnector dbc = _db.createConnector(dbname, true);
//create a simple doc to place into your new database
Map<String, Object> doc = new HashMap<String, Object>();
doc.put("_id", UUID.randomUUID().toString());
doc.put("season", "summer");
doc.put("climate", "arid");
dbc.create(doc);
} catch (Exception e) {
}
Examples on the internet are very complex for me, so I didn't understand anything and i did not find any tutorial, so i have two questions.
-How can i connect db ?
-How can i add/delete/update documents operations ?
If you give me examples codes, i will be really happy. Also you can suggest good tutorial. Thanks in advance.
I am also new to CouchDB/NoSQL. But I am answering my best ignore if it not helps to you.
It seems you are not even opening the session by passing user login credentials.
Also you are directly trying to put Map object into DB create.
Session studentDbSession = new Session("localhost",5984);
Database studentCouchDb = studentDbSession.getDatabase("DBNAME");
Document newdoc = new Document();
Map<String , String> properties = new HashMap<String,String>();
properties.put(STUDENT_KEY_NAME, "REDDY");
properties.put(STUDENT_KEY_MARKS, "90");
properties.put(STUDENT_KEY_ROLL, "007");
newdoc.putAll(properties);
studentCouchDb.saveDocument(newdoc);
For more information you can also refer Adding Document Using Java Couchdb4j.
How to set the app properties of a file using Google Drive v3 in java?
The reference says: "files.update with {'appProperties':{'key':'value'}}", but I don't understand how to apply that to my java code.
I've tried things like
file = service.files().create(body).setFields("id").execute();
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_ID_KEY, deviceId);
file.setAppProperties(properties);
service.files().update(file.getId(), file).setFields("appProperties").execute();
but then I get an error that "The resource body includes fields which are not directly writable."
And to get the data:
File fileProperty = service.files().get(sFileId).setFields("appProperties").execute();
So how to set and get the properties for the file?
Thanks! :)
Edit
I tried
file = service.files().create(body).setFields("id").execute();
Map<String, String> properties = new HashMap<>();
properties.put(DEVICE_ID_KEY, deviceId);
file.setAppProperties(properties);
service.files().update(file.getId(), file).execute();
but I still get the same error message.
To avoid this error on v3
"The resource body includes fields which are not directly writable."
when calling update, you need to create an empty File with the new changes and pass that to the update function.
I wrote this and other notes as a v3 Migration Guide here.
The Drive API client for Java v3 indicates that the File.setAppProperties will require a Hashmap<String,String> parameter. Try to remove the setFields("appProperties") call since you are trying to overwrite appProperties itself (you're still calling Update at this time).
When retrieving appProperties, you'll just need to call getAppProperties.
Hope this helps!
File fileMetadata = new File();
java.io.File filePath = new java.io.File(YOUR_LOCAL_FILE_PATH);
Map<String, String> map = new HashMap<String, String>();
map.put(YOUR_KEY, YOUR_VALUE); //can be filled with custom String
fileMetadata.setAppProperties(map);
FileContent mediaContent = new FileContent(YOUR_IMPORT_FORMAT, filePath);
File file = service.files().create(fileMetadata, mediaContent)
.setFields("id, appProperties").
.execute();
YOUR_IMPORT_FORMAT, fill this with the value in this link, https://developers.google.com/drive/api/v3/manage-uploads, there is explanation below the example code
setFields("id, appProperties"), fill this with the value in this link: https://developers.google.com/drive/api/v3/migration, this the most important part I think, if you don't set the value in the setFields method your additional input will not be written
With version v3, to add or update appProperties for an existing file and without this error:
"The resource body includes fields which are not directly writable."
You should do:
String fileId = "Your file id key here";
Map<String, String> appPropertiesMap = new HashMap<String, String>();
appPropertiesMap.put("MyKey", "MyValue");
appPropertiesMap.put("MySecondKey", "any value");
//set only the metadata you want to change
//do not set "id" !!! You will have "The resource body includes fields which are not directly writable." error
File fileMetadata = new File();
fileMetadata.setAppProperties(appPropertiesMap);
File updatedFileMetadata = driveService.files().update(fileId, fileMetadata).setFields("id, appProperties").execute();
System.out.printf("Hey, I see my appProperties :-) %s \n", updatedFileMetadata.toPrettyString());