Look at this simple source code written in Java:
Uri helpUrl = Uri.parse(getString(R.string.url_help));
try
{
helpUrl = Uri.parse(mainUrl).buildUpon()
.appendPath("xx")
.appendPath("yy")
.appendPath("zzz.html")
.build();
}
catch (Exception ex)
{
//error
}
Note that mainUrl can be provided as http or https and also it may be http://host/xxx or http://host/xxx/. In Java, it will always work. I'm looking for a way to do the same in Dart, but it looks like there's no any buildUpon equivalent. Any advice how to do what I need in Dart? In dart, path has no setter, path segments list has no setter too, so it won't help.
You'll want to use the UriBuilder class which is part of the uri package.
It's usage in your case will look something like this
var ub = UriBuilder.fromUri(Uri.tryParse('https://www.zombo.com/xx'));
ub.path += '/yy';
ub.path += '/zz';
Uri uri = ub.build();
// https://www.zombo.com/xx/yy/zz
There is no automatic management of path separators. It is just string based.
Related
I want to parse any complex swagger-API-document(swagger.json) to Java objects.
may be List>
what are available options?
I am trying with io.swagger.parser.SwaggerParser.
but want to make sure that I know other available options and I use the correct parser which suffices to parse any complex document.
currently we are trying as below.
public List<Map<String,Object>> parse(String swaggerDocString) throws SwaggerParseException{
try{
Swagger swagger = new SwaggerParser().parse(swaggerDocString);
return processSwagger(swagger);
}catch(Exception ex){
String exceptionRefId=OSGUtil.getExceptionReferenceId();
logger.error("exception ref id " + exceptionRefId + " : Error while loading swagger file " + ex);
throw new SwaggerParseException("", ex.getLocalizedMessage(),exceptionRefId);
}
}
public List<Map<String,Object>> processSwagger(Swagger swagger){
List<Map<String,Object>> finalResult=new ArrayList<>();
Map<String, Model> definitions = swagger.getDefinitions();
// loop all the available paths of the swagger
if(swagger.getPaths()!=null && swagger.getPaths().keySet()!=null &&swagger.getPaths().keySet().size()>0 ){
swagger.getPaths().keySet().forEach(group->{
//get the path
Path path=swagger.getPath(group);
//list all the operations of the path
Map<HttpMethod,Operation> mapList=path.getOperationMap();
mapList.forEach((httpMethod,operation)->{
processPathData(finalResult,operation,path,group,httpMethod,definitions,group);
});
});
}
return finalResult;
}
whats the differences between
swagger-compat-spec-parser,
swagger-parser
swagger has the implementations for all the technologies.
https://swagger.io/tools/open-source/open-source-integrations/
and details for parsing swagger into Java is here.
https://github.com/swagger-api/swagger-parser/tree/v1
I would like to
add/remove/update elements/attributes/values to the "subTree"
be able to save the updated "targetDoc" back to the "target" file location.
determine which tree model would be best for this xpath + tree modification procedure.
I thought I should somehow be able to get a MutableNodeInfo object, but I don't know how to do this. I tried using the processor.setConfigurationProperty(FeatureKeys.TREE_MODEL, Builder.LINKED_TREE); but this still gives me an underlying node of TinyElementImpl. I require xpath 2.0 to avoid having to enter default namespaces, which is why I am using saxon s9api instead of Java's default DOM model. I would also like to avoid using xslt/xquery if possible because these tree modifications are being done dynamically, making xslt/xquery more complicated in my situation.
public static void main(String[] args) {
// XML File namesspace URIs
Hashtable<String, String> namespaceURIs = new Hashtable<>();
namespaceURIs.put("def", "http://www.cdisc.org/ns/def/v2.0");
namespaceURIs.put("xmlns", "http://www.cdisc.org/ns/odm/v1.3");
namespaceURIs.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");
namespaceURIs.put("xlink", "http://www.w3.org/1999/xlink");
namespaceURIs.put("", "http://www.cdisc.org/ns/odm/v1.3");
// The source/target xml document
String target = "Path to file.xml";
// An xpath string
String xpath = "/ODM/Study/MetaDataVersion/ItemGroupDef[#OID/string()='IG.TA']";
Processor processor = new Processor(true);
// I thought this tells the processor to use something other than
// TinyTree
processor.setConfigurationProperty(FeatureKeys.TREE_MODEL,
Builder.LINKED_TREE);
DocumentBuilder builder = processor.newDocumentBuilder();
XPathCompiler xpathCompiler = processor.newXPathCompiler();
for (Entry<String, String> entry : namespaceURIs.entrySet()) {
xpathCompiler.declareNamespace(entry.getKey(), entry.getValue());
}
try {
XdmNode targetDoc = builder.build(Paths.get(target).toFile());
XPathSelector selector = xpathCompiler.compile(xpath).load();
selector.setContextItem(targetDoc);
XdmNode subTree = (XdmNode) selector.evaluateSingle();
// The following prints: class
// net.sf.saxon.tree.tiny.TinyElementImpl
System.out.println(subTree.getUnderlyingNode().getClass());
/*
* Here, is where I would like to modify subtree and save modified doc
*/
} catch (SaxonApiException e) {
e.printStackTrace();
}
}
I think you can supply a DOM node to Saxon and run XPath against it but it that case you don't use the document builder for Saxon's native trees, you build a DOM using the javax.xml.parsers.DocumentBuilder and once you have a W3C DOM node you can supply it to Saxon using the wrap method of a Saxon DocumentBuilder. Here is sample code taken from the file S9APIExamples.java in the Saxon 9.6 resources file:
// Build the DOM document
File file = new File("data/books.xml");
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder docBuilder;
try {
docBuilder = dfactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new SaxonApiException(e);
}
Document doc;
try {
doc = docBuilder.parse(new InputSource(file.toURI().toString()));
} catch (SAXException e) {
throw new SaxonApiException(e);
} catch (IOException e) {
throw new SaxonApiException(e);
}
// Compile the XPath Expression
Processor proc = new Processor(false);
DocumentBuilder db = proc.newDocumentBuilder();
XdmNode xdmDoc = db.wrap(doc);
XPathCompiler xpath = proc.newXPathCompiler();
XPathExecutable xx = xpath.compile("//ITEM/TITLE");
// Run the XPath Expression
XPathSelector selector = xx.load();
selector.setContextItem(xdmDoc);
for (XdmItem item : selector) {
XdmNode node = (XdmNode) item;
org.w3c.dom.Node element = (org.w3c.dom.Node) node.getExternalNode();
System.out.println(element.getTextContent());
}
There are also samples showing how to use Saxon with JDOM and other mutable tree implementations but I think you need Saxon PE or EE to have direct support for those.
The MutableNodeInfo interface in Saxon is designed very specifically to meet the needs of XQuery Update, and I would advise against trying to use it directly from Java; the implementation isn't likely to be robust when handling method calls other than those made by XQuery Update.
In fact, it's generally true that the Saxon NodeInfo interface is designed as a target for XPath, rather than for user-written Java code. I would therefore suggest using a third party tree model; the ones I like best are JDOM2 and XOM. Both of these allow you to mix direct Java navigation and update with use of XPath 2.0 navigation using Saxon.
Is there a function to do urlencoding in Dart? I am doing a AJAX call using XMLHttpRequest object and I need the url to be url encoded.
I did a search on dartlang.org, but it didn't turn up any results.
var uri = 'http://example.org/api?foo=some message';
var encoded = Uri.encodeFull(uri);
assert(encoded == 'http://example.org/api?foo=some%20message');
var decoded = Uri.decodeFull(encoded);
assert(uri == decoded);
http://www.dartlang.org/docs/dart-up-and-running/contents/ch03.html#ch03-uri
Update: There is now support for encode/decode URI in the Dart Uri class
Dart's URI code is placed in a separate library called dart:uri (so it can be shared between both dart:html and dart:io). It looks like it currently does not include a urlencode function so your best alternative, for now, is probably to use this Dart implementation of JavaScript's encodeUriComponent.
Uri.encodeComponent(url); // To encode url
Uri.decodeComponent(encodedUrl); // To decode url
I wrote this small function to convert a Map into a URL encoded string, which may be what you're looking for.
String encodeMap(Map data) {
return data.keys.map((key) => "${Uri.encodeComponent(key)}=${Uri.encodeComponent(data[key])}").join("&");
}
I dont' think there is yet. Check out http://unpythonic.blogspot.com/2011/11/oauth20-and-jsonp-with-dartin-web.html and the encodeComponent method.
Note, it's lacking some characters too, it needs to be expanded. Dart really should have this built in and easy to get to. It may have it in fact, but I didn't find it.
Safe Url Encoding in flutter
Ex.
String url = 'http://example.org/';
String postDataKey = "requestParam="
String postData = 'hdfhghdf+fdfbjdfjjndf'
In Case of get request :
Uri.encodeComponent(url+postDataKey+postData);
In Case of Post Data Request use flutter_inappwebview library
var data = postDataKey + Uri.encodeComponent(postData);
webViewController.postUrl(url: Uri.parse(url), postData: utf8.encode(data));
Uri.encodeComponent() is correct, Uri.encodeFull() has a bug, see below example:
void main() {
print('$text\n');
var coded = Uri.encodeFull(text);
print(coded);
print('\n');
coded = Uri.encodeComponent(text);
print(coded);
}
var text = '#2020-02-29T142022Z_1523651918_RC2EAF9OOHDB_RT.jpg';
My code access a file which is in "Conf" directory inside my project directory. I am currently opening the file using absolute path like below:
File.ReadAllLines("C:\project name\Conf\filename");
I was thinikng if it's possible to use the relative path like
File.ReadAllLines("/Conf/filename");
But it's not working; as expected it throws exception. I did checked MSDN (link below) but seems "ReadAllLines()" methods doesn't accept relative path.
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
Any idea, how can I use the relative path instead using absolute path?
Thanks,
Rahul
This is my favorite way of doing it.
Make your file an embedded resource.
/// <summary>
/// This class must be in the same folder as the embedded resource
/// </summary>
public class GetResources
{
private static readonly Type _type = typeof(GetResources);
public static string Get(string fileName)
{
using (var stream =
_type.Assembly.GetManifestResourceStream
(_type.Namespace + "." + fileName))
{
if (stream != null)
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
throw new FileNotFoundException(fileName);
}
}
As stated in MSDN you cannot use a relative path, however you might be able to use either Environment.CurrentDirectory or System.Reflection.Assembly.GetExecutingAssembly().Location
To make things simple, use the following:
string current_path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string[] lines_from_file = System.IO.File.ReadAllLines(current_path + "/Conf/filename");
...additional black magic here...
I want to generate complete Url (with domain name etc) of any file in MVC. Example: A .jpg file or an exe file.
Example: If I give "~/images/abc.jpg" it should return "http://www.mywebsite.com/images/abc.jpg"
I am aware of the Url.Action overload that takes the protocol as a parameter. But Url.Action can be used only for Actions.
I want something like Url.Content function that takes protocol as a parameter.
Do you know if any method to get complete url of any file?
I have tried: VirtualPathUtility.ToAbsolute, ResolveClientUrl, ResolveUrl but all of these don't seem to work.
new Uri(Request.Url, Url.Content("~/images/image1.gif"))
You can use the following code to replace "~/" to absoulute URL.
System.Web.VirtualPathUtility.ToAbsolute("~/")
Edit:
First you need to define a method.
public static string ResolveServerUrl(string serverUrl, bool forceHttps)
{
if (serverUrl.IndexOf("://") > -1)
return serverUrl;
string newUrl = serverUrl;
Uri originalUri = System.Web.HttpContext.Current.Request.Url;
newUrl = (forceHttps ? "https" : originalUri.Scheme) +
"://" + originalUri.Authority + newUrl;
return newUrl;
}
Now call this method will return the complete absolure url.
ResolveServerUrl(VirtualPathUtility.ToAbsolute("~/images/image1.gif"),false))
The output will be http://www.yourdomainname.com/images/image1.gif
Try use this.
Url.Action("~/images/image1.gif", "/", null, Request.Url.Scheme)