I am calling a web-service method through a web-service client generated by the netbeans IDE.
private String getCitiesByCountry(java.lang.String countryName) {
webService.GlobalWeatherSoap port = service.getGlobalWeatherSoap();
return port.getCitiesByCountry(countryName);
}
So i call this method inside my program,
String b = getWeather("Katunayake", "Sri Lanka");
and it will give me a string output which contains xml data.
String b = getWeather("Katunayake", "Sri Lanka"); = (java.lang.String) <?xml version="1.0" encoding="utf-16"?>
<CurrentWeather>
<Location>Katunayake, Sri Lanka (VCBI) 07-10N 079-53E 8M</Location>
<Time>Jun 22, 2015 - 06:10 AM EDT / 2015.06.22 1010 UTC</Time>
<Wind> from the SW (220 degrees) at 10 MPH (9 KT):0</Wind>
<Visibility> greater than 7 mile(s):0</Visibility>
<SkyConditions> partly cloudy</SkyConditions>
<Temperature> 86 F (30 C)</Temperature>
<DewPoint> 77 F (25 C)</DewPoint>
<RelativeHumidity> 74%</RelativeHumidity>
<Pressure> 29.74 in. Hg (1007 hPa)</Pressure>
<Status>Success</Status>
</CurrentWeather>
How may i get the value of <Location>,<SkyConditions>,<Temperature>.
You can go for XPath if you need only these 3 values. Otherwise, DOM reads the entire document. It is very easy to write XPath expressions those directly fetch the node to read values.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
String xml = ...; // <-- The XML SOAP response
Document xmlDocument = builder.parse(new ByteArrayInputStream(xml.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
String location = xPath.compile("/CurrentWeather/Location").evaluate(xmlDocument);
String skyCond = xPath.compile("/CurrentWeather/SkyConditions").evaluate(xmlDocument);
String tmp = xPath.compile("/CurrentWeather/Temperature").evaluate(xmlDocument);
If, you need to fetch many XML nodes and frequently, then go for DOM.
One way is using a DOM parser, using http://examples.javacodegeeks.com/core-java/xml/java-xml-parser-tutorial as a guide:
String b = getWeather("Katunayake", "Sri Lanka");
InputStream weatherAsStream = new ByteArrayInputStream(b.getBytes(StandardCharsets.UTF_8));
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fac.newDocumentBuilder();
org.w3c.dom.Document weatherDoc = builder.parse(weatherAsStream);
String location = weatherDoc.getElementsByTagName("Location").item(0).getTextContent();
String skyConditions = weatherDoc.getElementsByTagName("SkyConditions").item(0).getTextContent();
String temperature = weatherDoc.getElementsByTagName("Temperature").item(0).getTextContent();
This has no exception handling and might break if there are more than one elements with the same name, but you should be able to work from here.
Related
I'm seeing a behavior in the Google DLP library that puzzles me, and I'm hoping for some clarification. I'm using the Java wrapper library, google-cloud-dlp version 0.34.0-beta. Given the input:
Collection<String> input = Lists.newArrayList("Jenny Tutone 2665 Agua Vista Dr Los Gatos CA 95030 (408) 867-5309 or 408.867.5309x100"
I'm seeing the output:
███ █ ████ or █
If I pass in the same string as a collection of substrings:
Collection<String> input = Lists.newArrayList("Jenny Tutone", "2665 Agua Vista Dr", "Los Gatos", "CA 95030", "(408) 867-5309", "or", "408.867.5309x100");
I see very different results:
███, 2665 █, █ Gatos, █ 95030, █, or, █
I'm using all the InfoType types that I could find, which amounts to 67 of them. Am I doing something wrong here?
This is the meat of the code that invokes the Google DLP library:
private Collection<String> redactContent(Collection<String> input,
String replacement,
Likelihood minLikelihood,
List<InfoType> infoTypes) {
// Replace select info types with chosen replacement string
final Collection<RedactContentRequest.ReplaceConfig> replaceConfigs = infoTypes.stream()
.map(it -> RedactContentRequest.ReplaceConfig.newBuilder().setInfoType(it).setReplaceWith(replacement).build())
.collect(Collectors.toCollection(LinkedList::new));
final InspectConfig inspectConfig =
InspectConfig.newBuilder()
.addAllInfoTypes(infoTypes)
.setMinLikelihood(minLikelihood)
.build();
long itemCount = 0;
try (DlpServiceClient dlpClient = DlpServiceClient.create(settings)) {
// Google's DLP library is limited to 100 items per request, so the requests need to be chunked if the
// number of input items is greater.
Stream.Builder<Stream<ContentItem>> streamBuilder = Stream.builder();
for (long processed = 0; processed < input.size(); processed += maxItemsPerRequest) {
Collection<ContentItem> items =
input.stream()
.skip(processed)
.limit(maxItemsPerRequest)
.filter(item -> item != null && !item.isEmpty())
.map(item ->
ContentItem.newBuilder()
.setType(MediaType.PLAIN_TEXT_UTF_8.toString())
.setData(ByteString.copyFrom(item.getBytes(Charset.forName("UTF-8"))))
.build()
)
.collect(Collectors.toCollection(LinkedList::new));
RedactContentRequest request = RedactContentRequest.newBuilder()
.setInspectConfig(inspectConfig)
.addAllItems(Collections.unmodifiableCollection(items))
.addAllReplaceConfigs(replaceConfigs)
.build();
RedactContentResponse contentResponse = dlpClient.redactContent(request);
itemCount += contentResponse.getItemsCount();
streamBuilder.add(contentResponse.getItemsList().stream());
}
return streamBuilder.build()
.flatMap(stream -> stream.map(item -> item.getData().toStringUtf8()))
.collect(Collectors.toCollection(LinkedList::new));
}
}
Context can influence findings. Also in the case of an address, parts of the address may influence other parts. For example "Mountain View CA 94043" may match as a LOCATION but just "94043" by itself may not. When running this analysis, we don't cross cell boundaries when deciding on context and so in your second ArrayList example each string is looked at individually (in its own context).
Note: I am the PM for the DLP API.
Here are the servelet cum JSP code, let me know how we could protect them from XSS?
Servlet Code:
String strRequestScrip = SecurityCheck.getStringParameter(request,PARAM_SCRIP_CODE);
List arrScripLocator = MarketWatchUtils.getEqScripLocator(strRequestScrip, strExchangeCode, application);
request.setAttribute("arrScripLocator", arrScripLocator);
request.getRequestDispatcher("/ajax/ajaxScripLocator.jsp").forward(request, response);
Jsp Code:
final List arrScripLocator = (List) request.getAttribute("arrScripLocator");
int intScripLocatorSize = arrScripLocator != null ? arrScripLocator.size() : 0;
intScripLocatorSize = intScripLocatorSize <= 20 ? intScripLocatorSize : 20;
out.print(intScripLocatorSize);
You should use Jsoup to sanitize the request.
The code will look like this:
String unsafe ="<p><a href='http://example.com/' onclick='stealCookies()'>Link</a></p>";
String safe = Jsoup.clean(unsafe, Whitelist.basic());
// now: <p>Link</p>
I recommend you also read the OWASP XSS Filter Evasion Sheet.
Writing a WP8 Silverlight app. Is there a standard .NET technique available in this environment I can use to serialize an object like this
private static List<MemoryStream> MemoryStreamList = new List<MemoryStream>();
to save it to a file and restore it later?
I tried to use DataContractJsonSerializer for this which is good to serialize a List of simple custom objects, but it fails for List (I get System.Reflection.TargetInvocationException).
I would suggest converting your list to a list of byte arrays before persisting and then you should be able to serialize. Of course this comes with some overhead at deserialization as well.
Serialization part:
byte[] bytes = null;
var newList = MemoryStreamList.Select(x => x.ToArray()).ToList();
XmlSerializer ser = new XmlSerializer(newList.GetType());
using (var ms = new MemoryStream())
{
ser.Serialize(ms, newList);
//if you want your result as a string, then uncomment to lines below
//ms.Seek(0, SeekOrigin.Begin);
//using (var sr = new StreamReader(ms))
//{
//string serializedStuff = sr.ReadToEnd();
//}
//else you can call ms.ToArray() here and persist the byte[]
bytes = ms.ToArray();
}
Deserialization part:
using (var ms = new MemoryStream(bytes))
{
var result = ser.Deserialize(ms) as List<byte[]>;
}
I am using a thirdparty webservice. I got the response in XML format.
Now, i have to show the XML node values in grid view.
The following code i tried so far.
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
//Label2.Text = reader.ReadToEnd();
XmlDocument xml = new XmlDocument();
xml.Load(reader);
XmlNamespaceManager ns = new XmlNamespaceManager(xml.NameTable);
ns.AddNamespace("ms", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
XmlNode image = xml.SelectSingleNode("//ms:URL", ns);
XmlNode FormattedPrice = xml.SelectSingleNode("//ms:FormattedPrice", ns);
Now, i want to show the values of XMLnode value in grid view.
Please inform me, if you need more information.
Thanks in advance.
You can use an XMLDataSourcefor that:
http://www.codeproject.com/Articles/10898/Introduction-to-XMLDataSource-control-in-ASP-NET-2
Best regards.
Solution:
Instead of Get the HttpResponse in xmldocument.
I used XNamespace and XDocument.
XNamespace ns = "http://webservices.amazon.com/AWSECommerceService/2005-10-05"; // Linq
XDocument xd = XDocument.Load(response.GetResponseStream());
Then Use Linq to Read all Vlaues. Example:
var Image = xd.Descendants(ns + "Items").Elements(ns + "Item").Select(img => img.Elements(ns + "MediumImage").Select(img1 => (string)img1.Element(ns + "URL")).FirstOrDefault() ?? "Null").ToList();
I'm using SharePoint web services in C#. I have my code working to check files and check them out using the Lists web service. I need to test to see if a file exists; I can find lots of examples for doing this using the object model API, but I can't seem to find a straightforward way of doing this using web services.
Try the Lists.GetListItems with a suitable CAML query.
A CAML query like
<Query><Where><Eq><FieldRef Name="FileLeafRef" /><Value Type="Text">Filename.rtf</Value></Eq></Where></Query>
should work; the field 'FileLeafRef' is where the filename is stored.
This code may do, it's a little rough, but demonstrates how to get a list of files based on the title.
public static bool PageExists(string listName, string webPath, string pageTitle)
{
string pageId = "";
IntranetLists.Lists lists = new IntranetLists.Lists();
lists.UseDefaultCredentials = true;
lists.Url = webPath + "/_vti_bin/lists.asmx";
XmlDocument doc = new XmlDocument();
doc.LoadXml("<Document><Query><Where><Contains><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + pageTitle + "</Value></Contains></Where></Query><ViewFields /><QueryOptions /></Document>");
XmlNode listQuery = doc.SelectSingleNode("//Query");
XmlNode listViewFields = doc.SelectSingleNode("//ViewFields");
XmlNode listQueryOptions = doc.SelectSingleNode("//QueryOptions");
Guid g = GetWebID(webPath);
XmlNode items = lists.GetListItems(listName, string.Empty, listQuery, listViewFields, string.Empty, listQueryOptions, g.ToString());
}
return items.Count > 0;
}
public static XmlNodeList XpathQuery(XmlNode xmlToQuery, string xPathQuery)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlToQuery.OuterXml);
XmlNamespaceManager mg = new XmlNamespaceManager(doc.NameTable);
mg.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
mg.AddNamespace("z", "#RowsetSchema");
mg.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
mg.AddNamespace("y", "http://schemas.microsoft.com/sharepoint/soap/ois");
mg.AddNamespace("w", "http://schemas.microsoft.com/WebPart/v2");
mg.AddNamespace("d", "http://schemas.microsoft.com/sharepoint/soap/directory");
return doc.SelectNodes(xPathQuery, mg);
}
I also had similiar problems with this.
I have tried the following FieldRefs without success: "Name", "FileLeafRef" and "LinkFilenameNoMenu".
The post located at http://www.johanolivier.blogspot.com details what I had to do to get it working.