scala-spray: why do I get escaped strings with trailing quotes? - spray

I'm new to scala and spray and I'm having a very simple problem. I want my rest service to return unescaped strings when I return a string from a rest call, it stead i'm getting a compacted string with escapes in it. Here is my code:
Rest Service:
....
get {
respondWithMediaType(MediaTypes.`text/plain`) {
complete {
s"""
hey joe this is
"me"
bill"""
}
}
}
When I call the my service I get:
"\nhey joe this is\n\"me\"\n\bill"
But if I do a println() I see what I would expect. Please help.

I solved my own problem, it was the JSON support trait that was automatically marshalling the object
This trait Json4sSupport automatally marshal your objects as JSON hence the wrapping and compact print etc.
import spray.httpx.Json4sSupport
If you remove it you should be getting the unescaped results.
hope it helps anyone else out there.

We had the same problem using Jackson; we worked around the issue by creating an http response object instead, like so…
respondWithMediaType(`text/html`) {
complete {
new HttpResponse(StatusCodes.OK, HttpEntity(
"""
|<!DOCTYPE html>
|<html>
|<head>
|<title>Download app</title>
|</head>
|<body>
|<h2>
|Click here<br>
|</h2>
|</body>
|</html>
""".stripMargin
))
}
}

Related

Dart compare two strings return false

Im new to dart and have a problem during building my Flutter application.
I have a firestore database as a backend and im getting data from there.
When i want to compare part of the data called status with the text 'CREATED', using == comparator, dart will return false.
Can someone explain why and how to check it properly?
rideObject is a Map
Update:
Here is the function that has the condition in it:
Widget _getPage() {
if (rideObject == null) {
return OrderRidePage(
address: address,
ridesReference: reference,
setRideReference: this._setRideReference);
} else {
print(rideObject['status']);
if (rideObject['status'] == "CREATED") {
return LoadingPage(
removeRideReference: this._removeRideReference,
rideReference: rideReference);
} else {
return RidePage(
address: address,
ridesReference: reference,
setRideReference: _setRideReference);
}
}
}
The print statement returns to output:
I/flutter (15469): CREATED
Here you can see the structure of the rideObject
Funnily enough, the rideObject["status"] is String type as shown in here in console:
rideObject["status"] is String
true
"CREATED" is String
true
rideObject["status"]
"CREATED"
rideObject["status"] == "CREATED"
false
The String you got from your server is probably encoded and contains special character which you can't see, try to compare the hex values of both of the strings, and then replace all the special characters from the String returned by the server.
Using this, you can see the actual non visible difference between the two strings:
var text1 = utf8.encode(hardcodedText).toString();
var text2 = utf8.encode(textFromServer).toString();
If both are really strings, you can use "compareTo" which will return 0 if both are equal.
if(str1.compareTo(str2)==0){
}
It is explained here:
https://www.tutorialspoint.com/dart_programming/dart_programming_string_compareto_method.htm
I don't have a particular solution to this, but I updated to latest Flutter version that came up today, moved the "CREATED" string into constant and resolved an unrelated warning for another part of the application, and it suddenly started to work.
The answer for this problem is in the documentation of flutter:
https://api.flutter.dev/flutter/dart-core/String/compareTo.html
you can do:
(var.compareTo('WORD') == 0)
are equivalent
.compareTo()
Returns a negative value if is ordered before, a positive value if is ordered after, or zero if and are equivalent.thisother
Building off #yonez's answer, the encoding may be different after a string has been passed through a server.
Instead of: String.fromCharCodes(data)
Try using: utf8.decode(data)

Array.size() returned wrong values (Grails)

I'm developing an app using Grails. I want to get length of array.
I got a wrong value. Here is my code,
def Medias = params.medias
println params.medias // I got [37, 40]
println params.medias.size() // I got 7 but it should be 2
What I did wrong ?
Thanks for help.
What is params.medias (where is it being set)?
If Grials is treating it as a string, then using size() will return the length of the string, rather than an array.
Does:
println params.medias.length
also return 7?
You can check what Grails thinks an object is by using the assert keyword.
If it is indeed a string, you can try the following code to convert it into an array:
def mediasArray = Eval.me(params.medias)
println mediasArray.size()
The downside of this is that Eval presents the possibility of unwanted code execution if the params.medias is provided by an end user, or can be maliciously modified outside of your compiled code.
A good snippet on the "evil (or lack thereof) of eval" is here if you're interested (not mine):
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/
I think 7 is result of length of the string : "[37,40]"
Seems your media variable is an array not a collection
Try : params.medias.length
Thanks to everyone. I've found my mistake
First of all, I sent an array from client and my params.medias returned null,so I converted it to string but it is a wrong way.
Finally, I sent and array from client as array and in the grails, I got a params by
params."medias[]"
List medias = params.list('medias')
Documentation: http://grails.github.io/grails-doc/latest/guide/single.html#typeConverters

how to use regex in MVC 3 with razor

when i use MVC 3 with razor it's work fine but when i write a regex using #section head{
} that they not work
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
it have # so that's give me error that
Parser Error Description: An error occurred during the parsing of a
resource required to service this request. Please review the following
specific parse error details and modify your source file
appropriately. Parser Error Message: "\" is not valid at the start of
a code block. Only identifiers, keywords, comments, "(" and "{" are
valid.
A neater option is to escape the # by placing another # in front of it (##)
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(##((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(##\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
Add <text></text> around the function, it tells Razor to not parse the contents:
<text>
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(#\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
return pattern.test(emailAddress);
}
</text>
Sorry, folks, you aren't reading the error, it's complaining about the backslashes, not the #, and or #{ } don't help.

When parsing XML, the character é is missing

I have an XML as input to a Java function that parses it and produces an output. Somewhere in the XML there is the word "stratégie". The output is "stratgie". How should I parse the XML as to get the "é" character as well?
The XML is not produced by myself, I get it as a response from a web service and I am positive that "stratégie" is included in it as "stratégie".
In the parser, I have:
public List<Item> GetItems(InputStream stream) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(stream);
doc.getDocumentElement().normalize();
NodeList nodeLst = doc.getElementsByTagName("item");
List<Item> items = new ArrayList<Item>();
Item currentItem = new Item();
Node node = nodeLst.item(0);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element item = (Element) node;
if(node.getChildNodes().getLength()==0){
return null;
}
NodeList title = item.getElementsByTagName("title");
Element titleElmnt = (Element) title.item(0);
if (null != titleElmnt)
currentItem.setTitle(titleElmnt.getChildNodes().item(0).getNodeValue());
....
Using the debugger, I can see that titleElmnt.getChildNodes().item(0).getNodeValue() is "stratgie" (without the é).
Thank you for your help.
I strongly suspect that either you're parsing it incorrectly or (rather more likely) it's just not being displayed properly. You haven't really told us anything about the code or how you're using the result, which makes it hard to give very concrete advice.
As ever with encoding issues, the first thing to do is work out exactly where data is getting lost. Lots of logging tends to be the way forward: create a small test case that demonstrates the problem (as small as you can get away with) and log everything about the data. Don't just try to log it as raw text: log the Unicode value of each character. That way your log will have all the information even if there are problems with the font or encoding you use to view the log.
The answer was here: http://www.yagudaev.com/programming/java/7-jsp-escaping-html
You can either use utf-8 and have the 'é' char in your document instead of é, or you need to have a parser that understand this entity which exists in HTML and XHTML and maybe other XML dialects but not in pure XML : in pure XML there's "only" ", <, > and maybe &apos; I don't remember.
Maybe you can need to specify those special-char entities in your DTD or XML Schema (I don't know which one you use) and tell your parser about it.

How to parse a remote website and create a link on every single word for a dictionary tooltip?

I want to parse a random website, modify the content so that every word is a link (for a dictionary tooltip) and then display the website in an iframe.
I'm not looking for a complete solution, but for a hint or a possible strategy. The linking is my problem, parsing the website and displaying it in an iframe is quite simple. So basically I have a String with all the html content. I'm not even sure if it's better to do it serverside or after the page is loaded with JS.
I'm working with Ruby on Rails, jQuery, jRails.
Note: The content of the href tag depends on the word.
Clarification:
I tried a regexp and it already kind of works:
#site.gsub!(/[A-Za-z]+(?:['-][A-Za-z]+)?|\\d+(?:[,.]\\d+)?/) {|word| '' + word + ''}
But the problem is to only replace words in the text and leave the HTML as it is. So I guess it is a regex problem...
Thanks for any ideas.
I don't think a regexp is going to work for this - or, at least, it will always be brittle. A better way is to parse the page using Hpricot or Nokogiri, then go through it and modify the nodes that are plain text.
It sounds like you have it mostly planned out already.
Split the content into words and then for each word, create a link, such as whatever
EDIT (based on your comment):
Ahh ... I recommend you search around for screen scraping techniques. Most of them should start with removing anything between < and > characters, and replacing <br> and <p> with newlines.
I would use Nokogiri to remove the HTML structure before you use the regex.
no_html = Nokogiri::HTML(html_as_string).text
Simple. Hash the HTML, run your regex, then unhash the HTML.
<?php
class ht
{
static $hashes = array();
# hashes everything that matches $pattern and saves matches for later unhashing
function hash($text, $pattern) {
return preg_replace_callback($pattern, array(self,'push'), $text);
}
# hashes all html tags and saves them
function hash_html($html) {
return self::hash($html, '`<[^>]+>`');
}
# hashes and saves $value, returns key
function push($value) {
if(is_array($value)) $value = $value[0];
static $i = 0;
$key = "\x05".++$i."\x06";
self::$hashes[$key] = $value;
return $key;
}
# unhashes all saved values found in $text
function unhash($text) {
return str_replace(array_keys(self::$hashes), self::$hashes, $text);
}
function get($key) {
return self::$hashes[$key];
}
function clear() {
self::$hashes = array();
}
}
?>
Example usage:
ht::hash_html($your_html);
// your word->href converter here
ht::unhash($your_formatted_html);
Oh... right, I wrote this in PHP. Guess you'll have to convert it to ruby or js, but the idea is the same.

Resources