How to create a new string to represent the contents of the file read from the previous method? - reverse

I create two methods, the first named displayFile, it is used to read the string in the file. The second named reverse, it is used to reverse the string that read in the "displayFile".Now I want to create a new string in the main method, just named it as aString, which would be appeared in main method like :reverse(aString);.
So how to write this string? I mean, String aString= ,what do I need to write after "="
I only write displayFile(fileName);, I don't know how to treat reverse method, how to add it into main method.

Related

Extract a specified data object that resides inside a PDF form field to an external file

I am looking for a script to extract a data object nested inside a data object to a new data object. Aside from being able to easily clone the object by creating a new one, while I can also extract one of several objects nested inside an object that includes all its related properties and values, the name associated with the property and values is missing. Hence, I require a script to create a new object containing any one of several names including its related properties and values extracted from the existing object provided below.
{"J Doe Company":{"lastUpdate":"01/05/2023","website":"jdoecompany.com","userID":"jdoe1985#gmail.com","password":"igfndhsi1985","primaryCC":"Discover","secondaryCC":"Capital One","primaryBank":"Chase","secondaryBank":"","sq1":"Year Graduated HS","sa1":"1985","sq2":"","sa2":"","notes1":"Sample password record","notes2":""},"Bob The Builder":{"lastUpdate":"01/05/2023","website":"bobthebuilder.com","userID":"bobthebuilder#gmail.com","password":"bbob1985","primaryCC":"Amazon Visa","secondaryCC":"Mastercard","primaryBank":"Wells Fargo","secondaryBank":"","sq1":"First Girlfriend's Name","sa1":"Kaye","sq2":"","sa2":"","notes1":"Sample password record","notes2":""},"SpongeBob Square Pants":{"lastUpdate":"01/07/2023","website":"spongebobsquarepants.com","userID":"spongebob#gmail.com","password":"spongebob1999","primaryCC":"None/Not Applicable","secondaryCC":"","primaryBank":"None/Not Applicable","secondaryBank":"","sq1":"Year show debuted on TV","sa1":"1999","sq2":"","sa2":"","notes1":"Animated TV show for kids","notes2":""}}
You can run cpdf -output-json in.pdf -o put.json and process the result. The format is described in the cpdf manual.
Upon further trial and error after learning more about how to create and edit an object literal, the script required to add an object along with its key-value properties is as follows:
dsFld =getField("dataSrc");// dataSRC is a hidden field containing a JS object converted to a JSON string
oVendors = JSON.parse(dsFld.value); // oVendors is a JS object
oVendors[event.value]=oVendorsPropValues;//oVendorsPropValues = {key-value pairs}
dsFld.value = JSON.stringify(oVendors);// convert the JS obj back to a JSON string

Create list of custom objects from flat JSON data

I want to create an arraylist of type Adapter from a JSON. But since the JSON is not in arraylist format, I'm unable to use gson.fromJson() method.
Is there any way by which I can create a list of my custom object by parsing the following JSON?
JSON data:
"source":{"adapter-config.adapter[0].name":"testAdapter1",
"adapter-config.adapter[0].resolverName":"serviceResolver",
"adapter-config.adapter[0].parameters[0].key":"serviceId",
"adapter-config.adapter[0].parameters[0].value":"serviceIdPathInEvent",
"adapter-config.adapter[0].parameters[1].key":"appId",
"adapter-config.adapter[0].parameters[1].value":"appIdPathEvent",
"adapter-config.adapter[0].parameters[2].key":"env",
"adapter-config.adapter[0].parameters[2].value":"envPathInEvnet"}
My Adapter Object:
public class Adapter {
private String name;
private String resolverName;
private List<KeyValuePair<String, String>> attributeList;
}
Gson does not provide such functionality out of the box. However you can achieve this by manually reading the JSON data from a JsonReader, consuming the JSON property names with nextName() and then parsing them to determine which data they represent. You could either directly read from a JsonReader, or in case the shown JSON data is only an extract from a larger JSON document, you can implement a TypeAdapter for your List<Adapter>. That TypeAdapter could then either be registered with a GsonBuilder by providing new TypeToken<List<Adapter>>() {}.getType() as type, or you could annotate the field holding the List<Adapter> with #JsonAdapter.
For the actual parsing of List<Adapter>, I would recommend storing a current adapter (and its index in the list) in a local variable. Whenever you parse a JSON property name, you could then check if the index encoded in the name is equal to the index of the current adapter, then you are going to modify the existing instance, otherwise if the encoded index is equal to the index of the current adapter + 1 you create a new Adapter instance, add it to the list of adapters and reassign the current adapter variable and its index variable. Then you continue with parsing the remainder of the property name to find out which Adapter field values to set.
(In case you get stuck there, feel free to let me know in the comments and I can try to provide some concrete code; but it would probably be best if you tried it yourself first.)

How to read step method contents from allure listener

Currently, I am using allure StepLifecycleListener to listen to #step. I want to get some parameters inside the method.
For Eg : I want to get
"RequestIdentifier.userservice_CreateLogin" parameter in below
#Step("Perform user login with retrieved OTP")
public BaseResponseDTO performUserLogin(String deviceId, String authId, String otp) {
response = serviceManager.sendRequest(RequestIdentifier.userservice_CreateLogin, requestParams);
}
I can get String deviceId, String authId, String otp from StepResult getparameters() method, but how can I get some parameters inside the performUserLogin() method.
You can't. Step annotation works with the method's signature, not with its body. If you want to get RequestIdentifier.userservice_CreateLogin value, just overload the method and pass a corresponding value as an argument.
On the other hand, it seems like a public static variable. In this case, you can always explicitly access it from within your AllureStepListener. However, it'd be an ugly approach.
I'd consider redesigning your API the way it'll work with custom types (aka entities) rather than passing raw strings. In this case, you can always compose all the required data (including statics) into your custom entity and then easily access it within Step annotation via "Bla-bla {entity.field}" syntax.

Use a period in a field name in a Matlab struct

I'm using webwrite to post to an api. One of the field names in the json object I'm trying to setup for posting is odata.metadata. I'm making a struct that looks like this for the json object:
json = struct('odata.metadata', metadata, 'odata.type', type, 'Name', name,);
But I get an error
Error using struct
Invalid field name "odata.metadata"
Here's the json object I'm trying to use in Matlab. All strings for simplicity:
{
"odata.metadata": "https://website.com#Element",
"odata.type": "Blah.Blah.This.That",
"Name": "My Object"
}
Is there a way to submit this json object or is it a lost cause?
Field names are not allowed to have dots in them. The reason why is because this will be confused with accessing another nested structure within the structure itself.
For example, doing json.odata.metadata would be interpreted as json being a struct with a member whose field name is odata where odata has another member whose field name is metadata. This would not be interpreted as a member with the combined field name as odata.metadata. You're going to have to rename the field to something else or change the convention of your field name slightly.
Usually, the convention is to replace dots with underscores. An automated way to take care of this if you're not willing to manually rename the field names yourself is to use a function called matlab.lang.makeValidName that takes in a string and converts it into a valid field name. This function was introduced in R2014a. For older versions, it's called genvarname.
For example:
>> matlab.lang.makeValidName('odata.metadata')
ans =
odata_metadata
As such, either replace all dots with _ to ensure no ambiguities or use matlab.lang.makeValidName or genvarname to take care of this for you.
I would suggest using a a containers.Map instead of a struct to store your data, and then creating your JSON string by iterating over the Map filednames and appending them along with the data to your JSON.
Here's a quick demonstration of what I mean:
%// Prepare the Map and the Data:
metadata = 'https://website.com#Element';
type = 'Blah.Blah.This.That';
name = 'My Object';
example_map = containers.Map({'odata.metadata','odata.type','Name'},...
{metadata,type,name});
%// Convert to JSON:
JSONstr = '{'; %// Initialization
map_keys = keys(example_map);
map_vals = values(example_map);
for ind1 = 1:example_map.Count
JSONstr = [JSONstr '"' map_keys{ind1} '":"' map_vals{ind1} '",'];
end
JSONstr =[JSONstr(1:end-1) '}']; %// Finalization (get rid of the last ',' and close)
Which results in a valid JSON string.
Obviously if your values aren't strings you'll need to convert them using num2str etc.
Another alternative you might want to consider is the JSONlab FEX submission. I saw that its savejson.m is able to accept cell arrays - which can hold any string you like.
Other alternatives may include any of the numerous Java or python JSON libraries which you can call from MATLAB.
I probably shouldn't add this as an answer - but you can have '.' in a struct fieldname...
Before I go further - I do not advocate this and it will almost certainly cause bugs and a lot of trouble down the road... #rayryeng method is a better approach
If your struct is created by a mex function which creates a field that contains a "." -> then you will get what your after.
To create your own test see the Mathworks example and modify accordingly.
(I wont put the full code here to discourage the practice).
If you update the char example and compile to test_mex you get:
>> obj = test_mex
obj =
Doublestuff: [1x100 double]
odata.metadata: 'This is my char'
Note: You can only access your custom field in Matlab using dynamic fieldnames:
obj.('odata.metadata')
You need to use a mex capability to update it...

Saving and loading with Json

Until now I was using serializable for saving and loading data, but now I have switched to JSON. And as soon as I have started there is a problem. Json will not save me any class. I was trying to save standalone Variables.class. This class contains various static data - player type string, bonus type strings, scores. Then I did create private class in class, then class in method, but nothing. Output od System.out.println(json) is always just {}.
For example this was my last attempt to make things work:
public static void saveAVD() {
Variables v = new Variables();
String json = new Json().toJson(v);
System.out.println(json);
file.writeString(json.prettyPrint(json), false);
}
Note: File variable is located in local bin folder. Inside that file are also just two empty bracelets ({})
Any advice?
(Credit to noone, who answered this in a comment).
JSON will, by default, not serialize static fields. The quickest way to get the behavior you want would probably be to convert the Variables class into a singleton.