Java built program stopped showing select printer dialog - java

I have a Java program that is built, and is running as a standalone .Jar file. The last build was in start November, and it, along with the previous builds, have been running smoothly.
The function that has stopped working, is where the user wishes to print a receipt, and the program used to show a "Select printer" dialog screen.
But as of today, when the button that runs this function is clicked, nothing happens. The button click effects runs as they should, so the click is registered, but nothing else happens.
I have tried running the .jar file on both my own, and the users computer with same negative result.
However, when i run the project in IntelliJ, and click the button, everything works as it should, with no exceptions or warinings anywhere. I then tried rebuilding it using this very same code. But again, as a separate .jar file, nothing happens. The user, used the very same function as intended just 2 days ago, with the same .jar file that is not working now.
Edit: Opening the jar file in the commandwindow gives a NullPointerException at the line mentioned below.
A remote debug gives this explanation of the object beleived to cause the exception:
JavaFX PrinterJob Printer Microsoft Print to PDF
Collation = UNCOLLATED
Copies = 1
Sides = ONE_SIDED
JobName = JavaFX Print Job
Page ranges = null
Print color = COLOR
Print quality = NORMAL
Print resolution = Feed res=600dpi. Cross Feed res=600dpi.
Paper source = Paper source : Automatic
Page layout = Paper=Paper: A4 size=210.0x297.0 MM Orient=PORTRAIT leftMargin=54.0 rightMargin=54.0 topMargin=54.0 bottomMargin=54.0
Job Status = NOT_STARTED
public class PrintPage {
public void printSetup(Node node, PageOrientation or)
//The class where it prompts for the printer to be used.
{
Stage stage = new Stage();
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null) {
//Line below gives NullPointerException at the job.showPrintDialog(stage) item
if (job.showPrintDialog(stage)) print(job, node, or);
}
stage.close();
}
The errorstack leads from the line above to this part in the javafx PrinterJob class.
public synchronized boolean showPrintDialog(Window owner) {
// TBD handle owner
if (!isJobNew()) {
return false;
} else {
//This line is the next in the stack
return jobImpl.showPrintDialog(owner);
}
}
which leads to an error in:
com.sun.prism.j2d.print.J2DPrinterJob.showPrintDialog(J2DPrinterJob.java:161)
The only null item i see is the Page Ranges, which i can't seem to set.

Related

How to use applescript to close upload dialog window from chromedriver instance?

I have a selenium test (selenide to be precise) where the scenario requires a file upload.
The element to which I'm uploading the file is a hidden input field which is located at the end of DOM;
<input type="file" style="height: 0; width: 0; visibility: hidden;" tabindex="-1" accept="*">
and appears only after clicking on the area where the file is supposed to be "drag&dropped" or loaded from the system;
<a class="browse" ref="fileBrowse" href="#">select files...</a>
that means I am unable to use any method I've known until now without the need to click the element first - e.g., sendKeys, uploadFile, uploadFromClassPath, etc. However, the moment I click the element, a dialog window appears. After loading the file, the window won't close and I have yet to find a robust solution to close that window.
Situation how the dialog window looks within the macOS and chrome setup
I am using macOS and chrome, which means I cannot use "autoIT", and I was not able to run "sikuliX" either to create a simple screenshot script.
I was able, however, to scramble up an applescript using Automator which worked fine provided we omit the web driver's instance existence. Meaning; if I run the script from the console, setting the website exactly as the automated test would find it - it works... Unfortunately, it does not work once the test instantiates and runs within the webdriver.
I have two questions I hope someone with more experience could answer:
1) How to make the applescript use the webdriver's instance and not the regular chrome window - should this be solved somehow, it's a pretty neat solution
2) Any other idea on how to close the upload dialog window?
The applescript
on run {input, parameters}
-- Click “Google Chrome” in the Dock.
delay 6.006100
set timeoutSeconds to 2.000000
set uiScript to "click UI Element \"Google Chrome\" of list 1 of application process \"Dock\""
my doWithTimeout( uiScript, timeoutSeconds )
return input
-- Click the ÒCancelÓ button.
delay 3.763318
set timeoutSeconds to 2.0
set uiScript to "click UI Element \"Cancel\" of sheet 1 of window \"PowerFLOW portal - Google Chrome\" of application process \"Chrome\""
my doWithTimeout(uiScript, timeoutSeconds)
return input
end run
on doWithTimeout(uiScript, timeoutSeconds)
set endDate to (current date) + timeoutSeconds
repeat
try
run script "tell application \"System Events\"
" & uiScript & "
end tell"
exit repeat
on error errorMessage
if ((current date) > endDate) then
error "Can not " & uiScript
end if
end try
end repeat
end doWithTimeout
the code used to run the script within the test
try {
new ProcessBuilder("/path/to/the/script").start();
} catch (IOException e) {
e.printStackTrace();
}
}
Besides trying to use the applescript, I've tried "java robot class" but I wasn't able to close the dialog window.
Using the snippet below, the uncommented part escapes the entire chrome window (the window goes "grey"/inactive) and not the dialog window, which honestly surprised me, as I have thought the dialog window was the main working window at that moment.
The part that is commented works, but as you can imagine, it is useless, should the test be run on any other machine as the coordinates are specific to my machine only.
try {
Robot robot = new Robot();
//robot.mouseMove(906, 526);
//robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
//robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
} catch (AWTException e) {
e.printStackTrace();
}
The method itself looks just about like this
$$x("#ElementsCollection")
.findBy("text1")
.scrollIntoView(true)
.find(byXpath("#xpath")).val("text2")
.find(byXpath("#xpath") //this is the location of the <a> element mentioned above that needs to be clicked in order for <input type file> element to appear
.click();
$x("//input[#type=\"file\"]").sendKeys("/path/to/the/uploadedFile");
As I see, the original complexity on the way to achieve the goal is
the file is a hidden input field
and appears only after clicking on the area where the file is supposed to be "drag&dropped" or loaded from the system;
I.e. – the hidden file. Correct me if am wrong:)
But this should not be the problem, because the Selenium WebDriver's sendKeys command works with hidden elements of input tag with type=file. So just simple sendKeys should pass. The Selenide's uploadFromClassPath command is based on the original sendKeys - so it should pass too.
Here is a simple test that shows that uploading file does not depend on visibility of input element:
import org.junit.jupiter.api.Test;
import static com.codeborne.selenide.Condition.hidden;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Selenide.*;
import static com.codeborne.selenide.Selenide.$;
public class TheInternetTest {
#Test
void fileUpload() {
// GIVEN
open("https://the-internet.herokuapp.com/upload");
executeJavaScript(
"document.getElementById('file-upload').style.display = 'none'"
);
$("#file-upload").shouldBe(hidden);
// WHEN
$("#file-upload").uploadFromClasspath("temp.txt");
$("#file-submit").click();
// THEN
$("#uploaded-files").shouldHave(text("temp.txt"));
}
}
Check the full working project with this code here: https://github.com/yashaka/selenide-file-upload-demo/blob/main/src/test/java/TheInternetTest.java
P.S.
The common best practice when writing Web UI Tests is "find the simple way to reach the goal instead of the best way in context of real user simulation". That's why we try to bypass all windows that are out of control for application under test. So my recommendation would be - forget apple script, and work with the input file directly through selenium webdriver.

Eclipse Plugin: Get editor state information

i have the following problem and am grateful for any help.
I start a batch processing for a file in my plugin and unfortunately I have to make sure that the file is closed in the text editor.
I also have to make sure that other editor references for the same file are closed.
Examples:
"Menu => Window => new Window
"Menu => Editor => Toggle Split Horizontal/Vertical and Clone.
This I have also hopefully managed to do
Here's my code:
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage page = window.getActivePage();
IEditorReference[] editorReferences = page.getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
String name = editorReference.getName();
IEditorPart editorPart = editorReference.getEditor(false);
if (editorPart instanceof ITextEditor && name != null) {
// Here I note down various attributes, e.g. split
if (name.equals(memberName)) {
MPart mPart = editorPart.getSite().getService(MPart.class);
if (mPart != null) {
List<String> tags = mPart.getTags();
if (tags.contains(IPresentationEngine.SPLIT_HORIZONTAL)) {
openConfiguration.setSplitHorizontal();
} else if (tags.contains(IPresentationEngine.SPLIT_VERTICAL)) {
openConfiguration.setSplitVertical();
}
}
... // another attributes
// close Editor
page.closeEditor(editorPart, false);
}
}
}
}
Now I have the problem that the file is restored in the same state after the batch processing is finished. For example, if the user has done a "horizontal split" or a "clone" on the previously closed file, this should now be displayed exactly as before. When splitting, for example, also with the same ratio as before.
My solution is that I remember the relevant data before (when closing, see code above) and set it again after opening.
Question: Is this the right approach or is there a more elegant way?
Question: How do I determine the ratio for a split?
Question: How do I recognize a clone reference? ("Menu => Editor => Clone")
The plugin must run in an RCA that is still based on Eclipse 4.8 and supports the Eclipse 3.x API.

Tool is delaying output in eclipse plugin developemnt

I am developing plugin for eclipse. It will run my clang tool. In clang tool i am writing simple pass to check that every case and default statement must have the break statement.
I am running my clang tool using process builder.
I am using job API to run my tool and Display class to print the error.
when i run my plugin i am facing some issue.
Let say i commented my break statement of one of the case or default statement , it should print error in console that every case and default statement must have the break statement.
it is printing error after i type something else or some space or trying to uncomment after my comment .
similarly when i do uncomment , it should not print the error , but it is printing , but again when i type something or some space or trying to comment , error disappear.
following is the link of my code
https://github.com/sunilsarode/eclipse_plugin/blob/master/ccchecker/src/ccchecker/handlers/SampleHandler.java
following image show the first case not printing error on my eclipse console on which i am developing a plugin .
and this shows that second case printing error on my eclipse console on which i am developing a plugin .
any help in this ?
EDIT:
I want my plugin-in to output something on console view (not on development console ) or some dot kind of thing on the gutter of the text editor and when i click or hover on that dot , i want to show some popup with error message.
I tried to print message on console view by crating console using this link https://wiki.eclipse.org/FAQ_How_do_I_write_to_the_console_from_a_plug-in%3F
it works , but new problem is , i lost focus from text editor to console that i have created and because of this i am unable to test the problem i mentioned in question.
sorry too much i am expecting.
Following image show that text editor lost its focus to console view and the button you have mentioned is not there at console view but it is there at console of eclipse on which i am writing a code.
Following keypress method and addKeyListener is not working when i press the Ctrl+s. In order to get the save event we have to use the ICommandService with save command.
((StyledText) editor.getAdapter(Control.class)).addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent keyEvent) {
if (((keyEvent.stateMask & SWT.CTRL) == SWT.CTRL) && (keyEvent.keyCode == 's')) {
// System.out.println("From Display I am the Key down !!" + keyEvent.keyCode);
Job job = new Job("My job") {
#Override
protected IStatus run(IProgressMonitor arg0) {
// TODO Auto-generated method stub
StringBuilder builder = runCCChecker(path);
syncWithUi(builder);
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
}
});
In order to show the warning at each line I am using IMarker interface.
In order to run my tool only on current active file of eclipse editor on which I am firing save command , I am using IPartService service.
following is the link of my code
https://github.com/sunilsarode/eclipse_plugin/blob/master/ccchecker/src/ccchecker/handlers/SampleHandler.java
It is working fine. If anybody find any issue please let me know.

java PrinterDialog seemingly fails on Windows while working on Mac

I am writing a small java app to control the order process for a friend.
I am using the PrinterDialog construct to call the system printers and it seems to work pretty well on my Mac under development. However when I try the same code on a Windows machine the code will not open the system printer dialogue. There is no obvious "code failure", just nothing happens. I have tried copying the Jar file to windows and also re-compiling the project on NetBeans within Windows and neither seems to make any difference. There was a thread similar to this a year or two back but the writer seemed to imply simply re-building the project on a Windows machine had solved the problem when, for me, it seems to make no difference.
Any comments or pointers to get the app to work on Windows would be gratefully received.
The code in question is:-
private void actionPrint(ActionEvent event) {
try {
Stage printStage = new Stage();
FXMLLoader ploader = new FXMLLoader(getClass().getResource("OrderDocument.fxml"));
Node orderNode = (Node) ploader.load();
Group printerNode = new Group();
printerNode.getChildren().add(orderNode);
Scene printScene = new Scene(printerNode, 620, 875);
printStage.setScene(printScene);
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
PrinterJob job = PrinterJob.createPrinterJob();
job.showPrintDialog(printStage);
if (job != null) {
boolean success = job.printPage(pageLayout,printerNode);
if (success) {
job.endJob();
}
}
} catch (IOException ex) {
Logger.getLogger(OrderCreateController.class.getName()).log(Level.SEVERE, null, ex);
}
}
The line calling "showPrintDialog" has as its owner the stage on which I built the order document.
However re-reading the usage of "showPrintDialog" I now think it should refer to my main stage and when I effected this change the code worked on both Windows and Mac.
I am a little puzzled as to why the above code did work on Mac in the first place and this rather blinded me to finding it as a solution on Windows, so if anyone has any thoughts on that I will leave this open for a few days.

How to give focus to default program of shell-opened file, from Java?

From within Java, I am opening an Excel file with the default file handler (MS Excel, in this case :-) ) using the method described in this stackoverflow question:
Desktop dt = Desktop.getDesktop();
dt.open(new File(filename));
However, the Excel program doesn't get the focus. Is there any easy way to do so?
Edit: There is a related stackoverflow question for C#, but I didn't find any similar Java method.
Edit 2: I've did some simple tests, and discovered that Excel starts and gets the focus whenever no instance of Excel is running. When Excel is already open en NOT minimized, the application doesn't get the focus. If instead the Excel Windows was minimized, the above code will trigger a maximization of the window and Excel getting the focus (or vice versa :-) ).
If you only care about Windows (implied in the question), you can change the way you invoke Excel: use "cmd start...".
I have been using this piece of code to launch Windows applications for some time now. Works every time. It relies on the file association in Windows to find the application. The launched application becomes the focused window on the desktop.
In your case, Excel should be associated with .xls, .csv and other typical extensions. If it is, Windows will launch Excel, passing your file to it.
Usage:
MyUtilClass.startApplication( "c:\\mydir\\myfile.csv", "my window title" );
file is the full path to the input file for Excel and title is the window title (the application may or may not take it - Excel changes the window title).
public static void startApplication( String file, String title )
{
try
{
Runtime.getRuntime().exec( new String[] { "cmd", "/c", "start", title, file } );
}
catch( Exception e )
{
System.out.println( e.getMessage() );
}
}
From a scala-program, which runs in the JVM too, I can open an application, and that get's the focus by default. (Tested with xUbuntu, which is a kind of Linux).
import java.awt.Desktop
val dt = Desktop.getDesktop ();
dt.open (new java.io.File ("euler166.svg"));
I can't say, whether this is specific for Linux, or maybe something else - however starting Inkscape in my example, excel in yours, may take a few seconds, while the user impatiently clicks in the javaprogram again, thereby claiming the cursor back. Did you check for that?
You could then change to the last application, at least on Linux and Windows with ALT-Tab aka Meta-Tab (again shown in scala code, which you can easily transform to javacode, I'm sure):
import java.awt.Robot
import java.awt.event._
val rob = new Robot ()
rob.keyPress (KeyEvent.VK_META)
rob.keyPress (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_TAB)
rob.keyRelease (KeyEvent.VK_META)
but unfortunately the unknown source off more trouble, also known as user, might do nothing, so switching would be the false thing to do. Maybe with a thread, which checks for a certain amount of time, whether the java-program has the focus, but it keeps a form of roulette, in an interactional environment, because the user may have a fast or slow machine, or change to a third application meanwhile, and so on. Maybe a hint before triggering the new app is the best you can do?

Categories

Resources