So I need to run a Debian(.deb) file at some point in my JavaFX program and so I tried using the code below on Linux
Runtime.getRuntime().exec("sudo dpkg -i "+pathToResource.getValue().toString());
but as you already know that requires me to also pass in the password along somehow for this to work
on Windows I used this sample code here
Runtime.getRuntime().exec(pathToResource.getValue().toString());
and it whenever administrator privilleges are needed then the software will just request them from the user and everything will run smoothly
But this doesn't seem to work on Linux, it just goes silent and nothing happens,
I already have an alternative to try to use TerminalFx, but if there's Anyone who knows what an alternative to run the .deb file or any other alternative, I'll be grateful. Thanks in Advance.
So I ended up using shellScript
Here's What I Did
Requested the device password from the user through a simple JavaFX stage with just a text field and a submit button.
Then I used the password that I just got from the user to create a shell script(Bash)
Here's my sample code to do create the sample shell Script
File shell_file = new File("path_to_the_file_where_the_shell_file_will_be_created_at_example_install.sh");
String variableName = "#!/bin/bash\npassword='" + password_from_JavaFx_stage + "'\n" +
"echo $password | sudo -S dpkg -i " + path_to_file_to_be_installed;
shell_file.createNewFile()// you can put an if to check if the function worked and otherwise do some other actions
FileWriter myWriter = new
FileWriter("path_to_the_file_where_the_shell_file_will_be_created_at_example_install.sh");
myWriter.write(messageContent);
myWriter.close();
Then Just run the command using the Processbuilder here's is a sample code to do so
String[] command = {String.valueOf(shell_file)};
ProcessBuilder processBuilder = new ProcessBuilder().command(command);
try {
Process process = processBuilder.start();
//read the output
InputStreamReader inputStreamReader = new
InputStreamReader(process.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String output = null;
while ((output = bufferedReader.readLine()) != null) {
System.out.println(output);
}
process.waitFor();
//close the resources
bufferedReader.close();
process.destroy();
}catch(IOException | InterruptedException e) {
e.printStackTrace();
}
So That's the idea and it's my best hope this will save somebody's time and helps out in one way or another.
Related
My JavaFX program prepares and prints out a set of VBoxes.
This is ModPrintCycle. It is the Window that gives the options to print
public PrintCycle data;
//PrintCycle is a HashMap of VBoxes containing all the details
PrinterJob pj;
ChoiceBox<String> cbxPrinters = new ChoiceBox<String>();
ArrayList<Printer> arrPrinters = new ArrayList<Printer>();
//util.say just pops out a messagebox attached to ModPrintCycle.
public void printAll(ArrayList<String> pageList){
if(cbxPrinters.getSelectionModel().getSelectedIndex() >=0){
if (data.tables.size() > 0){
Printer curP = Printer.getDefaultPrinter();
if(arrPrinters.size() > 0 ){
curP = arrPrinters.get(cbxPrinters.getSelectionModel().getSelectedIndex());
}
try{
pj = PrinterJob.createPrinterJob(curP);
PageLayout pp = curP.createPageLayout(Paper.LEGAL, PageOrientation.PORTRAIT, MarginType.DEFAULT);
PageLayout pl = curP.createPageLayout(Paper.LEGAL, PageOrientation.LANDSCAPE, MarginType.DEFAULT);
for(String p : pageList){
Printable pt = data.tables.get(p);
pt.scaleToFit();
if(pt.isLandscape()){
pj.printPage(pl,pt);
}
else{
pj.printPage(pp,pt);
}
}
pj.endJob();
}catch(Exception e){
util.say(ModPrintCycle.this, "Error on Print");
}
}else{
util.say(ModPrintCycle.this, "Nothing to print");
}
}
else{
util.say(ModPrintCycle.this, "No Printer Selected");
}
}
Printer is installed and set as default, and my program detects it. But when I print, no errors pop out, and the printer receives no jobs.
I'm sure my program worked before (A Lubuntu 15.10, 32-bit.). But now, I transfered it to a different computer. A Lubuntu 15.10, 64-bit. I have openjfx and openjdk version "1.8.0_66-internal" installed.
What can I do to find out why it's not printing?
Tried to make a smaller print job, but to the same effect.
Button testPrint = new Button("Test Print");
testPrint.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent arg0) {
try{
Printer p = Printer.getDefaultPrinter();
PrinterJob pj = PrinterJob.createPrinterJob(p);
//util.say(ModShortcuts.this, "Print: " + pj.getJobStatus());
Boolean k = pj.printPage(p.createPageLayout(Paper.LEGAL,PageOrientation.PORTRAIT,MarginType.DEFAULT), new Text("Hey"));
//util.password(); //reused for a showAndWait() dialog
//util.say(ModShortcuts.this, "Print: " + pj.getJobStatus());
//util.say(ModShortcuts.this, "attempted Print using: " + pj.getPrinter().getName());
if(k){
//util.say(ModShortcuts.this, "Print: " + pj.getJobStatus());
pj.endJob();
//util.say(ModShortcuts.this, "Print: " + pj.getJobStatus());
}
}catch(Exception e){
e.printStackTrace();
}
}
});
vbox.getChildren().add(testPrint);
Uncommented, the output is
Print: Not Printing
Print: Printing
attempted Print using: AstinePrinter
Print: Printing
Print: Done
AstinePrinter is the name of my printer.
Edit: Using
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer
I installed Oracle Java 8, and still the same problem.
Edit: Also Oracle Java 7.
Edit:
Tried disabling the firewall, in case it was a port problem
sudo ufw disable
Still nothing.
I've found something called CUPS4J, and it allows me to bypass the problem it had concerning Java trying to access CUPS in a 64 bit Ubuntu. It prints out using Byte arrays, and luckily, JavaFX has a way to snapshot the chosen node.
It's a little blurry, but it's good enough. NOTE: I am no expert, and I don't know why this is needed. But doing this allowed me to use CUPS4J with no errors, so it must have been correct.
So, first of all, download the [ECLIPSE PROJECT] for cups4j,
because there are dependencies that have to be fixed. Import it into your project.
EDIT: The reason why the following is needed is that somehow, my package doesn't come with org.slf4j. If your class path says you have it, skip these steps.
Next, for each class there, all instances of Logger (cAsE
sEnSiTiVe) should be replaced with Log, and fix your imports (Ctrl+Shift+O). This will suggest a version of the Log, and LogFactory will be automatically detected. My import path says org.apache.commons.logging.*
Finally, remove the library dependency for org.slf4j in your build path under Libraries.
(I'm sure using the Runnable Jar is fine, but this is what I did because using the Runnable Jar gave me errors)
This is a simplification of what I did for my print function.
private void print(Region node){
//Make the image with the proper sizes
WritableImage wi = new WritableImage(
(int) Math.round(Math.ceil(node.getWidth())),
(int) Math.round(Math.ceil(node.getHeight())));
//shoot the image
wi = node.snapshot(new SnapshotParameters(), wi);
//write the image into a readable context
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
ImageIO.write(SwingFXUtils.fromFXImage(wi, null), "png", out);
}catch(Exception e){
System.out.println("Error with SnapShot function");
}
//Get your printer
CupsClient cc = new CupsClient();
CupsPrinter cp = cc.getDefaultPrinter();
//print the readable context
cp.print(new PrintJob.Builder(out.toByteArray()).build());
//unlike PrinterJob, you do not need to end it.
}
I'm not sure, but I've seen bug reports in the CUPS4J forum saying there's a problem with multiple pages, but I have yet to encounter that.
If someone has a better answer, feel free to add. But so far, this worked for me.
I am trying send pdf file to printer using soap client from web.
Using job in ax works fine.
I'am tried: winAPI::shellExecute(adobeExe, adobeParm);
Enable AOS printing on the AOS server
http://www.artofcreation.be/2014/01/27/how-to-print-any-file-in-ax/
But does not work for me.
Maybe for someone has managed to do it?
Maybe need with ghostScript or sumatraPDF ? or...?
Thanks in advance.
#File //File macro
System.Diagnostics.ProcessStartInfo processInfo;
System.Diagnostics.Process process;
System.Exception interopException;
// Parameters
Filename fileName = #"C:\test\test.pdf";
PrinterName printername = UserPrinterHandler::getDefaultPrinter();
;
printerName = '"' + printerName + '"';
try
{
// assert permissions
new InteropPermission(InteropKind::ClrInterop).assert();
process = new System.Diagnostics.Process();
processInfo = process.get_StartInfo();
processInfo.set_UseShellExecute(true);
processInfo.set_CreateNoWindow(true);
processInfo.set_FileName(fileName);
// the argument is the printer name
processInfo.set_Arguments(printerName);
// set the verb to printto
processInfo.set_Verb('printto');
processInfo.set_WindowStyle(System.Diagnostics.ProcessWindowStyle::Hidden);
process.Start();
// revert asserted permissions
CodeAccessPermission::revertAssert();
}
Log into the server as the AOS user account and make sure the printer is added, or re-add it. Can't hurt to do it again as your user account too.
As the title suggests, WLP won't run the process- it won't return anything to the process input stream nor to error stream.
If anyone knows about a configuration that needs to take place I would love to know..
(note the process Can run by running the command manually - in addition, the whole thing runs smooth on tomcat8 so..)
EDIT 1:
The problem was not the command execution under WLP as you guys stated, so I accepted the answer.
The problem is different : I sent a media file to a multipart servlet and stored it in a file on disk using the following code:
InputStream is = request.getInputStream();
String currentTime = new Long(System.currentTimeMillis()).toString();
String fileName = PATH + currentTime + "." + fileType;
File file = new File(fileName);
// write the image to a temporary location
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
while(true) {
int numRead = is.read(buffer);
if(numRead == -1) {
break;
}
os.write(buffer, 0, numRead);
os.flush();
}
is.close();
os.close();
and the file gets saved along with the following prefix:
While this does not happen on tomcat8 (using the same client)..
something is not trivial in the received input stream. (Note its a multipart servlet that set up via #MultipartConfig only)
Hope this post will help others..
guys,thanks for your help!
This will work in Liberty. I was able to test out the following code in a servlet and it printed the path of my current directory just fine:
String line;
Process p = Runtime.getRuntime().exec("cmd /c cd");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
Start with a simple command like this, and when you move up to more complex commands or scripts, make sure you are not burying exceptions that may come back. Always at least print the stack trace!
I'm interested in knowing how I can make an HTTP call from SSIS. For example, I would like to be able to download a file from http://www.domain.com/resource.zip and record the datetime of the download and the destination of the file on the drive. I would also like to capture such attributes as file size and capture the date & time when the download completed.
You can make use of the namespace System.Net.WebClient to make the Http request with the help of Script Task in SSIS. Following example shows how this can be achieved. The example was created in SSIS 2008 R2.
Step-by-step process:
Create a new SSIS package and create two variables namely RemoteUri and LocalFolder. Set the variable RemoteUri with the value http://www.google.com/intl/en_com/images/srpr/logo1w.png. this is the image url of the logo on the Google's home page. Set the variable LocalFolder with the value C:\temp\. this is the path where we are going to save the content. Refer screenshot #1.
On the SSIS package, place a Script Task. Replace the Main() method within the script task with the code provided under the Script Task Code section. Refer screenshot #2.
Screenshot #3 shows that the path C:\temp\ is empty.
Screenshot #4 shows successful execution of the package.
Screenshot #5 shows that the content (in this case the logo image) has been downloaded to the local folder path.
Screenshot #6 shows that the code was tested to download a .zip file. To achieve this, the value of the variable RemoteUri was changed with the content url that needs to be downloaded.
Script task code:
C# code that can be used only in SSIS 2008 and above.
public void Main()
{
Variables varCollection = null;
Dts.VariableDispenser.LockForRead("User::RemoteUri");
Dts.VariableDispenser.LockForRead("User::LocalFolder");
Dts.VariableDispenser.GetVariables(ref varCollection);
System.Net.WebClient myWebClient = new System.Net.WebClient();
string webResource = varCollection["User::RemoteUri"].Value.ToString();
string fileName = varCollection["User::LocalFolder"].Value.ToString() + webResource.Substring(webResource.LastIndexOf('/') + 1);
myWebClient.DownloadFile(webResource, fileName);
Dts.TaskResult = (int)ScriptResults.Success;
}
Screenshot #1:
Screenshot #2:
Screenshot #3:
Screenshot #4:
Screenshot #5:
Screenshot #6:
Just an alternative for #user756519 script, not as fast, but more bulletproof
public void Main()
{
Variables varCollection = null;
Dts.VariableDispenser.LockForRead("User::RemoteUri");
Dts.VariableDispenser.LockForRead("User::LocalFolder");
Dts.VariableDispenser.GetVariables(ref varCollection);
System.Net.WebClient myWebClient = new System.Net.WebClient();
string webResource = varCollection["User::RemoteUri"].Value.ToString();
string fileName = varCollection["User::LocalFolder"].Value.ToString() + webResource.Substring(webResource.LastIndexOf('/') + 1);
byte[] data;
using (WebClient client = new WebClient())
{
data = client.DownloadData(webResource);
}
FileInfo file = new System.IO.FileInfo(fileName);
file.Directory.Create(); // If the directory already exists, this method does nothing.
File.WriteAllBytes(file.FullName, data);
Dts.TaskResult = (int)ScriptResults.Success;
}
This way, webClient doesn't stay hanging, and also you're not dependent on the previous existence of C:\Temp directory.
Other than that, great answer from #user756519, very detailed.
Here are a couple of options:
Third party tools such as CozyRoc or BlueSSIS.
Script Task with WebClient
Script Task with HTTP Connection Manager
Script Task Examples at:
http://microsoft-ssis.blogspot.com/2011/05/download-source-file-from-website-with.html
I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.