Web script to get the properties of the document - javascript

Create a web script to get the parameters of the document in java Example url:
localhost:8080/alfresco/s/get-document-data?nodeRef=workspace://SpacesStore/3b3597e5-b5ec-41d5-b63b-54b050dccd1b&property=cm:name
As a result the script should return Json object of a kind:
{
"nodeRef": "workspace: // SpacesStore / 3b3597e5-b5ec-41d5-b63b-54b050dccd1b",
"value": "value property - the one we got from nodRef"
}
Create a web script to retrieve all subfolder settings along the way. Please help!
DocumentScript.java
import org.activiti.engine.impl.util.json.JSONException;
import org.apache.chemistry.opencmis.commons.impl.json.JSONObject;
import org.springframework.extensions.webscripts.*;
import java.io.IOException;
public class DocumentScript extends AbstractWebScript {
public static JSONObject obj = new JSONObject();
#Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
try {
String noderef = req.getParameter("nodeRef");
String valueRef = res.getEncodeResourceUrlFunction("value");
obj.put("nodeRef", noderef);
obj.put("value", valueRef);
String jsonString = obj.toString();
res.getWriter().write(jsonString);
} catch (JSONException e) {
throw new WebScriptException("Unable to serialize JSON");
}
}
}
document-script-context.xml
<bean class="alfresco.extension.templates.webscripts.repository.DocumentScript"
parent="templates.webscripts.repository">
</bean>
document-script.get.desc.xml
<webscript>
<shortname>Documents</shortname>
<description>JSON data
</description>
<url>/script-document?q={keyword}</url>
<authentication>user</authentication>
<format default="html"/>
<family>Alfresco Script</family>
</webscript>
document-script.get.html.ftl
{
"obj" : [
<#list obj as Obj>
{
"nodeRef" : "${Obj.nodeRef}",
"value" : "${Obj.value}"
}
<#if Obj_has_next>,</#if>
</#list>
]
}
Here I want to get the parameters of the document here is the code but it doesn't work, what's wrong with it?
06220015 Wrapped Exception (with status template): 06220002 Error during processing of the template 'The following has evaluated to null or missing: ==> obj [in template "repository/document-script.get.html.ftl" at line 3, column 8] Tip: If the failing expression is known to be legally null/missing, either specify a default value with myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing</#if>. (These only cover the last step of the expression; to cover the whole expression, use parenthessis: (myOptionVar.foo)!myDefault, (myOptionVar.foo)?? The failing instruction: ==> #list obj as Obj [in template "repository/document-script.get.html.ftl" at line 3, column 1]'.

You could start by creating a class for the JSON object then just do something like this:
String url = localhost:8080/alfresco/s/get-document-data?nodeRef=workspace://SpacesStore/3b3597e5-b5ec-41d5-b63b-54b050dccd1b&property=cm:name;
String[] values = url.split('?');
String[] value = values[0].split('=');
jsonObject.setNodeRef(value[1]);
.....
This will work if you know that your url has the exact same parameters you mentioned. Just use regexp. I haven't tested the code myself, give it a try.

Related

How to get the value of a specific HTML element in a given HTML document or webpage (by URL)?

I want to pass the url of a webpage containing a <span id="spanID"> value </span> tag to a method like setTextBoxText(string url, string id) which is written in a wpf application codeBehind (MainWindow.xaml.cs) and set the Text of a specific TextBox Control to the span value, without loading the webpage. (for Ex. tracking price of a product in amazon)
I prefer to execute JavaScript code to get value of html elements and set the content of wpf controls to the result of the js code (function)
something like this:
public partial class MainWindow : Window
{
string url = "https://websiteaddress.com/rest";
setTextBoxText(url, "spanID");
static void setTextBoxText(string url, string id)
{
// code to get document by given url
txtPrice.Text = getHtmlElementValue(id);
}
string getHtmlElementValue(string id)
{
// what code should be written here?
// any combination of js and c#?
// var result = document.getElementById(id).textContent;
// return result;
}
}
You can use the HttpClient to load the HTML content of an URL and then process the DOM object in a JavaScript like syntax by wrapping the response into a mshtml.HTMLDocument - requires reference to Microsoft.mshtml.dll:
private mshtml.HTMLDocument HtmlDocument { get; set; }
private async Task SetTextBoxTextAsync(string url, string id)
{
await UpdateHtmlDocumentAsync(url);
var value = GetHtmlElementValueById(id);
txtPrice.Text = value;
}
public async Task UpdateHtmlDocumentAsync(string url)
{
using (HttpClient httpClient = new HttpClient())
{
byte[] response = await httpClient.GetByteArrayAsync(url);
string httpResponseText = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
string htmlContent = WebUtility.HtmlDecode(httpResponseText);
this.HtmlDocument = new HTMLDocument();
(this.HtmlDocument as IHTMLDocument2).write(htmlContent);
}
}
public string GetHtmlElementValueById(string elementId)
=> this.HtmlDocument.getElementById(elementId).innerText;

Calling script from Blazor with parameters

I've been given a script function and would like to partially translate it to C# in a Blazor app
<script>
function pay() {
var token = document.getElementById('token').value;
var card = document.getElementById('card').value;
var exp = document.getElementById('exp').value;
var cvv = document.getElementById('cvv').value;
var paymentData = {
ssl_txn_auth_token: token,
ssl_card_number: card,
ssl_exp_date: exp ,
ssl_cvv2cvc2: cvv
};
ConvergeEmbeddedPayment.pay(paymentData);
return false;
}
</script>
I want to call the script (that is inside the script above)
ConvergeEmbeddedPayment.pay(paymentData);
Directly from c# . Like so
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", paymentData);
There is some good information here:
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-3.1
But it stops short of helping me.
What kind of variable should I pass in the paymentData parameter? And how should I pass it?
I've tried var , object and string and also tried JsonSerializer.Serialize( ); but no luck
Based on suggestion from #BurningKarl I tried Dictionary and object[] but
I get an error saying the content is missing or "Expected BEGIN_OBJECT but was STRING "
Looks like you have to create your own c# class that mimics the payment data object in your Javascript.
Something like this
public class PaymentData
{
public string ssl_txn_auth_token {get; set;}
public string ssl_card_number{get; set;}
public string ssl_exp_date{get; set;}
public string ssl_cvv2cvc2{get; set;}
}
Then you have to create an instance of this class and pass it to InvokeVoidAsync as an argument.
var data = new PaymentData ()
{
ssl_txn_auth_token = "authtokenvalue",// you have to get it from control
ssl_card_number = "card number",
ssl_exp_date: "date", // probably it should be daytime or similar
ssl_cvv2cvc2 = "111"
}
await JsRuntime.InvokeVoidAsync("ConvergeEmbeddedPayment.pay", data);

Strings with high Unicode characters become corrupted when passing from Javascript to Java

I am passing a string from Javascript to a React Native native Java module and then back to Javascript. However, any high Unicode characters such as emojis become corrupted after passing it to Java and turn into a pair of question marks.
For example, the string "testing123😃" becomes "testing123??"
How can I fix this so that the characters retain their values?
EDIT: The string is being processed by a React Native background upload library. Here is an excerpt of the code from that library that passes the text (which is in the parameters field) to the Java module:
import { NativeModules, DeviceEventEmitter } from 'react-native'
export type StartUploadArgs = {
url: string,
path: string,
method?: 'PUT' | 'POST',
// Optional, because raw is default
type?: 'raw' | 'multipart',
// This option is needed for multipart type
field?: string,
customUploadId?: string,
// parameters are supported only in multipart type
parameters?: { [string]: string },
headers?: Object,
notification?: NotificationArgs
}
const NativeModule = NativeModules.VydiaRNFileUploader || NativeModules.RNFileUploader // iOS is VydiaRNFileUploader and Android is NativeModules
//...
export const startUpload = (options: StartUploadArgs): Promise<string> => NativeModule.startUpload(options)
And here is an excerpt of the Java code that handles the string:
#ReactMethod
public void startUpload(ReadableMap options, final Promise promise) {
//...
HttpUploadRequest<?> request;
if (requestType.equals("raw")) {
request = new BinaryUploadRequest(this.getReactApplicationContext(), customUploadId, url)
.setFileToUpload(filePath);
} else {
if (!options.hasKey("field")) {
promise.reject(new IllegalArgumentException("field is required field for multipart type."));
return;
}
if (options.getType("field") != ReadableType.String) {
promise.reject(new IllegalArgumentException("field must be string."));
return;
}
request = new MultipartUploadRequest(this.getReactApplicationContext(), customUploadId, url)
.addFileToUpload(filePath, options.getString("field"));
}
request.setMethod(method)
.setMaxRetries(2)
.setDelegate(statusDelegate);
//...
if (options.hasKey("parameters")) {
if (requestType.equals("raw")) {
promise.reject(new IllegalArgumentException("Parameters supported only in multipart type"));
return;
}
ReadableMap parameters = options.getMap("parameters");
ReadableMapKeySetIterator keys = parameters.keySetIterator();
while (keys.hasNextKey()) {
String key = keys.nextKey();
if (parameters.getType(key) != ReadableType.String) {
promise.reject(new IllegalArgumentException("Parameters must be string key/values. Value was invalid for '" + key + "'"));
return;
}
request.addParameter(key, parameters.getString(key));
}
}
//...
String uploadId = request.startUpload();
promise.resolve(uploadId);
}
The java servlet specification assumes form params are ISO-8859-1 by default. Assuming you are using tomcat see https://cwiki.apache.org/confluence/display/TOMCAT/Character+Encoding for info on how to resolve this issue
Relevant quote from the page
POST requests should specify the encoding of the parameters and values
they send. Since many clients fail to set an explicit encoding, the
default used is US-ASCII for application/x-www-form-urlencoded and
ISO-8859-1 for all other content types.
Related SO post https://stackoverflow.com/a/19409520/1967484
Keep in mind its also possible for your console and your database to also not support high unicode characters.
Modifying the background upload library's code like this fixed the issue:
request = new MultipartUploadRequest(this.getReactApplicationContext(), customUploadId, url)
.addFileToUpload(filePath, options.getString("field"))
.setUtf8Charset(); // add this line

How to use JSON result in selenium webdriver

Im a beginner for automation testing.Here I want to get the data's from json to be used by selenium webdriver.I wrote one java class and hard coded something to get a result as a try.and getting an answer in console panel like
{
"name": "john",
"location": "jihu",
"job": [
{
"manager": [
{
"collegues": [
"ram",
"ranma",
],
}
}
}
(not exactly this).
Now i want to use this for one specific application using selenium webdriver. How can i move on with this.help me in detail.Thanks in advance.
From Selenium and Backend Comparison testing point of view i am answering the same .you need to parse json response using some Libraries like GSON , jackson etc into Java Pojo objects and then apply asserts on the fields you want to compare with json and UI. I guess you need to go through below topics first
1) Serialization -Deserialization API response
2) GSON or Jackson parsers
3) RestAssured ( Provides framework for API testing )
4) JAVA pojo classed and usage of them . you might need them to save your response in form of some Response class and compare objects .
You can use these online converters for converting a json object into Java Pojo Classes :
http://json2java.azurewebsites.net/ (I usually use this)
https://codebeautify.org/json-to-java-converter
and then place them in a package or in the same class as you wish :
You can better understand it by below example :
package com.demo.core;
import com.google.gson.Gson;
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class Demo {
public static void main(String r[]) {
Response response1 = RestAssured.given().get("http://dummy.restapiexample.com/api/v1/employee/1"); // use your method to get the API response (I have used RestAssured here)
String json = response1.asString(); // you can use your json response here and convert it into a String
Gson gson = new Gson();
Employee emp = gson.fromJson(json, Employee.class); // The response is now captured in this Employee class
System.out.println(emp.getEmployeeAge());
System.out.println(emp.getEmployeeName());
System.out.println(emp.getEmployeeSalary());
}
}
class Employee {
private String id;
private String employee_name;
private String employee_salary;
private String employee_age;
private String profile_image;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return this.employee_name;
}
public void setEmployeeName(String employee_name) {
this.employee_name = employee_name;
}
public String getEmployeeSalary() {
return this.employee_salary;
}
public void setEmployeeSalary(String employee_salary) {
this.employee_salary = employee_salary;
}
public String getEmployeeAge() {
return this.employee_age;
}
public void setEmployeeAge(String employee_age) {
this.employee_age = employee_age;
}
public String getProfileImage() {
return this.profile_image;
}
public void setProfileImage(String profile_image) {
this.profile_image = profile_image;
}
}
You can easily assert the values after the response is captured in Java classes using their getter methods like I have used in the code to get field values present in Employee class.
Please do let me know if you still got an issue.
If your result contains many fields than better to shift all converted java classes into a separate package for a clear code.

Return list to JSON to Angularjs

It is such that I must have sent some content from my controller over to Angularjs which shall come forth with words such as only L in themselves or E, so it goes in other words, of words where it like just let the words sign which has the single letter.
There is no fault forward by the console and what I believe is the problem is that it does not specify any value to the side.
i have try its here:
A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.
Load.js
var app = angular.module('WordSpreads',[]);
app.controller('WordSpreadsListValue', function ($scope, $http) {
$http(
{
method: 'GET',
url: '../Profile/MWordSpreads'
}).success(function (response) {
$scope.entries = data.List;;
});
console.log("TEST");//It does not appear in the console log.
});
Controller:
[HttpGet]
public JsonResult MWordSpreads()
{
WordsSpreadsListValue model = new WordsSpreadsListValue();
var db = HelperToTables.DbValue;
model.List = db.WordSpreads.ToList();
return Json(model.List, JsonRequestBehavior.AllowGet);
}
Model:
public class WordsSpreadsListValue
{
public List<WordSpread> List { get; set; }
}
Error giv me:
A circular reference was detected while serializing an object of type
'xxSitename.Models.LinqDatabase.WordSpread'
UPDATE:
model.List = db.WordSpreads.Select(x => new {
Name = x.name,
TextValue = x.text.ToString()
}).ToList();
ERROR :
Cannot implicitly convert type
'System.Collections.Generic.List<>' to
'System.Collections.Generic.List' MVCOrdklar2015
.
model.List = db.WordSpreads.Select(x => new { Prop1 = x.1, Prop2 = x.2}).ToList();
You are having trouble serializing model.List, the Json serialize is barfing on serializing model.List. If you make it a new object without navigation properties you will be fine.
In my experience it has to do with the navigation properties, I dont fully understand what it is. But, once you remove the navigation properties from the equation it will work.

Categories