webview with javaFX - javafx

hi every one i am trying to get to web application exist in my computer through java fx web view :
public void start(Stage stage) throws Exception {
WebView webView = new WebView();
WebEngine engine = webView.getEngine();
engine.load("172.0.0.0://HOWEB/documentation:8080");//loadContent("<html> href = C:/Users/kaisios/Desktop/attempt9000.html<\\html>");
VBox vBox = new VBox();
vBox.getChildren().addAll(webView);
Scene scene = new Scene(vBox, 800, 500);
stage.setScene(scene);
stage.show();
}
but it does not load the content .
NOTE: I have already run xamp server but i think the formula of the url is wrong

There are several things wrong with the URL:
The protocol: This is probably http. You need to specify the IP in the protocol part of the url instead
The loopback IP is 127.0.0.1 not 172.0.0.0
The port is specified right after the host, which in this case is the IP
The port may be incorrect (verify in your xampp control panel that the port used is indeed 8080)
the correct url (assuming the rest is correct; use your standard webbrowser to check first) is
http://127.0.0.1:8080/HOWEB/documentation
You could also use a file URL, if you don't want to run a server:
File file = new File("C:/Users/kaisios/Desktop/attempt9000.html");
engine.load(file.toURI().toString());
Listening to the onError event can help you identify the issue:
engine.setOnError(evt -> {
Throwable error = evt.getError();
if (error != null) {
error.printStackTrace();
}
});

Related

Android emulator port forwarding results in ERR_EMPTY_RESPONSE

My scenario is as follows. I have an Android Emulator which is hosting an EmbedIO web server through an App. When I try to access the URL to the web server from the host machine's (Mac) browser I receive ERR_EMPTY_RESPONSE error.
I have issued the following port forwarding commands through ADB:
adb forward tcp:8080 tcp:8080
In the browser I am navigating to: http://localhost:8080/api/ChangeBackGround
and the Android emulator web server is listening on: http://10.0.2.16:8080/api/ChangeBackGround
Here is the code that starts the web server in the Xamarin Forms App (runs on Android Emulator):
public static class WebServerFactory
{
public static WebServer CreateWebServer<T>(string url, string baseRoute)
where T : WebApiController, new()
{
var server = new WebServer(url)
.WithWebApi(baseRoute, api => api.WithController<T>());
// Listen for state changes.
server.StateChanged += (s, e) => Debug.WriteLine($"WebServer New State - {e.NewState}");
return server;
}
}
public class EventController : WebApiController
{
[Route(HttpVerbs.Get, "/ChangeBackGround")]
public void ChangeBackGround()
{
Device.BeginInvokeOnMainThread(() =>
{
App.Current.MainPage.BackgroundColor = Color.Green;
});
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new MainPage();
}
private WebServer _WebServer;
protected override void OnStart()
{
var localIPAddress = GetLocalIPAddress();
var url = $"http://{localIPAddress}:8080";
Task.Factory.StartNew(async () =>
{
_WebServer = WebServerFactory.CreateWebServer<EventController>(url, "/api");
await _WebServer.RunAsync();
});
((MainPage)MainPage).Url = url;
}
private string GetLocalIPAddress()
{
var IpAddress = Dns.GetHostAddresses(Dns.GetHostName()).FirstOrDefault();
if (IpAddress != null)
return IpAddress.ToString();
throw new Exception("Could not locate IP Address");
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
The scenario currently works on the iOS simulator and an Android physical device. But I always get ERR_EMPTY_RESPONSE even when I've setup the port forwarding rules.
Any help would be much appreciated.
Please first make sure your android emulator could connect internet properly.
If the problem perisist, you can try the following methods:
Method 1:
1.start your Command prompt by runing as an admistrator;
2.Run the following commands in sequence:
netsh int ip reset c:\resetlog.txt
netsh winsock reset
ipconfig /flushdns
exit
Method 2: (If method 1 didn't work,try modthod 2)
Open your Control Panel -->NetWork and Internet-->Network and Sharing Center-->Change adapter settings-->right click Ethenet and click Properties-->select Internet Protocol 4-->click Properties -->using the following NDS server addresses
Fill in the following configuration:
Preferred NDS Server: 1.1.1.1
Alternate NDS Server: 1.0.0.1
Method 3: (If above methods didn't work,try modthod 3)
Open Settings in your PC-->Open NetWork and Internet-->click Nnetwork reset-->press Reset Now
Note:
For more details, you can enter keywords How to fix "ERR_EMPTY_RESPONSE" Error [2021] in your browser and then you will find relative tutorail.
You should have you service listening on either one of these IPs:
127.0.0.1: The emulated device loopback interface (preferred, I don't think you have reasons to use a different one)
10.0.2.15: The emulated device network/ethernet interface
See https://developer.android.com/studio/run/emulator-networking#networkaddresses

dotnet core, console app, UDP, why aren't messages being received?

I'm struggling to get a dotnet core console application to receive a UDP message. When I use the same code in a dotnet framework console app, the messages are received, so I feel nothing should be blocking them (ie. firewall, etc.).
I've tried running this project using Visual Studio, and published a release version and run using dotnet in a command window, but nothing is received. No exceptions. It seems so simple. I'm at a loss. Any advice is appreciated. Thanks.
This is the code:
static void Main(string[] args)
{
var client = new UdpClient(10006);
var ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
var msgReceived = client.Receive(ref ipEndPoint);
Console.WriteLine($"received '{Encoding.ASCII.GetString(msgReceived)}'");
}
I see the same/similar question asked here, without an answer:
How to send and receive commands from a UDP network server via .NET Core console application
Are you sure you are actually sending data to that machine and port number.
The code should work ok. I put this in my Main and it receives the data.
I used threads so they can be in the same process, I didnt test it as seperate processes.
var threadReceiver = new Thread(() =>
{
var client = new UdpClient(10006);
var ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
var msgReceived = client.Receive(ref ipEndPoint);
Console.WriteLine($"received '{Encoding.ASCII.GetString(msgReceived)}'");
});
var threadSender = new Thread(() =>
{
var client = new UdpClient(10007);
var ipEndPoint = new IPEndPoint(IPAddress.Any, 0);
var bytes = Encoding.ASCII.GetBytes("this is the data");
Thread.Sleep(1000);
var msgReceived = client.Send(bytes, bytes.Length, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 10006)) ;
Console.WriteLine($"Sent data");
});
threadReceiver.Start();
threadSender.Start();
threadReceiver.Join();
This outputs :
Sent data
received 'this is the data'
When i ran this the first time I was asked by windows firewall to allow the traffic. I checked private and public networks. You need to make sure your firewall is enabled for the network type you're connected to. Check the network settings to see if windows thinks is public or private. You can setup firewall rules manually for the app in the Windows firewall settings.

Unable to load an html file (from local file system) using JxBrowser

Using JavaFX and Eclipse IDE, I have used the sample app from Teamdev for loading a sample file (notifications.html from my file system) but I keep getting the page not found/DNS error.
The file in question, notifications.html, is right there in the same package as the source file that invokes it as shown in the snippet below:
Scene scene = new Scene(new BorderPane(view), 700, 500);
primaryStage.setScene(scene);
primaryStage.show();
browser.loadURL("notifications.html");
I think my issue is composing the fully qualified path and since I'm using a Mac, it is not clear to me how to do this. I have tried:
browser.loadURL("Users/myusername/Documents/workspace/jxBrowser/src/application/notifications.html");
However it did not work.
You need to use loadHtml() instead loadUrl() suppose loadHtml goes to network and you try to download url from file on your pc. Read html from filesystem to String and pass it to loadHtml() method.
InputStream urlStream = getClass().getResourceAsStream("/notifications.html");
String html = null;
try (BufferedReader urlReader = new BufferedReader(new InputStreamReader (urlStream))) {
StringBuilder builder = new StringBuilder();
String row;
while ((row = urlReader.readLine()) != null) {
builder.append(row);
}
html = builder.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
browser.loadHTML(html);
for this code your html file must be in resources folder of your project

How to define a custom port for the WebDAV server using sardine?

In Sardine how do I change the port number to something different from port 80 (for HTTP) and 443 (for HTTPS)?
The User guide states that I have to "override SardineImpl#createDefaultSchemeRegistry() or provide your own configured HTTP client instance by instantiating SardineImpl#SardineImpl(org.apache.http.impl.client.HttpClientBuilder)" but I can't find how to define the port.
When I instantiate SardineImpl using:
HttpClientBuilder builder = HttpClientBuilder.create();
SardineImpl sardine = new SardineImpl(builder, "user", "password");
byte[] data;
data = FileUtils.readFileToByteArray(new File("test.txt"));
sardine.put("http://webdav-server:8095/projects/", data);
I obtain:
org.apache.http.NoHttpResponseException: webdav-server:8095 failed to respond
The server is accessible via browser so the problem must be with the definition of the port and I could not find an example on how to do this.
Can someone help me on this? Thanks in advance.
This is what I figured out after racking my brain trying to find a solution. Hopefully it helps someone else:
HttpClientBuilder builder = new HttpClientBuilder(){
#Override
public CloseableHttpClient build() {
SchemePortResolver spr = new SchemePortResolver() {
#Override
public int resolve(HttpHost httpHost) throws UnsupportedSchemeException {
return 8443; // SSL port to use
}
};
CloseableHttpClient httpclient = HttpClients.custom()
.useSystemProperties()
.setSchemePortResolver(spr)
.build();
return httpclient;
}
};
Sardine sardine = new SardineImpl(builder, "user", "passwd");
List<DavResource> resources = null;
resources = sardine.list("https://ftp-site.com/path/");
resources.forEach(resource -> {
System.out.println(resource.getName());
}
Hope that helps somebody.

AppHarbor NopCommerce running issue

I uploaded nopcommerce solution to appharbor (using this method Can't build notcommerce project under appharbor) and solution succesfully builded, but I receiving 403 error - Forbidden: Access is denied when trying to open page(Allow write-access to file system is set to true).
Thanks and hope for your help
The problem is that the standard NopCommerce solution contains two Web Projects. AppHarbor only deploys one web project per application, and in this case, we happen to deploy Nop.Admin which is not what you want.
To resolve this, you should take advantage of the AppHarbor solution file convention and create an AppHarbor.sln solution file that only references the Nop.Web project.
We use a wrapper in our base controller to ensure that all of our code is oblivious to appharbor port changing.
First, fix in Webhelper.cs:75
public virtual string GetThisPageUrl(bool includeQueryString, bool useSsl)
{
string url = string.Empty;
if (_httpContext == null)
return url;
if (includeQueryString)
{
string storeHost = GetStoreHost(useSsl);
if (storeHost.EndsWith("/"))
storeHost = storeHost.Substring(0, storeHost.Length - 1);
url = storeHost + _httpContext.Request.RawUrl;
}
else
{
#if DEBUG
var uri = _httpContext.Request.Url;
#else
//Since appharbor changes port number due to multiple servers, we need to ensure port = 80 as in AppHarborRequesWrapper.cs
var uri = new UriBuilder
{
Scheme = _httpContext.Request.Url.Scheme,
Host = _httpContext.Request.Url.Host,
Port = 80,
Path = _httpContext.Request.Url.AbsolutePath,
Fragment = _httpContext.Request.Url.Fragment,
Query = _httpContext.Request.Url.Query.Replace("?", "")
}.Uri;
#endif
url = uri.GetLeftPart(UriPartial.Path);
}
url = url.ToLowerInvariant();
return url;
}
So what we did is simply add files from https://gist.github.com/1158264 into Nop.Core\AppHarbor
and modified base controllers:
nopcommerce\Presentation\Nop.Web\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(RequestContext requestContext)
{
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current),
requestContext.RouteData));
}
//Same file from here downwards...
}
nopcommerce\Presentation\Nop.Web.Admin\Controllers\BaseNopController.cs
public class BaseNopController : Controller
{
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
//set work context to admin mode
EngineContext.Current.Resolve<IWorkContext>().IsAdmin = true;
//Source: https://gist.github.com/1158264
base.Initialize(new RequestContext(new AppHarborHttpContextWrapper(System.Web.HttpContext.Current), requestContext.RouteData));
//base.Initialize(requestContext);
}
//Same file from here downwards...
}
Enable the Directory Browsing feature in IIS Express
Note This method is for the web developers who experience the issue when they use IIS Express.
To do this, follow these steps:
Open a command prompt, and then go to the IIS Express folder on your computer. For example, go to the following folder in a command prompt:
C:\Program Files\IIS Express
Type the following command, and then press Enter:
appcmd set config /section:directoryBrowse /enabled:true
refrence :https://support.microsoft.com/en-us/kb/942062

Resources