Opening Page in IE using Java & Getting Confirmation on its load - java

I want to load a URL in the user's default browser. And once the webpage gets loaded completely I want to take its screenshot.
Currently I am doing it like this:
import java.awt.Desktop;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URI;
import javax.imageio.ImageIO;
public class Example {
public static void main(String x[]) throws Exception
{
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://192.168.1.125:8001/html/en/default/process/ProcessDesigner.jsp?wftId=81454277&wftVersion=1");
desktop.browse(oURL);
desktop.wait();
//desktop.print("");
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
Thread.sleep(20000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "jpg", new File("E:\\Akram\\SSFolder\\fi2.jpg"));
System.out.println("Done");
}
}
Here I am using the sleep function so that I should be able to capture snapshot after screen gets loaded, but some web pages may take longer to load.
So I want confirmation that the web page is ready / loaded completely so that I can take its snapshot.
How can I achieve this?

Related

ORA-29532: Java call terminated by uncaught Java exception: java.awt.HeadlessException

i execute java class to screenshot of my screen with following code:
import java.awt.AWTException;
import java.awt.FlowLayout;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FullScreenCapture extends JFrame {
private static final long serialVersionUID = 1L;
public static String capture() {
FullScreenCapture f = new FullScreenCapture();
String Ret;
try {
Thread.sleep(5000);
System.setProperty("java.awt.headless", "true");
Robot robot = new Robot();
String fileName = "D://FullScreenshot.jpg";
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit()
.getScreenSize());
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
System.out.println("Headless mode: " + ge.isHeadless());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, "jpg", new File(fileName));
Ret ="Capture Saved Successfully";
} catch (Exception e) {
System.out.println("Exception occurred");
Ret ="Wrong Error";
}
return Ret;
}
}
the program don't have any problems when executed in netbeans or in cmd,
but when load java of java class into oracle database
to call it as function,return error message java.awt.HeadlessException
You are using java.awt.Robot which needs a graphical, non-headless environment to work. As per Robot() javadoc:
AWTException - if the platform configuration does not allow low-level input control. This exception is always thrown when GraphicsEnvironment.isHeadless() returns true
The Oracle database server doesn't provide a graphical environment so it can't run your code. As per User Interfaces on the Server Oracle docs:
Oracle Database furnishes all core Java class libraries on the server, including those associated with presentation of the user interfaces. However, it is inappropriate for code running on the server to attempt to materialize or display a user interface on the server. Users running applications in Oracle JVM environment should not be expected nor allowed to interact with or depend on the display and input hardware of the server where Oracle Database is running.

Android's BitmapFactory returns corrupted image

I am participating in a project where we build an app which solves Rubiks' cubes. Initially we started with a desktop app using JavaFX but we decided to switch over to an Android app.
Since I already implemented a working model at least for color recognition, I wanted to reuse that and just build another UI around it. That is where I am stuck right now because I cannot even get Android's bitmap API to work. Unfortunately it looks like I need to stick with it since Swing/AWT/JavaFX image libraries are not available.
So I implemented a JUnit test which I cleaned up a bit:
package de.uniks.rubiksapp;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
#RunWith(RobolectricTestRunner.class)
public class TestBitmap {
#Test
public void testBitmap() {
Resources resources = RuntimeEnvironment.application.getResources();
InputStream testImageStream = resources.openRawResource(R.drawable.test_front);
Bitmap testImageBitmap = BitmapFactory.decodeStream(testImageStream);
//Bitmap testImageBitmap = BitmapFactory.decodeResource(resources, R.drawable.test_front);
// --- Pixel readout would be here --- //
System.out.println(testImageBitmap.getWidth() + "x" + testImageBitmap.getHeight() + "px");
FileOutputStream out = null;
try {
out = new FileOutputStream("test.png");
testImageBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
My problem currently is that the bitmaps I get from BitmapFactory seem to be corrupted. When I am trying to read specific pixels using Bitmap.getPixel(), they are always black. So I tried saving the image back to disk which works but the resulting files are only around 40 bytes large and cannot be opened.
Initially, I tried using Bitmap.decodeResource() instead of Bitmap.decodeStream() but that always returns images with a size of 100x100px, although my source images are 1240x800px large. Even when I use Bitmap.Options and set inScaled = false. At least the size is correct when using Bitmap.decodeStream().
Thanks for any help!

How do I open multiple tabs in IE instead of multiple windows using Selenium

I am using selenium Java. I need to open Multiple tabs and open different URL's in the newly opened tab. I am try to using getWindowHandles(), It is not working for Internet Explorer. Please suggest the proper solution for this.
Here is the code I have used:
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class Multiple
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.ie.driver","C:\\Selenium\\IEDriverServer.exe");
WebDriver d = new InternetExplorerDriver();
d.get("https://www.google.co.in/");
d.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
d.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
//d.switchTo().window(d.getWindowHandles().iterator().next());
ArrayList<String> tabs2 = new ArrayList<String> (d.getWindowHandles());
d.switchTo().window(tabs2.get(1));
d.get("https://www.facebook.com/login");
}
}
Using above code I'm able to open new tab but second URL is not entering.
Can any one give me the perfect solution for this?

Swing component add to ScrollPane(JavaFX)

I'm making JavaFX application which will open pdf files. I found free library for PDF Viewer but it's made in Swing. So I need to add JPanel to ScrollPane(JavaFX). I tried but without success.
I got this error:
Aug 13, 2016 9:59:09 PM org.icepdf.core.pobjects.Document
WARNING: PDF write support was not found on the class path.
I found here on stackoverflow how to add swing component to javafx pane and I do that but I got this error.
Any suggestion is welcome.
package application;
import java.awt.Component;
import java.io.File;
import java.net.MalformedURLException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.icepdf.ri.common.ComponentKeyBinding;
import org.icepdf.ri.common.SwingController;
import org.icepdf.ri.common.SwingViewBuilder;
import javafx.embed.swing.SwingNode;
import javafx.scene.Node;
import javafx.scene.layout.Pane;
public class PDFView{
public JPanel viewerComponentPanel;
public static Node showPDF(File sFiles) throws MalformedURLException {
String filePath = sFiles.toURI().toURL().toString();
// build a controller
SwingController controller = new SwingController();
// Build a SwingViewFactory configured with the controller
SwingViewBuilder factory = new SwingViewBuilder(controller);
// Use the factory to build a JPanel that is pre-configured
//with a complete, active Viewer UI.
JPanel viewerComponentPanel = factory.buildViewerPanel();
// add copy keyboard command
ComponentKeyBinding.install(controller, viewerComponentPanel);
// add interactive mouse link annotation support via callback
controller.getDocumentViewController().setAnnotationCallback(
new org.icepdf.ri.common.MyAnnotationCallback(
controller.getDocumentViewController()));
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode, viewerComponentPanel);
// Open a PDF document to view
controller.openDocument(filePath);
return swingNode;
}
private static void createAndSetSwingContent(final SwingNode swingNode, JPanel viewerComponentPanel) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(viewerComponentPanel);
}
});
}
}
This is main class where I call the method from PDFView class
for(int i=0;i<fileNumber;i++){
choosedName=sFiles[i].getName();
String ext=choosedName.substring(choosedName.lastIndexOf(".") + 1);
switch (ext) {
case "doc":
break;
case "docx":
break;
case "pdf":
tab = new Tab();
tab.setText(choosedName);
s1=new ScrollPane();
tab.setContent(s1);
s1.setContent(PDFView.showPDF(sFiles[i]));
tpane.getTabs().add(tab);
I downloaded icepdf viewer and core jars.
and a minimal change in your code:
//String filePath = sFiles.toURI().toURL().toString();
String filePath = sFiles.getAbsolutePath();
then, it worked for me, hope also works for you...

Java RestFul server - Getting images from web pages folder?

How do I get the images I stored in my web pages folder out so I can read them into a buffered image?
I found many explanations online on how it works but it's so confusing!
Maybe someone could help me by explaining it to me in a scenario familiar to me?
This is my server folder tree:
I want to read PNG pictures from images in Web Pages from within my ItemStorage class.
Here's what that class looks like:
import java.util.ArrayList;
import java.util.List;
import be.pxl.minecraft.model.Item;
import com.sun.jersey.spi.resource.Singleton;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
#Singleton
public class ItemStorage {
private ImageStorage test;
private HashMap<String, Image> categories;
private HashMap<String, BufferedImage> images;
private List<Item> recipesList;
public ItemStorage() {
File directory = new File("/images");
if (directory.isDirectory()) { //FILE PATH NOT A DIRECTORY
BufferedImage img = null;
for (File f : directory.listFiles()) {
try {
img = ImageIO.read(f);
images.put(f.getName(), img);
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
}
}
}
recipesList = new ArrayList<Item>();
//BufferedImage air = getImage("air"); //TRIED DIFFERENT APPROACH, SEE getImage()
//Armor
recipesList.add(new Item(7, 2, getImage("diamond_boots"), "Boots (Diamond)",
"0,0,0,1,0,1,1,0,1", String.format("%d,%d", getImage("air"), R.drawable.diamond_ingot )));
}
public void setItems(List<Item> list) {
recipesList = list;
}
public List<Item> getItems() {
return recipesList;
}
#Path("/images")
#Produces("image/png")
public Response getImage(String imageName) { //TRYING TO HTTP TO THE IMAGE
BufferedImage img = null;
try {
File imageFile = new File(imageName + ".png");
img = ImageIO.read(imageFile);
return Response.ok(img).build();
} catch (IOException ex) {
Logger.getLogger(ItemStorage.class.getName()).log(Level.SEVERE, "Error loading image", ex);
} finally {
return Response.ok(img).build();
}
}
}
As you can see, I tried to call the images both through HTTP and a simple IO directory.
This is a restful server running under tomcat 7.0.41.0
Please collaborate.
what puzzles me with your approach is, that you access a file from within your service, that is supposed to be located at the "root" ("/") directory. This is not inside your application.
In the rest service, there is no "context", as you have it in the servlet world. You need to identify the images folder somehow using a config option. You can also check the documentation of your REST server to see how to access the MessageContext and HTTPRequest. Then you can use them to access your web-application's runtime folder and access the images.

Categories

Resources