I need to parse file xml I have a link that display
<labels>
<label name="name1">
<description name="name1" url="http:............."/>
<description name="name2" url="http:............."/>
</label>
<label name="name2">
<description name="name1" url="http:............."/>
<description name="name2" url="http:............."/>
</label>
<labels>
and then display it on List.
I get the reply of url as xml contain using this method
if (reply) {
if (reply->error() == QNetworkReply::NoError) {
int available = reply->bytesAvailable();
if (available > 0) {
int bufSize = sizeof(char) * available + sizeof(char);
QByteArray buffer(bufSize, 0);
int read = reply->read(buffer.data(), available);
response = QString(buffer);
}
} else {
response =
QString("Error: ") + reply->errorString()
+ QString(" status:")
+ reply->attribute(
QNetworkRequest::HttpStatusCodeAttribute).toString();
}
reply->deleteLater();
}
How I can parse it and display item on list?
XMLDataModel directly parse the Xml into a QVariantMap:
if (reply->error() == QNetworkReply::NoError) {
XmlDataAccess xda;
QVariantMap data = xda.load(reply).value<QVariantMap>();
if (xda.hasError()) {
bb::data::DataAccessError error = xda.error();
qWarning() << " XML error: " << error.errorMessage();
} else{
emit requestSuccess(data);
}
} else {
[...]
Access it with data["label"].value().at(0), etc...
Related
I'm doing a custom validation for an ISBN number, I already have the function that checks the number and works perfect giving me the response by console, but I need to do the custom validator to get the error in the view with the form control and in this step this error is showing in console when I write an ISBN number, It's like it checks the errors but it doesn't know when its right and it should take the null response as a right ISBN number, at least thats what I saw in some examples.
core.js:6210 ERROR TypeError: Cannot read properties of null (reading 'CheckDigit')
at LibrosComponent_Template (libros.component.html:22)
at executeTemplate (core.js:9600)
at refreshView (core.js:9466)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
at refreshView (core.js:9516)
at refreshEmbeddedViews (core.js:10591)
at refreshView (core.js:9490)
at refreshComponent (core.js:10637)
at refreshChildComponents (core.js:9263)
This is my typescript,
export class LibrosComponent implements OnInit {
//ISBN Validator
isbnValue: string = ""
firstFormGroup: FormGroup;
secondFormGroup: FormGroup;
constructor(
private _formBuilder: FormBuilder,
) {}
ngOnInit() {
this.firstFormGroup = this._formBuilder.group({
tituloControl: ['', Validators.required],
isbnControl: ['', Validators.required],
},
{ validator: this.isbnValidate });
}
isbnValidate(g: FormGroup) {
var isbnValue = g.get('isbnControl').value
var subject = isbnValue;
// Checks for ISBN-10 or ISBN-13 format
var regex = /^(?:ISBN(?:-1[03])?:? )?(?=[0-9X]{10}$|(?=(?:[0-9]+[- ]){3})[- 0-9X]{13}$|97[89][0-9]{10}$|(?=(?:[0-9]+[- ]){4})[- 0-9]{17}$)(?:97[89][- ]?)?[0-9]{1,5}[- ]?[0-9]+[- ]?[0-9]+[- ]?[0-9X]$/;
if (regex.test(subject)) {
// Remove non ISBN digits, then split into an array
var chars = subject.replace(/[- ]|^ISBN(?:-1[03])?:?/g, "").split("");
// Remove the final ISBN digit from `chars`, and assign it to `last`
var last = chars.pop();
var sum = 0;
var check, i;
if (chars.length == 9) {
// Compute the ISBN-10 check digit
chars.reverse();
for (i = 0; i < chars.length; i++) {
sum += (i + 2) * parseInt(chars[i], 10);
}
check = 11 - (sum % 11);
if (check == 10) {
check = "X";
} else if (check == 11) {
check = "0";
}
} else {
// Compute the ISBN-13 check digit
for (i = 0; i < chars.length; i++) {
sum += (i % 2 * 2 + 1) * parseInt(chars[i], 10);
}
check = 10 - (sum % 10);
if (check == 10) {
check = "0";
}
}
if (check != last) {
return null;
} else {
return g.get('isbnControl').setErrors( {CheckDigit: true} )
}
} else {
return g.get('isbnControl').setErrors( {Invalid: true} );
}
}
}
In my HTML I have some inputs that are included in the form:
<form class="form" [formGroup]="firstFormGroup">
<div class="container-1">
<mat-form-field class="width">
<mat-label>TÃtulo</mat-label>
<input matInput formControlName="tituloControl" required>
</mat-form-field>
<mat-form-field class="width">
<mat-label>ISBN</mat-label>
<input matInput formControlName="isbnControl" required>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['CheckDigit']">Invalid ISBN check digit</mat-error>
<mat-error *ngIf="firstFormGroup.controls['isbnControl'].pristine || firstFormGroup.controls.isbnControl.errors['Invalid']">Invalid ISBN</mat-error>
</mat-form-field>
</form>
I already found the solution to the error, replacing the .errors [''] with hasError (''), the .errors[] is to read the property of the object that contains the validation error. But first I have to evaluate with the hasError () method if that property exists to access it.
I am using java and twitter4j.
Issue : I do not get proper response from status.getText() method, link references comes as text
I have a problem. My method is as follow:
Twitter twitter = null;
String userName = "clientname";
int numberOfTweets = 0;
StringBuilder timeLineText = new StringBuilder();
try {
twitter = new TwitterFactory(new GetAuthenticConfiguration().getConfigObject()).getInstance();
ResponseList<Status> statuses = twitter.getUserTimeline(userName);
timeLineText.append("<li>");
for (Status status : statuses) {
numberOfTweets++;
if (numberOfTweets > 12) {
break;
}
int remainder = numberOfTweets % 3;
if (remainder == 0) {
timeLineText.append("</li><li>");
} else {
StringBuilder tempText = new StringBuilder();
try {
tempText.append("<p>");
tempText.append("<span>");
tempText.append("<img alt=\"" + status.getUser().getScreenName() + "\" src=\"" + status.getUser().getMiniProfileImageURL() + "\" />");
tempText.append("<b>" + status.getUser().getName() + "</b> #" + status.getUser().getScreenName() + " " + new SimpleDateFormat("dd MMM").format(status.getCreatedAt()));
tempText.append("</span>");
tempText.append("<p>" + status.getText() + "</p>");
tempText.append("</p>");
} catch (Exception e) {
System.out.println(e);
}
timeLineText.append(tempText);
}
}
timeLineText.append("</li>");
} catch (Exception te) {
System.out.println(te);
}
The response i get is :
Can you tell us which Rolls-Royce #engine powers this aircraft? #AvGeek http://t.co/t5tNXQuMFB
instead of
Can you tell us which Rolls-Royce <a href="/hashtag/engine?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>engine</b></a> powers this aircraft? <a href="/hashtag/AvGeek?src=hash" data-query-source="hashtag_click" class="twitter-hashtag pretty-link js-nav" dir="ltr" ><s>#</s><b>AvGeek</b></a> <a href="http://t.co/t5tNXQuMFB" class="twitter-timeline-link u-isHiddenVisually" data-pre-embedded="true" dir="ltr" >pic.twitter.com/t5tNXQuMFB</a>
The issue is I am not getting the proper html . Can anyone tell me the reason of it please?
After doing lot of R & D, I have found out that Status.getText() method gives only plain text.
We have to manually convert it to links,hashtags and users.
Below is the method I have written to do that.
Just pass your getText() output to this method (tweet).
I hope this will help to many beginners of Twitter4J.
private String linkifyTweet(String tweet) {
Pattern pattern;
Matcher matcher;
String regex_url = "((https?://\\S+)|(www.\\S+))";
String regex_hashtag = "#(\\w+)";
String regex_user = "#(\\w+)";
//regex to apply links to all urls in the tweet
pattern = Pattern.compile(regex_url);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_url, "<a target=\"_blank\" href=\"$1\">$1</a>");
}
//regex to apply links to all hashtags in the tweet
pattern = Pattern.compile(regex_hashtag);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_hashtag, "<a target=\"_blank\" href=\"https://www.twitter.com/hashtag/$1?src=hash\">#$1</a>");
}
//regex to apply links to all users in the tweet
pattern = Pattern.compile(regex_user);
matcher = pattern.matcher(tweet);
if (matcher.find()) {
tweet = tweet.replaceAll(regex_user, "<a target=\"_blank\" href=\"https://www.twitter.com/$1\">#$1</a>");
}
//System.out.println(tweet);
return tweet;
}
I'm having a problem where my dynamically generated html is getting escaped and outputed on the screen. heres what I have:
#{
string TrialMessage = string.Empty;
if ((bool)ViewBag.msd.IsOnTrial == true)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var daysToTrialExpiation = expDate.AddDays(1) - System.DateTime.UtcNow;
TrialMessage = "<b>Trial Ends in: <span style=\"color:[Color];\">" + (daysToTrialExpiation.Days) + "</span> Days</b>";
if (daysToTrialExpiation.Days > 5)
{
TrialMessage = TrialMessage.Replace("[Color]", "green");
}
else if (daysToTrialExpiation.Days > 2)
{
TrialMessage = TrialMessage.Replace("[Color]", "orange");
}
else if (daysToTrialExpiation.Days > 0)
{
TrialMessage = TrialMessage.Replace("[Color]", "red");
}
else
{
TrialMessage = "<b style=\"color: red;\"> Trial Ended " + Math.Abs(daysToTrialExpiation.Days) + " Days Ago</b>";
}
}
}
When I use the TrialMessage in the View, I'm getting the escaped version of it outputted on the screen:
<b>Trial Ends in: <span style="color:green;">15</span> Days</b>
I have tried to use Html.Raw(TrialMessage) I've even tried to manually create an HTMLString with the same result. What am I missing?
Update: The way I'm outputting it on the view is:
#Html.Raw(TrialMessage)
In an effort to just get it working (it seems you're pressed for time) what if you removed html from the variable?
Perhaps something like this could work for you:
#{
string trialColor = string.Empty;
int trialDays = 0;
if ((bool)ViewBag.msd.IsOnTrial)
{
var expDate = (DateTime)ViewBag.msd.RenewalDate;
var trialDays = (expDate.AddDays(1) - System.DateTime.UtcNow).Days;
if (trialDays > 5)
{
trialColor = "green";
}
else if (trialDays > 2)
{
trialColor = "orange";
}
else
{
trialColor = "red";
}
}
}
...
#if((bool)ViewBag.msd.IsOnTrial && trialDays > 0)
{
<strong>Trial Ends in: <span style="color:#trialColor;">#trialDays </span> Days</strong>
} else if((bool)ViewBag.msd.IsOnTrial) {
<strong style="color: red;">Trial Ended #Math.Abs(trialDays) Days Ago</strong>
}
Note: untested code. It's been a bit since I've written razor.
I am trying to get the values inside this soap fault's "detail", but I haven't found any ways of doing so.
The response from the server:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Client</faultcode>
<faultstring>Many Errors</faultstring>
<detail>
<error_id>2</error_id>
<errors>
<error>
<error_id>1</error_id>
<error_description>Unknown Error</error_description>
</error>
<error>
<error_id>5</error_id>
<error_description>Not Authorized</error_description>
</error>
<error>
<error_id>9</error_id>
<error_description>Password should be at least 6 characters including one letter and one number</error_description>
</error>
</errors>
</detail>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I need to get the error_ids along with their respective error_descriptions. So far I've only managed to get the detail via kSOAP with the following way:
if (envelope.bodyIn instanceof SoapObject) {
return envelope.bodyIn.toString();
} else if (envelope.bodyIn instanceof SoapFault) {
SoapFault e = (SoapFault) envelope.bodyIn;
Node details = ((SoapFault) envelope.bodyIn).detail;
}
but I haven't managed to get a single value I need when I try to "navigate" through it.
Any help is greatly appreciated. I have found little to non information about handling soap faults with ksoap2 online...
The following code handles better
Iterator it = soapFaultClientException.getSoapFault().getFaultDetail().getDetailEntries();
while (it.hasNext())
{
Source errSource = it.next().getSource();
#SuppressWarnings("unchecked")
JAXBElement errJaxb = (JAXBElement) springWebServiceTemplate.getUnmarshaller().unmarshal(errSource);
ServerCustomizedError err = errJaxb.getValue();
....
}
Figured it out after all. Here is the way to do it:
Node details = ((SoapFault) envelope.bodyIn).detail;
Element detEle = details.getElement(NAMESPACE, "detail");
List<Error> errorList = new ArrayList<NewConnector.Error>();
Element idEle = detEle.getElement(NAMESPACE, "error_id");
str.append("id: " + idEle.getText(0));
str.append("\n");
Integer id = Integer.valueOf(idEle.getText(0));
if (id == 2) {
// many errors
Element errors = detEle.getElement(NAMESPACE, "errors");
int errorChildCount = errors.getChildCount();
for (int i = 0; i < errorChildCount; i++) {
Object innerError = errors.getChild(i);
if (innerError instanceof Element) {
Element error_id = ((Element) innerError).getElement(
NAMESPACE, "error_id");
Element error_descrion = ((Element) innerError)
.getElement(NAMESPACE, "error_description");
Error singleError = new Error(Integer.valueOf(error_id
.getText(0)), error_descrion.getText(0));
errorList.add(singleError);
str.append(singleError.toString() + "\n");
}
}
str.append("Found " + errorList.size() + " errors.\n");
str.append("errorscount:" + errors.getChildCount());
The code obviously needs improvements, but it's just a showcase of how to get each value. Cheers
I use the following method:
/**
* Method to retrieve the errorMessage from the given SoapFault.
* #param soapFault
* #return String representing the errorMessage found in the given SoapFault.
*/
private static String getSoapErrorMessage (SoapFault soapFault) {
String errorMessage;
try {
Node detailNode = soapFault.detail;
Element faultDetailElement = (Element)detailNode.getElement(0).getChild(1);
Element errorMessageElement = (Element)faultDetailElement.getChild(0);
errorMessage = errorMessageElement.getText(0);
}
catch (Exception e) {
e.printStackTrace();
errorMessage = "Could not determine soap error.";
}
return errorMessage;
}
I would like to allow the user of my XULRunner based app to be able to do copy/paste via a context menu.
Keyboard shortcuts Ctrl-C and Ctrl-V are already working fine
Here it is without flash. The getInputSelection function is from here: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?.
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="mywin" title="my app"
width="800" height="600" persist="screenX screenY width height sizemode"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<popupset>
<menupopup id="clipmenu">
<menuitem label="Copy" oncommand="copy()"/>
<menuitem label="Paste" oncommand="paste();"/>
</menupopup>
</popupset>
<browser
type="content-primary"
src="http://127.0.0.1/"
flex="1"
disablehistory="true"
id="browserId"
context="clipmenu"
/>
<script>
<![CDATA[
function copy()
{
var tabBrowser = document.getElementById("browserId");
var selectedTagName = tabBrowser.contentWindow.document.activeElement.tagName;
var windowObj;
if(selectedTagName == "IFRAME")
{
windowObj = tabBrowser.contentWindow.frames[tabBrowser.contentWindow.document.activeElement.name];
}
else
{
windowObj = document.getElementById("browserId").contentWindow;
}
var selectedText = windowObj.getSelection();
if(!selectedText || selectedText == "")
{
var focused = windowObj.document.activeElement;
if(focused && focused.value)
{
selectedText = getSelectionFromInput(focused);
}
}
//alert(selectedText + "---");
const clipHelper = Components.classes["#mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
clipHelper.copyString(selectedText);
}
function getSelectionFromInput(focused)
{
var focusedValue = focused.value;
var sel = getInputSelection(focused);
var selectedText = "";
if(focusedValue.length == (sel.end))
{
selectedText = focusedValue.substring(sel.start);
}
else
{
selectedText = focusedValue.substring(sel.start, (sel.end));
}
return selectedText;
}
function paste()
{
var clip = Components.classes["#mozilla.org/widget/clipboard;1"].getService(Components.interfaces.nsIClipboard);
var trans = Components.classes["#mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
trans.addDataFlavor("text/unicode");
clip.getData(trans, clip.kGlobalClipboard);
var str = new Object();
var len = new Object();
trans.getTransferData("text/unicode",str,len);
str = str.value.QueryInterface(Components.interfaces.nsISupportsString);
str = str.data.substring(0, len.value / 2);
var focused = document.commandDispatcher.focusedElement;
var focusedValue = focused.value;
var sel = getInputSelection(focused);
focused.value = focusedValue.substring(0,sel.start) + str + focusedValue.substring(sel.end);
}
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
]]>
</script>
</window>
Updated to support iframes.
Create menu using the code below.
<popupset>
<menupopup id="clipmenu">
<menuitem label="Copy" oncommand="copy();"/>
<menuseparator/>
<menuitem label="paste" oncommand="paste();"/>
</menupopup>
</popupset>
<browser type="content" src="chrome://myapp/content/theme1/index.html" flex="1" context="clipmenu"/>
Connect it to whatever you want, here am making it the context menu of the browser element by giving the id of menu in the context attribute of the browser element.
Then for each menu you can give the command to execute in oncommand event. We have given the function copy and paste.
Then write the code to copy text from whatever element you want or if you want to copy the selected data only.
See the below link for copying command.
http://www.deluxeblogtips.com/2010/06/javascript-copy-to-clipboard.html
One more example for "Copy" context menu in XULRunner under SWT Browser (code was implemented for Eclipse v3.5.1, XULRunner v1.8.1.3):
Browser browser = new Browser(parent, style | SWT.MOZILLA);
Menu menu = new Menu(browser);
MenuItem item = new MenuItem(menu, SWT.NONE);
item.setText("Copy");
item.addSelectionListener(new SelectionListener() {
#Override
public void widgetSelected(SelectionEvent e) {
nsIWebBrowser webBrowser = (nsIWebBrowser) browser.getWebBrowser();
nsIInterfaceRequestor req = (nsIInterfaceRequestor) webBrowser.queryInterface(nsIInterfaceRequestor.NS_IINTERFACEREQUESTOR_IID);
nsIDocShell docShell = (nsIDocShell) req.getInterface(nsIDocShell.NS_IDOCSHELL_IID);
nsIClipboardCommands cmds = (nsIClipboardCommands) docShell.queryInterface(nsIClipboardCommands.NS_ICLIPBOARDCOMMANDS_IID);
cmds.copySelection();
}
#Override
public void widgetDefaultSelected(SelectionEvent e) {
}
});
browser.setMenu(menu);