Adding a " to a string in code - java

I'm writing some code for web services for my Android app which uses JSON. The url should look like this
url = url + "?maddr=" + mailAddr + "&pwd=FB&lect=" + """ + lectName + """ + "&fb=Test";
This is because the Lectname may be two or more words. However the compiler wont accept """, is there a character I can precede the " with to get the compiler to accept it into my string?

Try " \" ". You have to escape the "
http://en.wikipedia.org/wiki/Escape_character
You need this in (nearly) every programming language.

Related

evaluate JSON expression in child object

I am trying to evaluate json expression using Josson, but it gives invalid function error
String json ="{\"data\":{\"B\":\"calc(348+(96*$.SelectedPump.stg*$.ModelMaster.count))\"},\"SelectedPump\":{\"stg\":10,\"ab\":200},\"ModelMaster\":{\"count\":20}}";
Josson josson = Josson.fromJsonString(json.toString());
System.out.println(josson.getNode("data.eval(B)"));
Stacktrace:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid function call eval() : Invalid function call calc() : Calc syntax error.
at com.octomix.josson.FuncDispatcher.apply(FuncDispatcher.java:84)
at com.octomix.josson.JossonCore.getPathBySteps(JossonCore.java:328)
at com.octomix.josson.JossonCore.getPathBySteps(JossonCore.java:352)
at com.octomix.josson.JossonCore.getPathBySteps(JossonCore.java:249)
at com.octomix.josson.JossonCore.getPathByExpression(JossonCore.java:211)
at com.octomix.josson.JossonCore.getNodeByExpression(JossonCore.java:147)
at com.octomix.josson.JossonCore.getNodeByExpression(JossonCore.java:142)
at com.octomix.josson.Josson.getNode(Josson.java:279)
The variables inside the math equation cannot contains special characters. You need to use substitution. The variable name can whatever you want without special characters and .. So, the statement of B become...
calc(348+(96*A*B), A:SelectedPump.stg, B:ModelMaster.count)
The function eval() in query data.eval(B) works on node data. So the original evaluation statement needs $. to re-start from the root to get the value. For this revised version eval(data.B), eval() works on the root node with parameter data.B. And therefore, $. is not necessary.
String json =
"{\n" +
" \"data\": {\n" +
" \"B\": \"calc(348+(96*A*B), A:SelectedPump.stg, B:ModelMaster.count)\"\n" +
" },\n" +
" \"SelectedPump\": {\n" +
" \"stg\": 10,\n" +
" \"ab\": 200\n" +
" },\n" +
" \"ModelMaster\": {\n" +
" \"count\": 20\n" +
" }\n" +
"}";
Josson josson = Josson.fromJsonString(json);
System.out.println(josson.getNode("eval(data.B)"));
// Output: 19548.0
Answer by Raymond Choi would be the best solution.
Alright, I have found a possible solution to this using Jossons template engine.
String json = "{\"data\":{\"B\":\"calc(348+(96*{{SelectedPump->stg}}*{{ModelMaster->count}}))\"},\"SelectedPump\":{\"stg\":10,\"ab\":200},\"ModelMaster\":{\"count\":20}}";
Jossons jossons = Jossons.fromJsonString(json);
String output = jossons.fillInPlaceholder("{\"s\":\"{{data->B}}\"}");
output = jossons.fillInPlaceholder(output);
System.out.println(output);
System.out.println(Josson.fromJsonString(output).getNode("$.eval(s)"));
It is necessary to adjust the JSON string to use placeholder to access the values from a different/nested node. We also have to create a new JSON string with a template that is filled in. Also also, it does sadly not recursively replace the placeholder, making it necessary to call jossons.fillInPlaceholder() two times. The first time it fetches the calculated formula and the second time it replaces the placeholder that are now present in the formula.
The output is:
output -> {"s":"calc(348+(96*10*20))"}
Josson.fromJsonString(output).getNode("$.eval(s)") -> 19548.0
The proposed code in the question fails, because Josson is not able to resolve nested/different node values. Pretty much as soon as we have a . present in the calc() formula, the syntax check fails. It is however possible to access nodes at the same level. So a JSON like this:
{
"data" : {
"B" : "calc(348+(96*SelectedPumpStg*ModelMasterCount))",
"SelectedPumpStg" : 10,
"ModelMasterCount" : 20
}
}
can be evaluated by:
String json = "{\"data\":{\"B\":\"calc(348+(96*SelectedPumpStg*ModelMasterCount))\",\"SelectedPumpStg\":10,\"ModelMasterCount\":20}}";
Josson josson = Josson.fromJsonString(json.toString());
System.out.println(josson.getNode("data.eval(B)"));
resulting in the same: 19548.0.
Either way, the input JSON has to be adjusted to work with Josson

Encoding special characters in wiremock response

I am facing a scenario where the character "�" occasionally gets returned from my okhttp requests, and the character is causing some downstream issues. So I have added code to remove this character should it exist and I would like to add a test case to ensure this works correctly. The issue is that wiremock does not seem to like this special character.
Normally I would pull out the data from the response as so:
String stringifiedResponse = response.getResponseString();
if (response.isSuccessful()) {
custResp = response.getData();
Normally this works fine for all my requests. However, when I set up wiremock to return a response with the special character (even as a single one, and I would like to test with many different fields), the stringified response does have the response but the data is null.
This is how I have set up the mocks in my test class
public static void mockCPInvalidChars(String ssn) {
String customerPrefillPrimaryOwnerRequest = " {\n" +
" \"customers\": [\n" +
" {\n" +
" \"partyId\": \"" + ssn + "\",\n" +
" \"idType\": \"LID\"\n" +
" }\n" +
" ]\n" +
"}";
String partyId =
ssn.substring(0, 3) + "-"
+ ssn.substring(3, 5) + "-"
+ ssn.substring(5, 9);
String customerPrefillPrimaryOwnerResponse = "{\"totalRecords\":1,\"customers\":[{\"partyId\":\"" + partyId + "\",\"idType\":\"LID\",\"sourceCode\":\"ICS\",\"firstName\":\"R�EEVES\",\"lastName\":\"WI�CKLIFF\",\"address1\":\"59 Ma�iling LANE\",\"address2\":\"ma�l2\",\"address3\":\"mail�3\",\"address4\":\"mai�l4\",\"city\":\"Mai�l\",\"state\":\"M�A\",\"zipCode\":\"010�10\",\"primaryPhone\":\"817504�0350\",\"alternatePhone\":\"81750�40351\",\"birthDate\":\"1902-0�2-10\",\"foreignIndicator\":\"N\",\"alternateAddress1\":\"88 LEG�AL LANE\",\"alternateAddress2\":\"leg�al2\",\"alternateAddress3\":\"lega�l3\",\"alternateAddress4\":\"lega�l4\",\"alternateCity\":\"LEG�AL\",\"alternateZipCode\":\"020�20\",\"alternateState\":\"L�A\",\"alternateForeignIndicator\":\"N\",\"mailTo\":\"\",\"alternateMailTo\":\"\",\"institutionId\":\"N\",\"taxId\":\"" + ssn + "\",\"taxIdIssuer\":\"S\"}]}";
stubFor(post(urlEqualTo("/my/url"))
.withRequestBody(equalToJson(customerPrefillPrimaryOwnerRequest))
.withHeader("Authorization", equalTo("Bearer " + OauthService.getOauthToken().orElse(new OauthToken()).getAccess_token()))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withHeader("Content-Length", String.valueOf(customerPrefillPrimaryOwnerResponse.length()))
.withBody(customerPrefillPrimaryOwnerResponse)));
}
Your issue is coming from not escaping the replacement character.
� translates to \uFFFD, but you'll need to escape the escape character as well (silly JSON), so that becomes \\uFFFD, or in the middle of another string "na\\uFFFDthan"

writing a specific string to a file with Java

my codes dont seem to properly address what i intend to achieve.
a long string instead of a well broken and seperated string
it does not handle the 'seperator' appropriately ( produces , instead of ",")
also the 'optional' ( produces ' instead of " '")
Current result:
LOAD DATA INFILE 'max.csv'BADFILE 'max.bad'DISCARDFILE
'max.dis' APPEND INTO TABLEADDRESSfields terminated by,optionally enclosed
by'(ID,Name,sex)
the intended result should look like this
is there a better way of doing this or improving the above codes
Yeah. Use the character \n to start a new line in the file, and escape " characters as \". Also, you'll want to add a space after each variable.
content = " LOAD DATA\nINFILE "+ fileName + " BADFILE "+ badName + " DISCARDFILE " +
discardName + "\n\nAPPEND\nINTO TABLE "+ table + "\n fields terminated by \"" + separator
+ "\" optionally enclosed by '" + optional + "'\n (" + column + ")";
This is assuming fileName, badName, and discardName include the quotes around the names.
Don't reinvent the wheel... the apache commons-io library does all that in one line:
FileUtils.write(new File(controlName), content);
Here's the javadoc for FileUtils.write(File, CharSequence):
Writes a CharSequence to a file creating the file if it does not exist
To insert a new line you need to use \n or \r\n for windows
for example
discardName + "\n" //New line here
"APPEND INTO TABLE"
For the double quote symbol on the other hand you need to specifically type \" around the comma:
"fields terminated by \"" + separator +"\""
which will produce this ","
and that is similar to what the optional variable needs to be

Query customized model in Alfresco

I've some customized models into Alfresco and I need to extract the aspect information and the content from Repository.
I need, passing the keywords and the model name (it's an aspect), to extract content or the aspects associated to the model.
search/{keywords}?model={model?}
this is the javascript I'm using to extract the content passing the model
var docs = search.luceneSearch("#kd\\:commonname_content_type_tag:\"" + model + "\"");
How can I concatenate two aspects properties?
I did it into Java but the syntax in Javascript seems quite different:
queryString = "+TYPE:\"" + Constants.createQNameString(CommonAspects.NAMESPACE_KD_CONTENT_MODEL, DrugModel.TYPE_SUPPLIER) + "\" ";
queryString += "+#kd\\:SupplierID:" + drugBrandNameBean.getSupplierID();
String supplier = contentQuery.getUUID(queryString);
Another question, how can I process the Javascript docs? Can I access to my aspects?
I tried something like that but it didn't works:
var docs = search.luceneSearch("#kd\\:commonname_content_type_tag:\"" + model + "\"");
for (var i=0; i<docs.length; i++) {
log += "Searching " + commonName + " - Name: " + docs[i].name + "\tPath: " + docs[i].displayPath;
log += "\tType: " + docs[i].commonname_content_type_tag + "\r\n";
}
The rows extracted are correct but the commonname_content_type_tag properties is always not defined:
Searching acarbose - Name: exenatide - Contraindication Path: /Company Home/CommonName Type: undefined
Thanks for the help!
Andrea
Try something like that:
docs[i].properties["kd:commonname_content_type_tag"]

new line in java

Java newbie here, I'm having trouble setting a new line in this code:
String FnameTextboxText = FnameTextbox.getText();
String LastnameTextboxText = LastnameTextbox.getText();
String CourseTextboxText = CourseTextbox.getText();
Summary.setText("Firstname:" + " " + FnameTextboxText + "\nLastname:" + " " + LastnameTextboxText + "\nCourse:" + " " + CourseTextboxText);
Also tried something like: "\n" + "Lastname" But its no good.
Do you have any idea on how to make new lines. So that it'll look like this;
Firstname: x
Lastname: y
Course: Z
Using netbeans 6.8. On windows.
I guess you need to use TextArea.
First, use TextArea
Second, test using \r or \n or \r\n
Sometimes, people use \n to make new line and sometimes, like me, use \r\n to make new line

Categories

Resources