I'm working on a java Applet which has a document loaded. On this Applet I have a custom "print" button which basically inits the print process of the document. This is the code that is executed after this button is pressed:
PropertyValue[] printProperties = new PropertyValue[1];
printProperties[0] = new PropertyValue();
printProperties[0].Name = "Print";
printProperties[0].Value = new Boolean(true);
xDispatchProvider = (XDispatchProvider)UnoRuntime.queryInterface (XDispatchProvider.class, xFrame);
dispatcher.executeDispatch(xDispatchProvider, ".uno:Print","_self", 0, printProperties);
someOtherProcess();
This code opens the native(?) print dialog which is the expected behaviour, and works so far. The problem is the "someOtherProcess" method. I need to execute this method right after the print dialog is closed either by pressing its "print" button or canceling/closing the print dialog.
Since executeDispatch is async I tried to make it synchronous using the "SynchronMode" in the PropertyValue[] with no success.
I found a way to listen to print events which are fired when the print process starts or when it's cancelled. This is the whole code:
PropertyValue[] printProperties = new PropertyValue[1];
printProperties[0] = new PropertyValue();
printProperties[0].Name = "Print";
printProperties[0].Value = new Boolean(true);
xDispatchProvider = (XDispatchProvider)UnoRuntime.queryInterface (XDispatchProvider.class, xFrame);
dispatcher.executeDispatch(xDispatchProvider, ".uno:Print","_self", 0, printProperties);
XPrintJobBroadcaster xPrintJobBroadcaster = (XPrintJobBroadcaster)UnoRuntime.queryInterface(XPrintJobBroadcaster.class, xComponent);
xPrintJobBroadcaster.addPrintJobListener(new MyPrintJobListener());
class MyPrintJobListener implements XPrintJobListener {
public void printJobEvent(PrintJobEvent printJobEvent) {
AppletLogger.log("printing");
}
public void disposing(com.sun.star.lang.EventObject eventObject) {
AppletLogger.log("disposing");
}
}
The "printJobEvent" is fired when the print process has either started, finished, cancelled and so on, but I can't find a way to know if the print dialog has been cancelled or closed as this doesn't fire any print event.
So my main questions are, is there a way to open a print dialog in a synchronous way so that the programs waits for the print dialog to close?
Is there a way to listen to the close event of the native print dialog window?
Thanks in advance!
Check the State property. If printing is cancelled, it should first show JOB_STARTED (which is 0) and then JOB_ABORTED (which is 3).
class MyPrintJobListener implements XPrintJobListener {
public void printJobEvent(PrintJobEvent printJobEvent) {
AppletLogger.log("print status: " + printJobEvent.State.getValue());
}
public void disposing(com.sun.star.lang.EventObject eventObject) {
AppletLogger.log("disposing");
}
}
Also the dispatcher didn't work for me. Use the API interface instead:
XPrintJobBroadcaster xPrintJobBroadcaster = (XPrintJobBroadcaster)
UnoRuntime.queryInterface(XPrintJobBroadcaster.class, xComponent);
xPrintJobBroadcaster.addPrintJobListener(new MyPrintJobListener());
XPrintable xPrintable =
(XPrintable)UnoRuntime.queryInterface(XPrintable.class, xComponent);
xPrintable.print(printProperties);
try { Thread.sleep(10000); } catch (Exception e) {} // Wait for print job.
Related
My problem is that in my app not show notification.
My application does that each time a button is pressed I create new thread and show notification with info that thread is running or waiting (this works fine). Then, if the thread is running, it will randomly sleep for 5-10 seconds and get data from the rest api and a notification should be displayed that the thread is finished (this notification is not displayed).
Fineshed notifications show after i press again button. As you can see in the image.
Image:
constructor view:
public MainView() {
Button ipButton = getIpButton();
setMargin(true);
setHorizontalComponentAlignment(Alignment.START, ipButton);
add(ipButton);
}
button:
private Button getIpButton() {
final UI ui = UI.getCurrent();
final VaadinSession session = VaadinSession.getCurrent();
Button ipButton = new Button("My IP");
AtomicInteger orderIndex = new AtomicInteger();
ipButton.addClickListener(_e -> {
int orderThread = orderIndex.getAndIncrement();
openBeginNotification(orderThread);
executor.submit(() -> {
try {
UI.setCurrent(ui);
VaadinSession.setCurrent(session);
long sleepTime = (long) (Math.random() * (10 - 5) + 5);
System.out.printf("%d: %ds\n", orderThread, sleepTime);
Thread.sleep(sleepTime * 1000);
IpDTO ip = restTemplate.getForObject("http://ip.jsontest.com/", IpDTO.class);
System.out.printf("%d: %s\n", orderThread, ip);
try {
VaadinSession.getCurrent().lock();
getFinishNotification(orderThread).open(); // here not show notification
VaadinSession.getCurrent().unlock();
} catch (Exception e) {
e.printStackTrace();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
});
return ipButton;
}
notification methods:
private void openBeginNotification(int orderThread) {
Notification notification;
if (executor.getActiveCount() == MAX_THREADS) {
// thread is in front
notification = getWaitNotification(orderThread);
} else {
// thread run
notification = getRunNotification(orderThread);
}
notification.open();
}
private Notification getRunNotification(int orderThread) {
return getNotification("Task " + orderThread + ": run", NotificationVariant.LUMO_PRIMARY);
}
private Notification getWaitNotification(int orderThread) {
return getNotification("Task " + orderThread + ": wait", NotificationVariant.LUMO_CONTRAST);
}
private Notification getFinishNotification(int orderThread) {
return getNotification("Task " + orderThread + ": finish", NotificationVariant.LUMO_SUCCESS);
}
private Notification getNotification(String notificationText, NotificationVariant variant) {
Notification notification = new Notification(notificationText, 1000);
notification.addThemeVariants(variant);
return notification;
}
First, you need to enable #Push to make Vaadin open a websocket connection that makes it possible for the server to directly send messages to the browser without waiting for the browser to send a message asking for changes (which happens when you click a button). The #Push annotation should be in different location depending on the Vaadin version you're using, so please refer to documentation to find the right place.
Second, please use UI::access instead of manually doing setCurrent and locking. While I didn't spot anything in your example that would break the happy case, there are still also a whole bunch of edge cases that you'd need to take into account. As an example, you're not cleaning up after setCurrent which might cause memory leaks and you're not unlocking in case something related to the notification throws an exception.
I was trying to add a Progress Monitor for a Wizard Dialog in Eclipse in Java using SWT, but I'm getting an unusual error with no message at all. Here is my code:
This is the class I made for displaying the progress monitor:
public class OpenWizardsAction implements IRunnableWithProgress{
private WizardDialog dialog;
private String monitorMessage;
public OpenWizardsAction(WizardDialog dialog,String monitorMessage)
{
this.dialog=dialog;
this.monitorMessage=monitorMessage;
}
#Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
{
// Tell the user what you are doing
monitor.beginTask(monitorMessage, IProgressMonitor.UNKNOWN);
// Do your work
if(Window.OK==dialog.open()) {}
// You are done
monitor.done();
}
}
And this is where I call this class:
WizardDialog dialog;
dialog = new WizardDialog(Display.getDefault().getActiveShell(), new RunWizard(runSum,runTable));
try {
IRunnableWithProgress op = new OpenWizardsAction(dialog,"Opening Run Wizard");
new ProgressMonitorDialog(Display.getDefault().getActiveShell()).run(true, true, op);
} catch (Exception e) {
MessageDialog.openError(Display.getDefault().getActiveShell(), "Unable to open Run Wizard", e.getMessage());
}
The MessageDialog.openError call shows empty message i.e. e.getMessage() is empty.
Is it because I'm using the same Display and Shell for both Wizard and ProgressMonitorDialog?
I also tried adding the below line in place of line 5 in the second code segment:
new ProgressMonitorDialog(new Shell(Display.getDefault(),SWT.NONE)).run(true, true, op);
Still there was error with an empty message.
I have this JavaFx app when I press one of the buttons, an other javafx class lauch!
so all what i need to know is : when I press the back button of the seconde class I need to find the first window with the same values entred in the bigging !
here what I can do for now:
Platform.runLater(new Runnable() {
#Override
public void run() {
try {
new MainApp().start(stage);
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
log.error(errors.toString());
}
}
});
I had the same problem and here is the solution:
let's suppose you have those 2 TextField one of them called apiurl and other called mainUrl ! all what you have to do is to to create String url = ""; and go to your button action and add this line : url=apiurl.getText(); in the initialize method in your controller add this : apiurl.setText(url); and this worked well for me !
I have written a piece of software that requires me to open and close an executable jar file.
At the moment I have the code able to open the jar with specific arguments
(I have used notepad in the code example as I do not have the Jar file or my original code on me, and needed to test what I had written for this example worked)
The issue I have is when I open and close notepad I get the correct behaviour, however when I try to close my JAR file I am not getting a response.
I have tried killing by the process name under task manager - go to details, the app name, and variants of java, java.exe, javaw etc.
Is it something to do with having launched the jar through CMD?
in which case I have another issue because I have several processes with the exact same name and am not sure how to get the ID when the name is the same.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// Click on the link below to continue learning how to build a desktop app using WinForms!
System.Diagnostics.Process.Start("http://aka.ms/dotnet-get-started-desktop");
}
//string jarFile = "/JarLocation";
//string jsonlocation = "/jsonlocation";
//string command = $"java - jar {jarfile} -qsArgs {jsonLocation}";
string command = "Notepad";
string processName = "Notepad";
List<int> processIDs = new List<int>();
int[] processID;
Thread testThread;
ThreadStart ts;
private void RunButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Running!");
// METHOD 1 // Launch through CMD directly (in a new thread and try to terminate by process name)
/*
new Thread(() =>
{
LaunchClient();
}).Start();
*/
// METHOD 2 // Generate
/*
foreach (int ID in processIDs)
{
Console.WriteLine($"Process {ID} Created");
}
*/
//Method 3
/*
testThread = new Thread(new ThreadStart(LaunchClient()));
//testThread.Start();
*/
// Method 4
ts = delegate { LaunchClient(); };
}
private void KillButton_Click(object sender, EventArgs e)
{
MessageBox.Show("Killing!");
try
{
// Method 1
Process[] ProcList = Process.GetProcessesByName(processName);
foreach (Process targetProc in ProcList)
{
targetProc.CloseMainWindow();
}
// Method 2
/*
foreach (int ID in processIDs)
{
Process killMe = Process.GetProcessById(ID);
killMe.CloseMainWindow();
}
*/
// Method 3
//testThread.Abort();
//Method 4
//ts.EndInvoke();
}
catch (Exception f)
{
Console.WriteLine("f.StackTrace");
}
}
public void LaunchClient()
{
Thread.CurrentThread.IsBackground = false;
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardInput = true;
//proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.StandardInput.WriteLine(command);
proc.StandardInput.Flush();
Console.WriteLine($"PROCESS ID: {proc.Id}");
processIDs.Add(proc.Id);
//proc.StandardInput.Close();
proc.WaitForExit();
}
}
Sorry to dump a large swathe of code but I thought seeing my implementation of the opening as well as the close would help.
EDIT:
Updated the code sample given to show the 4 different ways I have tried to handle this.
Method 1:
Closing process by name (works for notepad, but not my jar)
2: Trying to pass the process ID back and use that to close the process
(Cant see the ID outside of the thread running the cmd window)
3: using new threadstart (launchclient says 'method name expected')
4: Doesn't open Notepad at all.
If your JAR file is opened with your code, an useful technique is to listen for windowClosing, which happens when the user clicks the X button on Windows (and the equivalent on other systems):
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
How to define that inline button is pressed and how to get callbackdata using pengrad/telegram-bot-api library? I have this code to send message with inline keyboard button
private void approveAdmin(User u){
User admin = userService.findByUserRole("ROLE_ADMIN");
SendMessage sm = new SendMessage(admin.getChatId(),
"Do you approve user: "+u.getfName()+" "+u.getlName()+" as admin?");
sm.replyMarkup(new InlineKeyboardMarkup(new InlineKeyboardButton[]
{new InlineKeyboardButton("Approve user.").callbackData(u.getIdUser().toString())}));
BOT.execute(sm);
}
but how to handle update from inline button?
below snippet may helps you:
GetUpdatesResponse updatesResponse = bot.execute(new GetUpdates());
List<Update> updates = updatesResponse.updates();
for (Update update : updates) {
CallbackQuery callbackQuery = update.callbackQuery();
if (callbackQuery != null) {
//use the callbackQuery object peroperties to provide the appropriate response
}
//to make the update handler fully functional, make sure to check other types of messages
}