Monday, February 25, 2013

Executing an unix command from Java Application

Scenario:
Consider a scenario that, you are a Application Server Administrator at industryvertical.co.in . Frequently you want monitor last 300 lines of multiple Application servers Logs. So you decided to write a Web Application that would display last 300 Lines using unix command tail.
image
Here we got a big Question ? ? ? How to execute a Unix Command or Shell Script from a Java Application ?
We can accomplish this in N number of ways, one simple way is using Process Builder.
What is Process Builder ?
Process Builder Instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new sub processes with identical or related attributes.
Executing tail unix command from Java Class using Process Builder?
Program Code:
import java.io.InputStream;
import java.io.*;

public class Executeshell
{
public static void main(String args[]) throws IOException, InterruptedException
{
String cmd = "ssh 192.168.56.101 tail –n 300 
/optional/Oracle/Middleware/user_projects/domains/test/servers/ms1/logs/ms1.log";
ProcessBuilder p = new ProcessBuilder("bash","-c",cmd);
p.redirectErrorStream(true);
Process shell = p.start();
InputStream shellIn = shell.getInputStream();
int shellExitStatus = shell.waitFor(); 
  int c;
while ((c = shellIn.read()) != -1) {
    System.out.write(c);
    }
    try
    {
       shellIn.close();
    }
    catch (IOException ignoreMe)
    {}

}}
See the following part for the detailed compilation,execution and output of the above class(tail out of last 300 lines of application server logs using Java Class).
Compilation, Execution and Output:
[VM@localhost ~]$javac Executeshell.java
[VM@localhost ~]$java Executeshell thiru@192.168.56.102's password: ####<Feb 26, 2013 11:08:47 AM EST> <Info> <WebLogicServer> <localhost> <> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <> <> <> <1361894927199> <BEA-000000> <WebLogic Server "ms1" version:
WebLogic Server 10.3.4.0  Fri Dec 17 20:47:33 PST 2010 1384255  Copyright (c) 1995, 2009, Oracle and/or its affiliates. All rights reserved.>
####<Feb 26, 2013 11:08:53 AM EST> <Warning> <Management> <localhost> <ms1> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361894933244> <BEA-141277> <The JMX MBean PlatformMBeanServerUsed attribute is true, but the Platform MBeanServer was created without the hooks for the WLS security infrastructure. The Platform MBeanServer will NOT be used and Platform MBeans will NOT be available via the WLS Runtime or Domain Runtime MBeanServers. This can occur if you have defined Platform MBeanServer system properties or JVM options (-Dcom.sun.management.jmxremote or JRockit -XManagement).
To allow the Platform MBeanServer to be used, you must either remove the system properties/JVM options or start WLS with the following system property:
-Djavax.management.builder.initial=weblogic.management.jmx.mbeanserver.WLSMBeanServerBuilder
If you want to eliminate this log error and do not need Platform MBeans to be available via WLS, then set the PlatformMBeanUsed attribute in the JMXMBean to false.>
####<Feb 26, 2013 11:08:53 AM EST> <Warning> <Diagnostics> <localhost> <ms1> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361894933646> <BEA-320130> <Instrumentation module bea_wls_internal is disabled.>
####<Feb 26, 2013 11:08:54 AM EST> <Warning> <Diagnostics> <localhost> <ms1> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361894934333> <BEA-320130> <Instrumentation module bea_wls9_async_response is disabled.>
####<Feb 26, 2013 11:08:55 AM EST> <Warning> <Diagnostics> <localhost> <ms1> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361894935328> <BEA-320130> <Instrumentation module bea_wls_cluster_internal is disabled.>
####<Feb 26, 2013 11:08:58 AM EST> <Warning> <Diagnostics> <localhost> <ms1> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361894938036> <BEA-320130> <Instrumentation module kshop is disabled.>
####<Feb 26, 2013 11:11:41 AM EST> <Warning> <Diagnostics> <localhost> <ms1> <[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <> <1361895101643> <BEA-320130> <Instrumentation module bea_wls_deployment_internal is disabled.>
####<Feb 26, 2013 12:02:13 PM EST> <Error> <HTTP> <localhost> <ms1> <[ACTIVE] ExecuteThread: '7' for queue: 'weblogic.kernel.Default (self-tuning)'> <<WLS Kernel>> <> <6835268149690e46:-59e14881:13d17435391:-7ffd-0000000000002c34> <1361898133563> <BEA-101019> <[ServletContext@1251397904[app:kshop module:OGRDSBSWeb path:/OGRDSBSWeb spec-version:2.5]] Servlet failed with IOException
java.io.IOException: Error marshalling JAXB object of type "class com.industryvertical.ogrds.dataservice.service.retrievedata.dto.RetrieveDataResponse".
        at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:145)
        at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:254)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:724)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:647)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:638)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
        at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
        at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:183)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3717)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
        at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
        at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
Caused By: javax.xml.bind.MarshalException
- with linked exception:
[java.net.SocketException: Connection reset]
        at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:320)
        at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:244)
        at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75)
        at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:167)
        at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:143)
        at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:254)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:724)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:647)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:638)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
        at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
        at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:183)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3717)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
        at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)
        at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)
        at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)
        at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)
        at weblogic.work.ExecuteThread.execute(ExecuteThread.java:207)
        at weblogic.work.ExecuteThread.run(ExecuteThread.java:176)
Caused By: java.net.SocketException: Connection reset
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:96)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
        at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:568)
        at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:539)
        at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:427)
        at weblogic.servlet.internal.CharsetChunkOutput.flush(CharsetChunkOutput.java:298)
        at weblogic.servlet.internal.ChunkOutput$2.checkForFlush(ChunkOutput.java:648)
        at weblogic.servlet.internal.CharsetChunkOutput.write(CharsetChunkOutput.java:200)
        at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:148)
        at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:148)
        at com.sun.jersey.spi.container.servlet.WebComponent$Writer.write(WebComponent.java:230)
        at com.sun.jersey.spi.container.ContainerResponse$CommittingOutputStream.write(ContainerResponse.java:114)
        at com.sun.xml.bind.v2.runtime.output.UTF8XmlOutput.write(UTF8XmlOutput.java:407)
        at com.sun.xml.bind.v2.runtime.output.Encoded.write(Encoded.java:163)
        at com.sun.xml.bind.v2.runtime.output.UTF8XmlOutput.doText(UTF8XmlOutput.java:318)
        at com.sun.xml.bind.v2.runtime.output.UTF8XmlOutput.text(UTF8XmlOutput.java:299)
        at com.sun.xml.bind.v2.runtime.XMLSerializer.leafElement(XMLSerializer.java:325)
        at com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$1.writeLeafElement(RuntimeBuiltinLeafInfoImpl.java:210)
        at com.sun.xml.bind.v2.model.impl.RuntimeBuiltinLeafInfoImpl$1.writeLeafElement(RuntimeBuiltinLeafInfoImpl.java:197)
        at com.sun.xml.bind.v2.runtime.reflect.TransducedAccessor$CompositeTransducedAccessorImpl.writeLeafElement(TransducedAccessor.java:250)
        at com.sun.xml.bind.v2.runtime.property.SingleElementLeafProperty.serializeBody(SingleElementLeafProperty.java:98)
        at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:332)
        at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:699)
        at com.sun.xml.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:152)
        at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:332)
        at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:593)
        at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:320)
        at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:494)
        at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:315)
        at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:244)
        at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:75)
        at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:167)
        at com.sun.jersey.core.provider.jaxb.AbstractRootElementProvider.writeTo(AbstractRootElementProvider.java:143)
        at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:254)
        at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:724)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:647)
        at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:638)
        at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:309)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:425)
        at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:590)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
        at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
        at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:300)
        at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:183)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.wrapRun(WebAppServletContext.java:3717)
        at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3681)
        at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
In the forthcoming posts we will  see how to make use of some the SSH Libraries like SSHJ and JSCH. Let me know if have any queries and suggestions.
References:
1] http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html

No comments:

Post a Comment