Javafx - open login.microsoftonline.com page in webview component - windows

I have problem with opening login.microsoftonline.com page in webview component from javafx. I have simply code that should open this page without any trouble:
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
var url = "https://login.microsoftonline.com/";
webEngine.load(url);
VBox root = new VBox();
root.getChildren().add(webView);
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
System.out.println(webEngine.getLocation());
});
When I try to execute this code on machine with windows operating system I receive blank page:
When I execute the same code on macbook, site is opening:
I'm using java 10 and really no idea what's wrong. Does anybody have the same issue? Any idea how to solve this problem? maybe there is other component instead of webview that I can use to do my stuff?

This is not the solution to your problem but may lead you in the right direction. It seems that the site body is loaded using script. That script depends on other scripts I am guessing. It appears none of the other scripts are loading.
import com.sun.javafx.webkit.WebConsoleListener;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
*
* #author blj0011
*/
public class JavaFXApplication281 extends Application
{
#Override
public void start(Stage primaryStage)
{
try {
TrustManager trm = new X509TrustManager()
{
#Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
#Override
public void checkClientTrusted(X509Certificate[] certs, String authType)
{
}
#Override
public void checkServerTrusted(X509Certificate[] certs, String authType)
{
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{trm}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
WebConsoleListener.setDefaultListener(new WebConsoleListener()
{
#Override
public void messageAdded(WebView webView, String message, int lineNumber, String sourceId)
{
System.out.println("Console: [" + sourceId + ":" + lineNumber + "] " + message);
}
});
webEngine.setJavaScriptEnabled(true);
String url = "https://login.microsoftonline.com/";//"https://login.microsoftonline.com/jsdisabled";//
webEngine.load(url);
webEngine.getLoadWorker().stateProperty().addListener((obs, oldValue, newValue) -> {
System.out.println(newValue);
String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
System.out.println(html);
});
webEngine.setOnError((event) -> {
System.out.println(event.getMessage());
});
// webEngine.getLoadWorker().exceptionProperty().addListener((obs, oldExc, newExc) -> {
// if (newExc != null) {
// newExc.printStackTrace();
// }
// });
StackPane root = new StackPane();
root.getChildren().add(webView);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
catch (KeyManagementException ex) {
ex.printStackTrace();
}
catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
Output:
Console: [null:0] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Cannot load stylesheet https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/converged.v2.login.min_jumzhgrnvlj7lwxqltrteq2.css']
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/oldconvergedlogin_pcore.min_lwozjqawrstmtzsn2yunha2.js']
Console: [null:0] Cannot load script https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js. Failed integrity metadata check.
Console: [https://login.microsoftonline.com/common/oauth2/authorize?client_id=4345a7b9-9a63-4910-a426-35363201d503&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%3d5xhL9s5iN_65agH7ctGnRfQlJHUHgSrEvD4vkaO323RyB1klBHD6Qh5qidm6GuaIHM8_GaSANKH6y1ohWHalX4QU_YyqGJqXV8wphi2TVMAAY3yyXQk3GB-yqWm0j3oh&nonce=636748812038183968.MmMxNjY2YjEtNDIwZS00ZDhhLWI3YmItMWRhMWM5ZmRmMzk4MjJkMGExMDItZDAxZi00MTZmLWIxYjctOTNmZWU2YjgzZDRi&redirect_uri=https%3a%2f%2fwww.office.com%2f&ui_locales=en-US&mkt=en-US:30] Failed to load external resource ['https://secure.aadcdn.microsoftonline-p.com/ests/2.1.8233.17/content/cdnbundles/convergedloginpaginatedstrings-en.min_uzcugprrg6vz0z16am4meq2.js']
The above will also show you the HTML that was loaded. It is too long to add.
Some code from here to help troubleshoot the problem.
I do not have Java 10. I used Java 8.

I found out that web view is using webkit engine for mac os/ linux os and IE engine for windows machines. WebView on mac os is working fine but there is problem on windows machines. When I was investigating this issue I find out that there is problem in this IE engine. I have access to few machines with different version of IE 11 installed on. On machines with update version 11.0.85 I wasn't able to open this site, but when I tried on machine with update version 11.0.90 the problem doesn't exist anymore. So if someone is using Windows OS please try to update IE version maybe it will solve problem.

Had the same issue and I think I found the critical point: external script/link integrity fails.
This is not a platform browser issue, JavaFX (OpenJFK) relies on an embedded webkit engine.
The regression happened between version 40 and version 172 on windows JDK 8.
It's working fine with Oracle JDK 9.0.4
It's not working with Oracle JDK 11
More details at:
https://github.com/mguessan/davmail/issues/12
Issue similar to: Javafx - open login.microsoftonline.com page in webview component
=> Updated answer: implemented to override Microsoft form content and disable integrity check. This is not a fix of the webkit bug, just a workaround
try {
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
#Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if ("https".equals(protocol)) {
return new sun.net.www.protocol.https.Handler() {
#Override
protected URLConnection openConnection(URL url, Proxy proxy) throws IOException {
System.out.println("openConnection " + url);
if (url.toExternalForm().endsWith("/common/handlers/watson")) {
System.out.println("Failed: form calls watson");
}
final HttpsURLConnectionImpl httpsURLConnection = (HttpsURLConnectionImpl) super.openConnection(url, proxy);
if ("login.microsoftonline.com".equals(url.getHost())
&& "/common/oauth2/authorize".equals(url.getPath())) {
return new URLConnection(url) {
#Override
public void connect() throws IOException {
httpsURLConnection.connect();
}
public InputStream getInputStream() throws IOException {
byte[] content = readFully(httpsURLConnection.getInputStream());
String contentAsString = new String(content, "UTF-8");
System.out.println(contentAsString);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(contentAsString.replaceAll("integrity", "integrity.disabled").getBytes("UTF-8"));
return new ByteArrayInputStream(baos.toByteArray());
}
public OutputStream getOutputStream() throws IOException {
return httpsURLConnection.getOutputStream();
}
};
} else {
return httpsURLConnection;
}
}
};
}
return null;
}
});
} catch (Throwable t) {
System.out.println("Unable to register custom protocol handler");
}

Related

second scenario in my cucumber feature file is not executing

I'm trying to learn Cucumber with selenium java . have written two scenario's , when i run my feature file which contains two scenarios , only scenario #1 is executing , for scenario #2 its throwing Java null pointer exception
Feature: POC of my framework works
Scenario: Login test
Given I navigate to the Bugzilla website
When I click on login
And I enter the values
Then I check to see if i was successfully loged in or not
Scenario: File a bug test
Given I navigate to the File a bug page
When I click on widgets
And I enter the bug details
Then Bug should be submited succefully
My step definition file :
package cucumber.features;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import cucumber.api.java.en.And;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepDefinitions1 {
protected WebDriver driver;
protected String baseUrl;
// Scenario 1
#Given("^I navigate to the Bugzilla website$")
public void I_navigate_to_the_Bugzilla_website() throws Throwable {
driver = new FirefoxDriver();
baseUrl ="https://landfill.bugzilla.org/bugzilla-4.4-branch/index.cgi";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#When("^I click on login$")
public void I_click_on_login() throws Throwable {
driver.findElement(By.id("login_link_top")).click();
}
#And("^I enter the values$")
public void I_enter_the_values() throws Throwable {
driver.findElement(By.id("Bugzilla_login_top")).clear();
driver.findElement(By.id("Bugzilla_login_top")).sendKeys("jeevan.anekal#gmail.com");
driver.findElement(By.id("Bugzilla_password_top")).clear();
driver.findElement(By.id("Bugzilla_password_top")).sendKeys("testuser#123");
driver.findElement(By.id("log_in_top")).click();
}
#Then("^I check to see if i was successfully loged in or not$")
public void I_check_to_see_if_i_was_successfully_loged_in_or_not() throws Throwable {
System.out.println("Login Successfull");
}
// Scenario 2
#Given("^I navigate to the File a bug page$")
public void I_navigate_to_the_File_a_bug_page() throws Throwable {
driver.findElement(By.id("enter_bug")).click();
}
#When("^I click on widgets$")
public void I_click_on_widgets() throws Throwable {
driver.findElement(By.linkText("Widgets")).click();
}
#And("^I enter the bug details$")
public void I_enter_the_bug_details() throws Throwable {
new Select(driver.findElement(By.id("bug_severity"))).selectByVisibleText("trivial");
new Select(driver.findElement(By.id("cf_drop_down"))).selectByVisibleText("---");
new Select(driver.findElement(By.id("rep_platform"))).selectByVisibleText("Macintosh");
new Select(driver.findElement(By.id("op_sys"))).selectByVisibleText("Mac OS X 10.0");
driver.findElement(By.id("short_desc")).clear();
driver.findElement(By.id("short_desc")).sendKeys("OS crashed");
driver.findElement(By.id("comment")).clear();
driver.findElement(By.id("comment")).sendKeys("Os debugging issue");
}
#Then("^Bug should be submited succefully$")
public void Bug_should_be_submited_succefully() throws Throwable {
System.out.println("Bug submitted successfully");
}
}
Looks like you are not calling the browser and navigating to the page in scenario 2
You need do do something similar to this
#Given("^I navigate to the File a bug page$")
public void I_navigate_to_the_File_a_bug_page() throws Throwable {
driver = new FirefoxDriver();
baseUrl ="https://landfill.bugzilla.org/bugzilla-4.4-nch/index.cgi";
driver.get(baseUrl);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.id("enter_bug")).click();
enter code here
}
or use #Before hooks to initialize the browser
I think I kind get your problem here. I had encountered similar problem before.
So when running the feature file, either by clicking on the run button from the bar or right click in the feature file then run..., take a look at what it says when actually clicking it. Because if you hover over a certain scenario and click run, it will only run that scenario, not the whole feature file where there is more than 1 scenarios.

Launch browser automatically after spring-boot webapp is ready

How do I launch a browser automatically after starting the spring boot application.Is there any listener method callback to check if the webapp has been deployed and is ready to serve the requests,so that when the browser is loaded , the user sees the index page and can start interacting with the webapp?
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
// launch browser on localhost
}
Below code worked for me:
#EventListener({ApplicationReadyEvent.class})
void applicationReadyEvent() {
System.out.println("Application started ... launching browser now");
browse("www.google.com");
}
public static void browse(String url) {
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#SpringBootApplication
#ComponentScan(basePackageClasses = com.io.controller.HelloController.class)
public class HectorApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(HectorApplication.class, args);
openHomePage();
}
private static void openHomePage() throws IOException {
Runtime rt = Runtime.getRuntime();
rt.exec("rundll32 url.dll,FileProtocolHandler " + "http://localhost:8080");
}
}
You could do it by some java code. I am not sure if spring boot has something out of the box.
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class Browser {
public static void main(String[] args) {
String url = "http://www.google.com";
if(Desktop.isDesktopSupported()){
Desktop desktop = Desktop.getDesktop();
try {
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("xdg-open " + url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
I've recently been attempting to get this working myself, I know it's been a while since this question was asked but my working (and very basic/simple) solution is shown below. This is a starting point for anyone wanting to get this working, refactor as required in your app!
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import java.awt.*;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
openHomePage();
}
private static void openHomePage() {
try {
URI homepage = new URI("http://localhost:8080/");
Desktop.getDesktop().browse(homepage);
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
If you package the application as a WAR file, configure an application server, like Tomcat, and restart the configured application server through your IDE, IDEs can automatically open a browser-tab.
If you want to package your application as a JAR file, your IDE will not be able to open a web browser, so you have to open a web browser and type the desired link(localhost:8080). But in the developing phase, taking these boring steps might be very tedious.
It is possible to open a browser with Java programming language after the spring-boot application gets ready. You can use the third-party library like Selenium or use the following code snippet.
The code snippet to open a browser
#EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
if (Desktop.isDesktopSupported())
{
Desktop desktop = Desktop.getDesktop();
try
{
desktop.browse(new URI(url));
} catch (IOException | URISyntaxException e)
{
e.printStackTrace();
}
} else
{
Runtime runtime = Runtime.getRuntime();
String[] command;
String operatingSystemName = System.getProperty("os.name").toLowerCase();
if (operatingSystemName.indexOf("nix") >= 0 || operatingSystemName.indexOf("nux") >= 0)
{
String[] browsers = {"opera", "google-chrome", "epiphany", "firefox", "mozilla", "konqueror", "netscape", "links", "lynx"};
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < browsers.length; i++)
{
if (i == 0) stringBuffer.append(String.format("%s \"%s\"", browsers[i], url));
else stringBuffer.append(String.format(" || %s \"%s\"", browsers[i], url));
}
command = new String[]{"sh", "-c", stringBuffer.toString()};
} else if (operatingSystemName.indexOf("win") >= 0)
{
command = new String[]{"rundll32 url.dll,FileProtocolHandler " + url};
} else if (operatingSystemName.indexOf("mac") >= 0)
{
command = new String[]{"open " + url};
} else
{
System.out.println("an unknown operating system!!");
return;
}
try
{
if (command.length > 1) runtime.exec(command); // linux
else runtime.exec(command[0]); // windows or mac
} catch (IOException e)
{
e.printStackTrace();
}
}
}
Using Selenium to open a browser
To use the selenium library add the following dependency to your pom.xml file.
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
Then in your main class, add the following code snippet.
#EventListener({ApplicationReadyEvent.class})
private void applicationReadyEvent()
{
String url = "http://localhost:8080";
// pointing to the download driver
System.setProperty("webdriver.chrome.driver", "Downloaded-PATH/chromedriver");
ChromeDriver chromeDriver = new ChromeDriver();
chromeDriver.get(url);
}
Notice: It is possible to use most of the popular browsers like FirefoxDriver, OperaDriver, EdgeDriver, but it is necessary to download browsers' drivers beforehand.
Runtime rt = Runtime.getRuntime();
try {
rt.exec("cmd /c start chrome.exe https://localhost:8080");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The code above worked for me. Change chrome.exe to the browser of your choice and Url to to your choice.
Note: You must include the scheme - http or https, and the browser you choose must me installed, else your app will run without opening the browser automatically.
Works only for windows though.

How to write adb commands inside a Android application?

I want to know how to execute adb commands from within my code. For e.g I want to push a file inside the adb shell and I write this:
package org.example.adbshell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Process process;
try {
process = Runtime.getRuntime().exec("adb push C:/Users/Savio/Desktop/savio.xml /storage/sdcard0/");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
I should be able to see the savio.xml inside the /storage/sdcard0 folder. But for some reason I am unable to see the file. I am guessing that the command is not getting executed. What am I doing wrong here?
There are three type of command
System command // In this case below code is working. like mv/edit/cp/cd etc
Non routed command
Rooted command // You need to routed device.
Try this
Process process Runtime.getRuntime().exec("your command");
//or
Process process Runtime.getRuntime().exec("/path/your_command");
Its work for me of copying file :
Process process Runtime.getRuntime().exec("/system/bin/mv my_file_path");
You can read output data with the help of process object
// Use buffer reader for the same.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
There is no ADB command on Android's side. ADB is a part of Android SDK only and is always run on computer not on Android.
Also, Android knows nothing about C:/Users/Savio/Desktop/savio.xml as it is not a file in its filesystem.
You should rather implement desktop application with HTTP (or similar) server and use it to download and upload files from Android to PC. You can start with NanoHTTP, a lightweight HTTP implementation.
Or you can use server for communication between Android and computer and run ADB command on that computer based upon request from Android.

Mac OSX - Drag and drop in Swing appl running on applet

I'm having some issues making my swing application to work in Mac OSX. This swing application should run on an applet inside the browser.
Please note that this problem is exclusive to mac osx and only when the applet run on the browser
The problem I see is that the drop events are not properly delivered to the components inside the Applet.
The following example contains a label and a input field. If you drag from the label to the input field, the label text should be copy into the input field.
package com.example;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class DND extends JApplet {
/**
*
*/
private static final long serialVersionUID = 1L;
JTextField txtField;
JLabel lbl;
private void doStart() {
this.setLayout(new FlowLayout(FlowLayout.CENTER));
txtField = new JTextField(20);
lbl = new JLabel("Drag this text to the input field");
lbl.setPreferredSize(new Dimension(250, 100));
lbl.setBackground(Color.lightGray);
lbl.setBorder(BorderFactory.createLineBorder(Color.black));
lbl.setTransferHandler(new TransferHandler("text"));
MouseListener ml = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
JComponent jc = (JComponent) e.getSource();
TransferHandler th = jc.getTransferHandler();
th.exportAsDrag(jc, e, TransferHandler.COPY);
}
};
lbl.addMouseListener(ml);
add(txtField);
add(lbl);
setBackground(Color.lightGray);
setVisible(true);
}
#Override
public void start() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
doStart();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
With this code you have to generate a .jar file which will be used in the following html so you can run the applet in the browser:
<html>
<head>
<title>Menu test Applet</title>
</head>
<body>
<applet id="AppletID" height="800" width="600"
code="com.example.DND"
archive="*jar_file*.jar">
</applet>
</div>
</body>
</html>
If you pop the applet out of the browser using cmd+shift everything works as expected.
System specs:
Firefox 16.0.2
Mac OS X 10.7.5
JRE version 1.6.0_37-b06 (with plugin 1.6.0_37 but this problem also happens in 1.6.0_31)
Anyone have any idea what am I doing wrong?

Exception in Flying Saucer when processing images for custom UserAgentCallback

I've setup a test environment for Flying Saucer R8, and is testing building PDF's from templates and data. I'm using a custom UserAgentCallback to read external js/css and images locally from filesystem. The problem occured when introducing the following custom UserAgentCallback:
package support;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.xhtmlrenderer.swing.NaiveUserAgent;
public class FileUserAgent extends NaiveUserAgent {
#Override
public String resolveURI(String uri) {
URL url = null;
String path = null;
try {
url = new URL(uri);
path = url.getPath();
} catch (MalformedURLException e) {
// only path present
path = uri;
}
if (path.charAt(0) == '/') {
path = path.substring(1, path.length());
}
return path;
}
#Override
protected InputStream resolveAndOpenStream(String filepath) {
InputStream is = null;
try {
File file = new File(filepath);
is = new FileInputStream(file);
} catch (Exception e) {
System.out.print("an error occured when reading resource: " + e.getMessage());
}
return is;
}
}
The UserAgentCallback is able to read CSS without any problem, but when reading images either from src or background-image property i get the followng exception:
java.lang.ClassCastException: org.xhtmlrenderer.swing.AWTFSImage$OldAWTFSImage cannot be cast to org.xhtmlrenderer.pdf.ITextFSImage
at org.xhtmlrenderer.pdf.ITextOutputDevice.drawImage(ITextOutputDevice.java:761)
at org.xhtmlrenderer.render.AbstractOutputDevice.paintTiles(AbstractOutputDevice.java:300)
at org.xhtmlrenderer.render.AbstractOutputDevice.paintBackground0(AbstractOutputDevice.java:245)
at org.xhtmlrenderer.render.AbstractOutputDevice.paintBackground(AbstractOutputDevice.java:191)
at org.xhtmlrenderer.pdf.ITextOutputDevice.paintBackground(ITextOutputDevice.java:187)
at org.xhtmlrenderer.render.Box.paintBackground(Box.java:436)
at org.xhtmlrenderer.layout.Layer.paintBackgroundsAndBorders(Layer.java:243)
at org.xhtmlrenderer.layout.Layer.paint(Layer.java:329)
at org.xhtmlrenderer.pdf.ITextRenderer.paintPage(ITextRenderer.java:384)
at org.xhtmlrenderer.pdf.ITextRenderer.writePDF(ITextRenderer.java:348)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:315)
at org.xhtmlrenderer.pdf.ITextRenderer.createPDF(ITextRenderer.java:246)
from what i read in the flying-saucer forum you have to make sure to return the right ImageResource!
what helped for me was extending the class with ITextUserAgent instead of NaiveUserAgent. (ITextUserAgent extends NaiveUserAgent).

Resources