I have a String fetched from a Database and send from a backend using Servlet. The servlet constructs the JSON and send it to the client
I use this function to escape the JSON
public static String toHTML(String string){
StringBuffer sb = new StringBuffer();
for(int i=0;i<string.length();i++){
char ch=string.charAt(i);
switch(ch){
case '"':
sb.append("\\\"");
break;
case '\\':
sb.append("\\\\");
break;
case '\b':
sb.append("\\b");
break;
case '\f':
sb.append("\\f");
break;
case '\n':
sb.append("\\n");
break;
case '\r':
sb.append("\\r");
break;
case '\t':
sb.append("\\t");
break;
case '/':
sb.append("\\/");
break;
default:
//Reference: http://www.unicode.org/versions/Unicode5.1.0/
if((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){
String ss=Integer.toHexString(ch);
sb.append("\\u");
for(int k=0;k<4-ss.length();k++){
sb.append('0');
}
sb.append(ss.toUpperCase());
}
else{
sb.append(ch);
}
}
}//for
return sb.toString();
}
But, once displayed, I see the escaped characters. Example "something \r\n".
Any suggestions ?
JavaScript function to replace newline chars
var nl2br = function(str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
}
console.log(nl2br('asdf', false)); // asdf
console.log(nl2br('as\r\ndf', false)); // as<br>
//
// df
console.log(nl2br('as\n\rdf', true)); // as<br />
//
// df
\r\n is obivously nothing a browser can interpret. Replace \r\n with <br> and you got your line break in HTML. Replace the other tags accordingly.
Related
I have a small problem with the functions inside calculator02.cpp
there is an error when compile the code
warning: control reaches end of non-void function [-Wreturn-type]130 | }
Yes I know that in any case function must return the value what can I do to solve this problem? in this case I do not have any more cases apart from that ones inside the function itself, same with the get function;
Token Token_stream::get()
{
if (full) { // do we already have a Token ready?
// remove token from buffer
full = false;
return buffer;
}
char ch;
cin >> ch; // note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
case ';': // for "print"
case 'q': // for "quit"
case '(': case ')': case '+': case '-': case '*': case '/': case '}': case '{':
return Token(ch); // let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '9':
{
cin.putback(ch); // put digit back into the input stream
double val;
cin >> val; // read a floating-point number
return Token('8', val); // let '8' represent "a number"
}
default:
error("Bad token");
}
}
double primary()
{
Token t = ts.get();
switch (t.kind) {
case '(': // handle '(' expression ')'
{
double d = expression();
t = ts.get();
if (t.kind != ')') error("')' expected");
return d;
}
case '{':
{
double d = expression();
t = ts.get();
if(t.kind != '}') error("'}' Expected");
return d;
}
case '8': // we use '8' to represent a number
return t.value; // return the number's value
default:
error("primary expected");
}
}
Am developing USSD application which uses JSON API. My problem is that, I can't read the value entered by the user.
I have tried this method but it returns "Invalid JSON response type" from the server.
<?php
$ussdRequest = json_decode(#file_get_contents('php://input'));
header("Content-Type: application/json; charset=UTF-8");
$ussdResponse = new stdclass;
if ($ussdRequest != NULL)
switch ($ussdRequest->Type) {
case 'Initiation':
$ussdResponse->Message = 'Enter your full name: ';
$ussdResponse->Type = 'Response';
$msg = $ussdResponse->Message;
break;
case 'Response':
switch ($ussdRequest->Sequence) {
case 2:
$ussdResponse->Message = 'The message is: '+ $msg;
break;
}
}
echo json_encode($ussdResponse);
?>
I have MySQL database, QSqlTableModel and QTableView with few checkbox columns. It works, but the last click on checkbox does not cause changes in database. It means that if I launch a program, click on some checkbox once and close program, no changes in database will be made. If I'll change the state of several checkboxes, the last change will not be shown in database. Maybe there's something wrong in my setData method?
bool PartyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
QString h=headerData(index.column(),Qt::Horizontal).toString();
QVariant v=value;
switch(role)
{
case Qt::CheckStateRole:
if(h=="One" || h=="Two" || h=="Three" || h=="Four")
{
if(value.toInt()==Qt::Unchecked) v=0;
else v=1;
bool ret = QSqlTableModel::setData(index,v,Qt::EditRole);
if(ret) emit dataChanged(index,index);
return ret;
}
break;
case Qt::DisplayRole:
case Qt::EditRole:
.......
break;
default:
break;
}
return QSqlTableModel::setData(index,v,role);
}
QVariant PartyModel::data(const QModelIndex &idx, int role) const
{
QString h=headerData(idx.column(),Qt::Horizontal).toString();
QVariant v=QSqlTableModel::data(idx,role);
switch(role)
{
case Qt::CheckStateRole:
if(h=="One" || h=="Two" || h=="Three" || h=="Four")
v = (QSqlTableModel::data(idx,Qt::DisplayRole).toInt()==0 ? Qt::Unchecked : Qt::Checked);
break;
case Qt::DisplayRole:
if(h=="One" || h=="Two" || h=="Three" || h=="Four")
v="";
break;
default:
break;
}
return v;
}
Qt::ItemFlags PartyModel::flags(const QModelIndex &index) const
{
QString h=headerData(index.column(),Qt::Horizontal).toString();
Qt::ItemFlags f=QSqlQueryModel::flags(index);
if(h=="One" || h=="Two" || h=="Three" || h=="Four")
{
f |= Qt::ItemIsUserCheckable;
f &= ~Qt::ItemIsEditable;
}
return f;
}
The default "edit strategy" of QSqlTabelModel is OnRowChange, which means that changes are only submitted, as the name suggests, when the selected row changes. To submit changes to the database at other times, you need to either change the edit strategy to OnFieldChange, or manually call submit() or submitAll() at appropriate times.
Hopefully my title explains it but I need a function that will take 3 arguments (two numbers and an operator [*, +, /, -]), then compute the result.
Something like this:
function evaluateExpression (firstNum, secondNum, operator) {
...
return ...;
}
evaluateExpression (35, 7, '/'); // should return 5
Pseudocode:
evaluateExpression( first, second, op ) :
if op == "+" :
return first + second
else if op == "*" :
return first * second
... etc
else :
return error
One way:
if (operator === "+") { return firstNum + secondNum };
if (operator === "-") { return firstNum - secondNum };
if (operator === "/") { return firstNum / secondNum };
if (operator === "*") { return firstNum * secondNum };
if (operator === "%") { return firstNum % secondNum };
Another way:
switch (operator) {
case "+" : return firstNum + secondNum;
case "-" : return firstNum - secondNum;
case "/" : return firstNum / secondNum;
case "*" : return firstNum * secondNum;
case "%" : return firstNum % secondNum;
}
If you are using javascript, this could be another way:
eval(firstNum + operator + secondNum);
Even in python, you can use the eval method. Just convert the operands to strings and call the function.
evaluateExpression( first, second, op ) :
return eval(str(first) + op + str(second))
I'm using Node.js and Underscore.js. I can't determine whether to escape JSON data on server side or client side. For underscore doesn't auto escape interpolated values with syntax <%= someValue %> but with <%- someValue %>, which is in the contrast to EJS and may causes confusion. There was a issue on GitHub and also a commit of auto-escape version. But a comment beneath the issue said:
I'm of the general philosophy that escaping should be done closer to
your data than in the templating language
So, any suggestion that when to do HTML escape to AJAX data is better? Here's the server side helper function I have been using:
var htmlEscape = function(html){
return String(html)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
};
var xss = function(obj) {
if (obj instanceof Array) {
for (var i = 0; i < obj.length; i++) {
obj[i] = xss(obj[i]);
}
} else {
for(var key in obj) {
// key != '_id' for mongoose doc
if(obj[key] instanceof Object && !(obj[key] instanceof String)
&& !(obj[key] instanceof Function) && key != '_id') {
obj[key] = xss(obj[key]);
} else if (obj[key] instanceof String || typeof(obj[key]) == "string") {
obj[key] = htmlEscape(obj[key]);
} else {
obj[key] = obj[key];
}
}
}
return obj;
};
Then call it whenever return a JSON:
res.json(xss(someData));
It is always better to perform sanitization/escape operations on the server since anyone can mess with your client side code and send the data any way they want.
There is a great node.js module, node-validator, which has an xss() function as well as a bunch other functions to validate/sanitize your data.