Clear url in browser window using Java code - url

I am using navigate().to() method to navigate but new url is getting appended to old url as below, after executing navigate.to function thus resulting in 404 error
https://www.google.co.in/www.yahoo.co.in
Can anyone please help how should I get this to work?
public static void main(String[] args) throws InterruptedException {
WebDriver fd = new FirefoxDriver();
fd.get("http://www.google.co.in");
Thread.sleep(3000);
fd.navigate().to("www.yahoo.co.in");
}
}

I'm not sure how to use navigate().to() but this an alternative solution.
import java.awt.Desktop;
import java.net.URI;
....
try {
Desktop d = Desktop.getDesktop();
d.browse(new URI("http://www.google.co.in"));
Thread.sleep(3000);
d.browse(new URI("www.yahoo.co.in"));
} catch (Exception ex) {
ex.printStackTrace();
}

There are two options:
1) use again get() method from the WebDriver to navigate to the new URL.
2) use navigate().to() method, but use fully qualified URL parameter. Eg. "https://www.google.com"
From the WebDriver javadoc: #param url The URL to load. It is best to use a fully qualified URL
The navigate() method is useful for using the context on the current web context. i.e. go back, forward.
Basically, the get() and navigate().to() do the same thing. I just tried both and they work.
Reference: http://www.seleniumeasy.com/selenium-tutorials/difference-between-webdriver-get-and-navigate

Related

InvokeScriptAsync not launching script

I have an UWP app and I'm trying to get a script invoked from a WebView. The NavigationCompleted event raises and my javascript is included (I think) in the page but the script isn't executed.
Here's my C# code
public sealed partial class MainPage : Page
{
readonly WebView _webView = new WebView();
public MainPage()
{
this.InitializeComponent();
Facebook.Navigate(new Uri("http://www.facebook.com/"));
_webView.NavigationCompleted += WebView_OnNavigationCompleted;
_webView.ScriptNotify += WebView_OnScriptNotify;
}
private async void WebView_OnNavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
await _webView.InvokeScriptAsync("eval", new[]
{
"alert('HEY');" +
"window.external.notify('%%' + location.href);"
});
}
private void WebView_OnScriptNotify(object sender, NotifyEventArgs e)
{
var url = e.Value;
}
}
Also, I added http://www.facebook.com and https://www.facebook.com to my package manifest Content Uris list (include with all WinRT access).
I can't get the alert popping, same for the notify.
Thanks
As noted in the WebView docs, alert doesn't work in a WebView control.
For Script Notify to work you need to add the page to the app manifest as well:
To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's Uniform Resource Identifier (URI) in the ApplicationContentUriRules section of the app manifest.
And:
The URIs in this list must use HTTPS
So, try navigating to the https site instead.
Worst case, you can use a web allowed object in order to communicate back to your app as that can be injected in all cases.

Hybris + swagger integration swagger-ui.html UnknownResourceError

I'm trying to integrate swagger in MYcommercewebservices.
I read post and done all steps listed on it, but still having this error.
https://localhost:9002/mycommercewebservices/v2/v2/api-docs working fine. https://localhost:9002/mycommercewebservices/v2/swagger-ui.html - return UnknownResourceError.
Furthermore - if I navigate to https://localhost:9002/mycommercewebservices/swagger-ui.html (without 'v2') it'll show me this message (javascript alert):
Unable to infer base URL. This is common when using dynamic servlet
registration or when the API is behind an API Gateway. The base URL is
the root of where all the swagger resources are served. For e.g. if
the API is available at http://example.org/api/v2/api-docs then the
base URL is http://example.org/api/. Please enter the location
manually:
I found this controller, and probably part of the problem was in it because it was throwing an exception when I navigated to https://localhost:9002/mycommercewebservices/v2/swagger-ui.html
#Controller
public class DefaultController
{
#RequestMapping
public void defaultRequest(final HttpServletRequest request)
{
throw new UnknownResourceException("There is no resource for path " + YSanitizer.sanitize(request.getRequestURI()));
}
}
Now I disabled controller, but still having the same exception, but now it's in json format instead of .xml.
Thank you!
The main problem was in DefaultController (in MYcommercewebservices)
#Controller
public class DefaultController
{
#RequestMapping
public void defaultRequest(final HttpServletRequest request)
{
throw new UnknownResourceException("There is no resource for path " + YSanitizer.sanitize(request.getRequestURI()));
}
}
It was catching my request and throwing the exception.
When I disabled this controller, I continued to receive an exception, but now it was in json format(before it was in xml).
Than I added this to springmvc-v2-servlet.xml
<mvc:default-servlet-handler/>
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/>
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>
Now UI works fine!
Also there were another manipulation before all this, but you can find them in hybris experts(quite big post).

Start dart application from Server and load elements

I'm new in dart's programming and I'm building a dart app and I would like to start it from the server side. Like loading my homepage when I enter the url of my webpage.
On my server side I have this code that I took from tutorials from dart's webpage:
var server;
try{
server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V6, 4040);
}catch(e){
print("Couldn't bind to port 4044: $e");
exit(-1);
}
await for(HttpRequest req in server){
var file = new File('index.html');
if(await file.exists()){
print("Serving index.html.");
req.response.headers.contentType = ContentType.HTML;
try{
await file.openRead().pipe(req.response);
}catch(e){
print("Couldn't read file: $e");
exit(-1);
}
}else{
print("Couldn't open index.html");
req.response..statusCode = HttpStatus.NOT_FOUND..close();
}
}
But now my problem is about the client side, my elements are not loading, like css, images, etc.
You can see the appearance here
I think that I need to set something at my server side to load that. What is it?
Using the core dart:io methods for serving files is often not the easiest way. Take a look at shelf, f.e. It's a really neat framework for creating server applications that has a lot of plugins and extensions for middleware etc.
In your case, it seems like you just want to serve static content. I'd suggest you use shelf_static. It would go like this:
import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';
void main() {
var handler = createStaticHandler('your-web-directory/',
defaultDocument: 'index.html');
io.serve(handler, InternetAddress.LOOPBACK_IP_V6, 4040);
}

Servlet filter doesn't respond on given URL pattern

I have a JSF web application where all the pages that reside under directory web needs to be protected from unautheticatd use i.e., user should be in session to accesss these pages. I am using filter to validate the session for these pages. These pages are accessed via url like : /contextRoot/web/download.xhtml or /contextRoot/web/sign/upload.xhtml. Whereas other pages that reside outside web directory or in some other directory need not to go pass through session validation filter. My filter is like:
#WebFilter(filterName = "AuthenticationFilter", urlPatterns={"/web/*"}, dispatcherTypes = {DispatcherType.REQUEST})
public class AuthenticationFilter implements Filter {
private static final boolean debug = true;
private FilterConfig filterConfig = null;
public AuthenticationFilter() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
if (debug) {
log("AuthenticationFilter:doFilter()");
}
HttpSession session = ((HttpServletRequest) request).getSession(false);
if (session == null || session.getAttribute("username") == null) {
System.out.println("Your Session Not Active. You are redirected.");
//((HttpServletResponse) response).sendRedirect("home.xhtml");
} else {
System.out.println("Your Session is active. username : " + session.getAttribute("username"));
}
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch (Throwable t) {
// If an exception is thrown somewhere down the filter chain,
// we still want to execute our after processing, and then
// rethrow the problem after that.
problem = t;
t.printStackTrace();
}
}
}
I am using urlPattern /web/* so that every page inside web directory will go pass this filter. The filter is right now just printing stuff for debugging. But whenever I am accessing page inside web directory or any other page, it is not going through filter. I also tried using /faces/web/* as urlPattern but that also didn't work. But when I put /* as urlPattern, every accessed page goes through the filter.
I am accessing page as
http://localhost:8080/CodesignWebApp/faces/web/sign/SelectServer.xhtml http://localhost:8080/CodesignWebApp/faces/web/sign/FileUpload.xhtml?signmethod=MICROSOFT
I am suspecting something wrong with urlPattern.
I am accessing page as
http://localhost:8080/CodesignWebApp/faces/web/sign/SelectServer.xhtml
http://localhost:8080/CodesignWebApp/faces/web/sign/FileUpload.xhtml
The URL pattern of a #WebFilter (and #WebServlet) must match exactly those URLs you see in browser's address bar (and thus not the disk file system paths you actually have in the server side; it's also literally called an "URL pattern", not "file pattern" or whatever).
So, all in all, just this should do, provided that /CodesignWebApp is webapp's context root:
#WebFilter("/faces/web/*")
public class AuthenticationFilter implements Filter {
// ...
}
(filter name is not relevant and request dispatcher method you specified is the default already)
A different alternative is to get rid of ancient JSF 1.0 style /faces/* mapping altogether and replace it by the JSF 2.0 style *.xhtml mapping. You don't want the endusers to see raw JSF source code when they remove /faces part from the URL, right?
<servlet-mapping>
<servlet-name>facesServlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
This way you can just access the pages as follows:
http://localhost:8080/CodesignWebApp/web/sign/SelectServer.xhtml
http://localhost:8080/CodesignWebApp/web/sign/FileUpload.xhtml
And map the filter as follows:
#WebFilter("/web/*")
public class AuthenticationFilter implements Filter {
// ...
}
See also:
JSF Facelets: Sometimes I see the URL is .jsf and sometimes .xhtml. Why?

How to open IE with post info in C#?

I am developing a small program which as a windows form. On this form, I want to put a link, and when user click the link, a seperate IE browser will be open with post data.
Original, i used System.Diagnostics.Process.start(). However, I can not post data through this kind of call.
And I searched the web, some guy suggested to use "Microsoft web browser control", however, this need to add this control in my form,and display the explorer in the form, but I want a seperate IE opened.
And I saw in VB there is a method as CreateObject("InternetExplorer.Application"), but I can not find how to use it in C#.
So, do you have any suggestions on how to implement?
Drop a web browser on your form. It should have a default name of "webBrowser1" - you can change that if you like. Set the "Visible" property to "False". Double-click the form title bar to auto generate a load event in the code.
Call the Navigate method, which has this signature:
void Navigate(string urlString, string targetFrameName, byte[] postData, string additionalHeaders);
Like this:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate("http://www.google.com/", "_blank", Encoding.Default.GetBytes("THIS IS SOME POST DATA"), "");
}
You can pass any array of bytes you want in there... Encoding.Default.GetBytes() is just a fast way to pass a string through.
The trick is to use "_blank" for the target frame.
If you do a ShellExecute with a verb of OPEN on the url then the default web browser will be spawned and open the link. Alternatively, you can invoke Internet Explorer (once again using ShellExecute) with the url appended at the end of the string (so the string that you use for ShellExecute would look like this:
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://google.com");
You are talking about POST though, you cannot do a POST, the above line does a GET. Depending on how the website is set up you may be able to just append the parameters on the end of the url, like so:
System.Diagnostics.Process.Start(#"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com/search?q=bing");
You are definitely going to need to use Process.Start (or use a ProcessInfo) to get IE started : like this :
// open IE to a file on the Desktop as a result of clicking a LinkLabel on a WinForm
internal static string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("IExplore.exe", desktopPath + "\\someHTMLFile.htm");
}
If you scroll down in this page :
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.80).aspx
(the Process.Start docs for FrameWork 3.0)
you'll find a user contributed example of using ProcessInfo to control whether more than one of instance of IE is started, and how to pass command line arguments to IE.
This page :
http://msdn.microsoft.com/en-us/library/0w4h05yb.aspx
(the Process.Start docs for FrameWork 3.5)
shows you a complete example of launching IE, and how to pass url files as arguments.
I'm not completely clear on what you mean by "Post" in your message (I associate "Post" with ASP.NET), but you could write out an html file in a temporary location with whatever you liked in it, and then pass the address of that file when you launch IE using the techniques documented above. best,
You can also use .NET reflection to open a browser
This example shows you how to set some specific attributes of the InternetExplorer.Application
For example, I needed to be able to turn off the address bar and set the height and width. IE and other browser security does not allow you to turn off the address bar in the other examples
Our site is an internal MVC application and works with no issues.
System.Type oType = System.Type.GetTypeFromProgID("InternetExplorer.Application");
object IE = System.Activator.CreateInstance(oType);
IE.GetType().InvokeMember("menubar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
IE.GetType().InvokeMember("toolbar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
IE.GetType().InvokeMember("statusBar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
IE.GetType().InvokeMember("addressbar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
IE.GetType().InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { true });
IE.GetType().InvokeMember("Height", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 680 });
IE.GetType().InvokeMember("Width", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 1030 });
IE.GetType().InvokeMember("Navigate", System.Reflection.BindingFlags.InvokeMethod, null, IE, new object[] { "http://yoursite" });
The only drawback here is that this is opening IE specifically. The plus is that it gives you more control over the browser.
You also have access to the Events, Methods and Properties of the InternetExplorer.Application object.
https://msdn.microsoft.com/en-us/library/aa752084(v=vs.85).aspx
I hope that helps someone else as it did me.
I am working on binding to events and will update this after testing.
You can just start process by sending URL in Process.Start as parameter. There is a problem while calling StartProcess from WebForms GUI thread because of synchronization context. My solution uses thread pool for this purpose. Advantage of this solution is that an URL is opened in user preferred web browser that can be IE, Firefox etc.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming",
"CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#"),
System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void OpenUrl(string urlString)
{
try
{
ThreadPool.QueueUserWorkItem(delegate { StartProcess(urlString, null); });
}
catch (Exception ex)
{
log.Error("Exception during opening Url (thread staring): ", ex);
//do nothing
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void StartProcess(string processName, string arguments)
{
try
{
Process process = new Process();
process.StartInfo.FileName = processName;
if (!string.IsNullOrEmpty(arguments))
{
process.StartInfo.Arguments = arguments;
}
process.StartInfo.CreateNoWindow = false;
process.StartInfo.UseShellExecute = true;
process.Start();
}
catch (Exception ex)
{
log.ErrorFormat("Exception in StartProcess: process: [{0}], argument:[{1}], exception:{2}"
, processName, arguments, ex);
}
}
Actually, you can use process.start with posted query string data:
System.Diagnostics.Process.Start("IExplore.exe", "http://localhost/file.html?foo=bar&baz=duh");

Resources