How can I run cygwin from Java? - java

I want to start nutch from Java. How can I start cygwin from a Java program?

First of all you have to set the bash.exe to environment variable so this line will start bash.
Runtime rt= Runtime().getRuntime().execute("bash");

Rather than use Java to start Cygwin in order to invoke nutch you should probably look into integrating Nutch directly with your Java app. There's some documentation here:
"While the Nutch web app is a great way to get started with search, most projects using Nutch require the search function to be more tightly integrated with their application. There are various ways to achieve this, depending on the application. The two ways we'll look at here are using the Nutch API and using the OpenSearch API."

If you are trying to run a binary that requires the cygwin1.dll (which includes most commands you can execute from the cygwin bash shell) then you can run it by specifying the cygwin\bin directory in the path environment variable like this:
Process p = Runtime.getRuntime().exec(
"C:/path/to/cygwin/binary.exe", new String[] { "PATH=C:\\cygwin\\bin" });
This assumes you installed cygwin in C:\cygwin

You can use any Cygwin program without passing thru Cygwin, just like any regular Windows Console Application. Take a look at the Cygwin\bin\ dir. You may even bring the programs you want to your app dir, as long as you bring a copy of CYGWIN1.DLL as well.

A more interesting, more clever thing to do, would be starting Nutch from Cygwin or using a real Linux/Unix system.

Related

Running java program on web server

I need to run a single java program (which will change the content of some text files) on my new website. What's the easiest way to do that for example using php code?
Do I need to install JVM or any other software in order for this to work?
Please guide on how to do this step by step if possible.
You have to install a Java Runtime Environment (JRE) on your server to be able to run a java program.
http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html
To execute a java program in php, you can simply use the exec() function :
exec("java -jar yourProgram.jar");
http://php.net/manual/en/function.exec.php

convert java project into windows service [duplicate]

I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.
Apache Commons Daemon is a good alternative. It has Procrun for windows services, and Jsvc for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an exhaustive article with working example.
Besides that, you may look at the bin\service.bat in Apache Tomcat to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).
Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.
I've had some luck with the Java Service Wrapper
With Apache Commons Daemon you can now have a custom executable name and icon! You can also get a custom Windows tray monitor with your own name and icon!
I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.
Download WinRun4J and use the RCEDIT.exe program that comes with it to modify the Apache executable to embed your own custom icon like this:
> RCEDIT.exe /I MyServiceName.exe customIcon.ico
> RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico
Now install your Windows service like this (see documentation for more details and options):
> MyServiceName.exe //IS//MyServiceName \
--Install="C:\path-to\MyServiceName.exe" \
--Jvm=auto --Startup=auto --StartMode=jvm \
--Classpath="C:\path-to\MyJarWithClassWithMainMethod.jar" \
--StartClass=com.mydomain.MyClassWithMainMethod
Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.
> MyServiceNamew.exe //MS//MyServiceName
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
One more option is WinRun4J. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use.
(full disclosure: I work on this project).
Yet another answer is Yet Another Java Service Wrapper, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.
Some others I found, but didn't end up using:
Java Service Launcher I didn't use this because it looked more complicated to get working than YAJSW. I don't think this is a wrapper.
JSmooth Creating Window's services isn't its primary goal, but can be done. I didn't use this because there's been no activity since 2007.
If you use Gradle Build Tool you can try my windows-service-plugin, which facilitates using of Apache Commons Daemon Procrun.
To create a java windows service application with the plugin you need to go through several simple steps.
Create a main service class with the appropriate method.
public class MyService {
public static void main(String[] args) {
String command = "start";
if (args.length > 0) {
command = args[0];
}
if ("start".equals(command)) {
// process service start function
} else {
// process service stop function
}
}
}
Include the plugin into your build.gradle file.
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0"
}
}
apply plugin: "com.github.alexeylisyutenko.windows-service-plugin"
The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:
plugins {
id "com.github.alexeylisyutenko.windows-service-plugin" version "1.1.0"
}
Configure the plugin.
windowsService {
architecture = 'amd64'
displayName = 'TestService'
description = 'Service generated with using gradle plugin'
startClass = 'MyService'
startMethod = 'main'
startParams = 'start'
stopClass = 'MyService'
stopMethod = 'main'
stopParams = 'stop'
startup = 'auto'
}
Run createWindowsService gradle task to create a windows service distribution.
That's all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.
In ${project.buildDir}/windows-service directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries.
To install the service run <project-name>-install.bat and if you want to uninstall the service run <project-name>-uninstall.bat.
To start and stop the service use <project-name>w.exe executable.
Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.
For more information, please read about the plugin and Apache Commons Daemon Procrun.
I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.
Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.
Require .NET runtime installed.
JavaService is LGPL. It is very easy and stable. Highly recommended.
With Java 8 we can handle this scenario without any external tools. javapackager tool coming with java 8 provides an option to create self contained application bundles:
-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.
The following values are valid for type:
-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.
The following values are valid for type:
all: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.
installer: Runs all of the installers for the platform on which it is running.
image: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.
dmg: Generates a DMG file for OS X.
pkg: Generates a .pkg package for OS X.
mac.appStore: Generates a package for the Mac App Store.
rpm: Generates an RPM package for Linux.
deb: Generates a Debian package for Linux.
In case of windows refer the following doc we can create msi or exe as needed.
exe: Generates a Windows .exe package.
msi: Generates a Windows Installer package.
A pretty good comparison of different solutions is available at :
http://yajsw.sourceforge.net/#mozTocId284533
Personally like launch4j
I've used JavaService before with good success. It hasn't been updated in a couple of years, but was pretty rock solid back when I used it.
I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.
I thought about writing a service in C#, but my time constraints were too tight.
I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.
I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.
it's simple as you have to put shortcut in
Windows 7
C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)
Windows 10 :
In Run shell:startup
in it's property -> shortcut -> target - > java.exe -jar D:\..\runJar.jar
NOTE: This will run only after you login
With Admin Right
sc create serviceName binpath= "java.exe -jar D:\..\runJar.jar" Will create windows service
if you get timeout use cmd /c D:\JAVA7~1\jdk1.7.0_51\bin\java.exe -jar d:\jenkins\jenkins.war but even with this you'll get timeout but in background java.exe will be started. Check in task manager
NOTE: This will run at windows logon start-up(before sign-in, Based on service 'Startup Type')
Detailed explanation of creating windows service
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the Windows 2003 resource kit. It restricts the service to a single batch file but I only need one batch script to be converted into a service.
ciao!
I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.
It's possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.
See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.
The flow of above callbacks in Java with Foreign Memory structures are:
main()
Must register ServiceMain using StartServiceCtrlDispatcherW
Above call blocks until ServiceMain exits
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
Use SetServiceStatus(SERVICE_START_PENDING)
Initialise app
Use SetServiceStatus(SERVICE_RUNNING)
wait for app shutdown notification
Use SetServiceStatus(SERVICE_STOPPED)
int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
Must respond to service control events and report back using SetServiceStatus
On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
then set app shutdown notification
Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):
sc create YourJavaServiceName type= own binpath= "c:\Program Files\Your Release Dir\yourjavaservice.exe"

Call Cygwin from Java app

I need to call Cygwin from Java code ( example : to call make command in Cygwin from Java app which run on linux and windows ).Does anybody have experience with this problem ?
I think you have to differentiate youre code for linux and windows
on linux simply execute the command
on windows lauch your command in cygwin with
C:\cygwin\bin\bash.exe --login -i -c <cmd>
note: you may use apache commons exec to lauch an external command from java
Use ProcessBuilder from Java:
http://download.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
You will need to make sure your path/environment is set up properly, but that depends on your machine and set up.
Also, note that many cygwin "capabilities" (e.g., less, awk, sed, etc) are simply binaries (executables) that you can call directly -- no need for the bash shell to facilitate access to those. Look at the actual files in wherever your bin folder is (usually c:/cygwin/bin) and try calling those directly from ProcessBuilder. If you need to actually leverage the shell (e.g., pipes, variables, globbing, etc) then that's a different story -- you would then integrate with the bash.exe file itself (check the man page for usage info).

How to check if python is installed in windows from java?

How can I check from inside a java program if python is installed in windows?
Python does not add its path to the system Path and no assumption is to be made about the probable path of installation(i.e it can be installed anywhere).
Use the Java Runtime to exec the following command "python --version".
If it works, you have Python, and the standard output is the version number.
If it doesn't work, you don't have Python.
Most Python installers add keys to the Windows registry. Here's an article about how to add that information, you can use it to see how to read the information.
Have you tried querying the registry to check if it is installed? It is stored in
software\python\pythoncore
If the user has a (relatively) new version of python, that is installed with the MSI-package, you can use the MsiEnumProducts Function to check if python is installed.
exec(String command)
Executes the specified string command in a separate process.
Check for Python from command
this would work
Process process = Runtime.getRuntime().exec("cmd /c
C:\Python27\python --version");

How to create a windows service from java app

I've just inherited a java application that needs to be installed as a service on XP and vista. It's been about 8 years since I've used windows in any form and I've never had to create a service, let alone from something like a java app (I've got a jar for the app and a single dependency jar - log4j). What is the magic necessary to make this run as a service? I've got the source, so code modifications, though preferably avoided, are possible.
Apache Commons Daemon is a good alternative. It has Procrun for windows services, and Jsvc for unix daemons. It uses less restrictive Apache license, and Apache Tomcat uses it as a part of itself to run on Windows and Linux! To get it work is a bit tricky, but there is an exhaustive article with working example.
Besides that, you may look at the bin\service.bat in Apache Tomcat to get an idea how to setup the service. In Tomcat they rename the Procrun binaries (prunsrv.exe -> tomcat6.exe, prunmgr.exe -> tomcat6w.exe).
Something I struggled with using Procrun, your start and stop methods must accept the parameters (String[] argv). For example "start(String[] argv)" and "stop(String[] argv)" would work, but "start()" and "stop()" would cause errors. If you can't modify those calls, consider making a bootstrapper class that can massage those calls to fit your needs.
I've had some luck with the Java Service Wrapper
With Apache Commons Daemon you can now have a custom executable name and icon! You can also get a custom Windows tray monitor with your own name and icon!
I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!
Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).
Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.
Download WinRun4J and use the RCEDIT.exe program that comes with it to modify the Apache executable to embed your own custom icon like this:
> RCEDIT.exe /I MyServiceName.exe customIcon.ico
> RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico
Now install your Windows service like this (see documentation for more details and options):
> MyServiceName.exe //IS//MyServiceName \
--Install="C:\path-to\MyServiceName.exe" \
--Jvm=auto --Startup=auto --StartMode=jvm \
--Classpath="C:\path-to\MyJarWithClassWithMainMethod.jar" \
--StartClass=com.mydomain.MyClassWithMainMethod
Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.
> MyServiceNamew.exe //MS//MyServiceName
A simple way is the NSSM Wrapper Wrapper (see my blog entry).
One more option is WinRun4J. This is a configurable java launcher that doubles as a windows service host (both 32 and 64 bit versions). It is open source and there are no restrictions on its use.
(full disclosure: I work on this project).
Yet another answer is Yet Another Java Service Wrapper, this seems like a good alternative to Java Service Wrapper as has better licensing. It is also intended to be easy to move from JSW to YAJSW. Certainly for me, brand new to windows servers and trying to get a Java app running as a service, it was very easy to use.
Some others I found, but didn't end up using:
Java Service Launcher I didn't use this because it looked more complicated to get working than YAJSW. I don't think this is a wrapper.
JSmooth Creating Window's services isn't its primary goal, but can be done. I didn't use this because there's been no activity since 2007.
If you use Gradle Build Tool you can try my windows-service-plugin, which facilitates using of Apache Commons Daemon Procrun.
To create a java windows service application with the plugin you need to go through several simple steps.
Create a main service class with the appropriate method.
public class MyService {
public static void main(String[] args) {
String command = "start";
if (args.length > 0) {
command = args[0];
}
if ("start".equals(command)) {
// process service start function
} else {
// process service stop function
}
}
}
Include the plugin into your build.gradle file.
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "gradle.plugin.com.github.alexeylisyutenko:windows-service-plugin:1.1.0"
}
}
apply plugin: "com.github.alexeylisyutenko.windows-service-plugin"
The same script snippet for new, incubating, plugin mechanism introduced in Gradle 2.1:
plugins {
id "com.github.alexeylisyutenko.windows-service-plugin" version "1.1.0"
}
Configure the plugin.
windowsService {
architecture = 'amd64'
displayName = 'TestService'
description = 'Service generated with using gradle plugin'
startClass = 'MyService'
startMethod = 'main'
startParams = 'start'
stopClass = 'MyService'
stopMethod = 'main'
stopParams = 'stop'
startup = 'auto'
}
Run createWindowsService gradle task to create a windows service distribution.
That's all you need to do to create a simple windows service. The plugin will automatically download Apache Commons Daemon Procrun binaries, extract this binaries to the service distribution directory and create batch files for installation/uninstallation of the service.
In ${project.buildDir}/windows-service directory you will find service executables, batch scripts for installation/uninstallation of the service and all runtime libraries.
To install the service run <project-name>-install.bat and if you want to uninstall the service run <project-name>-uninstall.bat.
To start and stop the service use <project-name>w.exe executable.
Note that the method handling service start should create and start a separate thread to carry out the processing, and then return. The main method is called from different threads when you start and stop the service.
For more information, please read about the plugin and Apache Commons Daemon Procrun.
I think the Java Service Wrapper works well. Note that there are three ways to integrate your application. It sounds like option 1 will work best for you given that you don't want to change the code. The configuration file can get a little crazy, but just remember that (for option 1) the program you're starting and for which you'll be specifying arguments, is their helper program, which will then start your program. They have an example configuration file for this.
Use "winsw" which was written for Glassfish v3 but works well with Java programs in general.
Require .NET runtime installed.
JavaService is LGPL. It is very easy and stable. Highly recommended.
With Java 8 we can handle this scenario without any external tools. javapackager tool coming with java 8 provides an option to create self contained application bundles:
-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.
The following values are valid for type:
-native type
Generate self-contained application bundles (if possible). Use the -B option to provide arguments to the bundlers being used. If type is specified, then only a bundle of this type is created. If no type is specified, all is used.
The following values are valid for type:
all: Runs all of the installers for the platform on which it is running, and creates a disk image for the application. This value is used if type is not specified.
installer: Runs all of the installers for the platform on which it is running.
image: Creates a disk image for the application. On OS X, the image is the .app file. On Linux, the image is the directory that gets installed.
dmg: Generates a DMG file for OS X.
pkg: Generates a .pkg package for OS X.
mac.appStore: Generates a package for the Mac App Store.
rpm: Generates an RPM package for Linux.
deb: Generates a Debian package for Linux.
In case of windows refer the following doc we can create msi or exe as needed.
exe: Generates a Windows .exe package.
msi: Generates a Windows Installer package.
A pretty good comparison of different solutions is available at :
http://yajsw.sourceforge.net/#mozTocId284533
Personally like launch4j
I've used JavaService before with good success. It hasn't been updated in a couple of years, but was pretty rock solid back when I used it.
I didn't like the licensing for the Java Service Wrapper. I went with ActiveState Perl to write a service that does the work.
I thought about writing a service in C#, but my time constraints were too tight.
I always just use sc.exe (see http://support.microsoft.com/kb/251192). It should be installed on XP from SP1, and if it's not in your flavor of Vista, you can download load it with the Vista resource kit.
I haven't done anything too complicated with Java, but using either a fully qualified command line argument (x:\java.exe ....) or creating a script with Ant to include depencies and set parameters works fine for me.
it's simple as you have to put shortcut in
Windows 7
C:\users\All Users\Start Menu\Programs\Startup(Admin) or User home directory(%userProfile%)
Windows 10 :
In Run shell:startup
in it's property -> shortcut -> target - > java.exe -jar D:\..\runJar.jar
NOTE: This will run only after you login
With Admin Right
sc create serviceName binpath= "java.exe -jar D:\..\runJar.jar" Will create windows service
if you get timeout use cmd /c D:\JAVA7~1\jdk1.7.0_51\bin\java.exe -jar d:\jenkins\jenkins.war but even with this you'll get timeout but in background java.exe will be started. Check in task manager
NOTE: This will run at windows logon start-up(before sign-in, Based on service 'Startup Type')
Detailed explanation of creating windows service
Another good option is FireDaemon. It's used by some big shops like NASA, IBM, etc; see their web site for a full list.
I am currently requiring this to run an Eclipse-based application but I need to set some variables first that is local to that application. sc.exe will only allow executables but not scripts so I turned to autoexnt.exe which is part of the Windows 2003 resource kit. It restricts the service to a single batch file but I only need one batch script to be converted into a service.
ciao!
I have been using jar2exe for last few years to run our Java applications as service on Windows. It provides an option to create an exe file which can be installed as Windows service.
It's possible to implement a Windows service in 100% Java code by combining the use of Foreign Memory and Linker API (previewing from JDK16 upwards) with OpenJDK jextract project to handle the Windows Service callbacks, and then use jpackage to produce a Windows EXE which can then be registered as a Windows Service.
See this example which outlines the work needed to implement a Windows service. All Windows service EXE must provide callbacks for the main entrypoint ServiceMain and Service Control Handler, and use API calls StartServiceCtrlDispatcherW, RegisterServiceCtrlHandlerExW and SetServiceStatus in Advapi.DLL.
The flow of above callbacks in Java with Foreign Memory structures are:
main()
Must register ServiceMain using StartServiceCtrlDispatcherW
Above call blocks until ServiceMain exits
void ServiceMain(int dwNumServicesArgs, MemoryAddress lpServiceArgVectors)
Must register SvcCtrlHandler using RegisterServiceCtrlHandlerExW
Use SetServiceStatus(SERVICE_START_PENDING)
Initialise app
Use SetServiceStatus(SERVICE_RUNNING)
wait for app shutdown notification
Use SetServiceStatus(SERVICE_STOPPED)
int SvcCtrlHandler(int dwControl, int dwEventType, MemoryAddress lpEventData, MemoryAddress lpContext)
Must respond to service control events and report back using SetServiceStatus
On receiving SERVICE_CONTROL_STOP reports SetServiceStatus(SERVICE_STOP_PENDING)
then set app shutdown notification
Once finished the Java application, jpackage can create runtime+EXE which can then be installed and registered as a Windows Service. Run as Adminstrator (spaces after = are important):
sc create YourJavaServiceName type= own binpath= "c:\Program Files\Your Release Dir\yourjavaservice.exe"

Categories

Resources