[jboss-cvs] JBossAS SVN: r96764 - in projects/fresh/trunk: fresh-scripting/src/main/java/org/jboss/fresh/deployer and 12 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Mon Nov 23 17:29:15 EST 2009
Author: ctomc
Date: 2009-11-23 17:29:15 -0500 (Mon, 23 Nov 2009)
New Revision: 96764
Added:
projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/RegistryContext.java
projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryContext.java
projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryStore.java
Modified:
projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml
projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/deployer/ScriptingService.java
projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/shell/commands/ScriptExe.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/ctx/FlatContext.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/RootVFSService.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/ShellExecutorService.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/VFSFileService.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/AbstractExecutable.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/Shell.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/MountExe.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/LazySystemShellImpl.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/ShellImpl.java
projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/SystemShellImpl.java
projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/deployer/SSHService.java
projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/DaemonStarter.java
projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/SSHShell.java
projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/persist/HibernateProvider.java
projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/DefaultRootVFS.java
projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSMeta.java
projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSStore.java
Log:
everything is now mc based
Modified: projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml
===================================================================
--- projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-jar/src/main/resources/META-INF/fresh-jboss-beans.xml 2009-11-23 22:29:15 UTC (rev 96764)
@@ -20,11 +20,12 @@
<bean name="FreshSSHServer" class="org.jboss.fresh.deployer.SSHService">
+ <property name="systemShell"><inject bean="FreshSystemShell"/></property>
<depends>FreshSystemShell</depends>
</bean>
<bean name="FreshSystemShell" class="org.jboss.fresh.shell.impl.LazySystemShellImpl" >
- <annotation>@org.jboss.aop.microcontainer.aspects.jndi.JndiBinding(name = "java:/FRESH/SystemShell")</annotation>
+ <!--annotation>@org.jboss.aop.microcontainer.aspects.jndi.JndiBinding(name = "java:/FRESH/SystemShell")</annotation-->
<constructor>
<parameter><inject bean="jboss.kernel:service=KernelController"/></parameter>
<parameter>
@@ -34,17 +35,18 @@
-->
<list elementClass="java.lang.String">
<!--value>FreshPoolService</value-->
- <value>FreshVFSService</value>
- <value>FreshRootVFSService</value>
+ <value>FreshVFSMeta</value>
+ <value>FreshVFSStore</value>
+ <value>FreshVFS</value>
+ <value>FreshRootVFS</value>
<value>FreshVFSInit</value>
<value>FreshScripting</value>
<value>FreshShellInit</value>
- <value>FreshContextBinder</value>
+ <value>FreshGlobalContext</value>
</list>
- </parameter>
- <parameter>java:/FRESH/VFS</parameter>
+ </parameter>
</constructor>
- <property name="JNDIName">java:/FRESH/SystemShell</property>
+ <!--property name="JNDIName">java:/FRESH/SystemShell</property-->
<!--property name="threadPoolName">java:/FRESH/ThreadPool</property-->
<!--property name="JNDIName">java:/FRESH/SystemShell</property>
<property name="threadPoolName">java:/FRESH/ThreadPool</property>
@@ -52,6 +54,7 @@
<property name="GCInterval">10000</property-->
<property name="threadPool"><inject bean="jboss.system:service=ThreadPool"/></property>
<property name="executableRegistry"><inject bean="LazyExecutableRegistry"/></property>
+ <property name="VFS"><inject bean="FreshVFS"/></property>
</bean>
<bean name="LazyExecutableRegistry" class="org.jboss.fresh.shell.impl.LazyExecutableRegistry">
@@ -60,8 +63,27 @@
</constructor>
</bean>
+ <bean name="FreshVFSMeta" class="org.jboss.fresh.vfs.impl.mem.MemVFSMeta">
+ <constructor>
+ <parameter><null/></parameter>
+ <parameter>root</parameter>
+ </constructor>
+ </bean>
+ <bean name="FreshVFSStore" class="org.jboss.fresh.vfs.impl.mem.MemVFSStore">
+ <constructor>
+ <parameter><inject bean="FreshVFSMeta"/></parameter>
+ <parameter>root</parameter>
+ </constructor>
+ </bean>
+ <bean name="FreshVFS" class="org.jboss.fresh.vfs.impl.DefaultVFS" mode="On Demand">
+ <constructor>
+ <parameter><inject bean="FreshVFSMeta"/></parameter>
+ <parameter><inject bean="FreshVFSStore"/></parameter>
+ <parameter><bean class="org.jboss.fresh.vfs.impl.TimeTagFactory"/></parameter>
+ </constructor>
+ </bean>
- <bean name="FreshVFSService" class="org.jboss.fresh.deployer.VFSService" mode="On Demand">
+ <!--bean name="FreshVFSService" class="org.jboss.fresh.deployer.VFSService" mode="On Demand">
<annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=VFS.Mem",exposedInterface=org.jboss.fresh.deployer.VFSServiceMBean.class)</annotation>
<property name="JNDIName">java:/FRESH/VFSMem</property>
<property name="VFSImpl">org.jboss.fresh.vfs.impl.DefaultVFS</property>
@@ -70,16 +92,38 @@
<property name="metaPropertyString">memfs.name=root</property>
<property name="storePropertyString">memfs.name=root</property>
<property name="tagFactory">org.jboss.fresh.vfs.impl.TimeTagFactory</property>
- </bean>
+ </bean-->
- <bean name="FreshRootVFSService" class="org.jboss.fresh.deployer.RootVFSService" mode="On Demand">
+ <bean name="FreshRootVFS" class="org.jboss.fresh.vfs.impl.DefaultRootVFS" mode="On Demand">
+ <constructor>
+ <parameter>
+ <map keyClass="java.lang.String" valueClass="org.jboss.beans.metadata.spi.factory.BeanFactory">
+ <entry>
+ <key>/</key>
+ <value>
+ <inject bean="FreshVFS"/>
+ </value>
+ </entry>
+ </map>
+ </parameter>
+ </constructor>
+ <!--property name="JNDIName">java:/FRESH/VFS</property>
+ <property name="automount">/=java:/FRESH/VFSMem</property-->
+ <depends>FreshVFS</depends>
+ </bean>
+
+
+ <!--bean name="FreshRootVFSService" class="org.jboss.fresh.deployer.RootVFSService" mode="On Demand">
<property name="JNDIName">java:/FRESH/VFS</property>
<property name="automount">/=java:/FRESH/VFSMem</property>
<depends>FreshVFSService</depends>
- </bean>
+ </bean-->
+
+
+
<bean name="FreshVFSInit" class="org.jboss.fresh.deployer.ShellExecutorService" mode="On Demand">
- <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=VFS.Mem.Init",exposedInterface=org.jboss.fresh.deployer.ShellExecutorServiceMBean.class)</annotation>
+ <!--annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=VFS.Mem.Init",exposedInterface=org.jboss.fresh.deployer.ShellExecutorServiceMBean.class)</annotation-->
<property name="batchCode">
mkdir /home
mkdir /home/admin
@@ -213,20 +257,20 @@
</property>
<property name="executeOnStart">true</property>
<property name="stopOnError">false</property>
- <property name="useLocal">true</property>
- <property name="svcName">java:/FRESH/SystemShell</property>
+ <property name="systemShell"><inject bean="FreshSystemShell"/></property>
<depends>FreshSystemShell</depends>
</bean>
<bean name="FreshScripting" class="org.jboss.fresh.deployer.ScriptingService" mode="On Demand">
- <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=Scripting",exposedInterface=org.jboss.fresh.deployer.ScriptingServiceMBean.class)</annotation>
- <property name="JNDIName">java:/FRESH/Scripting</property>
+ <!--annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=Scripting",exposedInterface=org.jboss.fresh.deployer.ScriptingServiceMBean.class)</annotation-->
+ <!--property name="JNDIName">java:/FRESH/Scripting</property-->
+ <!--property name="systemShell"><inject bean="FreshSystemShell"/></property-->
<depends>FreshSystemShell</depends>
<depends>FreshVFSInit</depends>
</bean>
<bean name="FreshShellInit" class="org.jboss.fresh.deployer.VFSFileService" mode="On Demand">
- <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=init-rc",exposedInterface=org.jboss.fresh.deployer.VFSFileServiceMBean.class)</annotation>
+ <!--annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=init-rc",exposedInterface=org.jboss.fresh.deployer.VFSFileServiceMBean.class)</annotation-->
<property name="file">/etc/shell/init.rc</property>
<property name="content">
set PATH = .:/bin
@@ -234,19 +278,16 @@
set SESSION_TIMEOUT = 1800000
set PROCESS_TIMEOUT = 60000
</property>
+ <property name="systemShell"><inject bean="FreshSystemShell"/></property>
<depends>FreshSystemShell</depends>
<depends>FreshVFSInit</depends>
</bean>
<bean name="FreshGlobalContext" class="org.jboss.fresh.ctx.FlatContext" mode="On Demand">
- <annotation>@org.jboss.aop.microcontainer.aspects.jndi.JndiBinding(name = "java:/FRESH/GlobalContext")</annotation>
+ <!--annotation>@org.jboss.aop.microcontainer.aspects.jndi.JndiBinding(name = "java:/FRESH/GlobalContext")</annotation-->
</bean>
- <bean name="FreshContextBinder" class="org.jboss.fresh.deployer.ContextBinder" mode="On Demand">
- <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name="FRESH:service=GlobalContext",exposedInterface=org.jboss.fresh.deployer.ContextBinderMBean.class)</annotation>
- <property name="JNDIName">java:/FRESH/GlobalContext</property>
- </bean>
<bean name="ExecutableRegistry" class="org.jboss.fresh.shell.impl.BeanFactoryExecutableRegistry" mode="On Demand">
<constructor>
Modified: projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/deployer/ScriptingService.java
===================================================================
--- projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/deployer/ScriptingService.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/deployer/ScriptingService.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -9,6 +9,7 @@
import org.apache.bsf.BSFManager;
import org.apache.bsf.util.event.EventAdapterRegistry;
+import org.jboss.beans.metadata.api.annotations.Create;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
@@ -24,7 +25,7 @@
import java.util.LinkedList;
-public class ScriptingService extends NamingBinder implements ScriptingServiceMBean {
+public class ScriptingService {
private String cfgPath;
private List langs = new LinkedList();
@@ -62,7 +63,8 @@
</scripting>
*/
-
+
+ @Create
public void doStart() throws Exception {
// lookup the config file and initialize stuff
@@ -154,7 +156,7 @@
});
- super.doStart();
+
}
@@ -234,17 +236,6 @@
}
- protected String getBindClass() {
- return ScriptingCentral.class.getName();
- }
-
- protected Object classToInstance(Class c) {
- setServiceObject( this );
- //return new ScriptingServiceJMXProxy(getRegisteredName());
- //return java.lang.reflect.Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class [] {com.parsek.cp2.scripting.ScriptingCentral.class}, new JMXProxyHandler(getRegisteredName()));
- return this;
- }
-
//
public boolean isLanguageSupported(String name) {
Modified: projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/shell/commands/ScriptExe.java
===================================================================
--- projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/shell/commands/ScriptExe.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-scripting/src/main/java/org/jboss/fresh/shell/commands/ScriptExe.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -64,7 +64,8 @@
PrintWriter err = new PrintWriter(new BufferWriter(getStdOut()), true);
// now lookup ScriptingServices
- ScriptingCentral sc = (ScriptingCentral) getShell().getContext().get("ScriptingServices");
+ ScriptingCentral sc = getComponentByType(ScriptingCentral.class);
+ //ScriptingCentral sc = (ScriptingCentral) getShell().getContext().get("ScriptingServices");
if (sc == null) {
if (canThrowEx()) {
throw new RuntimeException("ScriptingServices not bound in context.");
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/ctx/FlatContext.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/ctx/FlatContext.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/ctx/FlatContext.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,9 +1,10 @@
package org.jboss.fresh.ctx;
+import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
-public class FlatContext implements Context {
+public class FlatContext implements Context, Serializable {
private HashMap map = new HashMap();
private Context ctx;
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/RootVFSService.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/RootVFSService.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/RootVFSService.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -18,8 +18,8 @@
* @version $Revision: 3032 $
* @modified $Author: strukelj $
*/
- at JMX(name = "FRESH:service=VFS.Root", exposedInterface = RootVFSServiceMBean.class)
-public class RootVFSService extends RegistryNamingBinder implements RootVFSServiceMBean {
+//@JMX(name = "FRESH:service=VFS.Root", exposedInterface = RootVFSServiceMBean.class)
+public class RootVFSService{
private static Logger log = Logger.getLogger(RootVFSService.class);
private RootVFS vfs;
@@ -39,8 +39,13 @@
protected Object classToInstance(Class c) {
- vfs = new DefaultRootVFS();
- return vfs;
+ try {
+ vfs = new DefaultRootVFS(null);
+ return vfs;
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ return null;
}
protected boolean bindByReference() {
@@ -48,7 +53,7 @@
}
public void doStart() throws Exception {
- super.doStart();
+ //super.doStart();
if (props != null) {
InitialContext ctx = new InitialContext();
Set set = props.entrySet();
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/ShellExecutorService.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/ShellExecutorService.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/ShellExecutorService.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,32 +1,26 @@
package org.jboss.fresh.deployer;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.StringReader;
-import java.io.StringWriter;
+import org.jboss.beans.metadata.api.annotations.Create;
+import org.jboss.fresh.io.IOUtils;
+import org.jboss.fresh.shell.ProcessInfo;
+import org.jboss.fresh.shell.Shell;
+import org.jboss.fresh.shell.ShellConsoleInputStream;
+import org.jboss.fresh.shell.ShellException;
+import org.jboss.fresh.shell.ShellObjectReader;
+import org.jboss.fresh.shell.SystemShell;
+import org.jboss.fresh.util.TextLayout;
+
+import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
-import javax.naming.InitialContext;
+/**
+ * This is a simple service that sustains a file on the disk. It it it simply puts an integer specifying the number of invocations made from beginning of its running.
+ */
-import javax.naming.InitialContext;
-import org.jboss.fresh.shell.*;
-import org.jboss.fresh.shell.ejb.RemoteShellHome;
-import org.jboss.fresh.shell.ejb.RemoteShell;
-import org.jboss.fresh.io.IOUtils;
-import org.jboss.fresh.util.TextLayout;
+public class ShellExecutorService {
-/** This is a simple service that sustains a file on the disk. It it it simply puts an integer specifying the number of invocations made from beginning of its running. */
-
-public class ShellExecutorService extends ServiceModule implements ShellExecutorServiceMBean {
-
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(ShellExecutorService.class);
private static SimpleDateFormat sdf = new SimpleDateFormat("'['dd.MM' 'HH:mm:ss']'");
@@ -34,11 +28,10 @@
private String bfile;
private boolean qoe = false;
private String flog;
- private String svcname;
private boolean exeOnStart;
- private boolean useLocal;
private String bcode;
+ private SystemShell systemShell;
// Attributes ----------------------------------------------------
@@ -88,42 +81,29 @@
}
- public void setSvcName(String val) {
- svcname = val;
- }
- public String getSvcName() {
- return svcname;
+ public SystemShell getSystemShell() {
+ return systemShell;
}
- public void setUseLocal(boolean val) {
- useLocal = val;
+ public void setSystemShell(SystemShell systemShell) {
+ this.systemShell = systemShell;
}
- public boolean getUseLocal() {
- return useLocal;
- }
-
-
+ @Create
public void doStart() throws Exception {
if (exeOnStart) execute();
}
private class Executor {
-
+
private boolean stopOnError = false;
- private String eSvcname = "SystemShell";
- private boolean eUseLocal = true;
+
public Executor() {
super();
this.stopOnError = qoe;
- this.eUseLocal = useLocal;
- this.eSvcname = svcname;
- if (eSvcname == null) {
- eSvcname = eUseLocal ? "SystemShell": "ShellSession";
- }
}
// we open a log file
@@ -132,116 +112,71 @@
BufferedReader in = null;
public void execute() throws Exception {
- PrintWriter out = null;
- if(bos != null)
- out = new PrintWriter(new OutputStreamWriter(bos));
+ PrintWriter out = null;
+ if (bos != null)
+ out = new PrintWriter(new OutputStreamWriter(bos));
- try {
+ try {
- if (eUseLocal) {
- InitialContext ctx = new InitialContext();
- SystemShell sysshell = (SystemShell) ctx.lookup(eSvcname);
- Shell shell = sysshell.startSession(null, false);
- try {
- // now line by line
- // And put all exceptions to log too.
- String cmd = in.readLine();
- while (cmd != null) {
- cmd = cmd.trim();
- if(out!=null) {
- out.println(getTime() + " Executing: " + cmd);
- out.flush();
- }
-
- if(! "".equals(cmd)) {
- ProcessInfo pinf = shell.execute(cmd, true);
-
- BufferedInputStream bin = new BufferedInputStream(new ShellConsoleInputStream(new ShellObjectReader(shell, pinf.procid)));
- try {
- IOUtils.copy(bin, bos, 50000);
- } catch (Exception ex) {
- try {
- if(out != null) {
- out.println(getTime() + " Exception has occured:");
- ex.printStackTrace(out);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- if (stopOnError) {
- throw ex;
- }
- }
-
- }
- cmd = in.readLine();
+ Shell shell = systemShell.startSession(null, false);
+
+ try {
+ // now line by line
+ // And put all exceptions to log too.
+ String cmd = in.readLine();
+ while (cmd != null) {
+ cmd = cmd.trim();
+ if (out != null) {
+ out.println(getTime() + " Executing: " + cmd);
+ out.flush();
}
- } finally {
- try {
- shell.close();
- } catch (ShellException e) {
- }
- }
- } else {
- // we get RemoteShell
- InitialContext ctx = new InitialContext();
- RemoteShellHome home = (RemoteShellHome) ctx.lookup(eSvcname);
- RemoteShell shell = home.create();
- try {
- // now line by line
- // And put all exceptions to log too.
- String cmd = in.readLine();
- while (cmd != null) {
-
- cmd = cmd.trim();
-
- if(out != null) {
- out.println(getTime() + " Executing: " + cmd);
- out.flush();
+ if (!"".equals(cmd)) {
+ ProcessInfo pinf = shell.execute(cmd, true);
+
+ BufferedInputStream bin = new BufferedInputStream(new ShellConsoleInputStream(new ShellObjectReader(shell, pinf.procid)));
+ try {
+ IOUtils.copy(bin, bos, 50000);
+ } catch (Exception ex) {
+ try {
+ if (out != null) {
+ out.println(getTime() + " Exception has occured:");
+ ex.printStackTrace(out);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ if (stopOnError) {
+ throw ex;
+ }
}
- if(! "".equals(cmd)) {
- ProcessInfo pinf = shell.execute(cmd);
- BufferedInputStream bin = new BufferedInputStream(new ShellConsoleInputStream(new ShellObjectReader(shell, pinf.procid)));
- try {
- IOUtils.copy(bin, bos, 50000);
- } catch (Exception ex) {
- try {
- if(out!=null) {
- out.println(getTime() + " Exception has occured:");
- ex.printStackTrace(out);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (stopOnError) {
- throw ex;
- }
- }
- }
- cmd = in.readLine();
}
- } finally {
- shell.remove();
+ cmd = in.readLine();
}
+ } finally {
+ try {
+ shell.close();
+ } catch (ShellException e) {
+ }
}
+
} finally {
try {
in.close();
} catch (Exception ex) {
}
try {
- if(out != null)
- out.close();
+ if (out != null)
+ out.close();
} catch (Exception ex) {
}
- }
+ }
}
}
-
+
public void execute() throws Exception {
// we open a log file
BufferedOutputStream bos = null;
@@ -254,9 +189,9 @@
}
}
- if(bcode != null && bcode.length() > 1 && bfile != null) {
+ if (bcode != null && bcode.length() > 1 && bfile != null) {
log.warn("Both batch file and batch code parameters are set. Using batch file!");
- if(bos!=null) {
+ if (bos != null) {
PrintWriter out = new PrintWriter(bos);
try {
out.println(getTime() + " Both batch file and batch code parameters are set. Using batch file!");
@@ -272,12 +207,12 @@
BufferedReader in = null;
- if(bfile != null) {
+ if (bfile != null) {
// we open a batch file
try {
in = new BufferedReader(new FileReader(bfile));
} catch (Exception ex) {
- if(bos!=null) {
+ if (bos != null) {
PrintWriter out = new PrintWriter(bos);
try {
out.println(getTime() + " Exception has occured:");
@@ -293,14 +228,14 @@
throw ex;
}
- } else if(bcode != null) {
+ } else if (bcode != null) {
in = new BufferedReader(new StringReader(bcode));
}
-
+
Executor exe = new Executor();
exe.bos = bos;
exe.in = in;
-
+
exe.execute();
}
@@ -317,9 +252,9 @@
}
}
- if(bcode != null && bcode.length() > 1 && bfile != null) {
+ if (bcode != null && bcode.length() > 1 && bfile != null) {
log.warn("Both batch file and batch code parameters are set. Using batch file!");
- if(bos!=null) {
+ if (bos != null) {
PrintWriter out = new PrintWriter(bos);
try {
out.println(getTime() + " Both batch file and batch code parameters are set. Using batch file!");
@@ -335,12 +270,12 @@
// we open a batch file
BufferedReader in = null;
- if(bfile != null) {
+ if (bfile != null) {
try {
in = populate(new BufferedReader(new FileReader(bfile)), params);
- } catch (Exception ex) {
- if(bos != null) {
+ } catch (Exception ex) {
+ if (bos != null) {
PrintWriter out = new PrintWriter(bos);
try {
out.println(getTime() + " Exception has occured:");
@@ -355,32 +290,32 @@
}
throw ex;
}
- } else if(bcode != null) {
+ } else if (bcode != null) {
in = populate(new BufferedReader(new StringReader(bcode)), params);
}
Executor exe = new Executor();
exe.bos = bos;
exe.in = in;
-
+
exe.execute();
}
- private BufferedReader populate(BufferedReader job, Map params) throws IOException {
- if (params != null && !params.isEmpty()) {
- StringBuffer sb = new StringBuffer();
- for (String line = job.readLine(); line != null; line = job.readLine()) {
- sb.append(line).append("\r\n");
- }
- TextLayout tl = new TextLayout("{","}");
- tl.setPattern(sb.toString());
- StringWriter sw = new StringWriter();
- tl.bind(sw, params);
- return new BufferedReader(new StringReader(sw.toString()));
- }
- return job;
- }
-
+ private BufferedReader populate(BufferedReader job, Map params) throws IOException {
+ if (params != null && !params.isEmpty()) {
+ StringBuffer sb = new StringBuffer();
+ for (String line = job.readLine(); line != null; line = job.readLine()) {
+ sb.append(line).append("\r\n");
+ }
+ TextLayout tl = new TextLayout("{", "}");
+ tl.setPattern(sb.toString());
+ StringWriter sw = new StringWriter();
+ tl.bind(sw, params);
+ return new BufferedReader(new StringReader(sw.toString()));
+ }
+ return job;
+ }
+
protected static String getTime() {
return sdf.format(new Date());
}
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/VFSFileService.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/VFSFileService.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/deployer/VFSFileService.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,12 +1,11 @@
package org.jboss.fresh.deployer;
+import org.jboss.beans.metadata.api.annotations.Create;
import org.jboss.fresh.io.IOUtils;
-import javax.naming.InitialContext;
import org.jboss.fresh.shell.ProcessInfo;
import org.jboss.fresh.shell.Shell;
import org.jboss.fresh.shell.ShellOutputStream;
import org.jboss.fresh.shell.SystemShell;
-import org.jboss.fresh.shell.ejb.RemoteShell;
import javax.naming.Context;
import java.io.InputStream;
@@ -16,7 +15,7 @@
/**
* Service creates a file in VFS.
*/
-public class VFSFileService extends ServiceModule implements VFSFileServiceMBean {
+public class VFSFileService {
private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(VFSFileService.class);
static final org.apache.log4j.Level TRACE = new ApacheLevel(5000, "TRACE", 7);
static final org.apache.log4j.Level NOTICE = new ApacheLevel(25000, "NOTICE", 5);
@@ -33,6 +32,7 @@
private String sourceFile;
private String classpathFile;
private URL url;
+ private SystemShell systemShell;
public String getName() {
return "VFS File Service";
@@ -79,27 +79,25 @@
}
+ public SystemShell getSystemShell() {
+ return systemShell;
+ }
+
+ public void setSystemShell(SystemShell systemShell) {
+ this.systemShell = systemShell;
+ }
+
+ @Create
public void doStart() throws Exception {
if (file == null || file.trim().length() == 0) {
throw new Exception("File name not defined. Please define VFS file name.");
}
Context ctx = null;
- Shell shell = null;
- RemoteShell rshell = null;
+ Shell shell = systemShell.startSession(null, false);
ShellOutputStream sos = null;
OutputStreamWriter osw = null;
try {
- ctx = new InitialContext();
-
- try {
- SystemShell sysshell = (SystemShell) ctx.lookup("java:/FRESH/SystemShell");
- log.log(TRACE, "Retrieved SystemShell from RegistryContext: 'SystemShell'.");
- shell = sysshell.startSession(null, false);
- } catch (javax.naming.NameNotFoundException nnfe) {
- throw nnfe;
-
- }
log.debug("Using shell: " + shell);
String path = "";
@@ -110,8 +108,6 @@
log.debug(cmd);
if (shell != null) {
shell.executeAsObject(cmd);
- } else {
- rshell.executeAsObject(cmd);
}
}
@@ -197,13 +193,8 @@
ProcessInfo pinf = null;
cmd = "cat > " + file;
log.debug(cmd);
- if (shell != null) {
- pinf = shell.execute(cmd);
- sos = new ShellOutputStream(shell, pinf.procid);
- } else {
- pinf = rshell.execute(cmd);
- sos = new ShellOutputStream(rshell, pinf.procid);
- }
+ pinf = shell.execute(cmd);
+ sos = new ShellOutputStream(shell, pinf.procid);
osw = new OutputStreamWriter(sos, "UTF-8");
osw.write(content);
log.log(NOTICE, "Created file " + file + ", processed " + content.length() + " characters.");
@@ -219,11 +210,7 @@
}
cmd = "cat > " + file + " &< " + f.getAbsolutePath();
log.debug(cmd);
- if (shell != null) {
- shell.execute(cmd);
- } else {
- rshell.execute(cmd);
- }
+ shell.execute(cmd);
log.log(NOTICE, "Created file " + file + ", wrote " + f.length() + " bytes.");
} else if (url != null) {
InputStream is = null;
@@ -236,13 +223,8 @@
ProcessInfo pinf = null;
cmd = "cat > " + file;
log.debug(cmd);
- if (shell != null) {
- pinf = shell.execute(cmd);
- sos = new ShellOutputStream(shell, pinf.procid);
- } else {
- pinf = rshell.execute(cmd);
- sos = new ShellOutputStream(rshell, pinf.procid);
- }
+ pinf = shell.execute(cmd);
+ sos = new ShellOutputStream(shell, pinf.procid);
long size = IOUtils.copy(is, sos);
@@ -258,11 +240,7 @@
} else if (create) {
cmd = "touch " + file;
log.debug(cmd);
- if (shell != null) {
- shell.execute(cmd);
- } else {
- rshell.execute(cmd);
- }
+ shell.execute(cmd);
log.log(NOTICE, "Created empty file " + file + ".");
}
@@ -274,12 +252,6 @@
}
}
// should not close shells. if(shell != null) { try { shell.close(); } catch (Exception e) { } }
- if (rshell != null) {
- try {
- rshell.remove();
- } catch (Exception e) {
- }
- }
if (osw != null) {
try {
osw.close();
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/AbstractExecutable.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/AbstractExecutable.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/AbstractExecutable.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -752,5 +752,8 @@
public boolean errorProcessed() {
return errProcessed;
}
+ public <T>T getComponentByType(Class<T> type){
+ return this.shell.getComponentByType(type);
+ }
}
\ No newline at end of file
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/Shell.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/Shell.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/Shell.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -100,5 +100,7 @@
public void using() throws ShellException;
boolean isValid();
+
+ public <T>T getComponentByType(Class<T> type);
}
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/MountExe.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/MountExe.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/commands/MountExe.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -39,9 +39,9 @@
return;
}
- RootVFS rootfs = null;
+ RootVFS rootfs = getComponentByType(RootVFS.class);
- InitialContext ctx = new InitialContext();
+ /*InitialContext ctx = new InitialContext();
try {
rootfs = (RootVFS) ctx.lookup("java:/CP2/VFS");
} catch(ClassCastException ex) {
@@ -50,7 +50,7 @@
} catch(NameNotFoundException ex) {
error("Root VFS not bound (should be at: java:/CP2/VFS)");
return;
- }
+ }*/
if(params.length == 0) {
Iterator it = rootfs.listMounts().entrySet().iterator();
@@ -66,16 +66,9 @@
String path = params[0];
String jndi = params[1];
- VFS vfs = null;
+ VFS vfs = getComponentByType(VFS.class);
- try {
- vfs = (VFS) ctx.lookup(jndi);
- } catch(NameNotFoundException ex) {
- error("No VFS bound at: " + jndi);
- return;
- }
-
if(rootfs instanceof RootVFS) {
rootfs.mount(path, vfs);
} else {
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/LazySystemShellImpl.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/LazySystemShellImpl.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/LazySystemShellImpl.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -8,6 +8,7 @@
import org.jboss.dependency.spi.ControllerState;
import org.jboss.fresh.shell.Shell;
import org.jboss.fresh.vfs.UserCtx;
+import org.jboss.fresh.vfs.VFS;
public class LazySystemShellImpl extends SystemShellImpl
{
@@ -15,8 +16,8 @@
private List<String> onDemandBeans;
private AtomicBoolean initialized = new AtomicBoolean(false);
- public LazySystemShellImpl(Controller controller, List<String> onDemandBeans,String vfsName)throws Exception {
- super(vfsName);
+ public LazySystemShellImpl(Controller controller, List<String> onDemandBeans)throws Exception {
+ super();
this.controller = controller;
this.onDemandBeans = onDemandBeans;
}
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/ShellImpl.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/ShellImpl.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/ShellImpl.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,24 +1,18 @@
package org.jboss.fresh.shell.impl;
-import java.io.ByteArrayInputStream;
-import java.io.EOFException;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.text.SimpleDateFormat;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
+import org.apache.log4j.Logger;
+import org.jboss.fresh.ctx.Context;
import org.jboss.fresh.events.EventBroadcaster;
import org.jboss.fresh.events.EventCentral;
+import org.jboss.fresh.io.*;
+import org.jboss.fresh.shell.*;
+import org.jboss.fresh.shell.events.ShellEvent;
+import org.jboss.fresh.shell.events.ShellEventBroadcaster;
+import org.jboss.fresh.shell.parser.Cmd;
+import org.jboss.fresh.shell.parser.CmdLines;
+import org.jboss.fresh.shell.parser.ParseException;
+import org.jboss.fresh.shell.parser.ShellCmdParser;
+import org.jboss.fresh.util.StringUtils;
import org.jboss.fresh.vfs.FileInfo;
import org.jboss.fresh.vfs.FileName;
import org.jboss.fresh.vfs.UserCtx;
@@ -26,36 +20,15 @@
import org.jboss.fresh.vfs.impl.LazyVFSOutputStream;
import org.jboss.fresh.vfs.impl.SecureVFS;
import org.jboss.fresh.vfs.impl.VFSInputStream;
-import org.jboss.fresh.ctx.Context;
-import org.jboss.fresh.io.Buffer;
-import org.jboss.fresh.io.BufferImpl;
-import org.jboss.fresh.io.BufferObjectReader;
-import org.jboss.fresh.io.InBuffer;
-import org.jboss.fresh.io.InputStreamBuffer;
-import org.jboss.fresh.io.MemFileBufferImpl;
-import org.jboss.fresh.io.MultiBufferObjectReader;
-import org.jboss.fresh.io.NullBuffer;
-import org.jboss.fresh.io.OutBuffer;
-import org.jboss.fresh.io.OutputStreamBuffer;
+
import javax.naming.InitialContext;
-import org.jboss.fresh.shell.EnvProperties;
-import org.jboss.fresh.shell.Executable;
-import org.jboss.fresh.shell.NoSuchProcessException;
-import org.jboss.fresh.shell.ProcessInfo;
-import org.jboss.fresh.shell.SessionTimeoutException;
-import org.jboss.fresh.shell.Shell;
-import org.jboss.fresh.shell.ShellException;
-import org.jboss.fresh.shell.ShellIOException;
-import org.jboss.fresh.shell.SystemShell;
-import org.jboss.fresh.shell.ExecutableRegistry;
-import org.jboss.fresh.shell.events.ShellEvent;
-import org.jboss.fresh.shell.events.ShellEventBroadcaster;
-import org.jboss.fresh.shell.parser.Cmd;
-import org.jboss.fresh.shell.parser.CmdLines;
-import org.jboss.fresh.shell.parser.ParseException;
-import org.jboss.fresh.shell.parser.ShellCmdParser;
-import org.jboss.fresh.util.StringUtils;
-import org.apache.log4j.Logger;
+import java.io.ByteArrayInputStream;
+import java.io.EOFException;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.*;
/**
* @todo We need to clearly say that we are out of threads when we are out of threads.
@@ -78,542 +51,541 @@
public class ShellImpl implements Shell {
- private String uid;
- private boolean interactive;
+ private String uid;
+ private boolean interactive;
- private UserCtx uctx;
- private SystemShellImpl sshell;
- private VFS vfs;
+ private UserCtx uctx;
+ private SystemShellImpl sshell;
+ private VFS vfs;
- //private Cache cache;
- private Context ctx;
+ //private Cache cache;
+ private Context ctx;
- private Process active = null;
- private Buffer shellout;
+ private Process active = null;
+ private Buffer shellout;
// private PrintWriter wout;
- private MultiBufferObjectReader outreader;
+ private MultiBufferObjectReader outreader;
// private Buffer shellin;
// private int STD_BUF_SIZE=5; // should be read from some ENV var.
- private static final String EVENT_SOURCE = "ShellImpl";
- private static final String EVENT_CLASS = "Shell";
+ private static final String EVENT_SOURCE = "ShellImpl";
+ private static final String EVENT_CLASS = "Shell";
- public static final long SESS_TIMEOUT = 1800000L; // 30 min //36000000L; // 10 hrs
- public static final long PROC_TIMEOUT = 1200000L; // 20 mins
- public static final long BUFFER_TIMEOUT = 1200000L; // 20 mins
+ public static final long SESS_TIMEOUT = 1800000L; // 30 min //36000000L; // 10 hrs
+ public static final long PROC_TIMEOUT = 1200000L; // 20 mins
+ public static final long BUFFER_TIMEOUT = 1200000L; // 20 mins
- public static final String STDINPROC_ID = "-1";
- public static final String STDIN_ID = "0";
+ public static final String STDINPROC_ID = "-1";
+ public static final String STDIN_ID = "0";
- // Buffer limits
- public static final int BUF_MAX_SIZE = 10; // should be read from some environment variable ... no executable can have it's setting for in or out greater than this
- public static final int IN_BUF_SIZE = 5, OUT_BUF_SIZE = 5; // test case only, should be determined by exe specific info
+ // Buffer limits
+ public static final int BUF_MAX_SIZE = 10; // should be read from some environment variable ... no executable can have it's setting for in or out greater than this
+ public static final int IN_BUF_SIZE = 5, OUT_BUF_SIZE = 5; // test case only, should be determined by exe specific info
- // Timeout limits
- public static final long PROC_TIMEOUT_MAX = 300000L; // 5 min - should be read from some global variable ... no executable can have it's setting greater - meaning if non-zero value specified, no zero allowed on individual ...
- public static final long PROC_INST_TIMEOUT = 150000L; // test case only, should be determined by exe specific info
+ // Timeout limits
+ public static final long PROC_TIMEOUT_MAX = 300000L; // 5 min - should be read from some global variable ... no executable can have it's setting greater - meaning if non-zero value specified, no zero allowed on individual ...
+ public static final long PROC_INST_TIMEOUT = 150000L; // test case only, should be determined by exe specific info
- // we could save this setting in a wrapped around stream/writer/reader
- // or we could save this satting with the process...
+ // we could save this setting in a wrapped around stream/writer/reader
+ // or we could save this satting with the process...
- private ShellRuntime runtime;
- private ExecutableRegistry registry;
- //private HashMap procmap=new HashMap();
- private Map procmap = Collections.synchronizedMap(new HashMap());
+ private ShellRuntime runtime;
+ private ExecutableRegistry registry;
+ //private HashMap procmap=new HashMap();
+ private Map procmap = Collections.synchronizedMap(new HashMap());
- private long startTime;
- private long lastUsed;
- private boolean closed = false;
+ private long startTime;
+ private long lastUsed;
+ private boolean closed = false;
private long closureTime;
private String closureReason;
private static final Logger log = Logger.getLogger("org.jboss.fresh.shell.impl.ShellImpl");
- private static final Logger cmdlog = Logger.getLogger("org.jboss.fresh.shell.impl.ShellImpl.CMD");
+ private static final Logger cmdlog = Logger.getLogger("org.jboss.fresh.shell.impl.ShellImpl.CMD");
- private EventBroadcaster eb;
- private EventCentral ec;
+ private EventBroadcaster eb;
+ private EventCentral ec;
- private EnvProperties props = new EnvProperties();
+ private EnvProperties props = new EnvProperties();
SimpleDateFormat sdf_date = new SimpleDateFormat("yyyy-MM-dd");
- SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ SimpleDateFormat sdf_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf_time_millis = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static ThreadLocal preparedProcess = new ThreadLocal();
-
- // SysShell assigned shell session id
- public ShellImpl(String id, boolean interactive, SystemShellImpl sysshell, UserCtx uctx, VFS vfs) {
- this.interactive = interactive;
- uid = id;
- this.uctx = uctx;
- sshell = sysshell;
- this.vfs = vfs;
- props = new EnvProperties(System.getProperties());
- // I don't really see when shellin would be of any use.
- //shellin=new BufferImpl();
- //shellin.setMaxSize(STD_BUF_SIZE);
- if (interactive) {
- ProcessGroup stdproc = new ProcessGroup(STDINPROC_ID, null, null);
+ // SysShell assigned shell session id
- shellout = new BufferImpl();
- // CAREFUL HERE: If you print too much to out at the very beginning - in terms of objects
- // you will deadlock
- //shellout.setMaxSize(1);
- shellout.setMaxSize(20);
- stdproc.setOutputBuffer(shellout);
- stdproc.setIOTimeout(PROC_INST_TIMEOUT);
- procmap.put(STDINPROC_ID, stdproc);
+ public ShellImpl(String id, boolean interactive, SystemShellImpl sysshell, UserCtx uctx, VFS vfs) {
+ this.interactive = interactive;
+ uid = id;
+ this.uctx = uctx;
+ sshell = sysshell;
+ this.vfs = vfs;
+ props = new EnvProperties(System.getProperties());
+ // I don't really see when shellin would be of any use.
+ //shellin=new BufferImpl();
+ //shellin.setMaxSize(STD_BUF_SIZE);
- outreader = new MultiBufferObjectReader(null, shellout);
+ if (interactive) {
+ ProcessGroup stdproc = new ProcessGroup(STDINPROC_ID, null, null);
+ shellout = new BufferImpl();
+ // CAREFUL HERE: If you print too much to out at the very beginning - in terms of objects
+ // you will deadlock
+ //shellout.setMaxSize(1);
+ shellout.setMaxSize(20);
+ stdproc.setOutputBuffer(shellout);
+ stdproc.setIOTimeout(PROC_INST_TIMEOUT);
+ procmap.put(STDINPROC_ID, stdproc);
+
+ outreader = new MultiBufferObjectReader(null, shellout);
+
//log.debug("Shellout buffer: " + shellout);
- }
+ }
- runtime = new ShellRuntime(this, interactive);
- runtime.setOutBuffer(shellout);
+ runtime = new ShellRuntime(this, interactive);
+ runtime.setOutBuffer(shellout);
- // we need user, we need to set pwd
- String home = "/home/mare";
- props.setProperty("PWD", home);
- runtime.setPWD(home);
+ // we need user, we need to set pwd
+ String home = "/home/mare";
+ props.setProperty("PWD", home);
+ runtime.setPWD(home);
- props.setProperty("SystemShell.startTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sshell.getStartTime()));
+ props.setProperty("SystemShell.startTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sshell.getStartTime()));
- // we had to set path first. Without it exes run without FileInfo in the init() phase.
- runtime.init(shellout);
- runtime.started();
+ // we had to set path first. Without it exes run without FileInfo in the init() phase.
+ runtime.init(shellout);
+ runtime.started();
- runtime.prompt();
+ runtime.prompt();
// wout.close();
- startTime = System.currentTimeMillis();
- }
+ startTime = System.currentTimeMillis();
+ }
- public void setRegistry(ExecutableRegistry registry)
- {
- if (registry != null)
- {
- runtime.setRegistry(registry);
- }
- }
+ public void setRegistry(ExecutableRegistry registry) {
+ if (registry != null) {
+ runtime.setRegistry(registry);
+ }
+ }
- private EventBroadcaster getEventBroadcaster() {
+ private EventBroadcaster getEventBroadcaster() {
- Context ctx = getContext();
- EventCentral evc = (EventCentral) ctx.get("EventCentral");
- if (evc == ec) {
- return eb;
- }
+ Context ctx = getContext();
+ EventCentral evc = (EventCentral) ctx.get("EventCentral");
+ if (evc == ec) {
+ return eb;
+ }
- synchronized(this) {
- if (evc == ec) {
- return eb;
- }
+ synchronized (this) {
+ if (evc == ec) {
+ return eb;
+ }
- if(evc == null) {
- // we cause unregister event
- if (eb != null) {
- eb.close();
- }
- eb = null;
- ec = null;
- return null;
- }
+ if (evc == null) {
+ // we cause unregister event
+ if (eb != null) {
+ eb.close();
+ }
+ eb = null;
+ ec = null;
+ return null;
+ }
- String compid = null;
+ String compid = null;
- if(eb!=null) {
- // we don't cause unregister event - just another register event
- compid = eb.getComponentID();
- eb.close();
- eb = new ShellEventBroadcaster(evc, this, EVENT_SOURCE, eb.getComponentID());
- } else {
- eb = new ShellEventBroadcaster(evc, this, EVENT_SOURCE);
- }
+ if (eb != null) {
+ // we don't cause unregister event - just another register event
+ compid = eb.getComponentID();
+ eb.close();
+ eb = new ShellEventBroadcaster(evc, this, EVENT_SOURCE, eb.getComponentID());
+ } else {
+ eb = new ShellEventBroadcaster(evc, this, EVENT_SOURCE);
+ }
- ec = evc;
- }
+ ec = evc;
+ }
- return eb;
- }
+ return eb;
+ }
- public void setVFS(VFS vfs) {
- this.vfs = vfs;
- }
+ public void setVFS(VFS vfs) {
+ this.vfs = vfs;
+ }
- public String getSessionID() {
- return uid;
- }
+ public String getSessionID() {
+ return uid;
+ }
- public Process getProcess(Object id) {
- return (Process) procmap.get(id);
- }
+ public Process getProcess(Object id) {
+ return (Process) procmap.get(id);
+ }
- public SystemShell getSystemShell() {
- return sshell;
- }
+ public SystemShell getSystemShell() {
+ return sshell;
+ }
- public String getClientInfo() throws ShellException {
- String cuser = _getEnvProperty("cp2.client.user");
- String capp = _getEnvProperty("cp2.client.app");
- String chost = _getEnvProperty("cp2.client.host");
+ public String getClientInfo() throws ShellException {
+ String cuser = _getEnvProperty("cp2.client.user");
+ String capp = _getEnvProperty("cp2.client.app");
+ String chost = _getEnvProperty("cp2.client.host");
- if (cuser == null) {
- cuser = "cuser_unknown";
- }
- if (chost == null) {
- chost = "chost_unknown";
- }
- if (capp == null) {
- capp = "capp_unknown";
- }
+ if (cuser == null) {
+ cuser = "cuser_unknown";
+ }
+ if (chost == null) {
+ chost = "chost_unknown";
+ }
+ if (capp == null) {
+ capp = "capp_unknown";
+ }
- return cuser + "@" + chost + " [" + capp + "] ";
- }
+ return cuser + "@" + chost + " [" + capp + "] ";
+ }
- public String getClientAndProjectInfo() throws ShellException {
- String cuser = _getEnvProperty("cp2.client.user");
- String capp = _getEnvProperty("cp2.client.app");
- String chost = _getEnvProperty("cp2.client.host");
+ public String getClientAndProjectInfo() throws ShellException {
+ String cuser = _getEnvProperty("cp2.client.user");
+ String capp = _getEnvProperty("cp2.client.app");
+ String chost = _getEnvProperty("cp2.client.host");
- if (cuser == null) {
- cuser = "cuser_unknown";
- }
- if (chost == null) {
- chost = "chost_unknown";
- }
- if (capp == null) {
- capp = "capp_unknown";
- }
+ if (cuser == null) {
+ cuser = "cuser_unknown";
+ }
+ if (chost == null) {
+ chost = "chost_unknown";
+ }
+ if (capp == null) {
+ capp = "capp_unknown";
+ }
- String project = _getEnvProperty("PROJECT");
- if (project == null) {
- project = "";
- }
+ String project = _getEnvProperty("PROJECT");
+ if (project == null) {
+ project = "";
+ }
- return cuser + "@" + chost + " [" + capp + "] [" + project + "] ";
- }
+ return cuser + "@" + chost + " [" + capp + "] [" + project + "] ";
+ }
- public ProcessInfo execute(String cmdline) throws ShellException {
- preStartTimeoutCheck();
- return _execute(cmdline, true, true, false);
- }
+ public ProcessInfo execute(String cmdline) throws ShellException {
+ preStartTimeoutCheck();
+ return _execute(cmdline, true, true, false);
+ }
- public ProcessInfo prepareExecution(String cmdline) throws ShellException {
- preStartTimeoutCheck();
- return _execute(cmdline, null, true, true, false, true);
- }
+ public ProcessInfo prepareExecution(String cmdline) throws ShellException {
+ preStartTimeoutCheck();
+ return _execute(cmdline, null, true, true, false, true);
+ }
- public ProcessInfo execute(String cmdline, List input) throws ShellException {
- preStartTimeoutCheck();
- return _execute(cmdline, input, true, true, false, false);
- }
+ public ProcessInfo execute(String cmdline, List input) throws ShellException {
+ preStartTimeoutCheck();
+ return _execute(cmdline, input, true, true, false, false);
+ }
- public ProcessInfo _execute(String cmdline) throws ShellException {
- return _execute(cmdline, true, true, false);
- }
+ public ProcessInfo _execute(String cmdline) throws ShellException {
+ return _execute(cmdline, true, true, false);
+ }
- public ProcessInfo execute(String cmdline, boolean ui) throws ShellException {
- preStartTimeoutCheck();
- return _execute(cmdline, true, true, ui);
- }
+ public ProcessInfo execute(String cmdline, boolean ui) throws ShellException {
+ preStartTimeoutCheck();
+ return _execute(cmdline, true, true, ui);
+ }
- public ProcessInfo execute(String cmdline, List input, boolean ui) throws ShellException {
- preStartTimeoutCheck();
- return _execute(cmdline, input, true, true, ui, false);
- }
+ public ProcessInfo execute(String cmdline, List input, boolean ui) throws ShellException {
+ preStartTimeoutCheck();
+ return _execute(cmdline, input, true, true, ui, false);
+ }
- public ProcessInfo _execute(String cmdline, boolean ui) throws ShellException {
- return _execute(cmdline, true, true, ui);
- }
+ public ProcessInfo _execute(String cmdline, boolean ui) throws ShellException {
+ return _execute(cmdline, true, true, ui);
+ }
- public ProcessInfo execute(String cmdline, boolean hasin, boolean hasout) throws ShellException {
- return _execute(cmdline, hasin, hasout, false);
- }
+ public ProcessInfo execute(String cmdline, boolean hasin, boolean hasout) throws ShellException {
+ return _execute(cmdline, hasin, hasout, false);
+ }
- public ProcessInfo execute(String cmdline, boolean hasin, boolean hasout, boolean ui) throws ShellException {
- return _execute(cmdline, hasin, hasout, ui);
- }
+ public ProcessInfo execute(String cmdline, boolean hasin, boolean hasout, boolean ui) throws ShellException {
+ return _execute(cmdline, hasin, hasout, ui);
+ }
- public ProcessInfo _execute(String cmdline, boolean hasin, boolean hasout, boolean ui) throws ShellException {
- return _execute(cmdline, null, hasin, hasout, ui, false);
- }
-
- public ProcessInfo _execute(String cmdline, List input, boolean hasin, boolean hasout, boolean ui, boolean prepareOnly) throws ShellException {
+ public ProcessInfo _execute(String cmdline, boolean hasin, boolean hasout, boolean ui) throws ShellException {
+ return _execute(cmdline, null, hasin, hasout, ui, false);
+ }
- try {
+ public ProcessInfo _execute(String cmdline, List input, boolean hasin, boolean hasout, boolean ui, boolean prepareOnly) throws ShellException {
+
+ try {
preStartTimeoutCheck();
if (cmdline == null || cmdline.length() == 0) {
- runtime.prompt();
- return null;
- }
+ runtime.prompt();
+ return null;
+ }
cmdline = convertCharset(cmdline);
if (cmdline.equals("exit")) {
closureReason = "Client issued 'exit'";
close();
- return null;
- } else if(cmdline.equals("tsingle")) {
- _setEnvProperty("TMODE", "SINGLE");
- return null;
- } else if(cmdline.equals("tmulti")) {
- _setEnvProperty("TMODE", null);
- return null;
- }
+ return null;
+ } else if (cmdline.equals("tsingle")) {
+ _setEnvProperty("TMODE", "SINGLE");
+ return null;
+ } else if (cmdline.equals("tmulti")) {
+ _setEnvProperty("TMODE", null);
+ return null;
+ }
//log.debug("log: " + log);
- String [] lines = cutInput(cmdline);
+ String[] lines = cutInput(cmdline);
cmdline = lines[0];
-
- cmdline = cmdline.trim();
- String cuser = _getEnvProperty("cp2.client.user");
- String chost = _getEnvProperty("cp2.client.host");
- String capp = null;
- String project = _getEnvProperty("PROJECT");
- if (project == null) {
- project = "";
- }
+ cmdline = cmdline.trim();
+ String cuser = _getEnvProperty("cp2.client.user");
+ String chost = _getEnvProperty("cp2.client.host");
+ String capp = null;
- if(cuser != null || chost != null) {
- capp = _getEnvProperty("cp2.client.app");
+ String project = _getEnvProperty("PROJECT");
+ if (project == null) {
+ project = "";
+ }
- if (cuser == null) {
- cuser = "cuser_unknown";
- }
- if (chost == null) {
- chost = "chost_unknown";
- }
- if (capp == null) {
- capp = "capp_unknown";
- }
+ if (cuser != null || chost != null) {
+ capp = _getEnvProperty("cp2.client.app");
- cmdlog.info(cuser + "@" + chost + " [" + capp + "] [" + project + "] " + cmdline);
- } else {
- cmdlog.info("[" + project + "] " + cmdline);
- }
+ if (cuser == null) {
+ cuser = "cuser_unknown";
+ }
+ if (chost == null) {
+ chost = "chost_unknown";
+ }
+ if (capp == null) {
+ capp = "capp_unknown";
+ }
- HistoryItem hi = addHistory(_getEnvProperty("PROJECT"), cuser, capp, chost, cmdline);
+ cmdlog.info(cuser + "@" + chost + " [" + capp + "] [" + project + "] " + cmdline);
+ } else {
+ cmdlog.info("[" + project + "] " + cmdline);
+ }
+
+ HistoryItem hi = addHistory(_getEnvProperty("PROJECT"), cuser, capp, chost, cmdline);
cmdline = StringUtils.unescapeJavaX(cmdline);
cmdline = runtime.unaliasCmdLine(cmdline);
ShellCmdParser parser = new ShellCmdParser(cmdline);
- LinkedList job = new LinkedList();
+ LinkedList job = new LinkedList();
- CmdLines cmdLines = parser.parse();
+ CmdLines cmdLines = parser.parse();
- cmdLines = resolveVars(cmdLines);
- cmdLines.setStdInLines(lines[1]);
- cmdLines.setStdInput(input);
-
- Iterator it = cmdLines.iterator();
- while (it.hasNext()) {
- Cmd cmd = (Cmd) it.next();
- makeProcess(cmdLines, cmd, job, hasin, hasout, ui);
- }
+ cmdLines = resolveVars(cmdLines);
+ cmdLines.setStdInLines(lines[1]);
+ cmdLines.setStdInput(input);
- if (job.size() > 1) {
- ProcessGroup p = sshell.createProcessGroup(job);
- if (p == null) {
- throw new ShellException("[ShellImpl][execute] Failed to create ProcessGroup.");
- }
- InBuffer ib = ((Process) job.getFirst()).getInputBuffer();
- OutBuffer ob = ((Process) job.getLast()).getOutputBuffer();
- p.setRedirected(((Process) job.getLast()).isRedirected());
+ Iterator it = cmdLines.iterator();
+ while (it.hasNext()) {
+ Cmd cmd = (Cmd) it.next();
+ makeProcess(cmdLines, cmd, job, hasin, hasout, ui);
+ }
+ if (job.size() > 1) {
+ ProcessGroup p = sshell.createProcessGroup(job);
+ if (p == null) {
+ throw new ShellException("[ShellImpl][execute] Failed to create ProcessGroup.");
+ }
+ InBuffer ib = ((Process) job.getFirst()).getInputBuffer();
+ OutBuffer ob = ((Process) job.getLast()).getOutputBuffer();
+ p.setRedirected(((Process) job.getLast()).isRedirected());
+
//log.debug("PRocessGroup ib: " + ib);
//log.debug("PRocessGroup ob: " + ob);
- p.setInputBuffer(ib);
- p.setOutputBuffer(ob);
- p.setCommandLine(cmdline);
+ p.setInputBuffer(ib);
+ p.setOutputBuffer(ob);
+ p.setCommandLine(cmdline);
- if (active == null) {
- active = p;
- }
+ if (active == null) {
+ active = p;
+ }
// if(interactive) {
// outreader.replacePrimaryBuffer(ob);
// }
- procmap.put(p.getID(), p);
- p.setUserInitiated(ui);
+ procmap.put(p.getID(), p);
+ p.setUserInitiated(ui);
- hi.setProcessID(p.getID());
+ hi.setProcessID(p.getID());
// We don't use it anywhere - WRONG - we use it when NoProcessForID Exceptions occur
LinkedList chs = hi.getChildren();
- LinkedList ls = p.getProcessList();
- it = ls.iterator();
- while(it.hasNext()) {
- Process cp = (Process) it.next();
- chs.add(cp);
- }
+ LinkedList ls = p.getProcessList();
+ it = ls.iterator();
+ while (it.hasNext()) {
+ Process cp = (Process) it.next();
+ chs.add(cp);
+ }
- if (!prepareOnly) {
- p.start(); // We have a problem with concurrent modification on job
- } else {
- preparedProcess.set(p);
- }
-
- ProcessInfo pinfo = new ProcessInfo();
- pinfo.procid = p.getID();
- pinfo.inbuf_maxsize = ib.getMaxSize();
- pinfo.outbuf_maxsize = ob.getMaxSize();
- return pinfo;
- } else {
- Process p = (Process) job.getFirst();
+ if (!prepareOnly) {
+ p.start(); // We have a problem with concurrent modification on job
+ } else {
+ preparedProcess.set(p);
+ }
+
+ ProcessInfo pinfo = new ProcessInfo();
+ pinfo.procid = p.getID();
+ pinfo.inbuf_maxsize = ib.getMaxSize();
+ pinfo.outbuf_maxsize = ob.getMaxSize();
+ return pinfo;
+ } else {
+ Process p = (Process) job.getFirst();
// System.out.println("Putting the process in the procmap: " + p.getID() + " : " + p);
- InBuffer ib = p.getInputBuffer();
- OutBuffer ob = p.getOutputBuffer();
+ InBuffer ib = p.getInputBuffer();
+ OutBuffer ob = p.getOutputBuffer();
//log.debug("PRocess ib: " + ib);
//log.debug("PRocess ob: " + ob);
- if (active == null) {
- active = p;
- }
+ if (active == null) {
+ active = p;
+ }
// if(interactive) {
// outreader.replacePrimaryBuffer(ob);
// }
// System.out.println("ACTIVE SET: " + active);
- procmap.put(p.getID(), p);
+ procmap.put(p.getID(), p);
//log.debug("***\n***[execute] Created process " + p.getID() + "\n***");
- log.debug("Created process " + p.getID());
+ log.debug("Created process " + p.getID());
- p.setUserInitiated(ui);
+ p.setUserInitiated(ui);
- hi.setProcessID(p.getID());
- hi.getChildren().add(p);
+ hi.setProcessID(p.getID());
+ hi.getChildren().add(p);
- if (!prepareOnly) {
- p.start();
- } else {
- preparedProcess.set(p);
- }
-
+ if (!prepareOnly) {
+ p.start();
+ } else {
+ preparedProcess.set(p);
+ }
+
// System.out.println("Started the process.");
- ProcessInfo pinfo = new ProcessInfo();
- pinfo.procid = p.getID();
- pinfo.inbuf_maxsize = ib.getMaxSize();
- pinfo.outbuf_maxsize = ob.getMaxSize();
- return pinfo;
- }
- } catch (SessionTimeoutException ex) {
+ ProcessInfo pinfo = new ProcessInfo();
+ pinfo.procid = p.getID();
+ pinfo.inbuf_maxsize = ib.getMaxSize();
+ pinfo.outbuf_maxsize = ob.getMaxSize();
+ return pinfo;
+ }
+ } catch (SessionTimeoutException ex) {
throw new SessionTimeoutException("Exception executing: " + cmdline + " - " + ex.getMessage());
} catch (ParseException ex) {
- log.error("Exception occured during parsing of the command line!", ex);
- throw new ShellException("Exception occured during parsing of the command line!", ex, cmdline);
- }
- // now we have several processes in the job list.
- // we still need to run them all.
- // If
+ log.error("Exception occured during parsing of the command line!", ex);
+ throw new ShellException("Exception occured during parsing of the command line!", ex, cmdline);
+ }
+ // now we have several processes in the job list.
+ // we still need to run them all.
+ // If
- // we need to interpret the command line
- // that is - we need to parse it
- // first command can be an internal command like cd
- // or it can be an executable
+ // we need to interpret the command line
+ // that is - we need to parse it
+ // first command can be an internal command like cd
+ // or it can be an executable
- // If not internal command:
- // we need to determine if executable with the specified name exists
- // executable name is a relative name or an absolute name
- // if absolute name we resolve it relative to all components of the PATH
- // until we find the first one that matches the pattern.
- // It's clear that we need VFS to be able to give us the list of all executables in the specified directory.
- //
- // (For starters we can put them all in the /bin directory and expect only name.)
- //
- // When we locate an executable, we need to allocate stdin and stdout Buffers for it.
- // Then we need to set ENV to it
+ // If not internal command:
+ // we need to determine if executable with the specified name exists
+ // executable name is a relative name or an absolute name
+ // if absolute name we resolve it relative to all components of the PATH
+ // until we find the first one that matches the pattern.
+ // It's clear that we need VFS to be able to give us the list of all executables in the specified directory.
+ //
+ // (For starters we can put them all in the /bin directory and expect only name.)
+ //
+ // When we locate an executable, we need to allocate stdin and stdout Buffers for it.
+ // Then we need to set ENV to it
- // We need to allocate a Process
- // We then put the Process in the process map allocating an uid along the way.
- // We then start a process and return an uid to the process.
+ // We need to allocate a Process
+ // We then put the Process in the process map allocating an uid along the way.
+ // We then start a process and return an uid to the process.
- // --------------------
- // Let's just run an executable
- // ok, we associate it with the exepath, we set user
- // we allocate in/out buffers
- // we set Buffers on the exe
- // we store it in the Process
- // we store the process in our process map
- // we run the process/executable
- // we return process id. (process id is what? shouldn't SystemShell create a process for us?)
- // (If we create processes ourselves then there is no way to go to one central place and say
- // kill process number 10. Which is a process started by some user in his shell.)
- // To have this sort of control, we need the central to have access to the Process and say kill
- // on it.
+ // --------------------
+ // Let's just run an executable
+ // ok, we associate it with the exepath, we set user
+ // we allocate in/out buffers
+ // we set Buffers on the exe
+ // we store it in the Process
+ // we store the process in our process map
+ // we run the process/executable
+ // we return process id. (process id is what? shouldn't SystemShell create a process for us?)
+ // (If we create processes ourselves then there is no way to go to one central place and say
+ // kill process number 10. Which is a process started by some user in his shell.)
+ // To have this sort of control, we need the central to have access to the Process and say kill
+ // on it.
- }
+ }
- /**
- * To be used in conjunction with prepareExecution
- * @throws ShellException
- */
- public void completeExecution() throws ShellException {
+ /**
+ * To be used in conjunction with prepareExecution
+ *
+ * @throws ShellException
+ */
+ public void completeExecution() throws ShellException {
//System.out.println(" completeExecution entered");
- preStartTimeoutCheck();
- //System.out.println(" completeExecution 1");
- Process p = (Process) preparedProcess.get();
- //System.out.println(" completeExecution 2 p == " + p);
- if(p == null) {
- //new Exception("No prepared process found").printStackTrace();
- throw new ShellException("No prepared process found - was prepareExecution() called in this thread?");
- }
- //System.out.println(" completeExecution 3");
- preparedProcess.remove();
+ preStartTimeoutCheck();
+ //System.out.println(" completeExecution 1");
+ Process p = (Process) preparedProcess.get();
+ //System.out.println(" completeExecution 2 p == " + p);
+ if (p == null) {
+ //new Exception("No prepared process found").printStackTrace();
+ throw new ShellException("No prepared process found - was prepareExecution() called in this thread?");
+ }
+ //System.out.println(" completeExecution 3");
+ preparedProcess.remove();
//System.out.println(" *Calling Process.start()");
- p.start();
- }
+ p.start();
+ }
-
+
private String[] cutInput(String cmdline) {
- int idx = cmdline.indexOf("\n");
-
- if(idx != -1) {
- int e1 = idx;
+ int idx = cmdline.indexOf("\n");
- for(int i=idx-1; i>=0; i--) {
- char c = cmdline.charAt(i);
- if(c != '\r') {
- e1 = i+1;
- break;
- }
- }
+ if (idx != -1) {
+ int e1 = idx;
- return new String[] {cmdline.substring(0, e1), (idx == cmdline.length()-1) ? "" : cmdline.substring(idx+1)};
- }
-
- return new String[] {cmdline, null};
- }
+ for (int i = idx - 1; i >= 0; i--) {
+ char c = cmdline.charAt(i);
+ if (c != '\r') {
+ e1 = i + 1;
+ break;
+ }
+ }
+ return new String[]{cmdline.substring(0, e1), (idx == cmdline.length() - 1) ? "" : cmdline.substring(idx + 1)};
+ }
+ return new String[]{cmdline, null};
+ }
- private String convertCharset(String cmdline) throws ShellException {
+
+ private String convertCharset(String cmdline) throws ShellException {
// check environment settings
String enc = getEnvProperty("TERMINAL_ENC");
- if (enc == null) {
- return cmdline;
- }
+ if (enc == null) {
+ return cmdline;
+ }
try {
return new String(new String(cmdline).getBytes("ISO8859_1"), enc);
- } catch(IOException ex) {
+ } catch (IOException ex) {
setEnvProperty("TERMINAL_ENC_ERROR", "Unsupported charset: " + enc);
}
@@ -625,7 +597,7 @@
HistoryItem hitem = new HistoryItem(project, cuser, capp, chost, cmdline);
History h = (History) ctx.get("History");
- if(h == null) {
+ if (h == null) {
h = new History();
ctx.put("History", h);
}
@@ -633,11 +605,11 @@
h.add(hitem);
Context actx = (Context) ctx.get("AppContext");
- if(actx == null) {
+ if (actx == null) {
log.debug("AppContext not available");
} else {
h = (History) actx.get("History");
- if(h == null) {
+ if (h == null) {
h = new History();
actx.put("History", h);
}
@@ -648,14 +620,15 @@
// would be nice to have a wrapper that returns null and throws no exceptions
try {
actx = (Context) new InitialContext().lookup("java:/FRESH/GlobalContext");
- } catch(Exception ex) {
+ } catch (Exception ex) {
}
+ //actx = getComponentByType(Context.class);
- if(actx == null) {
+ if (actx == null) {
log.debug("GlobalContext not available");
} else {
h = (History) actx.get("History");
- if(h == null) {
+ if (h == null) {
h = new History();
actx.put("History", h);
}
@@ -666,535 +639,532 @@
return hitem;
}
- public HistoryItem getHistoryItem(String id) {
-log.info("id: " + id);
- HistoryItem ti = null;
- Context c = ctx;
- for(int i=0; i<3; i++) {
-log.info("i: " + i + ", ctx: " + c);
- HashMap map = new HashMap();
+ public HistoryItem getHistoryItem(String id) {
+ log.info("id: " + id);
+ HistoryItem ti = null;
+ Context c = ctx;
+ for (int i = 0; i < 3; i++) {
+ log.info("i: " + i + ", ctx: " + c);
+ HashMap map = new HashMap();
- c.loadMappings(map);
+ c.loadMappings(map);
- java.util.TreeMap sm = new java.util.TreeMap(map);
- Iterator it0 = sm.entrySet().iterator();
- while (it0.hasNext()) {
- Map.Entry ent = (Map.Entry) it0.next();
- log.info(ent.getKey() + "\t=\t" + ent.getValue() + "\t" + ent.getValue().getClass().getName());
- }
+ java.util.TreeMap sm = new java.util.TreeMap(map);
+ Iterator it0 = sm.entrySet().iterator();
+ while (it0.hasNext()) {
+ Map.Entry ent = (Map.Entry) it0.next();
+ log.info(ent.getKey() + "\t=\t" + ent.getValue() + "\t" + ent.getValue().getClass().getName());
+ }
- History h = (History) c.get("History");
- Iterator it = h.list().iterator();
- while(it.hasNext()) {
- HistoryItem hi = (HistoryItem) it.next();
- log.info("compare: " + hi.getProcessID() + " vs. " + id);
- if(hi.getProcessID().equals(id)) {
- ti = hi;
- break;
- //Iterator it2 = hi.getChildren().iterator;
- //while(it2.hasNext()) {
- // Process p = (Process) it.next();
- //}
- }
- }
+ History h = (History) c.get("History");
+ Iterator it = h.list().iterator();
+ while (it.hasNext()) {
+ HistoryItem hi = (HistoryItem) it.next();
+ log.info("compare: " + hi.getProcessID() + " vs. " + id);
+ if (hi.getProcessID().equals(id)) {
+ ti = hi;
+ break;
+ //Iterator it2 = hi.getChildren().iterator;
+ //while(it2.hasNext()) {
+ // Process p = (Process) it.next();
+ //}
+ }
+ }
- if(ti == null) {
- if(i==0) {
- c = (Context) ctx.get("AppContext");
- if(c == null) {
- try {
- c = (Context) new InitialContext().lookup("java:/FRESH/GlobalContext");
- } catch(Exception ex) {}
- i++;
- }
- } else if(i==1) {
+ if (ti == null) {
+ if (i == 0) {
+ c = (Context) ctx.get("AppContext");
+ if (c == null) {
+ try {
+ c = (Context) new InitialContext().lookup("java:/FRESH/GlobalContext");
+ } catch (Exception ex) {
+ }
+ i++;
+ }
+ } else if (i == 1) {
- try {
- c = (Context) new InitialContext().lookup("java:/FRESH/GlobalContext");
- } catch(Exception ex) {}
- if (c == null) {
- i++;
- }
- }
- }
- }
+ try {
+ c = (Context) new InitialContext().lookup("java:/FRESH/GlobalContext");
+ } catch (Exception ex) {
+ }
+ if (c == null) {
+ i++;
+ }
+ }
+ }
+ }
- return ti;
- }
+ return ti;
+ }
+ public ProcessInfo execute(Executable exe, String exepath, String[] params) throws ShellException {
- public ProcessInfo execute(Executable exe, String exepath, String[] params) throws ShellException {
-
try {
preStartTimeoutCheck();
- } catch(SessionTimeoutException ex) {
+ } catch (SessionTimeoutException ex) {
StringBuffer sb = new StringBuffer(exepath);
- if(params != null) {
- for(int i=0; i<params.length; i++) {
+ if (params != null) {
+ for (int i = 0; i < params.length; i++) {
sb.append(" \'").append(params[i]).append('\'');
}
}
- throw new SessionTimeoutException("Exception executing: " + sb + " - " + ex.getMessage() );
+ throw new SessionTimeoutException("Exception executing: " + sb + " - " + ex.getMessage());
}
Process p = sshell.createProcess(this);
- long ptimeout = PROC_INST_TIMEOUT;
+ long ptimeout = PROC_INST_TIMEOUT;
- p.setIOTimeout(ptimeout);
- p.setExecutable(exe);
- exe.setProcess(p);
- exe.setShell(this);
+ p.setIOTimeout(ptimeout);
+ p.setExecutable(exe);
+ exe.setProcess(p);
+ exe.setShell(this);
- p.setCommandLine(null); // don't know what to do with this
- p.setParams(params);
- p.setExePath(exepath);
- p.setInputBuffer(exe.getStdIn());
- p.setOutputBuffer(exe.getStdOut());
+ p.setCommandLine(null); // don't know what to do with this
+ p.setParams(params);
+ p.setExePath(exepath);
+ p.setInputBuffer(exe.getStdIn());
+ p.setOutputBuffer(exe.getStdOut());
- procmap.put(p.getID(), p);
+ procmap.put(p.getID(), p);
//log.debug("***\n***[execute2] Created process " + p.getID() + "\n***");
- log.debug("Created process " + p.getID());
- p.setUserInitiated(false); // what does it mean again ?
- p.start();
- //log.debug("Started the process.");
+ log.debug("Created process " + p.getID());
+ p.setUserInitiated(false); // what does it mean again ?
+ p.start();
+ //log.debug("Started the process.");
- ProcessInfo pinfo = new ProcessInfo();
- pinfo.procid = p.getID();
- pinfo.inbuf_maxsize = exe.getStdIn().getMaxSize();
- pinfo.outbuf_maxsize = exe.getStdOut().getMaxSize();
- return pinfo;
- }
+ ProcessInfo pinfo = new ProcessInfo();
+ pinfo.procid = p.getID();
+ pinfo.inbuf_maxsize = exe.getStdIn().getMaxSize();
+ pinfo.outbuf_maxsize = exe.getStdOut().getMaxSize();
+ return pinfo;
+ }
+ public Process createProcess(Executable exe, String[] params, String path, boolean useThreadPool) throws ShellException {
- public Process createProcess(Executable exe, String [] params, String path, boolean useThreadPool) throws ShellException {
-
try {
preStartTimeoutCheck();
- } catch(SessionTimeoutException ex) {
+ } catch (SessionTimeoutException ex) {
StringBuffer sb = new StringBuffer(path);
- if(params != null) {
- for(int i=0; i<params.length; i++) {
+ if (params != null) {
+ for (int i = 0; i < params.length; i++) {
sb.append(" \'").append(params[i]).append('\'');
}
}
- throw new SessionTimeoutException("Exception executing: " + sb + " - " + ex.getMessage() );
+ throw new SessionTimeoutException("Exception executing: " + sb + " - " + ex.getMessage());
}
Process p = sshell.createProcess(this, useThreadPool);
- long ptimeout = PROC_INST_TIMEOUT;
+ long ptimeout = PROC_INST_TIMEOUT;
- p.setIOTimeout(ptimeout);
- p.setExecutable(exe);
- exe.setProcess(p);
+ p.setIOTimeout(ptimeout);
+ p.setExecutable(exe);
+ exe.setProcess(p);
- StringBuffer cmdline = new StringBuffer();
- cmdline.append(path == null ? "<cmd>" : path);
- if(params!=null) {
- for(int i=0; i<params.length; i++) {
- cmdline.append(" ").append(params[i]);
- }
- }
+ StringBuffer cmdline = new StringBuffer();
+ cmdline.append(path == null ? "<cmd>" : path);
+ if (params != null) {
+ for (int i = 0; i < params.length; i++) {
+ cmdline.append(" ").append(params[i]);
+ }
+ }
- p.setCommandLine(cmdline.toString());
- p.setParams(params);
- p.setExePath(path);
- p.setInputBuffer(exe.getStdIn());
- p.setOutputBuffer(exe.getStdOut());
+ p.setCommandLine(cmdline.toString());
+ p.setParams(params);
+ p.setExePath(path);
+ p.setInputBuffer(exe.getStdIn());
+ p.setOutputBuffer(exe.getStdOut());
- procmap.put(p.getID(), p);
- log.debug("Created process " + p.getID());
- p.setUserInitiated(false); // what does it mean again ?
+ procmap.put(p.getID(), p);
+ log.debug("Created process " + p.getID());
+ p.setUserInitiated(false); // what does it mean again ?
- return p;
- }
+ return p;
+ }
- private CmdLines resolveVars(CmdLines cmds) throws ShellException {
+ private CmdLines resolveVars(CmdLines cmds) throws ShellException {
- LinkedList cmdsl = new LinkedList();
+ LinkedList cmdsl = new LinkedList();
- Iterator it = cmds.iterator();
- while (it.hasNext()) {
- Cmd cmd = (Cmd) it.next();
- String scmd = cmd.getExec();
- // we leave cmd as it is.
+ Iterator it = cmds.iterator();
+ while (it.hasNext()) {
+ Cmd cmd = (Cmd) it.next();
+ String scmd = cmd.getExec();
+ // we leave cmd as it is.
- String[] params = cmd.getParams();
- LinkedList ops = new LinkedList();
- // we process each one - look for $ then look for eof or space.
- // we try resolve $ if can't then leave it as it is.
+ String[] params = cmd.getParams();
+ LinkedList ops = new LinkedList();
+ // we process each one - look for $ then look for eof or space.
+ // we try resolve $ if can't then leave it as it is.
//log.debug("cmdline parameters: ");
- for (int i = 0; i < params.length; i++) {
+ for (int i = 0; i < params.length; i++) {
- String c = params[i];
+ String c = params[i];
//log.debug("*** " + c);
// in here we do several things. We resolve env vars only if " or without
// we do pathname expansion if not " or ' and *, ? or [ is present
-
/*
- if(c.startsWith("'")) {
- if(c.endsWith("'")) {
- ops.add(c.substring(1, c.length()-1));
- continue;
- } else {
- ops.add(c.substring(1, c.length()));
- continue;
- }
- }
+ if(c.startsWith("'")) {
+ if(c.endsWith("'")) {
+ ops.add(c.substring(1, c.length()-1));
+ continue;
+ } else {
+ ops.add(c.substring(1, c.length()));
+ continue;
+ }
+ }
- if(c.endsWith("'")) {
- ops.add(c.substring(0, c.length()-1));
- continue;
- }
+ if(c.endsWith("'")) {
+ ops.add(c.substring(0, c.length()-1));
+ continue;
+ }
*/
// if starts with " and ends with " then we need to remove that
// if it does not end with " then we treat it as if it is not within quotes
- if (c.startsWith("'") && c.endsWith("'") && c.length() > 1) {
- ops.add(c.substring(1, c.length() - 1));
- continue;
- }
+ if (c.startsWith("'") && c.endsWith("'") && c.length() > 1) {
+ ops.add(c.substring(1, c.length() - 1));
+ continue;
+ }
- StringBuffer outc = new StringBuffer();
- StringTokenizer st = new StringTokenizer(c, "$ ", true);
- boolean isVar = false;
- while (st.hasMoreTokens()) {
- String t = st.nextToken();
+ StringBuffer outc = new StringBuffer();
+ StringTokenizer st = new StringTokenizer(c, "$ ", true);
+ boolean isVar = false;
+ while (st.hasMoreTokens()) {
+ String t = st.nextToken();
//log.debug("[SSH] : t: " + t);
- if (t.equals("$")) {
- isVar = true;
+ if (t.equals("$")) {
+ isVar = true;
//log.debug("[SSH] : found $");
- } else {
- if (isVar) {
- // lookup t
- String p = null;
- int j = 0;
- StringBuffer psmp = new StringBuffer();
+ } else {
+ if (isVar) {
+ // lookup t
+ String p = null;
+ int j = 0;
+ StringBuffer psmp = new StringBuffer();
//log.debug("[SSH] : init psmp: " + psmp);
- for (j = 0; j < t.length() && p == null; j++) {
+ for (j = 0; j < t.length() && p == null; j++) {
//log.debug("[SSH] : trying " + psmp);
- psmp.append(t.charAt(j));
- p = getEnvProperty(cmd, psmp.toString());
- }
+ psmp.append(t.charAt(j));
+ p = getEnvProperty(cmd, psmp.toString());
+ }
- if (p == null) {
+ if (p == null) {
//log.debug("[SSH] : no property for this name");
- outc.append("$").append(t);
- } else {
+ outc.append("$").append(t);
+ } else {
//log.debug("[SSH] : found property: " + p);
- outc.append(p);
- if (j < t.length()) {
+ outc.append(p);
+ if (j < t.length()) {
//log.debug("[SSH] : appending a remnant: " + t.substring(j, t.length()));
- outc.append(t.substring(j, t.length()));
- }
- }
+ outc.append(t.substring(j, t.length()));
+ }
+ }
- isVar = false;
- } else {
- outc.append(t);
- }
- }
- }
- c = outc.toString();
+ isVar = false;
+ } else {
+ outc.append(t);
+ }
+ }
+ }
+ c = outc.toString();
- if (c.startsWith("\"") && c.endsWith("\"") && c.length() > 1) {
- ops.add(c.substring(1, c.length() - 1));
- continue;
- }
+ if (c.startsWith("\"") && c.endsWith("\"") && c.length() > 1) {
+ ops.add(c.substring(1, c.length() - 1));
+ continue;
+ }
- if (c.indexOf("?") != -1 || c.indexOf("*") != -1 || (c.indexOf("[") != -1 && c.indexOf("]") != -1)) {
+ if (c.indexOf("?") != -1 || c.indexOf("*") != -1 || (c.indexOf("[") != -1 && c.indexOf("]") != -1)) {
// System.out.println("It's a pattern! : " + c);
- try {
- FPExpand fpe = new FPExpand(this);
- fpe.expand(c);
- Vector vx = fpe.getMatches();
- Iterator itx = vx.iterator();
- while (itx.hasNext()) {
- ops.add(((FileInfo) itx.next()).getFileName().toString());
- }
- } catch (Exception ex) {
- log.error("Could not expand", ex);
- }
+ try {
+ FPExpand fpe = new FPExpand(this);
+ fpe.expand(c);
+ Vector vx = fpe.getMatches();
+ Iterator itx = vx.iterator();
+ while (itx.hasNext()) {
+ ops.add(((FileInfo) itx.next()).getFileName().toString());
+ }
+ } catch (Exception ex) {
+ log.error("Could not expand", ex);
+ }
- continue;
- }
+ continue;
+ }
- ops.add(c);
- }
+ ops.add(c);
+ }
- String[] pout = new String[ops.size()];
- Iterator it2 = ops.iterator();
- for (int i = 0; it2.hasNext(); i++) {
- pout[i] = (String) it2.next();
- }
+ String[] pout = new String[ops.size()];
+ Iterator it2 = ops.iterator();
+ for (int i = 0; it2.hasNext(); i++) {
+ pout[i] = (String) it2.next();
+ }
- //cmdsl.add(new Cmd(scmd, pout, null, null));
- cmd.setParams(pout);
- cmdsl.add(cmd);
- }
+ //cmdsl.add(new Cmd(scmd, pout, null, null));
+ cmd.setParams(pout);
+ cmdsl.add(cmd);
+ }
- cmds.setCmds(cmdsl);
- return cmds;
- }
+ cmds.setCmds(cmdsl);
+ return cmds;
+ }
private void makeProcess(CmdLines cmdl, Cmd cmd, LinkedList joblist, boolean hasin, boolean hasout, boolean ui) throws ShellException {
- String command = cmd.getExec();
- String exepath = "/bin/" + command;
- String[] params = cmd.getParams();
+ String command = cmd.getExec();
+ String exepath = "/bin/" + command;
+ String[] params = cmd.getParams();
- int inbufmax = IN_BUF_SIZE;
- int outbufmax = OUT_BUF_SIZE;
+ int inbufmax = IN_BUF_SIZE;
+ int outbufmax = OUT_BUF_SIZE;
- Properties env = _getEnvProperties();
+ Properties env = _getEnvProperties();
- String ibs = getEnvProperty("IN_BUF_SIZE");
- if (ibs != null) {
- try {
- inbufmax = Integer.parseInt(ibs);
- } catch (Exception ex) {
- log.error("Problem while reading buffer", ex);
- }
- }
+ String ibs = getEnvProperty("IN_BUF_SIZE");
+ if (ibs != null) {
+ try {
+ inbufmax = Integer.parseInt(ibs);
+ } catch (Exception ex) {
+ log.error("Problem while reading buffer", ex);
+ }
+ }
- String obs = getEnvProperty("OUT_BUF_SIZE");
- if (obs != null) {
- try {
- outbufmax = Integer.parseInt(obs);
- } catch (Exception ex) {
- log.error("Problem while wrinting buffer", ex);
- }
- }
+ String obs = getEnvProperty("OUT_BUF_SIZE");
+ if (obs != null) {
+ try {
+ outbufmax = Integer.parseInt(obs);
+ } catch (Exception ex) {
+ log.error("Problem while wrinting buffer", ex);
+ }
+ }
- long ptimeout = PROC_INST_TIMEOUT;
+ long ptimeout = PROC_INST_TIMEOUT;
- if (inbufmax > BUF_MAX_SIZE) {
- inbufmax = BUF_MAX_SIZE;
- }
+ if (inbufmax > BUF_MAX_SIZE) {
+ inbufmax = BUF_MAX_SIZE;
+ }
- if (PROC_TIMEOUT_MAX != 0) {
- if (ptimeout == 0 || ptimeout > PROC_TIMEOUT_MAX) {
- ptimeout = PROC_TIMEOUT_MAX;
- }
- }
+ if (PROC_TIMEOUT_MAX != 0) {
+ if (ptimeout == 0 || ptimeout > PROC_TIMEOUT_MAX) {
+ ptimeout = PROC_TIMEOUT_MAX;
+ }
+ }
- Executable exe = runtime.loadExe(command);
+ Executable exe = runtime.loadExe(command);
+ // Exe is ok, we have created it.
- // Exe is ok, we have created it.
-
// System.out.println("Successfully loaded executable.");
- // Now we ask sysshell to create process.
+ // Now we ask sysshell to create process.
// System.out.println("Creating new process ...");
- Process p = sshell.createProcess(this);
- setupEnv(cmd, p);
+ Process p = sshell.createProcess(this);
+ setupEnv(cmd, p);
- p.setIOTimeout(ptimeout);
+ p.setIOTimeout(ptimeout);
// System.out.println("Created process: " + p);
- // We only create in buffer if we are the first, otherwise we simply use
- // previous exe's output buffer. To know if we are first it would help to have
- // access to job list
- InBuffer in = null;
- if (joblist.size() == 0) {
+ // We only create in buffer if we are the first, otherwise we simply use
+ // previous exe's output buffer. To know if we are first it would help to have
+ // access to job list
+ InBuffer in = null;
+ if (joblist.size() == 0) {
- if (cmdl.getSLStdInRedir() != null) {
- try {
- InputStreamBuffer bin = new InputStreamBuffer(new FileInputStream(cmdl.getSLStdInRedir()), cmdl.isSLInObjMode());
- bin.setProperties(env);
- in = bin;
- } catch (IOException ex) {
- throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
- }
+ if (cmdl.getSLStdInRedir() != null) {
+ try {
+ InputStreamBuffer bin = new InputStreamBuffer(new FileInputStream(cmdl.getSLStdInRedir()), cmdl.isSLInObjMode());
+ bin.setProperties(env);
+ in = bin;
+ } catch (IOException ex) {
+ throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
+ }
- } else if (cmdl.getStdInRedir() != null) {
- try {
- //in=new InputStreamBuffer(new VFSInputStream(new SecureVFS(vfs, uctx), cmdl.getStdInRedir()), cmdl.isInObjMode());
- if(cmdl.getStdInLines() != null) {
- String enc = env.getProperty("ENC");
- ByteArrayInputStream bain;
- if(enc != null) {
- bain = new ByteArrayInputStream(cmdl.getStdInLines().getBytes("ENC"));
- } else {
- bain = new ByteArrayInputStream(cmdl.getStdInLines().getBytes());
- }
- InputStreamBuffer bin = new InputStreamBuffer(bain, false);
- bin.setProperties(env);
- in = bin;
-
- } else {
- FileName fname = new FileName(cmdl.getStdInRedir());
- if (fname.isRelative()) {
- fname = new FileName(getEnvProperty("PWD")).absolutize(fname);
- }
- InputStreamBuffer bin = new InputStreamBuffer(new VFSInputStream(new SecureVFS(vfs, uctx), fname.toString()), cmdl.isInObjMode());
- bin.setProperties(env);
- in = bin;
- }
+ } else if (cmdl.getStdInRedir() != null) {
+ try {
+ //in=new InputStreamBuffer(new VFSInputStream(new SecureVFS(vfs, uctx), cmdl.getStdInRedir()), cmdl.isInObjMode());
+ if (cmdl.getStdInLines() != null) {
+ String enc = env.getProperty("ENC");
+ ByteArrayInputStream bain;
+ if (enc != null) {
+ bain = new ByteArrayInputStream(cmdl.getStdInLines().getBytes("ENC"));
+ } else {
+ bain = new ByteArrayInputStream(cmdl.getStdInLines().getBytes());
+ }
+ InputStreamBuffer bin = new InputStreamBuffer(bain, false);
+ bin.setProperties(env);
+ in = bin;
- } catch (IOException ex) {
- throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
- }
+ } else {
+ FileName fname = new FileName(cmdl.getStdInRedir());
+ if (fname.isRelative()) {
+ fname = new FileName(getEnvProperty("PWD")).absolutize(fname);
+ }
+ InputStreamBuffer bin = new InputStreamBuffer(new VFSInputStream(new SecureVFS(vfs, uctx), fname.toString()), cmdl.isInObjMode());
+ bin.setProperties(env);
+ in = bin;
+ }
- }
+ } catch (IOException ex) {
+ throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
+ }
+ }
- if (in == null) {
+
+ if (in == null) {
//log.debug("No output redirect setup...");
- if (hasin) {
- if (!"SINGLE".equals(getEnvProperty("TMODE"))) {
- in = new BufferImpl();
- } else {
- in = new MemFileBufferImpl();
- }
- // here we set whatever is maxsize for inputbuffer for this executable - we have this set
- // as attribute on the file or something ...
- // FIXME
- List input = cmdl.getStdInput();
- if(input != null) {
- in.setMaxSize(input.size());
- try {
- ((Buffer)in).putBuffer(new LinkedList(input), 1000);
- in.close();
- } catch (IOException ex) {
- throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
- }
- }
- in.setMaxSize(inbufmax); // should be a variable
+ if (hasin) {
+ if (!"SINGLE".equals(getEnvProperty("TMODE"))) {
+ in = new BufferImpl();
+ } else {
+ in = new MemFileBufferImpl();
+ }
+ // here we set whatever is maxsize for inputbuffer for this executable - we have this set
+ // as attribute on the file or something ...
+ // FIXME
+ List input = cmdl.getStdInput();
+ if (input != null) {
+ in.setMaxSize(input.size());
+ try {
+ ((Buffer) in).putBuffer(new LinkedList(input), 1000);
+ in.close();
+ } catch (IOException ex) {
+ throw new ShellException("Exception occured while initializing input buffer: " + ex.toString());
+ }
+ }
+ in.setMaxSize(inbufmax); // should be a variable
- } else {
- in = new NullBuffer();
- }
- }
+ } else {
+ in = new NullBuffer();
+ }
+ }
- } else {
+ } else {
//log.debug("Piping in previous out...");
- Object o_in = ((Process) joblist.getLast()).getOutputBuffer();
- if (!(o_in instanceof InBuffer)) {
- throw new ShellException("Invalid pipe chain. Trying to read from write-only buffer.");
- }
- in = (InBuffer) o_in;
- }
+ Object o_in = ((Process) joblist.getLast()).getOutputBuffer();
+ if (!(o_in instanceof InBuffer)) {
+ throw new ShellException("Invalid pipe chain. Trying to read from write-only buffer.");
+ }
+ in = (InBuffer) o_in;
+ }
//log.debug("\n\nin = " + in);
- OutBuffer out = null;
+ OutBuffer out = null;
- if (cmdl.size() == joblist.size() + 1) {
+ if (cmdl.size() == joblist.size() + 1) {
- if (cmdl.getSLStdOutRedir() != null) {
- try {
- OutputStreamBuffer bout = new OutputStreamBuffer(new FileOutputStream(cmdl.getSLStdOutRedir(), cmdl.getSLAppend()), cmdl.isSLOutObjMode());
- bout.setProperties(env);
- out = bout;
- p.setRedirected(true);
- } catch (IOException ex) {
- throw new ShellException("Exception occured while initializing output buffer: " + ex.toString());
- }
+ if (cmdl.getSLStdOutRedir() != null) {
+ try {
+ OutputStreamBuffer bout = new OutputStreamBuffer(new FileOutputStream(cmdl.getSLStdOutRedir(), cmdl.getSLAppend()), cmdl.isSLOutObjMode());
+ bout.setProperties(env);
+ out = bout;
+ p.setRedirected(true);
+ } catch (IOException ex) {
+ throw new ShellException("Exception occured while initializing output buffer: " + ex.toString());
+ }
- } else if (cmdl.getStdOutRedir() != null) {
- try {
- ////out=new OutputStreamBuffer(new VFSOutputStream(new SecureVFS(vfs, uctx), cmdl.getStdOutRedir(), cmdl.getAppend()), cmdl.isOutObjMode());
+ } else if (cmdl.getStdOutRedir() != null) {
+ try {
+ ////out=new OutputStreamBuffer(new VFSOutputStream(new SecureVFS(vfs, uctx), cmdl.getStdOutRedir(), cmdl.getAppend()), cmdl.isOutObjMode());
- //if(TxSupport.isActive()) throw new ShellException("Illegal state - inside transaction.");
- //TxSupport.begin();
- try {
- FileName fname = new FileName(cmdl.getStdOutRedir());
- if (fname.isRelative()) {
- fname = new FileName(getEnvProperty("PWD")).absolutize(fname);
- }
- OutputStreamBuffer bout = new OutputStreamBuffer(new LazyVFSOutputStream(new SecureVFS(vfs, uctx), fname.toString(), cmdl.getAppend()), cmdl.isOutObjMode());
- bout.setProperties(env);
- out = bout;
- p.setRedirected(true);
- //TxSupport.commit();
- } catch (Exception ex) {
- //TxSupport.rollback();
- throw ex;
- }
- } catch (Exception ex) {
- log.error("Exception occured while initializing output buffer: ", ex);
- throw new ShellException("Exception occured while initializing output buffer: " + ex.toString());
- }
- }
- }
+ //if(TxSupport.isActive()) throw new ShellException("Illegal state - inside transaction.");
+ //TxSupport.begin();
+ try {
+ FileName fname = new FileName(cmdl.getStdOutRedir());
+ if (fname.isRelative()) {
+ fname = new FileName(getEnvProperty("PWD")).absolutize(fname);
+ }
+ OutputStreamBuffer bout = new OutputStreamBuffer(new LazyVFSOutputStream(new SecureVFS(vfs, uctx), fname.toString(), cmdl.getAppend()), cmdl.isOutObjMode());
+ bout.setProperties(env);
+ out = bout;
+ p.setRedirected(true);
+ //TxSupport.commit();
+ } catch (Exception ex) {
+ //TxSupport.rollback();
+ throw ex;
+ }
+ } catch (Exception ex) {
+ log.error("Exception occured while initializing output buffer: ", ex);
+ throw new ShellException("Exception occured while initializing output buffer: " + ex.toString());
+ }
+ }
+ }
//log.debug("\n\nout = " + out);
- if (out == null) {
- if (hasout) {
- if (!"SINGLE".equals(getEnvProperty("TMODE"))) {
- out = new BufferImpl();
- } else {
- out = new MemFileBufferImpl();
- }
-
- // here we set whatever is maxsize for inputbuffer for this executable - we have this set
- // as attribute on the file or something ...
- // FIXME
- out.setMaxSize(outbufmax); // should be a variable
+ if (out == null) {
+ if (hasout) {
+ if (!"SINGLE".equals(getEnvProperty("TMODE"))) {
+ out = new BufferImpl();
+ } else {
+ out = new MemFileBufferImpl();
+ }
- } else {
- out = new NullBuffer();
- }
+ // here we set whatever is maxsize for inputbuffer for this executable - we have this set
+ // as attribute on the file or something ...
+ // FIXME
+ out.setMaxSize(outbufmax); // should be a variable
- if ((cmdl.size() == joblist.size() + 1) && ui && interactive) {
- procmap.put(STDIN_ID, p);
- outreader.replacePrimaryBuffer((InBuffer) out);
- }
- }
+ } else {
+ out = new NullBuffer();
+ }
+ if ((cmdl.size() == joblist.size() + 1) && ui && interactive) {
+ procmap.put(STDIN_ID, p);
+ outreader.replacePrimaryBuffer((InBuffer) out);
+ }
+ }
+
//log.debug("\n\nfinal out = " + out);
- p.setInputBuffer(in);
- p.setOutputBuffer(out);
+ p.setInputBuffer(in);
+ p.setOutputBuffer(out);
// System.out.println("Set allocated resurces on executable ...");
//log.debug("exe stdin = " + in);
//log.debug("exe stdout = " + out);
- exe.setStdIn(in);
- exe.setStdOut(out);
- exe.setShell(this);
+ exe.setStdIn(in);
+ exe.setStdOut(out);
+ exe.setShell(this);
// System.out.println("Setting executable on Process ...");
- p.setExecutable(exe);
- exe.setProcess(p);
+ p.setExecutable(exe);
+ exe.setProcess(p);
- p.setCommandLine(command);
- p.setParams(params);
- p.setOriginalParams(cmd.getOriginalParams());
- p.setExePath(exepath);
+ p.setCommandLine(command);
+ p.setParams(params);
+ p.setOriginalParams(cmd.getOriginalParams());
+ p.setExePath(exepath);
- joblist.add(p);
+ joblist.add(p);
- }
+ }
+ private void setupEnv(Cmd cmd, Process p) throws ShellException {
+ Map enviro = cmd.getEnvironment();
+ if (enviro != null) {
+ Iterator eit = enviro.entrySet().iterator();
+ EnvProperties penv = p.getEnv();
+ while (eit.hasNext()) {
+ Map.Entry ent = (Map.Entry) eit.next();
+ penv.setEnvProperty((String) ent.getKey(), (String) ent.getValue());
+ }
+ }
+ }
- private void setupEnv(Cmd cmd, Process p) throws ShellException {
- Map enviro = cmd.getEnvironment();
- if(enviro != null) {
- Iterator eit = enviro.entrySet().iterator();
- EnvProperties penv = p.getEnv();
- while(eit.hasNext()) {
- Map.Entry ent = (Map.Entry) eit.next();
- penv.setEnvProperty((String) ent.getKey(), (String) ent.getValue());
- }
- }
- }
-
/*
public String executeAsString(String cmdline) throws ShellException {
// Similar to above. The difference is only when we start the process.
@@ -1208,105 +1178,106 @@
return null;
}
*/
- public Object executeAsObject(String cmdline) throws ShellException {
- preStartTimeoutCheck();
- return _executeAsObject(cmdline, null, false);
- }
- public Object executeAsObject(String cmdline, List input) throws ShellException {
- preStartTimeoutCheck();
- return _executeAsObject(cmdline, input, false);
- }
+ public Object executeAsObject(String cmdline) throws ShellException {
+ preStartTimeoutCheck();
+ return _executeAsObject(cmdline, null, false);
+ }
- public Object executeAsObject(String cmdline, boolean ui) throws ShellException {
- preStartTimeoutCheck();
- return _executeAsObject(cmdline, null, ui);
- }
+ public Object executeAsObject(String cmdline, List input) throws ShellException {
+ preStartTimeoutCheck();
+ return _executeAsObject(cmdline, input, false);
+ }
- public Object executeAsObject(String cmdline, List input, boolean ui) throws ShellException {
- preStartTimeoutCheck();
- return _executeAsObject(cmdline, input, ui);
- }
+ public Object executeAsObject(String cmdline, boolean ui) throws ShellException {
+ preStartTimeoutCheck();
+ return _executeAsObject(cmdline, null, ui);
+ }
- public Object _executeAsObject(String cmdline, List input, boolean ui) throws ShellException {
- // similar to above only this time we take results as Object and return
- // an object. The above is really a flavor of this and not vice versa.
+ public Object executeAsObject(String cmdline, List input, boolean ui) throws ShellException {
+ preStartTimeoutCheck();
+ return _executeAsObject(cmdline, input, ui);
+ }
- // start executable. set up nullbuffer on its stdi
- try {
- ProcessInfo pinfo = _execute(cmdline, input, false, true, ui, false); // NullInput In case no redirects specified of course
+ public Object _executeAsObject(String cmdline, List input, boolean ui) throws ShellException {
+ // similar to above only this time we take results as Object and return
+ // an object. The above is really a flavor of this and not vice versa.
- // read one object from its std out
+ // start executable. set up nullbuffer on its stdi
+ try {
+ ProcessInfo pinfo = _execute(cmdline, input, false, true, ui, false); // NullInput In case no redirects specified of course
+
+ // read one object from its std out
// System.out.println(">>>BUFFER : " + getBuffer(pinfo.procid, 1));
- InBuffer buf = null;
- try {
- buf = getBuffer(pinfo.procid, 1);
- } catch(org.jboss.fresh.shell.NoSuchProcessException ex) {
- return null;
- }
+ InBuffer buf = null;
+ try {
+ buf = getBuffer(pinfo.procid, 1);
+ } catch (org.jboss.fresh.shell.NoSuchProcessException ex) {
+ return null;
+ }
- BufferObjectReader in = new BufferObjectReader(buf); // get out buffer
+ BufferObjectReader in = new BufferObjectReader(buf); // get out buffer
- in.setTimeout((int) BUFFER_TIMEOUT);
+ in.setTimeout((int) BUFFER_TIMEOUT);
- Object retObj = null;
- while (!in.isFinished()) { // �e ho�emo, da sa izvede do konca moramo prebrati vse - dokler se ne zapre.
- try {
+ Object retObj = null;
+ while (!in.isFinished()) { // �e ho�emo, da sa izvede do konca moramo prebrati vse - dokler se ne zapre.
+ try {
- if (retObj == null) {
+ if (retObj == null) {
//log.debug("########\n\n\n\\n Timeout: " + in.getTimeout());
- retObj = in.readObject(); // read it
- } else {
+ retObj = in.readObject(); // read it
+ } else {
//log.debug("########\n\n\n\\n Timeout_1: " + in.getTimeout());
- in.readObject(); // dump it
- }
- } catch (IOException ex) {
+ in.readObject(); // dump it
+ }
+ } catch (IOException ex) {
//log.debug("[ShellImpl] executeAsObject:");
- log.error(ex.getMessage(), ex);
- }
- }
+ log.error(ex.getMessage(), ex);
+ }
+ }
- // DON'T close std out. It's not our business to close stdout.
- //in.close();
+ // DON'T close std out. It's not our business to close stdout.
+ //in.close();
- // return that object
- return retObj;
- } catch (ShellException ex) {
- log.error(ex.getMessage(), ex);
- throw ex;
- } catch (Throwable t) {
- log.error(t.getMessage(), t);
- throw new ShellException(t);
- }
- }
+ // return that object
+ return retObj;
+ } catch (ShellException ex) {
+ log.error(ex.getMessage(), ex);
+ throw ex;
+ } catch (Throwable t) {
+ log.error(t.getMessage(), t);
+ throw new ShellException(t);
+ }
+ }
- public EnvProperties getEnv() {
- return props;
- }
+ public EnvProperties getEnv() {
+ return props;
+ }
- public Properties getEnvProperties() throws ShellException {
- used();
- return props.getEnvProperties();
- }
+ public Properties getEnvProperties() throws ShellException {
+ used();
+ return props.getEnvProperties();
+ }
- public Properties _getEnvProperties() throws ShellException {
+ public Properties _getEnvProperties() throws ShellException {
return props._getEnvProperties();
- }
+ }
- public void setEnvProperty(String name, String value) throws ShellException {
- used();
- props._setEnvProperty(name, value);
- }
+ public void setEnvProperty(String name, String value) throws ShellException {
+ used();
+ props._setEnvProperty(name, value);
+ }
- public void _setEnvProperty(String name, String value) throws ShellException {
- props._setEnvProperty(name, value);
- //runtime.setEnvProperty(name, value);
- }
+ public void _setEnvProperty(String name, String value) throws ShellException {
+ props._setEnvProperty(name, value);
+ //runtime.setEnvProperty(name, value);
+ }
- public String getEnvProperty(String name) throws ShellException {
- used();
- return props._getEnvProperty(name);
- }
+ public String getEnvProperty(String name) throws ShellException {
+ used();
+ return props._getEnvProperty(name);
+ }
private String getEnvProperty(Cmd cmd, String name) throws ShellException {
Object val = cmd.getEnvironment().get(name);
@@ -1316,26 +1287,27 @@
return String.valueOf(val);
}
- public String _getEnvProperty(String name) throws ShellException {
+ public String _getEnvProperty(String name) throws ShellException {
return props._getEnvProperty(name);
- }
+ }
- public ShellRuntime getRuntime() {
- return runtime;
- }
+ public ShellRuntime getRuntime() {
+ return runtime;
+ }
- /* (non-Javadoc)
- * @see org.jboss.fresh.shell.Shell#setROEnvProperty(java.lang.String, java.lang.String)
- */
- public synchronized void setROEnvProperty(String name, String value)
- throws ShellException {
- props.setROEnvProperty(name, value);
- }
+ /* (non-Javadoc)
+ * @see org.jboss.fresh.shell.Shell#setROEnvProperty(java.lang.String, java.lang.String)
+ */
- public LinkedList readBuffer(String id, int maxsize) throws IOException {
+ public synchronized void setROEnvProperty(String name, String value)
+ throws ShellException {
+ props.setROEnvProperty(name, value);
+ }
- Process p = null;
+ public LinkedList readBuffer(String id, int maxsize) throws IOException {
+ Process p = null;
+
/*
if(id.equals(STDIN_ID)) {
if(active==null) {
@@ -1345,79 +1317,79 @@
}
}
*/
- try {
+ try {
//log.debug(" --- Shell Impl --- readBuffer() entered.");
- //used();
- if (id.equals(STDIN_ID)) {
- if (!interactive) {
- throw new NoSuchProcessException("No process for STDIN. Session is not in interactive mode.");
- }
+ //used();
+ if (id.equals(STDIN_ID)) {
+ if (!interactive) {
+ throw new NoSuchProcessException("No process for STDIN. Session is not in interactive mode.");
+ }
// System.out.println("OH NO ! id = " + id);
- LinkedList retobj = outreader.readBuffer(maxsize);
+ LinkedList retobj = outreader.readBuffer(maxsize);
// System.out.println("<<<<<<<<");
- p = (Process) procmap.get(id);
- if (p != null) {
- p.using();
- }
+ p = (Process) procmap.get(id);
+ if (p != null) {
+ p.using();
+ }
- return retobj;
- }
+ return retobj;
+ }
- p = (Process) procmap.get(id);
- if (p == null) {
- // let's find process data for id
- HistoryItem ti = getHistoryItem(id);
- throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
- }
+ p = (Process) procmap.get(id);
+ if (p == null) {
+ // let's find process data for id
+ HistoryItem ti = getHistoryItem(id);
+ throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
+ }
- p.using();
- // we need an input stream around outputbuffer
- // we need to save it like together with the Process
- InBuffer b = (InBuffer) p.getOutputBuffer();
+ p.using();
+ // we need an input stream around outputbuffer
+ // we need to save it like together with the Process
+ InBuffer b = (InBuffer) p.getOutputBuffer();
// System.out.println("ShellImpl: read() : getting from buffer: " + b);
- // if(list.size()>b.getMaxSize()) throw new ShellIOException("Buffer sent by client exeeds the communicated maximum size.");
+ // if(list.size()>b.getMaxSize()) throw new ShellIOException("Buffer sent by client exeeds the communicated maximum size.");
- LinkedList list = b.getBuffer(p.getIOTimeout(), maxsize);
- if (p.isRedirected() && b.isClosed()) {
- p.markCompleted();
- }
+ LinkedList list = b.getBuffer(p.getIOTimeout(), maxsize);
+ if (p.isRedirected() && b.isClosed()) {
+ p.markCompleted();
+ }
- if (log.isDebugEnabled()) {
- log.debug(" --- Shell Impl --- readBuffer() " + list);
- }
+ if (log.isDebugEnabled()) {
+ log.debug(" --- Shell Impl --- readBuffer() " + list);
+ }
- return list;
- } catch (EOFException ex) {
+ return list;
+ } catch (EOFException ex) {
//log.debug(" --- Shell Impl --- readBuffer() EOFException caught...");
- if (p != null && p.getThrowable() != null) {
+ if (p != null && p.getThrowable() != null) {
//log.debug(" --- Shell Impl --- readBuffer() throwing throwable...");
- throw new ShellIOException(p.getThrowable());
- } else {
+ throw new ShellIOException(p.getThrowable());
+ } else {
//log.debug(" --- Shell Impl --- readBuffer() throwing EOFException...");
- throw ex;
- }
- } catch (IOException ex) {
- throw ex;
- } catch (Exception ex) {
+ throw ex;
+ }
+ } catch (IOException ex) {
+ throw ex;
+ } catch (Exception ex) {
//log.debug(" --- Shell Impl --- readBuffer() Exception caught...");
- log.error(ex.getMessage(), ex);
+ log.error(ex.getMessage(), ex);
//log.debug("Throwing ShellException... " + ex.getMessage());
- throw new ShellIOException(ex);
- }
- }
+ throw new ShellIOException(ex);
+ }
+ }
- public Object read(String id) throws IOException {
+ public Object read(String id) throws IOException {
- // get the process with this ID
- // get the ObjectReader wrapped around stdout Buffer of the process
- // read next object from it and return it. It's supposed to be of type byte []
- // if we employ buffer pooling then maybe what we get is some other object and we need to extract
- // byte [] from it and return buffer to the pool.
+ // get the process with this ID
+ // get the ObjectReader wrapped around stdout Buffer of the process
+ // read next object from it and return it. It's supposed to be of type byte []
+ // if we employ buffer pooling then maybe what we get is some other object and we need to extract
+ // byte [] from it and return buffer to the pool.
- // read is done in sync fashion.
+ // read is done in sync fashion.
// System.out.println("ShellImpl: read() : retrieving process for id " + id);
- Process p = null;
+ Process p = null;
/*
if(id.equals(STDIN_ID)) {
if(active==null) {
@@ -1427,419 +1399,424 @@
}
}
*/
- try {
- //used();
- if (id.equals(STDIN_ID)) {
- if (!interactive) {
- throw new NoSuchProcessException("No process for STDIN. Session is not in interactive mode.");
- }
+ try {
+ //used();
+ if (id.equals(STDIN_ID)) {
+ if (!interactive) {
+ throw new NoSuchProcessException("No process for STDIN. Session is not in interactive mode.");
+ }
// System.out.println("OH NO SHIT! id = " + id);
- Object retobj = outreader.readObject();
+ Object retobj = outreader.readObject();
// System.out.println("<<<<<<<<");
- p = (Process) procmap.get(id);
- if (p != null) {
- p.using();
- }
- return retobj;
- }
+ p = (Process) procmap.get(id);
+ if (p != null) {
+ p.using();
+ }
+ return retobj;
+ }
- p = (Process) procmap.get(id);
- if (p == null) {
- // let's find process data for id
- HistoryItem ti = getHistoryItem(id);
- throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
- }
+ p = (Process) procmap.get(id);
+ if (p == null) {
+ // let's find process data for id
+ HistoryItem ti = getHistoryItem(id);
+ throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
+ }
- p.using();
- // we need an input stream around outputbuffer
- // we need to save it like together with the Process
- InBuffer b = (InBuffer) p.getOutputBuffer();
+ p.using();
+ // we need an input stream around outputbuffer
+ // we need to save it like together with the Process
+ InBuffer b = (InBuffer) p.getOutputBuffer();
// System.out.println("ShellImpl: read() : getting from buffer: " + b);
- Object obj = b.get(p.getIOTimeout());
+ Object obj = b.get(p.getIOTimeout());
- if (log.isDebugEnabled()) {
- log.debug(" --- Shell Impl --- read() " + obj);
- }
+ if (log.isDebugEnabled()) {
+ log.debug(" --- Shell Impl --- read() " + obj);
+ }
- return obj;
- // This is not quite ok. We need Wrap exception to throw ...
- } catch (EOFException ex) {
- if (p.getThrowable() != null) {
- throw new ShellIOException(p.getThrowable());
- } else {
- throw ex;
- }
- } catch (Exception ex) {
- log.error(ex.getMessage(), ex);
+ return obj;
+ // This is not quite ok. We need Wrap exception to throw ...
+ } catch (EOFException ex) {
+ if (p.getThrowable() != null) {
+ throw new ShellIOException(p.getThrowable());
+ } else {
+ throw ex;
+ }
+ } catch (Exception ex) {
+ log.error(ex.getMessage(), ex);
//log.debug("Throwing ShellException... " + ex.getMessage());
- throw new ShellIOException(ex);
- }
+ throw new ShellIOException(ex);
+ }
- }
+ }
- public void writeBuffer(String id, LinkedList list) throws IOException {
+ public void writeBuffer(String id, LinkedList list) throws IOException {
- // check to see if size of list is within limits - we need to get input buffer of the process
+ // check to see if size of list is within limits - we need to get input buffer of the process
//log.debug(" --- Shell Impl --- writeBuffer() " + list );
//Iterator it=list.iterator();
//while(it.hasNext()) {
// System.out.println(" " + it.next());
//}
- Process p = null;
- try {
- //used();
- p = (Process) procmap.get(id);
- if (p == null) {
- // let's find process data for id
- HistoryItem ti = getHistoryItem(id);
- throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
- }
+ Process p = null;
+ try {
+ //used();
+ p = (Process) procmap.get(id);
+ if (p == null) {
+ // let's find process data for id
+ HistoryItem ti = getHistoryItem(id);
+ throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
+ }
- p.using();
- // we need an input stream around outputbuffer
- // we need to save it like together with the Process
- OutBuffer b = (OutBuffer) p.getInputBuffer();
+ p.using();
+ // we need an input stream around outputbuffer
+ // we need to save it like together with the Process
+ OutBuffer b = (OutBuffer) p.getInputBuffer();
// System.out.println("ShellImpl: read() : getting from buffer: " + b);
- if(b == null) {
- if (!p.isDone()) {
- throw new EOFException("StdIn not available any more (funny: process not done yet)");
- } else {
- throw new EOFException("StdIn not available any more (process done executing)");
- }
+ if (b == null) {
+ if (!p.isDone()) {
+ throw new EOFException("StdIn not available any more (funny: process not done yet)");
+ } else {
+ throw new EOFException("StdIn not available any more (process done executing)");
+ }
}
- if (list.size() > b.getMaxSize()) {
- throw new ShellException("Buffer sent by client exeeds the communicated maximum size.");
- }
+ if (list.size() > b.getMaxSize()) {
+ throw new ShellException("Buffer sent by client exeeds the communicated maximum size.");
+ }
- b.putBuffer(list, p.getIOTimeout());
- } catch (EOFException ex) {
- if (p.getThrowable() != null) {
- throw new ShellIOException(p.getThrowable());
- } else {
- throw ex;
- }
- } catch (Exception ex) {
- log.error(ex.getMessage(), ex);
+ b.putBuffer(list, p.getIOTimeout());
+ } catch (EOFException ex) {
+ if (p.getThrowable() != null) {
+ throw new ShellIOException(p.getThrowable());
+ } else {
+ throw ex;
+ }
+ } catch (Exception ex) {
+ log.error(ex.getMessage(), ex);
//log.debug("Throwing ShellException... " + ex.getMessage());
- throw new ShellIOException(ex);
- }
- }
+ throw new ShellIOException(ex);
+ }
+ }
- public void write(String id, Object obj) throws IOException {
+ public void write(String id, Object obj) throws IOException {
//log.debug(" --- Sell Impl --- write() " + obj );
- Process p = null;
- try {
- //used();
- p = (Process) procmap.get(id);
- if (p == null) {
- // let's find process data for id
- HistoryItem ti = getHistoryItem(id);
- throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
- }
+ Process p = null;
+ try {
+ //used();
+ p = (Process) procmap.get(id);
+ if (p == null) {
+ // let's find process data for id
+ HistoryItem ti = getHistoryItem(id);
+ throw new NoSuchProcessException("No process for id: " + id + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
+ }
- p.using();
- // we need an input stream around outputbuffer
- // we need to save it like together with the Process
- OutBuffer b = (OutBuffer) p.getInputBuffer();
+ p.using();
+ // we need an input stream around outputbuffer
+ // we need to save it like together with the Process
+ OutBuffer b = (OutBuffer) p.getInputBuffer();
// System.out.println("ShellImpl: read() : getting from buffer: " + b);
- if(b == null) {
- if (!p.isDone()) {
- throw new EOFException("StdIn not available any more (funny: process not done yet)");
- } else {
- throw new EOFException("StdIn not available any more (process done executing)");
- }
+ if (b == null) {
+ if (!p.isDone()) {
+ throw new EOFException("StdIn not available any more (funny: process not done yet)");
+ } else {
+ throw new EOFException("StdIn not available any more (process done executing)");
+ }
}
- boolean res = b.put(obj, 0);
- if (!res) {
- throw new IOException("Timeout while trying to write in the buffer: " + b);
- }
- } catch (EOFException ex) {
- if (p.getThrowable() != null) {
- throw new ShellIOException(p.getThrowable());
- } else {
- throw ex;
- }
- } catch (Exception ex) {
- log.error(ex.getMessage(), ex);
+ boolean res = b.put(obj, 0);
+ if (!res) {
+ throw new IOException("Timeout while trying to write in the buffer: " + b);
+ }
+ } catch (EOFException ex) {
+ if (p.getThrowable() != null) {
+ throw new ShellIOException(p.getThrowable());
+ } else {
+ throw ex;
+ }
+ } catch (Exception ex) {
+ log.error(ex.getMessage(), ex);
//log.debug("Throwing ShellException... " + ex.getMessage());
- throw new ShellIOException(ex);
- }
- }
+ throw new ShellIOException(ex);
+ }
+ }
- public Buffer getBuffer(String procid, int bufid) throws ShellException {
- //used();
- // get process
- Process p = null;
- p = (Process) procmap.get(procid);
+ public Buffer getBuffer(String procid, int bufid) throws ShellException {
+ //used();
+ // get process
+ Process p = null;
+ p = (Process) procmap.get(procid);
- if (p == null) {
- // let's find process data for id
- HistoryItem ti = getHistoryItem(procid);
- throw new NoSuchProcessException("No process for id: " + procid + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
- }
+ if (p == null) {
+ // let's find process data for id
+ HistoryItem ti = getHistoryItem(procid);
+ throw new NoSuchProcessException("No process for id: " + procid + " (" + (ti == null ? " No info available for process" : ti.toString()) + ")");
+ }
- p.using();
- // we need an input stream around outputbuffer
- // we need to save it like together with the Process
- if (bufid == 0) {
- return (Buffer) p.getInputBuffer();
- } else if (bufid == 1) {
- return (Buffer) p.getOutputBuffer();
- } else {
- throw new ShellException("Illegal buffer id : " + bufid);
- }
- }
+ p.using();
+ // we need an input stream around outputbuffer
+ // we need to save it like together with the Process
+ if (bufid == 0) {
+ return (Buffer) p.getInputBuffer();
+ } else if (bufid == 1) {
+ return (Buffer) p.getOutputBuffer();
+ } else {
+ throw new ShellException("Illegal buffer id : " + bufid);
+ }
+ }
- // stream ids: 0: stdin, 1: stdout
- public void close(String id, int streamid) throws IOException {
- //try {
- // used();
- //} catch (ShellException ex) {
- // throw new ShellIOException(ex);
- //}
+ // stream ids: 0: stdin, 1: stdout
- Process p = (Process) procmap.get(id);
+ public void close(String id, int streamid) throws IOException {
+ //try {
+ // used();
+ //} catch (ShellException ex) {
+ // throw new ShellIOException(ex);
+ //}
- // No need to throw exception. So process does not exist, so what. Effectively it means all buffers are closed on it.
- // The intended operation is not necessary.
- //if(p==null) throw new ShellIOException(new NoSuchProcessException("No process for id: " + id));
- if (p == null) {
- return;
- }
- try {
- p.using();
- } catch (ShellException ex) {
- //throw new ShellIOException(ex);
- }
+ Process p = (Process) procmap.get(id);
- if (streamid == 0) {
- // close stdin
- InBuffer b = p.getInputBuffer();
+ // No need to throw exception. So process does not exist, so what. Effectively it means all buffers are closed on it.
+ // The intended operation is not necessary.
+ //if(p==null) throw new ShellIOException(new NoSuchProcessException("No process for id: " + id));
+ if (p == null) {
+ return;
+ }
+ try {
+ p.using();
+ } catch (ShellException ex) {
+ //throw new ShellIOException(ex);
+ }
+
+ if (streamid == 0) {
+ // close stdin
+ InBuffer b = p.getInputBuffer();
//log.debug("[shell-impl] ********* closing " + b);
- log.debug("closing input " + b);
- if (b != null) {
- b.close();
- }
- } else if (streamid == 1) {
- OutBuffer b = p.getOutputBuffer();
+ log.debug("closing input " + b);
+ if (b != null) {
+ b.close();
+ }
+ } else if (streamid == 1) {
+ OutBuffer b = p.getOutputBuffer();
//log.debug("[shell-impl] ********* closing " + b);
- log.debug("closing output " + b);
- // closeAndDiscard explicitly tells OutBuffer that nothing will
- // be read from it any more. Not even what it may still have inside.
- b.closeAndDiscard();
- } else {
- throw new ShellIOException(new ShellException("Wrong stream id: " + streamid));
- }
- }
+ log.debug("closing output " + b);
+ // closeAndDiscard explicitly tells OutBuffer that nothing will
+ // be read from it any more. Not even what it may still have inside.
+ b.closeAndDiscard();
+ } else {
+ throw new ShellIOException(new ShellException("Wrong stream id: " + streamid));
+ }
+ }
- public String getPrompt() {
- return "$>";
- }
+ public String getPrompt() {
+ return "$>";
+ }
// we need to make sure we don't remove it if it hasn't been completely read yet.
// if it hasn't been read yet, then closure of outputstream removes it.
// but what method would that be?
// What we have to do is tag it so we know we only wait for buffer to be closed.
// Then when buffer is closed, we remove it. If buffer is closed we can remove it here
- public boolean removeProcess(String id) {
- // Don't see any reason for calling this here
- //used();
+ public boolean removeProcess(String id) {
- Process p = (Process) procmap.get(id);
+ // Don't see any reason for calling this here
+ //used();
+
+ Process p = (Process) procmap.get(id);
//log.debug("ShellImpl : removeProcess() : " + id + " p: " + p);
- if (p != null) {
- // now we know the process has ended and we reset active to null
+ if (p != null) {
+ // now we know the process has ended and we reset active to null
//log.debug("ShellImpl : removeProcess() : p.getOutputBuffer(): " + p.getOutputBuffer());
//log.debug("ShellImpl : removeProcess() : is closed?: " + p.getOutputBuffer().isClosed());
- if (p.getOutputBuffer().isClosed() && !p.isRedirected()) {
+ if (p.getOutputBuffer().isClosed() && !p.isRedirected()) {
// System.out.println("ShellImpl: removeProcess: buffer " + p.getOutputBuffer() + " is closed.");
- procmap.remove(id);
+ procmap.remove(id);
//log.debug("***\n***[removeProcess] Remove request. Removed process: " + id + "\n***");
- log.debug("Remove request. Removed process: " + id);
- active = null;
+ log.debug("Remove request. Removed process: " + id);
+ active = null;
// System.out.println("ShellImpl: removeProcess: ACTIVE SET: " + active);
// wout=new PrintWriter(new BufferedWriter(new BufferWriter(shellout)));
// wout.close();
- }
+ }
- if (interactive && p.isUserInitiated()) {
- runtime.prompt();
- }
+ if (interactive && p.isUserInitiated()) {
+ runtime.prompt();
+ }
- } else {
+ } else {
//log.debug("ShellImpl : removeProcess() : NO SUCH PROCESS");
- }
+ }
- return p == null;
+ return p == null;
- }
+ }
- public VFS getVFS() throws ShellException {
- return vfs;
- }
+ public VFS getVFS() throws ShellException {
+ return vfs;
+ }
- public UserCtx getUserCtx() throws ShellException {
- return uctx;
- }
+ public UserCtx getUserCtx() throws ShellException {
+ return uctx;
+ }
- public void setPWD(String path) {
- // executeAsObject("cd " + path);
- }
+ public void setPWD(String path) {
+ // executeAsObject("cd " + path);
+ }
- public void _setPWD(String path) {
- props.setProperty("PWD", path);
- runtime.setPWD(path);
- }
+ public void _setPWD(String path) {
+ props.setProperty("PWD", path);
+ runtime.setPWD(path);
+ }
- // sysshell contains a reference to us. We need to tell it to clean us completely
- public void close() throws ShellException {
+ // sysshell contains a reference to us. We need to tell it to clean us completely
+ public void close() throws ShellException {
+
//log.debug("CLOSING SHELL SESSION");
- sshell.closeSession(uid);
+ sshell.closeSession(uid);
- // make sure the following line is called last
- closed = true;
+ // make sure the following line is called last
+ closed = true;
closureTime = System.currentTimeMillis();
StringBuffer stack = new StringBuffer();
- StackTraceElement [] trace = Thread.currentThread().getStackTrace();
- if(trace != null && trace.length > 2) {
- for(int i=2; i<trace.length; i++) {
+ StackTraceElement[] trace = Thread.currentThread().getStackTrace();
+ if (trace != null && trace.length > 2) {
+ for (int i = 2; i < trace.length; i++) {
stack.append("\t").append(trace[i]).append("\r\n");
}
}
closureReason = "method close() called on shell at: " + stack;
// unregister eventBroadcaster
- if (eb != null) {
- eb.close();
- }
+ if (eb != null) {
+ eb.close();
+ }
- }
+ }
- // kill any active jobs, dispose of any resources ...
- // NEVER CALL THIS ONE DIRECTLY. ONLY SysShell CAN CALL IT. ALWAYS USE close() INSTEAD.
- public void dispose() {
- // enumeriraj skozi procmap in pozapri vse in streame in vse out streame.
+ // kill any active jobs, dispose of any resources ...
+ // NEVER CALL THIS ONE DIRECTLY. ONLY SysShell CAN CALL IT. ALWAYS USE close() INSTEAD.
- // let's help a little - let's close all the in buffers of all the processes:
- // and system out also.
+ public void dispose() {
+ // enumeriraj skozi procmap in pozapri vse in streame in vse out streame.
+ // let's help a little - let's close all the in buffers of all the processes:
+ // and system out also.
- try {
- EventBroadcaster eb = getEventBroadcaster();
- if (eb != null) {
- eb.dispatchEvent(new ShellEvent(EVENT_CLASS, "shellDispose", this));
- }
- } catch (Exception ex) {
- log.error(ex.getMessage(), ex);
- }
- try {
- if (interactive) {
+ try {
+ EventBroadcaster eb = getEventBroadcaster();
+ if (eb != null) {
+ eb.dispatchEvent(new ShellEvent(EVENT_CLASS, "shellDispose", this));
+ }
+ } catch (Exception ex) {
+ log.error(ex.getMessage(), ex);
+ }
+
+ try {
+ if (interactive) {
//log.debug("[shell impl] dispose: closing " + shellout);
- log.debug("dispose: closing shellout " + shellout);
- shellout.close();
- }
+ log.debug("dispose: closing shellout " + shellout);
+ shellout.close();
+ }
- Map procs;
- synchronized(procmap) {
- procs = new HashMap(procmap);
- }
- Iterator it = procs.values().iterator();
- while (it.hasNext()) {
- Process p = (Process) it.next();
- InBuffer b = p.getInputBuffer();
+ Map procs;
+ synchronized (procmap) {
+ procs = new HashMap(procmap);
+ }
+ Iterator it = procs.values().iterator();
+ while (it.hasNext()) {
+ Process p = (Process) it.next();
+ InBuffer b = p.getInputBuffer();
//log.debug("[shell impl] dispose: closing in " + b);
- log.debug("dispose: closing in " + b);
- if (b != null) {
- b.close();
- }
- OutBuffer b2 = p.getOutputBuffer();
+ log.debug("dispose: closing in " + b);
+ if (b != null) {
+ b.close();
+ }
+ OutBuffer b2 = p.getOutputBuffer();
//log.debug("[shell impl] dispose: closing out " + b);
- log.debug("dispose: closing out " + b2);
- if (b2 != null) {
- b2.close();
- }
- }
- } catch (IOException ex) {
- log.error(ex.getMessage(), ex);
- }
+ log.debug("dispose: closing out " + b2);
+ if (b2 != null) {
+ b2.close();
+ }
+ }
+ } catch (IOException ex) {
+ log.error(ex.getMessage(), ex);
+ }
- }
+ }
- public Map getProcesses() {
- synchronized(procmap) {
- return Collections.unmodifiableMap(new HashMap(procmap));
- }
- }
+ public Map getProcesses() {
+ synchronized (procmap) {
+ return Collections.unmodifiableMap(new HashMap(procmap));
+ }
+ }
- // check every process we know of
- public void doGC() {
- long now = System.currentTimeMillis();
- long sess_tout = SESS_TIMEOUT;
- long proc_tout = PROC_TIMEOUT;
+ // check every process we know of
- String str;
- try {
- // be careful not to call getEnvProperty, because it updates lastUsed time and breaks gc of sessions
- str = (String) props.getEnvProperty("SESSION_TIMEOUT");
- sess_tout = Long.parseLong(str);
- } catch (Exception ex) {
- }
+ public void doGC() {
+ long now = System.currentTimeMillis();
+ long sess_tout = SESS_TIMEOUT;
+ long proc_tout = PROC_TIMEOUT;
+ String str;
+ try {
+ // be careful not to call getEnvProperty, because it updates lastUsed time and breaks gc of sessions
+ str = (String) props.getEnvProperty("SESSION_TIMEOUT");
+ sess_tout = Long.parseLong(str);
+ } catch (Exception ex) {
+ }
+
// DEBUG DEBUG DEBUG - throw this out NOW
//sess_tout = 60000l;
//log.debug("--- Session TIMEOUT : " + sess_tout);
- try {
- // be careful not to call getEnvProperty, because it updates lastUsed time and breaks gc of sessions
- str = (String) props.getEnvProperty("PROCESS_TIMEOUT");
- proc_tout = Long.parseLong(str);
- } catch (Exception ex) {
- }
+ try {
+ // be careful not to call getEnvProperty, because it updates lastUsed time and breaks gc of sessions
+ str = (String) props.getEnvProperty("PROCESS_TIMEOUT");
+ proc_tout = Long.parseLong(str);
+ } catch (Exception ex) {
+ }
- Map map = null;
- synchronized(procmap) {
- map = new HashMap(procmap);
- }
- Iterator it = map.values().iterator();
- while (it.hasNext()) {
- Process p = (Process) it.next();
- long t = p.lastUsed();
+ Map map = null;
+ synchronized (procmap) {
+ map = new HashMap(procmap);
+ }
+ Iterator it = map.values().iterator();
+ while (it.hasNext()) {
+ Process p = (Process) it.next();
+ long t = p.lastUsed();
- if (now - t > proc_tout) {
- //log.debug("[ShellImpl] doGC : Process timed out : " + p.getID());
- log.info("Process timed out : " + p.getID());
- if (p.isFinished()) {
- sshell.endProcess(p.getID());
- } else {
- Executable e = p.getExecutable();
- if (e != null) {
- e.sendMessage("KILL");
- }
- }
- procmap.remove(p.getID());
- //log.debug("***\n***[doGC] Process timed out. (" + proc_tout + ") Removed process " + p.getID() + "\n***");
- log.debug("Process timed out. (" + proc_tout + ") Removed process " + p.getID());
- } else if (p.isRedirected() ? p.isMarkedComplete() && p.canDispose() : p.canDispose()) {
- procmap.remove(p.getID());
- //log.debug("***\n***[doGC] Process has finished. Removed process " + p.getID() + "\n***");
- log.debug("Process has finished. Removed process " + p.getID());
- }
- }
+ if (now - t > proc_tout) {
+ //log.debug("[ShellImpl] doGC : Process timed out : " + p.getID());
+ log.info("Process timed out : " + p.getID());
+ if (p.isFinished()) {
+ sshell.endProcess(p.getID());
+ } else {
+ Executable e = p.getExecutable();
+ if (e != null) {
+ e.sendMessage("KILL");
+ }
+ }
+ procmap.remove(p.getID());
+ //log.debug("***\n***[doGC] Process timed out. (" + proc_tout + ") Removed process " + p.getID() + "\n***");
+ log.debug("Process timed out. (" + proc_tout + ") Removed process " + p.getID());
+ } else if (p.isRedirected() ? p.isMarkedComplete() && p.canDispose() : p.canDispose()) {
+ procmap.remove(p.getID());
+ //log.debug("***\n***[doGC] Process has finished. Removed process " + p.getID() + "\n***");
+ log.debug("Process has finished. Removed process " + p.getID());
+ }
+ }
checkTimedOut(now, sess_tout);
}
@@ -1847,15 +1824,15 @@
private void checkTimedOut(long now, long sess_tout) {
long l = lastUsed();
- if (l == 0) {
- return;
- }
-
+ if (l == 0) {
+ return;
+ }
+
//log.debug("[ShellImpl] doGC : Session last used: " + l + " vs. now: " + now + " (" + (now-l) + ")");
if (now - l > sess_tout) {
//log.debug("[ShellImpl] doGC : Session timed out : " + uid);
try {
- closureReason = "Shell session timed out (inactive for: " + (now - l) + "ms, timeout set to: " + sess_tout + "ms)" ;
+ closureReason = "Shell session timed out (inactive for: " + (now - l) + "ms, timeout set to: " + sess_tout + "ms)";
close();
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
@@ -1881,9 +1858,9 @@
public void used() throws ShellException {
- if (closed) {
- throw new SessionTimeoutException("Shell instance has been closed at " + sdf_time.format(new Date(closureTime)) + " - " + closureReason);
- }
+ if (closed) {
+ throw new SessionTimeoutException("Shell instance has been closed at " + sdf_time.format(new Date(closureTime)) + " - " + closureReason);
+ }
//log.debug("#$#$# used: ");
//log.info("used()");
//new Exception().printStackTrace();
@@ -1891,13 +1868,13 @@
// System.out.println("used");
}
- public long lastUsed() {
- return lastUsed;
- }
+ public long lastUsed() {
+ return lastUsed;
+ }
- public Executable loadExe(String command) throws ShellException {
- return runtime.loadExe(command);
- }
+ public Executable loadExe(String command) throws ShellException {
+ return runtime.loadExe(command);
+ }
/*
public Cache getCache() {
return cache;
@@ -1907,28 +1884,33 @@
this.cache=c;
}
*/
- public Context getContext() {
- return ctx;
- }
- public void setContext(Context c) {
- this.ctx = c;
- }
+ public Context getContext() {
+ return ctx;
+ }
- public void using() throws ShellException {
- used();
- }
+ public void setContext(Context c) {
+ this.ctx = c;
+ }
- public long getStartTime() {
- return startTime;
- }
+ public void using() throws ShellException {
+ used();
+ }
- public boolean isValid() {
- try {
- using();
- } catch (Exception ex) {
- return false;
- }
- return true;
+ public long getStartTime() {
+ return startTime;
+ }
+
+ public boolean isValid() {
+ try {
+ using();
+ } catch (Exception ex) {
+ return false;
+ }
+ return true;
}
+
+ public <T>T getComponentByType(Class<T> type){
+ throw new RuntimeException("MC Magick should happen here...");
+ }
}
\ No newline at end of file
Modified: projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/SystemShellImpl.java
===================================================================
--- projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/SystemShellImpl.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-shell/src/main/java/org/jboss/fresh/shell/impl/SystemShellImpl.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,16 +1,11 @@
package org.jboss.fresh.shell.impl;
import org.jboss.beans.metadata.api.annotations.Inject;
-import org.jboss.fresh.deployer.RegistryNamingBinder;
-import org.jboss.fresh.deployer.NamingBinder;
-import javax.naming.InitialContext;
import org.jboss.fresh.shell.*;
import org.jboss.fresh.vfs.UserCtx;
import org.jboss.fresh.vfs.VFS;
import org.jboss.util.threadpool.ThreadPool;
-import org.jboss.aop.microcontainer.aspects.jndi.JndiBinding;
-import javax.naming.NamingException;
import java.util.*;
/**
@@ -25,14 +20,14 @@
//@Bean(name = "SystemShell")
//@JndiBinding(name = "java:/FRESH/SystemShell")
-public class SystemShellImpl extends NamingBinder implements SystemShell {
+public class SystemShellImpl implements SystemShell {
protected static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(SystemShellImpl.class);
HashMap shellmap = new HashMap();
HashMap procmap = new HashMap();
//private String threadPoolName;
- private String vfsName;
+ private VFS VFS;
private Date startTime;
@@ -46,44 +41,23 @@
long gcPeriod = 10000L;
- public SystemShellImpl(String vfsname) throws Exception {
- this.vfsName = vfsname;
+ public SystemShellImpl() throws Exception {
+
log.info("calling do start!");
startTime = new Date();
- doStart();
+ // doStart();
reinitGC();
}
- @Override
- protected boolean bindByReference() {
- return true;
- }
+
public void setThreadPool(ThreadPool threadPool) {
this.threadPool = threadPool;
}
- protected String getBindClass() {
- return SystemShell.class.getName();
- }
- protected Object classToInstance(Class c) {
- return this;
- }
-
- /*public void setThreadPoolName(String threadPoolName) {
- this.threadPoolName = threadPoolName;
- }*/
-
- /*public SystemShellImpl(String tpname, String vfsname) {
- threadPoolName = tpname;
- vfsName = vfsname;
- startTime = new Date();
- reinitGC();
- }*/
-
public void setExecutableRegistry(ExecutableRegistry registry) {
this.registry = registry;
}
@@ -122,18 +96,12 @@
return newID();
}
-
public VFS getVFS() {
- VFS vfs = null;
- try {
- InitialContext ctx = new InitialContext();
- vfs = (VFS) ctx.lookup(vfsName);
- } catch (NamingException ex) {
- log.error(ex.getMessage(), ex);
- throw new RuntimeException("org.jboss.fresh.shell.impl.SystemShellImpl: startSession: " + vfsName + " not bound.");
- }
+ return VFS;
+ }
- return vfs;
+ public void setVFS(VFS VFS) {
+ this.VFS = VFS;
}
public Shell startSession(UserCtx uctx, boolean interactive) {
Modified: projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/deployer/SSHService.java
===================================================================
--- projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/deployer/SSHService.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/deployer/SSHService.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,34 +1,28 @@
package org.jboss.fresh.deployer;
+import org.jboss.beans.metadata.api.annotations.Create;
+import org.jboss.fresh.shell.SystemShell;
import org.jboss.fresh.ssh.DaemonStarter;
import org.jboss.logging.Logger;
-public class SSHService extends ServiceModule implements SSHServiceMBean {
+public class SSHService {
private static final Logger log = Logger.getLogger(SSHService.class);
private Thread th = null;
private String home;
- private String ssjndi;
+ private SystemShell systemShell;
- public String getName() {
- return "SSHService";
- }
- public void setHomeDirectory(String home) {
- this.home = home;
- }
- public String getHomeDirectory() {
- return home;
- }
+ public SystemShell getSystemShell() {
+ return systemShell;
+ }
- public void setSystemShellJNDI(String name) {
- this.ssjndi = name;
- }
+ public void setSystemShell(SystemShell systemShell) {
+ this.systemShell = systemShell;
+ }
- public String getSystemShellJNDI() {
- return ssjndi;
- }
+ @Create
public void doStart() {
th = new Thread() {
@@ -37,7 +31,7 @@
//com.sshtools.j2ssh.SshServer.main(new String [] {"-start"});
try {
DaemonStarter.setConfigDir(home);
- DaemonStarter.setSystemShellJNDI(ssjndi);
+ DaemonStarter.setSystemShell(systemShell);
DaemonStarter.initialize();
} catch (Exception ex) {
log.error("could not start ssh service",ex);
Modified: projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/DaemonStarter.java
===================================================================
--- projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/DaemonStarter.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/DaemonStarter.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -12,6 +12,7 @@
import com.sshtools.j2ssh.configuration.ConfigurationLoader;
import com.sshtools.j2ssh.configuration.ConfigurationException;
import com.sshtools.j2ssh.configuration.ConfigurationContext;
+import org.jboss.fresh.shell.SystemShell;
import java.io.IOException;
@@ -24,14 +25,14 @@
public class DaemonStarter extends SshDaemon {
private static String rootDir = "";
- private static String systemShellJNDI = "";
+ private static SystemShell systemShell;
public static void setConfigDir(String dir) {
rootDir = dir;
}
- public static void setSystemShellJNDI(String ss){
- systemShellJNDI = ss;
+ public static void setSystemShell(SystemShell ss){
+ systemShell = ss;
}
public static void initialize() throws IOException, ConfigurationException {
@@ -53,8 +54,8 @@
- if(systemShellJNDI!=null && !systemShellJNDI.trim().equals(""))
- SSHShell.setSystemShellJNDI(systemShellJNDI);
+ if(systemShell!=null )
+ SSHShell.setSystemShell(systemShell);
start();
}
Modified: projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/SSHShell.java
===================================================================
--- projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/SSHShell.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-ssh/src/main/java/org/jboss/fresh/ssh/SSHShell.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -8,7 +8,6 @@
import org.jboss.fresh.io.BufferInputStream;
import org.jboss.fresh.io.EOLFixInputStream;
import org.jboss.fresh.io.PrintWriter2;
-import javax.naming.InitialContext;
import org.jboss.fresh.shell.ProcessInfo;
import org.jboss.fresh.shell.ShellException;
import org.jboss.fresh.shell.ShellOutputStream;
@@ -20,7 +19,11 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
public class SSHShell extends NativeProcessProvider {
@@ -30,7 +33,7 @@
static final int OVERWRITE = 0;
static final int INSERT = 1;
- static private String ssjndi = "java:/FRESH/SystemShell";
+
static private String homeDir = "../fresh/users";
static private int MAX_HISTORY_SIZE = 200;
@@ -58,11 +61,12 @@
int screen_rows;
int screen_cols;
+ private static SystemShell systemShell;
//static PoolImpl pool;
- public static void setSystemShellJNDI(String name) {
- ssjndi = name;
+ public static void setSystemShell(SystemShell systemShell) {
+ SSHShell.systemShell = systemShell; //todo this is sooo bad...
}
@@ -85,10 +89,9 @@
StringBuffer errMessage = new StringBuffer();
try {
- InitialContext ctx = new InitialContext();
- SystemShell ssh = (SystemShell) ctx.lookup(ssjndi);
- shell = (ShellImpl) ssh.startSession(null, false);
+ shell = (ShellImpl) systemShell.startSession(null, false);
+
// go to root directory
try {
shell.executeAsObject("cd /");
@@ -109,9 +112,6 @@
log.info("Successfully initialized shell: " + shell);
- } catch (NamingException e) {
- log.error("Exception while initializin SSHShell: ", e);
- throw new RuntimeException(e);
} catch (ShellException e) {
log.error("Exception while initializin SSHShell: ", e);
throw new RuntimeException(e);
@@ -422,6 +422,7 @@
}
// this method returns necessary bytes to the client to reflect user's input
+
private void addChar(byte val) {
// we need to check carret location
// if carret is at the end of the line then we just send back the char
@@ -467,6 +468,7 @@
// this method scans unprocessed buffer and tries to identify any control
// byte sequences it reacts accordingly
+
private void processInput() {
// if buffer starts with 1b then it's a control sequence
// if it's already longer than 3 then it ends with 7e
@@ -1253,6 +1255,7 @@
// this is input from stdin
// we are in command mode otherwise we wouldn't receive this
+
public void addByte(int b) {
// buffer should never be full here - that would be an internal error
// add it to buffer first
@@ -1291,6 +1294,7 @@
* If CTRL-C and process mode - then it tries to kill the process
* If CTRL-D and process mode - then it switches to command mode
*/
+
class InMasterOutputStream extends OutputStream {
boolean closed = false;
@@ -1455,6 +1459,7 @@
// put this master out to delegate mode - will not read line editor's output
// but process's output
+
public void setInputStream(BufferInputStream in) {
delegate = in;
delegateReal = new EOLFixInputStream(in);
@@ -1498,6 +1503,7 @@
}
// this method writes to the buffer at the end of current content
+
synchronized void addBytes(byte[] abuf, int aoffs, int alen) {
shrink();
@@ -1576,6 +1582,7 @@
// In order to have performance, we must do our buffering in here
// when reading from delegate InputStream
//
+
public int read(byte[] abuf, int aoffs, int alen) throws IOException {
log.debug("read byte[]");
while (!closed) {
Modified: projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/persist/HibernateProvider.java
===================================================================
--- projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/persist/HibernateProvider.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/persist/HibernateProvider.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -9,76 +9,22 @@
public class HibernateProvider {
- private static String ver;
- private static String useVer;
- private static void findVersion() {
-
-/* if(ver != null) return;
-
- RegistryContext ctx = new RegistryContext();
- Object sessFactory = ctx.lookup(jndiSessFactory);
-
- String name = sessFactory.getClass().getName();
- int pos = name.lastIndexOf(".");
- String basePkg = name.substring(0, pos);
-
- ClassLoader cl = sessFactory.getClass().getClassLoader();
- Class env = cl.loadClass(basePkg + ".cfg.Environment");
- Field fld = env.getField("VERSION");
-
- ver = (String) fld.get(null);
-*/
- //if(ver == null) throw new RuntimeException("No version info found for hibernate! Call useVersion()");
- if(ver == null)
- ver = "3.0";
- }
-
-
- public static void useVersion(String ver) {
- HibernateProvider.ver = ver;
- useVer = ver;
- }
-
public static HibernateProviderInstance getHibernateProviderInstance(Object sessFactory) throws Exception {
- findVersion();
- if("3.0".equals(ver)) {
Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.fresh.persist.hibernate3.Hibernate3ProviderInstance");
Constructor cs = clazz.getConstructor(new Class[] {Object.class});
return (HibernateProviderInstance) cs.newInstance(new Object[] {sessFactory});
- } else if("2.1.6".equals(ver)) {
- Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.fresh.persist.hibernate216.Hibernate216ProviderInstance");
- Constructor cs = clazz.getConstructor(new Class[] {Object.class});
- return (HibernateProviderInstance) cs.newInstance(new Object[] {sessFactory});
- } else if("2.0 parsek-mod".equals(ver)) {
- //return new HibernateModProviderInstance(sessFactory);
- Class clazz = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.fresh.persist.hibernate2mod.Hibernate2ModProviderInstance");
- Constructor cs = clazz.getConstructor(new Class[] {Object.class});
- return (HibernateProviderInstance) cs.newInstance(new Object[] {sessFactory});
- }else if ("3.0 alpha".equals(ver)){
- throw new RuntimeException("Hibernate 3 alpha is no longer supported. use 3.0 final");
- }
- throw new RuntimeException("Unsupported hibernate version: " + ver);
}
public static String getSessionFactoryName() {
- findVersion();
- if("3.0".equals(ver)) {
return "org.hibernate.SessionFactory";
- } else if("2.1.6".equals(ver)) {
- return "net.sf.hibernate.SessionFactory";
- } else if("2.0 parsek-mod".equals(ver)) {
- return "net.sf.hibernate.SessionFactory";
- }
-
- throw new RuntimeException("Unsupported hibernate version: " + ver);
}
@@ -89,8 +35,6 @@
return hpi.buildSessionFactory(cnt, p);
}
- public static String getVersion() {
- return ver;
- }
+
}
Added: projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/RegistryContext.java
===================================================================
--- projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/RegistryContext.java (rev 0)
+++ projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/RegistryContext.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -0,0 +1,348 @@
+package org.jboss.fresh.registry;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.NameNotFoundException;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import java.util.Hashtable;
+
+
+/**
+ * The whole point of this class is to have a usage similar to jndi InitialContext where you just create a new instance
+ * possibly passing it info on where and how to connect and then use it. So it's pluggable and allows different implementations
+ * underneath.
+ *
+ * At the same time you can go directly using it and bypass InitialContext initialization routine
+ */
+public class RegistryContext implements Context {
+
+
+ private StaticRegistryContext reg;
+
+
+ public RegistryContext() throws NamingException {
+ this("<default>");
+ }
+
+ public RegistryContext(String store) throws NamingException {
+ reg = new StaticRegistryContext(store);
+ }
+
+ // Default implementation for now is to use StaticRegistry
+ private StaticRegistryContext getImpl() {
+ return reg;
+ }
+
+
+ /**
+ * Adds a new environment property to the environment of this context.
+ */
+ public Object addToEnvironment(String propName, Object propVal) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.addToEnvironment(propName, propVal);
+ }
+
+ /**
+ * Binds a name to an object.
+ */
+ public void bind(Name name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ ctx.bind(name, obj);
+ }
+
+ /**
+ * Binds a name to an object.
+ */
+ public void bind(String name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ ctx.bind(name, obj);
+ }
+
+
+ public void bindWithParents(String name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ Name n = ctx.getNameParser("").parse(name);
+ while (n.size() > 1) {
+ String ctxName = n.get(0);
+ try {
+ ctx = (Context) ctx.lookup(ctxName);
+ } catch (NameNotFoundException e) {
+ ctx = ctx.createSubcontext(ctxName);
+ }
+ n = n.getSuffix(1);
+ }
+
+ ctx.bind(n.get(0), obj);
+ }
+
+
+ public void bindWithParents(Name name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ Name n = name;
+ while (n.size() > 1) {
+ String ctxName = n.get(0);
+ try {
+ ctx = (Context) ctx.lookup(ctxName);
+ } catch (NameNotFoundException e) {
+ ctx = ctx.createSubcontext(ctxName);
+ }
+ n = n.getSuffix(1);
+ }
+
+ ctx.bind(n.get(0), obj);
+ }
+
+ /**
+ * Closes this context.
+ */
+ public void close() throws NamingException {
+ Context ctx = getImpl();
+ ctx.close();
+ }
+
+ /**
+ * Composes the name of this context with a name relative to this context.
+ */
+ public Name composeName(Name name, Name prefix) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.composeName(name, prefix);
+ }
+
+
+ /**
+ * Composes the name of this context with a name relative to this context.
+ */
+ public String composeName(String name, String prefix) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.composeName(name, prefix);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(Name name) throws NamingException {
+ return createSubcontext(name, false);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(Name name, boolean mkparents) throws NamingException {
+ StaticRegistryContext ctx = getImpl();
+ return ctx.createSubcontext(name, mkparents);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(String name) throws NamingException {
+ return createSubcontext(name, false);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(String name, boolean mkparents) throws NamingException {
+ StaticRegistryContext ctx = getImpl();
+ return ctx.createSubcontext(name, mkparents);
+ }
+
+ /**
+ * Destroys the named context and removes it from the namespace.
+ */
+ public void destroySubcontext(Name name) throws NamingException {
+ Context ctx = getImpl();
+ ctx.destroySubcontext(name);
+ }
+
+
+ /**
+ * Destroys the named context and removes it from the namespace.
+ */
+ public void destroySubcontext(String name) throws NamingException {
+ Context ctx = getImpl();
+ ctx.destroySubcontext(name);
+ }
+
+
+ /**
+ * Retrieves the environment in effect for this context.
+ */
+ public Hashtable getEnvironment() throws NamingException {
+ Context ctx = getImpl();
+ return ctx.getEnvironment();
+ }
+
+
+ /**
+ * Retrieves the full name of this context within its own namespace.
+ */
+ public String getNameInNamespace() throws NamingException {
+ Context ctx = getImpl();
+ return ctx.getNameInNamespace();
+ }
+
+
+ /**
+ * Retrieves the parser associated with the named context.
+ */
+ public NameParser getNameParser(Name name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.getNameParser(name);
+ }
+
+
+ /**
+ * Retrieves the parser associated with the named context.
+ */
+ public NameParser getNameParser(String name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.getNameParser(name);
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the class names of objects bound to them.
+ */
+ public NamingEnumeration list(Name name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.list(name);
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the class names of objects bound to them.
+ */
+ public NamingEnumeration list(String name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.list(name);
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the objects bound to them.
+ */
+ public NamingEnumeration listBindings(Name name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.listBindings(name);
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the objects bound to them.
+ */
+ public NamingEnumeration listBindings(String name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.listBindings(name);
+ }
+
+
+ /**
+ * Retrieves the named object.
+ */
+ public Object lookup(Name name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.lookup(name);
+ }
+
+
+ /**
+ * Retrieves the named object.
+ */
+ public Object lookup(String name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.lookup(name);
+ }
+
+
+
+ /**
+ * Retrieves the named object, following links except for the terminal atomic component of the name.
+ */
+ public Object lookupLink(Name name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.lookupLink(name);
+ }
+
+
+
+ /**
+ * Retrieves the named object, following links except for the terminal atomic component of the name.
+ */
+ public Object lookupLink(String name) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.lookupLink(name); }
+
+
+ /**
+ * Binds a name to an object, overwriting any existing binding.
+ */
+ public void rebind(Name name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ ctx.rebind(name, obj);
+ }
+
+
+ /**
+ * Binds a name to an object, overwriting any existing binding.
+ */
+ public void rebind(String name, Object obj) throws NamingException {
+ Context ctx = getImpl();
+ ctx.rebind(name, obj);
+ }
+
+
+ /**
+ * Removes an environment property from the environment of this context.
+ */
+ public Object removeFromEnvironment(String propName) throws NamingException {
+ Context ctx = getImpl();
+ return ctx.removeFromEnvironment(propName);
+ }
+
+
+ /**
+ * Binds a new name to the object bound to an old name, and unbinds the old name.
+ */
+ public void rename(Name oldName, Name newName) throws NamingException {
+ Context ctx = getImpl();
+ ctx.rename(oldName, newName);
+ }
+
+
+ /**
+ * Binds a new name to the object bound to an old name, and unbinds the old name.
+ */
+ public void rename(String oldName, String newName) throws NamingException {
+ Context ctx = getImpl();
+ ctx.rename(oldName, newName);
+ }
+
+
+ /**
+ * Unbinds the named object.
+ */
+ public void unbind(Name name) throws NamingException {
+ Context ctx = getImpl();
+ ctx.unbind(name);
+ }
+
+
+ /**
+ * Unbinds the named object.
+ */
+ public void unbind(String name) throws NamingException {
+ Context ctx = getImpl();
+ ctx.unbind(name);
+ }
+
+ /**
+ * You can use the returned object to synchronize on the specific context tree
+ * @return
+ */
+ public Object getMutex() {
+ return reg.getMutex();
+ }
+}
Added: projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryContext.java
===================================================================
--- projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryContext.java (rev 0)
+++ projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryContext.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -0,0 +1,394 @@
+package org.jboss.fresh.registry;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.CompositeName;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.NameNotFoundException;
+import java.util.Hashtable;
+import java.util.Enumeration;
+import java.util.LinkedList;
+
+
+public class StaticRegistryContext implements Context {
+ private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(StaticRegistryContext.class);
+ private StaticRegistryStore regStore;
+ private Hashtable env = new Hashtable();
+ private CompositeName name;
+ private String root;
+
+ public StaticRegistryContext(String root) throws NamingException {
+ this.root = root;
+ regStore = StaticRegistryStore.getStore(root);
+ name = new CompositeName("");
+ }
+
+ public StaticRegistryContext(String root, CompositeName nm) {
+ this.root = root;
+ regStore = StaticRegistryStore.getStore(root);
+ name = nm;
+ }
+
+ public StaticRegistryContext(String root, Name nm) throws NamingException {
+ this.root = root;
+ regStore = StaticRegistryStore.getStore(root);
+ name = new CompositeName();
+
+ Enumeration enom = nm.getAll();
+ while(enom.hasMoreElements()) {
+ name.add((String)enom.nextElement());
+ }
+ }
+
+ private void getRegistryStore() {
+ if(regStore!=null) return;
+ regStore = StaticRegistryStore.getStore(root);
+ }
+
+ private synchronized void ensureStore() {
+ if(regStore!=null) return;
+ regStore = StaticRegistryStore.createStore(root);
+ }
+
+ /**
+ * Adds a new environment property to the environment of this context.
+ */
+ public Object addToEnvironment(String propName, Object propVal) throws NamingException {
+
+ return env.put(propName, propVal);
+ }
+
+ /**
+ * Binds a name to an object.
+ */
+ public void bind(Name name, Object obj) throws NamingException {
+ final String oldName = name==null ? "<null>" : name.toString();
+
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ log.debug("bind(): Name revamped: " + oldName + " -> " + name);
+ ensureStore();
+ regStore.bind(name, obj);
+ }
+
+ /**
+ * Binds a name to an object.
+ */
+ public void bind(String name, Object obj) throws NamingException {
+ bind(new CompositeName(name), obj);
+ }
+
+
+ /**
+ * Closes this context.
+ */
+ public void close() throws NamingException {
+
+ }
+
+
+ private Name normalize(Name name) {
+ if(name.size() > 0) {
+ Name nm = name.getPrefix(1);
+ if(nm.size() == 0)
+ name = name.getSuffix(1);
+ }
+
+ return name;
+ }
+
+
+ /**
+ * Composes the name of this context with a name relative to this context.
+ */
+ public Name composeName(Name name, Name prefix) throws NamingException {
+ CompositeName retName = new CompositeName();
+ retName.addAll(prefix);
+ retName.addAll(name);
+ return retName;
+
+ }
+
+
+ /**
+ * Composes the name of this context with a name relative to this context.
+ */
+ public String composeName(String name, String prefix) throws NamingException {
+
+ if(name.startsWith("/")) name = name.substring(1);
+ if(prefix.endsWith("/")) prefix = prefix.substring(0, prefix.length()-1);
+
+ CompositeName retName = new CompositeName(prefix + "/" + name);
+ return retName.toString();
+ }
+
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(Name name) throws NamingException {
+ return createSubcontext(name, false);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(Name name, boolean mkparents) throws NamingException {
+ final String oldName = name == null ? "<null>" : name.toString();
+
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ log.debug("createSubcontext(): Name recomposed: " + oldName + " -> " + name);
+
+ ensureStore();
+ return regStore.createSubcontext(name, mkparents);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(String name) throws NamingException {
+ return createSubcontext(new CompositeName(name), false);
+ }
+
+ /**
+ * Creates and binds a new context.
+ */
+ public Context createSubcontext(String name, boolean mkparents) throws NamingException {
+ return createSubcontext(new CompositeName(name), mkparents);
+ }
+
+
+ /**
+ * Destroys the named context and removes it from the namespace.
+ */
+ public void destroySubcontext(Name name) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+
+ getRegistryStore();
+ if(regStore!=null) regStore.destroySubcontext(name);
+ }
+
+
+ /**
+ * Destroys the named context and removes it from the namespace.
+ */
+ public void destroySubcontext(String name) throws NamingException {
+ destroySubcontext(new CompositeName(name));
+ }
+
+
+ /**
+ * Retrieves the environment in effect for this context.
+ */
+ public Hashtable getEnvironment() throws NamingException {
+
+ return env;
+ }
+
+
+ /**
+ * Retrieves the full name of this context within its own namespace.
+ */
+ public String getNameInNamespace() throws NamingException {
+
+ return String.valueOf(name);
+ }
+
+
+ /**
+ * Retrieves the parser associated with the named context.
+ */
+ public NameParser getNameParser(Name name) throws NamingException {
+
+ return StaticRegistryStore.getNameParser();
+ }
+
+
+ /**
+ * Retrieves the parser associated with the named context.
+ */
+ public NameParser getNameParser(String name) throws NamingException {
+
+ return StaticRegistryStore.getNameParser();
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the class names of objects bound to them.
+ */
+ public NamingEnumeration list(Name name) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ getRegistryStore();
+ if(regStore!=null)
+ return regStore.list(name);
+ else
+ return new StaticRegistryStore.ListNameEnum(new LinkedList());
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the class names of objects bound to them.
+ */
+ public NamingEnumeration list(String name) throws NamingException {
+
+ return list(new CompositeName(name));
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the objects bound to them.
+ */
+ public NamingEnumeration listBindings(Name name) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ getRegistryStore();
+ if(regStore!=null)
+ return regStore.listBindings(name);
+ else
+ return new StaticRegistryStore.ListNameEnum(new LinkedList());
+ }
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the objects bound to them.
+ */
+ public NamingEnumeration listBindings(String name) throws NamingException {
+ return listBindings(new CompositeName(name));
+ }
+
+
+ /**
+ * Retrieves the named object.
+ */
+ public Object lookup(Name name) throws NamingException {
+
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ getRegistryStore();
+ if(regStore == null) {
+ String strn = String.valueOf(name);
+ if("".equals(strn) || "/".equals(strn)) {
+ return this;
+ }
+ throw new NameNotFoundException("Name not found: " + name + " (Store does not exist: " + root + ")");
+ }
+ return regStore.lookup(name);
+ }
+
+
+ /**
+ * Retrieves the named object.
+ */
+ public Object lookup(String name) throws NamingException {
+
+ return lookup(new CompositeName(name));
+ }
+
+
+
+ /**
+ * Retrieves the named object, following links except for the terminal atomic component of the name.
+ */
+ public Object lookupLink(Name name) throws NamingException {
+
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ getRegistryStore();
+ if(regStore == null) throw new NameNotFoundException("Name not found: " + name + " (Store does not exist: " + root + ")");
+ return regStore.lookupLink(name);
+ }
+
+
+
+ /**
+ * Retrieves the named object, following links except for the terminal atomic component of the name.
+ */
+ public Object lookupLink(String name) throws NamingException {
+
+ return lookupLink(new CompositeName(name));
+ }
+
+
+ /**
+ * Binds a name to an object, overwriting any existing binding.
+ */
+ public void rebind(Name name, Object obj) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ name = composeName(name, this.name);
+ ensureStore();
+ regStore.rebind(name, obj);
+ }
+
+
+ /**
+ * Binds a name to an object, overwriting any existing binding.
+ */
+ public void rebind(String name, Object obj) throws NamingException {
+ rebind(new CompositeName(name), obj);
+ }
+
+
+ /**
+ * Removes an environment property from the environment of this context.
+ */
+ public Object removeFromEnvironment(String propName) throws NamingException {
+
+ return env.remove(propName);
+ }
+
+
+ /**
+ * Binds a new name to the object bound to an old name, and unbinds the old name.
+ */
+ public void rename(Name oldName, Name newName) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ oldName = composeName(oldName, this.name);
+ newName = composeName(newName, this.name);
+
+ ensureStore();
+ regStore.rename(oldName, newName);
+ }
+
+
+ /**
+ * Binds a new name to the object bound to an old name, and unbinds the old name.
+ */
+ public void rename(String oldName, String newName) throws NamingException {
+ rename(new CompositeName(oldName), new CompositeName(newName));
+ }
+
+
+ /**
+ * Unbinds the named object.
+ */
+ public void unbind(Name name) throws NamingException {
+ // Always prefix it - you don't want a user to escape the cage
+ getRegistryStore();
+ if(regStore == null) return;
+ name = composeName(name, this.name);
+ regStore.unbind(name);
+ }
+
+
+ /**
+ * Unbinds the named object.
+ */
+ public void unbind(String name) throws NamingException {
+ unbind(new CompositeName(name));
+ }
+
+
+ public String toString() {
+ return super.toString() + ": " + String.valueOf(name);
+ }
+
+ public Object getMutex() {
+ ensureStore();
+ return regStore.getMutex();
+ }
+}
Added: projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryStore.java
===================================================================
--- projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryStore.java (rev 0)
+++ projects/fresh/trunk/fresh-util/src/main/java/org/jboss/fresh/registry/StaticRegistryStore.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -0,0 +1,505 @@
+package org.jboss.fresh.registry;
+
+import javax.naming.Context;
+import javax.naming.Name;
+import javax.naming.CompositeName;
+import javax.naming.NameClassPair;
+import javax.naming.Binding;
+import javax.naming.NameParser;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.NameNotFoundException;
+import javax.naming.NameAlreadyBoundException;
+import javax.naming.NotContextException;
+import javax.naming.ContextNotEmptyException;
+
+import java.util.HashMap;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.LinkedHashMap;
+
+public class StaticRegistryStore {
+
+ static HashMap stores = new HashMap();
+ static NameParser parser = new RegistryNameParser();
+ SubCtx root;
+ String sname;
+ Object mutex = new Object();
+
+ static private final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(StaticRegistryStore.class);
+
+ public static StaticRegistryStore getStore(String root) {
+ return (StaticRegistryStore) stores.get(root);
+ }
+
+ private static Name normalize(Name name) {
+ if(name.size() > 0) {
+ Name nm = name.getPrefix(1);
+ if(nm.get(0).length() == 0)
+ name = name.getSuffix(1);
+ }
+
+ return name;
+ }
+
+ public static synchronized StaticRegistryStore createStore(String root) {
+
+ StaticRegistryStore stor = (StaticRegistryStore) stores.get(root);
+ if(stor != null) return stor;
+
+ stor = new StaticRegistryStore(root);
+ stores.put(root, stor);
+ return stor;
+ }
+
+ public StaticRegistryStore(String name) {
+ this.sname = name;
+ root = new SubCtx(sname);
+ }
+
+ private BindData getRootData() {
+ return new BindData(new CompositeName(), root.getClass().getName(), root);
+ }
+
+ private BindData getBindData(Name name) throws NameNotFoundException {
+log.debug("getBind name: " + name);
+ name = normalize(name);
+ int size = name.size();
+
+ if(size == 0) return getRootData();
+
+ SubCtx ctx = root;
+ BindData dat = null;
+
+ Enumeration enom = name.getAll();
+ for(int i = 0; enom.hasMoreElements(); i++) {
+ String str = (String) enom.nextElement();
+log.debug(" getBind co_ " + str);
+ dat = (BindData) ctx.get(str);
+log.debug(" getBind ctx: " + ctx);
+ if(i<size-1) {
+ if(dat == null) throw new NameNotFoundException(String.valueOf(name) + " : " + String.valueOf(name.getPrefix(i+1)) + " is not a context.");
+ Object o = dat.getObject();
+ if(!(o instanceof SubCtx)) throw new NameNotFoundException(String.valueOf(name) + " : " + String.valueOf(name.getPrefix(i+1)) + " is not a context.");
+ ctx = (SubCtx) o;
+ }
+ }
+
+ return dat;
+
+ }
+
+ private void bindData(BindData dat) {
+ Name name = dat.getName();
+
+log.debug("bindData name: " + name);
+log.debug(" bindData dat: " + dat);
+
+ int size = name.size();
+
+ SubCtx ctx = root;
+
+ Enumeration enom = name.getAll();
+ for(int i=0; i<size-1; i++) {
+ String str = (String) enom.nextElement();
+ ctx = (SubCtx) ((BindData)ctx.get(str)).getObject();
+ }
+
+ ctx.put(name.get(size-1), dat);
+ }
+
+
+ private void removeData(Name name) {
+ name = normalize(name);
+ int size = name.size();
+
+ SubCtx ctx = root;
+
+ Enumeration enom = name.getAll();
+ for(int i=0; i<size-1; i++) {
+ String str = (String) enom.nextElement();
+ ctx = (SubCtx) ((BindData)ctx.get(str)).getObject();
+ }
+
+ ctx.remove(name.get(size-1));
+ }
+
+
+ /**
+ * Binds a name to an object.
+ */
+ public synchronized void bind(Name name, Object obj) throws NamingException {
+ log.debug("bind : " + name + " -> " + obj);
+
+ name = normalize(name);
+ // get data for name
+ BindData dat = getBindData(name);
+
+ if(dat != null) throw new NameAlreadyBoundException(String.valueOf(name));
+
+ Name name2 = name.getPrefix(name.size()-1);
+ log.debug(" bind check parent: " + name2);
+ //System.out.println("Checking if parent exists: " + name2);
+ dat = getBindData(name2);
+
+ if(dat == null) throw new NameNotFoundException("Parent context does not exist: " + String.valueOf(name2));
+
+ if(!(dat.getObject() instanceof SubCtx)) throw new NotContextException("Parent name is taken by object that is not context: " + String.valueOf(name2));
+
+ dat = new BindData(name, obj.getClass(), obj);
+ bindData(dat);
+ }
+
+
+
+ /**
+ * Creates and binds a new context.
+ */
+ public synchronized Context createSubcontext(Name name, boolean mkparents) throws NamingException {
+
+ if(mkparents) {
+ int size = name.size()-1;
+ Enumeration enom = name.getAll();
+ Context ct = new StaticRegistryContext(sname);
+ for(int i=0; i<size && enom.hasMoreElements(); i++) {
+ String nmpart = (String) enom.nextElement();
+ try {
+ ct = (Context) ct.lookup(nmpart);
+ } catch(NameNotFoundException ex) {
+ ct = ct.createSubcontext(nmpart);
+ }
+ }
+ }
+
+ // get data for name
+ log.debug("createSubcontext: " + name);
+ name = normalize(name);
+ BindData dat = getBindData(name);
+
+ if(dat != null) throw new NameAlreadyBoundException(String.valueOf(name));
+
+ Name name2 = name.getPrefix(name.size()-1);
+ //System.out.println("Checking if parent exists: " + name2);
+ dat = getBindData(name2);
+
+ if(dat == null) throw new NameNotFoundException("Parent context does not exist: " + String.valueOf(name2));
+
+ SubCtx sub = new SubCtx(sname);
+ dat = new BindData(name, sub.getClass(), sub);
+ bindData(dat);
+
+ return new StaticRegistryContext(sname, name);
+ }
+
+
+
+ /**
+ * Destroys the named context and removes it from the namespace.
+ */
+ public synchronized void destroySubcontext(Name name) throws NamingException {
+ // get data for name
+ name = normalize(name);
+ BindData dat = getBindData(name);
+
+ if(dat == null) throw new NameNotFoundException(String.valueOf(name));
+
+ if(!(dat.getObject() instanceof SubCtx)) throw new NotContextException("Object is bound that is not context: " + String.valueOf(name));
+
+ SubCtx sub = (SubCtx) dat.getObject();
+
+ if(sub.size() != 0) throw new ContextNotEmptyException("Context is not empty: " + String.valueOf(name));
+
+ removeData(name);
+ }
+
+
+
+ /**
+ * Retrieves the parser associated with the named context.
+ */
+ public static synchronized NameParser getNameParser() throws NamingException {
+ return parser;
+ }
+
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the class names of objects bound to them.
+ */
+ public synchronized NamingEnumeration list(Name name) throws NamingException {
+ // get data for name
+ name = normalize(name);
+ BindData dat = getBindData(name);
+
+ if(dat==null) throw new NameNotFoundException(String.valueOf(name));
+
+ if(dat.getObject() instanceof SubCtx) {
+ SubCtx ctx = (SubCtx) dat.getObject();
+
+ return new ListNameEnum(ctx.list());
+ } else {
+ throw new NotContextException(String.valueOf(name));
+ }
+
+ }
+
+
+
+ /**
+ * Enumerates the names bound in the named context, along with the objects bound to them.
+ */
+ public synchronized NamingEnumeration listBindings(Name name) throws NamingException {
+ // get data for name
+ name = normalize(name);
+ BindData dat = getBindData(name);
+
+ if(dat==null) throw new NameNotFoundException(String.valueOf(name));
+
+ if(dat.getObject() instanceof SubCtx) {
+ SubCtx ctx = (SubCtx) dat.getObject();
+
+ return new ListNameEnum(ctx.listBindings());
+ } else {
+ throw new NotContextException(String.valueOf(name));
+ }
+
+ }
+
+
+ /**
+ * Retrieves the named object.
+ */
+ public synchronized Object lookup(Name name) throws NamingException {
+ name = normalize(name);
+ BindData dat = getBindData(name);
+
+ if(dat==null) throw new NameNotFoundException(String.valueOf(name));
+
+ if(dat.getObject() instanceof SubCtx) {
+ return new StaticRegistryContext(sname, name);
+ } else {
+ return dat.getObject();
+ }
+ }
+
+
+
+ /**
+ * Retrieves the named object, following links except for the terminal atomic component of the name.
+ */
+ public synchronized Object lookupLink(Name name) throws NamingException {
+ // we don't have links - I think
+ name = normalize(name);
+ return lookup(name);
+ }
+
+
+
+ /**
+ * Binds a name to an object, overwriting any existing binding.
+ */
+ public synchronized void rebind(Name name, Object obj) throws NamingException {
+ name = normalize(name);
+ unbind(name);
+ bind(name, obj);
+ }
+
+
+
+ /**
+ * Binds a new name to the object bound to an old name, and unbinds the old name.
+ */
+ public synchronized void rename(Name oldName, Name newName) throws NamingException {
+ // get data for name
+ oldName = normalize(oldName);
+ newName = normalize(newName);
+ BindData dat = getBindData(oldName);
+
+ if(dat==null) throw new NameNotFoundException(String.valueOf(oldName));
+
+ unbind(oldName);
+ bind(newName, dat.getObject());
+ }
+
+
+
+ /**
+ * Unbinds the named object.
+ */
+ public synchronized void unbind(Name name) throws NamingException {
+
+ // get data for name
+ name = normalize(name);
+ Name name2 = name.getPrefix(name.size()-1);
+ BindData dat = getBindData(name2);
+
+ if(dat==null) throw new NameNotFoundException(String.valueOf(name2));
+
+ dat = getBindData(name);
+ if(dat==null) return;
+
+ if(dat.getObject() instanceof SubCtx) {
+ throw new NamingException("Name is a context. To remove context use destroyContext() : " + String.valueOf(name));
+ }
+
+ removeData(name);
+ }
+
+ public Object getMutex() {
+ return mutex;
+ }
+
+ static class BindData {
+
+ Name name;
+ String className;
+ Object obj;
+
+ BindData(Name name, Class clazz, Object obj) {
+ this(name, clazz.getName(), obj);
+ }
+
+ BindData(Name name, String clazz, Object obj) {
+ this.name = name;
+ this.className = clazz;
+ this.obj = obj;
+ }
+
+ Name getName() {
+ return name;
+ }
+
+ String getObjectClassName() {
+ return className;
+ }
+
+ Object getObject() {
+ return obj;
+ }
+
+ }
+
+
+ static class SubCtx {
+
+ String sname;
+ LinkedHashMap map = new LinkedHashMap();
+
+ SubCtx(String sname) {
+ this.sname = sname;
+ }
+ public int size() {
+ return map.size();
+ }
+
+ public List list() {
+ LinkedList ls = new LinkedList();
+
+ // fill a list with NameClassPair
+ Iterator it = map.entrySet().iterator();
+ while(it.hasNext()) {
+ Map.Entry ent = (Map.Entry) it.next();
+ String nm = (String) ent.getKey();
+ BindData dat = (BindData) ent.getValue();
+
+ NameClassPair b;
+
+ if(dat.getObject() instanceof SubCtx) {
+ b = new NameClassPair(nm, org.jboss.fresh.registry.StaticRegistryContext.class.getName(), true);
+ } else {
+ b = new NameClassPair(nm, dat.getObjectClassName(), true);
+ }
+
+ ls.add(b);
+ }
+
+ return ls;
+ }
+
+ public List listBindings() throws NamingException {
+
+ LinkedList ls = new LinkedList();
+
+ // fill a list with Bindings
+ Iterator it = map.entrySet().iterator();
+ while(it.hasNext()) {
+ Map.Entry ent = (Map.Entry) it.next();
+ String nm = (String) ent.getKey();
+ BindData dat = (BindData) ent.getValue();
+
+ Binding b;
+ if(dat.getObject() instanceof SubCtx) {
+ b = new Binding(nm, org.jboss.fresh.registry.StaticRegistryContext.class.getName(), new StaticRegistryContext(sname, dat.getName()), true);
+ } else {
+ b = new Binding(nm, dat.getObjectClassName(), dat.getObject(), true);
+ }
+
+ ls.add(b);
+ }
+
+ return ls;
+ }
+
+
+ public Object get(String name) {
+ return map.get(name);
+ }
+
+ public Object put(String name, Object val) {
+ return map.put(name, val);
+ }
+
+ public Object remove(String name) {
+ return map.remove(name);
+ }
+
+ LinkedHashMap getMap() {
+ return map;
+ }
+
+ public String toString() {
+ return super.toString() + ": " + map;
+ }
+ }
+
+
+ static class ListNameEnum implements NamingEnumeration {
+
+ Iterator it;
+
+ ListNameEnum(List ls) {
+ it = ls.iterator();
+ }
+
+ public void close() {
+ }
+
+ public boolean hasMore() {
+ return it.hasNext();
+ }
+
+ public Object next() {
+ return it.next();
+ }
+
+ public boolean hasMoreElements() {
+ return it.hasNext();
+ }
+
+ public Object nextElement() {
+ return next();
+ }
+ }
+
+
+ static class RegistryNameParser implements NameParser {
+
+ public Name parse(String name) throws NamingException {
+ return new CompositeName(name);
+ }
+
+ }
+}
Modified: projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/DefaultRootVFS.java
===================================================================
--- projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/DefaultRootVFS.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/DefaultRootVFS.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -29,16 +29,20 @@
import org.jboss.fresh.vfs.VFSException;
import org.jboss.fresh.io.IOUtils;
-/**
- * @author gospodar
- *
- * TODO To change the template for this generated type comment go to
- * Window - Preferences - Java - Code Style - Code Templates
- */
+
public class DefaultRootVFS implements RootVFS, VFSAuth {
private HashMap mounts = new LinkedHashMap();
+ public DefaultRootVFS(Map<String,VFS> mounts)throws Exception{
+ if (mounts!=null){
+ for (Map.Entry<String,VFS> entry:mounts.entrySet()){
+ mount(entry.getKey(),entry.getValue());
+ }
+ }
+
+ }
+
protected MountData findFS(FileName name) {
while(name != null) {
Modified: projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSMeta.java
===================================================================
--- projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSMeta.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSMeta.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,7 +1,13 @@
package org.jboss.fresh.vfs.impl.mem;
+import org.jboss.fresh.vfs.FileInfo;
+import org.jboss.fresh.vfs.FileName;
+import org.jboss.fresh.vfs.VFSException;
+import org.jboss.fresh.vfs.VFSMeta;
+import org.jboss.fresh.vfs.VFSMetaCacheUpdater;
+import org.jboss.fresh.registry.RegistryContext;
+
import org.apache.log4j.Logger;
-import org.jboss.fresh.vfs.*;
import javax.naming.*;
import java.util.Collection;
@@ -11,437 +17,430 @@
public class MemVFSMeta implements VFSMeta {
- private static final String INTERNAL_FILE = "==__node__";
- private String sfJndiName;
- private VFSMetaCacheUpdater cup;
- InitialContext fsroot;
+ private static final String INTERNAL_FILE = "==__node__";
+ private String sfJndiName;
+ private VFSMetaCacheUpdater cup;
+ private RegistryContext fsroot;
+ private static Logger log = Logger.getLogger(MemVFSMeta.class);
- private static Logger log = Logger.getLogger(MemVFSMeta.class);
+ public MemVFSMeta(String sfJndiName, String fsname) throws Exception {
+ this.sfJndiName = sfJndiName;
+ fsroot = new RegistryContext(fsname);
+ FileInfo inf = new FileInfo(new FileName("/"));
+ inf.setCreateDate(new Date());
+ inf.setFileType(FileInfo.TYPE_DIR);
+ inf.setLastModified(inf.getCreateDate());
+ inf.setLength(0);
- public MemVFSMeta(String sfJndiName, String fsname) throws Exception {
- this.sfJndiName = sfJndiName;
- fsroot = (InitialContext) new InitialContext().lookup(fsname);
+ Context rootCtx = (Context) fsroot.lookup("/");
+ try {
+ rootCtx.lookup(INTERNAL_FILE);
+ } catch(NameNotFoundException ex) {
+ rootCtx.bind(INTERNAL_FILE, fileInfoToFNode(inf));
+ }
+ }
- FileInfo inf = new FileInfo(new FileName("/"));
- inf.setCreateDate(new Date());
- inf.setFileType(FileInfo.TYPE_DIR);
- inf.setLastModified(inf.getCreateDate());
- inf.setLength(0);
- Context rootCtx = (Context) fsroot.lookup("/");
- try {
- rootCtx.lookup(INTERNAL_FILE);
- } catch (NameNotFoundException ex) {
- rootCtx.bind(INTERNAL_FILE, fileInfoToFNode(inf));
- }
- }
+ //***** VFSMeta METHODS *****
+ public void setCacheUpdater(VFSMetaCacheUpdater updater) {
+ cup = updater;
+ }
- //***** VFSMeta METHODS *****
+ public VFSMetaCacheUpdater getCacheUpdater() {
+ return cup;
+ }
- public void setCacheUpdater(VFSMetaCacheUpdater updater) {
- cup = updater;
- }
+ public Object getResolvedNode(String name) throws VFSException, NamingException {
+ Object node = null;
- public VFSMetaCacheUpdater getCacheUpdater() {
- return cup;
- }
+ if("/".equals(name)) {
+ name = "";
+ }
- public Object getResolvedNode(String name) throws VFSException, NamingException {
- Object node = null;
+ for(int i=0; i<256; i++) {
+ try {
+ node = fsroot.lookup(name);
+ } catch(NameNotFoundException ex) {
+ }
- if ("/".equals(name)) {
- name = "";
- }
+ if(node instanceof FNode) {
+ FNode fnode = (FNode) node;
+ if(fnode.getType() == FNode.LINK) {
+ name = fnode.getLinkRef();
+ } else {
+ return node;
+ }
+ } else {
+ return node;
+ }
+ }
- for (int i = 0; i < 256; i++) {
- try {
- node = fsroot.lookup(name);
- } catch (NameNotFoundException ex) {
- }
+ throw new VFSException("Link resolution infinitely looped: " + name);
+ }
- if (node instanceof FNode) {
- FNode fnode = (FNode) node;
- if (fnode.getType() == FNode.LINK) {
- name = fnode.getLinkRef();
- } else {
- return node;
- }
- } else {
- return node;
- }
- }
+ private FNode fileInfoToFNode(FileInfo finfo) {
+ FNode node = new FNode();
+ node.setName(finfo.getFileName().toString());
+ node.setAttrs(finfo.getAttributes());
+ node.setCreateDate( finfo.getCreateDate());
+ node.setLastModified( finfo.getLastModified());
+ node.setType(finfo.getFileType() == FileInfo.TYPE_FILE ? FNode.FILE : finfo.getFileType() == FileInfo.TYPE_DIR ? FNode.DIR : FNode.LINK);
+ node.setMime(finfo.getMime());
+ node.setFileContent(new MemFile());
+ node.setLength(finfo.getLength());
+ node.setTag(finfo.getTag());
+ return node;
+ }
- throw new VFSException("Link resolution infinitely looped: " + name);
- }
+ private FileInfo fnodeToFileInfo(FileName name, FNode node) throws VFSException {
+ FileInfo inf = new FileInfo(name);
+ inf.setAttributes(node.getAttrs());
+ inf.setCreateDate(node.getCreateDate());
+ inf.setFileType(node.getType() == FNode.FILE ? FileInfo.TYPE_FILE : node.getType() == FNode.DIR ? FileInfo.TYPE_DIR : FileInfo.TYPE_LINK);
+ inf.setLastModified(node.getLastModified());
+ inf.setLength(node.getLength());
+ inf.setMime(node.getMime());
+ inf.setTag(node.getTag());
+ if(node.getLink() != null) {
+ inf.setTarget(new FileName(node.getLink()));
+ }
+ return inf;
+ }
- private FNode fileInfoToFNode(FileInfo finfo) {
- FNode node = new FNode();
- node.setName(finfo.getFileName().toString());
- node.setAttrs(finfo.getAttributes());
- node.setCreateDate(finfo.getCreateDate());
- node.setLastModified(finfo.getLastModified());
- node.setType(finfo.getFileType() == FileInfo.TYPE_FILE ? FNode.FILE : finfo.getFileType() == FileInfo.TYPE_DIR ? FNode.DIR : FNode.LINK);
- node.setMime(finfo.getMime());
- node.setFileContent(new MemFile());
- node.setLength(finfo.getLength());
- node.setTag(finfo.getTag());
- return node;
- }
+ private void updateFNodeWithFileInfo(FNode node, FileInfo finfo) {
+ node.setAttrs(finfo.getAttributes());
+ node.setCreateDate( finfo.getCreateDate());
+ node.setLastModified( finfo.getLastModified());
+ node.setType(finfo.getFileType() == FileInfo.TYPE_FILE ? FNode.FILE : finfo.getFileType() == FileInfo.TYPE_DIR ? FNode.DIR : FNode.LINK);
+ node.setMime(finfo.getMime());
+ node.setLength(finfo.getLength());
+ node.setTag(finfo.getTag());
+ }
- private FileInfo fnodeToFileInfo(FileName name, FNode node) throws VFSException {
- FileInfo inf = new FileInfo(name);
- inf.setAttributes(node.getAttrs());
- inf.setCreateDate(node.getCreateDate());
- inf.setFileType(node.getType() == FNode.FILE ? FileInfo.TYPE_FILE : node.getType() == FNode.DIR ? FileInfo.TYPE_DIR : FileInfo.TYPE_LINK);
- inf.setLastModified(node.getLastModified());
- inf.setLength(node.getLength());
- inf.setMime(node.getMime());
- inf.setTag(node.getTag());
- if (node.getLink() != null) {
- inf.setTarget(new FileName(node.getLink()));
- }
- return inf;
- }
+ private FileInfo childToFileInfo(FileName name, Object child) throws VFSException, NamingException {
+ if(child instanceof FNode) {
+ return fnodeToFileInfo(name, (FNode)child);
+ } else if(child instanceof Context) {
+ Context ctx = (Context) child;
+ try {
+ FNode node = (FNode) ctx.lookup(INTERNAL_FILE);
+ return fnodeToFileInfo(name, node);
+ } catch(NameNotFoundException ex) {
+ throw new RuntimeException("Internal error - missing child node: " + INTERNAL_FILE + " (for key: " + name + ")");
+ }
+ } else {
+ throw new RuntimeException("Internal error: child of illegal type: " + child.getClass().getName());
+ }
+ }
- private void updateFNodeWithFileInfo(FNode node, FileInfo finfo) {
- node.setAttrs(finfo.getAttributes());
- node.setCreateDate(finfo.getCreateDate());
- node.setLastModified(finfo.getLastModified());
- node.setType(finfo.getFileType() == FileInfo.TYPE_FILE ? FNode.FILE : finfo.getFileType() == FileInfo.TYPE_DIR ? FNode.DIR : FNode.LINK);
- node.setMime(finfo.getMime());
- node.setLength(finfo.getLength());
- node.setTag(finfo.getTag());
- }
+ /** Name must be valid FileName object.
+ */
+ public boolean exists(FileName name) throws Exception {
- private FileInfo childToFileInfo(FileName name, Object child) throws VFSException, NamingException {
- if (child instanceof FNode) {
- return fnodeToFileInfo(name, (FNode) child);
- } else if (child instanceof Context) {
- Context ctx = (Context) child;
- try {
- FNode node = (FNode) ctx.lookup(INTERNAL_FILE);
- return fnodeToFileInfo(name, node);
- } catch (NameNotFoundException ex) {
- throw new RuntimeException("Internal error - missing child node: " + INTERNAL_FILE + " (for key: " + name + ")");
- }
- } else {
- throw new RuntimeException("Internal error: child of illegal type: " + child.getClass().getName());
- }
- }
+ // Convert to CompositeName
+ // lookup RegistryContext
+ // if NameNotFoundException it doesn't exist
- /**
- * Name must be valid FileName object.
- */
- public boolean exists(FileName name) throws Exception {
+ Object node = null;
- // Convert to CompositeName
- // lookup RegistryContext
- // if NameNotFoundException it doesn't exist
+ try {
+ node = getResolvedNode(name.toString());
+ } catch(NameNotFoundException ex) {
+ }
- Object node = null;
+ if(node == null)
+ return false;
- try {
- node = getResolvedNode(name.toString());
- } catch (NameNotFoundException ex) {
- }
+ return true;
+ }
- if (node == null)
- return false;
- return true;
- }
+ public int countNamingEnum(NamingEnumeration enom) throws NamingException {
+ int i = 0;
+ for(;enom.hasMore();i++) {
+ enom.next();
+ }
+ return i;
+ }
- public int countNamingEnum(NamingEnumeration enom) throws NamingException {
- int i = 0;
- for (; enom.hasMore(); i++) {
- enom.next();
- }
- return i;
- }
+ /** Path must be valid FileName object.
+ */
+ public int countChildren(FileName path) throws Exception {
+ // Convert to CompositeName
+ // get NameEnumeration
+ // return count
+ NamingEnumeration names = null;
+ Object node = null;
+ try {
+ node = getResolvedNode(path.toString());
+ } catch(NameNotFoundException ex) {}
+ if(node == null)
+ throw new VFSException("File not found: " + path);
- /**
- * Path must be valid FileName object.
- */
- public int countChildren(FileName path) throws Exception {
- // Convert to CompositeName
- // get NameEnumeration
- // return count
- NamingEnumeration names = null;
- Object node = null;
- try {
- node = getResolvedNode(path.toString());
- } catch (NameNotFoundException ex) {
- }
+ if(!(node instanceof Context))
+ throw new VFSException("File is not a directory");
- if (node == null)
- throw new VFSException("File not found: " + path);
+ try {
+ names = ((Context) node).list("");
+ } catch(NotContextException ex) {
+ throw new VFSException("File is not a directory");
+ }
- if (!(node instanceof Context))
- throw new VFSException("File is not a directory");
+ return countNamingEnum(names);
+ }
- try {
- names = ((Context) node).list("");
- } catch (NotContextException ex) {
- throw new VFSException("File is not a directory");
- }
- return countNamingEnum(names);
- }
+ /** Path must point to existing file or dir and must not be null.
+ */
+ public List resolvePath(FileName path) throws Exception {
+ // Convert to CompositeName
+ // get FileInfo
+ // as long as fileinfo is link keep looking up reference to next fileinfo
+ // and adding FileInfo for every next component to return list.
+ // if found broken link return whatever you have in list
+ // first item in a list is always passed path param
+ LinkedList ls = new LinkedList();
- /**
- * Path must point to existing file or dir and must not be null.
- */
- public List resolvePath(FileName path) throws Exception {
- // Convert to CompositeName
- // get FileInfo
- // as long as fileinfo is link keep looking up reference to next fileinfo
- // and adding FileInfo for every next component to return list.
+ if(path == null) {
+ ls.add(new FileName("/"));
+ return ls;
+ }
- // if found broken link return whatever you have in list
- // first item in a list is always passed path param
- LinkedList ls = new LinkedList();
+ //ls.add(path);
- if (path == null) {
- ls.add(new FileName("/"));
- return ls;
- }
+ Object node = null;
+ String name = path.toString();
- //ls.add(path);
+ for(int i=0; i<256; i++) {
+ try {
+ node = fsroot.lookup(name);
+ } catch(NameNotFoundException ex) {
+ node = null;
+ }
- Object node = null;
- String name = path.toString();
+ if(node instanceof FNode) {
+ ls.add(new FileName(name));
+ FNode fnode = (FNode) node;
+ if(fnode.getType() == FNode.LINK) {
+ name = fnode.getLinkRef();
+ } else {
+ return ls;
+ }
+ } else {
+ ls.add(new FileName(name));
+ return ls;
+ }
+ }
- for (int i = 0; i < 256; i++) {
- try {
- node = fsroot.lookup(name);
- } catch (NameNotFoundException ex) {
- node = null;
- }
+ throw new VFSException("Link resolution infinitely looped: " + name);
- if (node instanceof FNode) {
- ls.add(new FileName(name));
- FNode fnode = (FNode) node;
- if (fnode.getType() == FNode.LINK) {
- name = fnode.getLinkRef();
- } else {
- return ls;
- }
- } else {
- ls.add(new FileName(name));
- return ls;
- }
- }
+ }
- throw new VFSException("Link resolution infinitely looped: " + name);
- }
+ public FileInfo getFileInfo(FileName name) throws Exception {
+ // Convert to CompositeName
+ // get FileInfo
+ // return null if no info for name
+ Object node = getResolvedNode(name.toString());
- public FileInfo getFileInfo(FileName name) throws Exception {
- // Convert to CompositeName
- // get FileInfo
- // return null if no info for name
+ if(node == null)
+ return null;
- Object node = getResolvedNode(name.toString());
+ if(node instanceof FNode) {
+ return fnodeToFileInfo(name, (FNode) node);
+ } else if(node instanceof Context) {
+ Context ctx = (Context) node;
+ try {
+ node = ctx.lookup(INTERNAL_FILE);
+ } catch(NameNotFoundException ex) {
+ throw new RuntimeException("Internal error - missing child node: " + INTERNAL_FILE + " (for key: " + name + ")");
+ }
+ }
- if (node == null)
- return null;
+ if(node == null)
+ throw new RuntimeException("Internal error: node should not be null for key: " + name);
- if (node instanceof FNode) {
- return fnodeToFileInfo(name, (FNode) node);
- } else if (node instanceof Context) {
- Context ctx = (Context) node;
- try {
- node = ctx.lookup(INTERNAL_FILE);
- } catch (NameNotFoundException ex) {
- throw new RuntimeException("Internal error - missing child node: " + INTERNAL_FILE + " (for key: " + name + ")");
- }
- }
+ return fnodeToFileInfo(name, (FNode) node);
+ }
- if (node == null)
- throw new RuntimeException("Internal error: node should not be null for key: " + name);
- return fnodeToFileInfo(name, (FNode) node);
- }
+ public List list(FileName path) throws Exception {
+ // Convert to CompositeName
+ // enumerate values for the name
+ // return a list of them
- public List list(FileName path) throws Exception {
+ NamingEnumeration names = null;
+ Object node = null;
+ try {
+ node = getResolvedNode(path.toString());
+ } catch(NameNotFoundException ex) {}
- // Convert to CompositeName
- // enumerate values for the name
- // return a list of them
+ if(node == null)
+ throw new VFSException("File not found: " + path);
- NamingEnumeration names = null;
- Object node = null;
- try {
- node = getResolvedNode(path.toString());
- } catch (NameNotFoundException ex) {
- }
+ if(!(node instanceof Context))
+ throw new VFSException("File is not a directory");
- if (node == null)
- throw new VFSException("File not found: " + path);
+ try {
+ names = ((Context) node).listBindings("");
+ } catch(NotContextException ex) {
+ throw new VFSException("File is not a directory");
+ }
- if (!(node instanceof Context))
- throw new VFSException("File is not a directory");
+ LinkedList ls = new LinkedList();
+ while(names.hasMore()) {
+ Binding binding = (Binding) names.next();
+ if(! INTERNAL_FILE.equals(binding.getName()))
+ ls.add(childToFileInfo(path.absolutize(binding.getName().toString()), binding.getObject()));
+ }
- try {
- names = ((Context) node).listBindings("");
- } catch (NotContextException ex) {
- throw new VFSException("File is not a directory");
- }
+ return ls;
+ }
- LinkedList ls = new LinkedList();
- while (names.hasMore()) {
- Binding binding = (Binding) names.next();
- if (!INTERNAL_FILE.equals(binding.getName()))
- ls.add(childToFileInfo(path.absolutize(binding.getName().toString()), binding.getObject()));
- }
+ public Collection getLinks(FileName target) throws Exception {
- return ls;
- }
+ // return all fileinfos that link to this one
+ // why would we need that?
+ // it means we need to keep reverse references - a pain
+ throw new RuntimeException();
+ }
- public Collection getLinks(FileName target) throws Exception {
+ public void create(FileInfo fi) throws Exception {
+ // save fi under CompositeName
+ // what if it exists already ?
+ // Error, it must not exist
- // return all fileinfos that link to this one
- // why would we need that?
- // it means we need to keep reverse references - a pain
- throw new RuntimeException();
- }
+ try {
+ // check father
+ // Noro - v primeru direktorija moramo narediti nov context !!!
+ if(fi.getFileType() == FileInfo.TYPE_DIR) {
- public void create(FileInfo fi) throws Exception {
- // save fi under CompositeName
- // what if it exists already ?
- // Error, it must not exist
+ try {
+ fsroot.lookup(fi.getFileName().toString());
+ throw new VFSException("Directory exists already: " + fi.getFileName());
+ } catch(NameNotFoundException ex) {
+ }
- try {
- // check father
- // Noro - v primeru direktorija moramo narediti nov context !!!
- if (fi.getFileType() == FileInfo.TYPE_DIR) {
+ Context nuctx = fsroot.createSubcontext(fi.getFileName().toString());
+ nuctx.bind(INTERNAL_FILE, fileInfoToFNode(fi));
+ } else {
+ fsroot.bind(fi.getFileName().toString(), fileInfoToFNode(fi));
+ }
+ } catch(NamingException ex) {
+ throw new VFSException("Could not create file: " + fi.getFileName(), ex);
+ }
+ }
- try {
- fsroot.lookup(fi.getFileName().toString());
- throw new VFSException("Directory exists already: " + fi.getFileName());
- } catch (NameNotFoundException ex) {
- }
- Context nuctx = fsroot.createSubcontext(fi.getFileName().toString());
- nuctx.bind(INTERNAL_FILE, fileInfoToFNode(fi));
- } else {
- fsroot.bind(fi.getFileName().toString(), fileInfoToFNode(fi));
- }
- } catch (NamingException ex) {
- throw new VFSException("Could not create file: " + fi.getFileName(), ex);
- }
- }
+ // lahko spremeni katerikoli metainfo, samo filename-a ne (na ravni tabel se torej ne spremeni filename, parent in name),
+ // ker je to edini primary key, ki ga imam na voljo iz parametrov;
+ // problem pri primary key-ih pa je v drugih tabelah, kjer bo treba najprej vse vrstice pobrisat in nato
+ // novo vnest... (ni druge; ce bi hoteli ugotoviti, kaj ekzactly se updata, bi bilo se bolj potratno... odvisno od primera)
+ public void update(FileInfo fi) throws Exception {
+ // look up info for CompositeName
+ // apply new info to it
+ Object node = null;
+ try {
+ node = fsroot.lookup(fi.getFileName().toString());
+ } catch(NameNotFoundException ex) {
+ }
+ if(node == null)
+ throw new VFSException("File does not exist: " + fi.getFileName());
- // lahko spremeni katerikoli metainfo, samo filename-a ne (na ravni tabel se torej ne spremeni filename, parent in name),
- // ker je to edini primary key, ki ga imam na voljo iz parametrov;
- // problem pri primary key-ih pa je v drugih tabelah, kjer bo treba najprej vse vrstice pobrisat in nato
- // novo vnest... (ni druge; ce bi hoteli ugotoviti, kaj ekzactly se updata, bi bilo se bolj potratno... odvisno od primera)
- public void update(FileInfo fi) throws Exception {
- // look up info for CompositeName
- // apply new info to it
- Object node = null;
- try {
- node = fsroot.lookup(fi.getFileName().toString());
- } catch (NameNotFoundException ex) {
- }
+ if(node instanceof FNode) {
+ updateFNodeWithFileInfo((FNode) node, fi);
+ } else if(node instanceof Context) {
+ node = ((Context) node).lookup(INTERNAL_FILE);
+ updateFNodeWithFileInfo((FNode) node, fi);
+ } else {
+ throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
+ }
+ }
- if (node == null)
- throw new VFSException("File does not exist: " + fi.getFileName());
- if (node instanceof FNode) {
- updateFNodeWithFileInfo((FNode) node, fi);
- } else if (node instanceof Context) {
- node = ((Context) node).lookup(INTERNAL_FILE);
- updateFNodeWithFileInfo((FNode) node, fi);
- } else {
- throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
- }
- }
+ // ko klices getInt na result setu, pa da je ta int nastavljen na NULL, dobis nazaj 0! Zato ne sme biti noben index 0!
+ public void remove(FileName name) throws Exception {
+ // remove entry
+ // if directory you need to remove context
+ Object node = null;
+ try {
+ node = fsroot.lookup(name.toString());
+ } catch(NameNotFoundException ex) {
+ }
+ if(node == null)
+ throw new VFSException("File does not exist: " + name);
- // ko klices getInt na result setu, pa da je ta int nastavljen na NULL, dobis nazaj 0! Zato ne sme biti noben index 0!
- public void remove(FileName name) throws Exception {
- // remove entry
- // if directory you need to remove context
- Object node = null;
- try {
- node = fsroot.lookup(name.toString());
- } catch (NameNotFoundException ex) {
- }
+ if(node instanceof FNode) {
+ fsroot.unbind(name.toString());
+ } else if(node instanceof Context) {
+ // remove INTERNAL_FILE first
+ String nnode = name.toString() + INTERNAL_FILE;
+ Object co = fsroot.lookup(nnode);
+ fsroot.unbind(nnode);
+ try {
+ fsroot.destroySubcontext(name.toString());
+ } catch (Exception ex) {
+ fsroot.bind(nnode, co);
+ throw ex;
+ } catch (Throwable t) {
+ fsroot.bind(nnode, co);
+ throw new RuntimeException("Error while removing directory: ", t);
+ }
+ } else {
+ throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
+ }
- if (node == null)
- throw new VFSException("File does not exist: " + name);
+ }
- if (node instanceof FNode) {
- fsroot.unbind(name.toString());
- } else if (node instanceof Context) {
- // remove INTERNAL_FILE first
- String nnode = name.toString() + INTERNAL_FILE;
- Object co = fsroot.lookup(nnode);
- fsroot.unbind(nnode);
- try {
- fsroot.destroySubcontext(name.toString());
- } catch (Exception ex) {
- fsroot.bind(nnode, co);
- throw ex;
- } catch (Throwable t) {
- fsroot.bind(nnode, co);
- throw new RuntimeException("Error while removing directory: ", t);
- }
- } else {
- throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
- }
- }
+ public void rename(FileName oldPath, FileName newPath) throws Exception {
+ // lookup structure and change the name
+ // rename is same as move - should be called move
+ Object node = null;
+ try {
+ node = fsroot.lookup(oldPath.toString());
+ } catch(NameNotFoundException ex) {
+ }
- public void rename(FileName oldPath, FileName newPath) throws Exception {
- // lookup structure and change the name
- // rename is same as move - should be called move
- Object node = null;
+ if(node == null)
+ throw new RuntimeException("Internal error - Node does not exist: " + oldPath.toString());
- try {
- node = fsroot.lookup(oldPath.toString());
- } catch (NameNotFoundException ex) {
- }
+ if(node instanceof FNode) {
+ fsroot.rename(oldPath.toString(), newPath.toString());
+ } else if(node instanceof Context) {
+ // rename is already covered in naming
+ // we have to move it first
+ fsroot.rename(oldPath.toString(), newPath.toString());
+ if(!newPath.getName().equals(oldPath.getName())) {
+ try {
+ node = fsroot.lookup(newPath.toString() + INTERNAL_FILE);
+ } catch(NameNotFoundException ex) {
+ }
- if (node == null)
- throw new RuntimeException("Internal error - Node does not exist: " + oldPath.toString());
+ if(node == null)
+ throw new RuntimeException("Internal error - Node does not exist: " + newPath.toString() + INTERNAL_FILE);
- if (node instanceof FNode) {
- fsroot.rename(oldPath.toString(), newPath.toString());
- } else if (node instanceof Context) {
- // rename is already covered in naming
- // we have to move it first
- fsroot.rename(oldPath.toString(), newPath.toString());
- if (!newPath.getName().equals(oldPath.getName())) {
- try {
- node = fsroot.lookup(newPath.toString() + INTERNAL_FILE);
- } catch (NameNotFoundException ex) {
- }
+ ((FNode) node).setName(newPath.getName());
+ }
+ } else {
+ throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
+ }
- if (node == null)
- throw new RuntimeException("Internal error - Node does not exist: " + newPath.toString() + INTERNAL_FILE);
+ }
- ((FNode) node).setName(newPath.getName());
- }
- } else {
- throw new RuntimeException("Internal error - Node is of wrong type: " + node.getClass().getName());
- }
- }
-
-
- public float moveBefore(FileName currFile, FileName nextFile) throws Exception {
- // this operation moves a file whithin it's parent. Native FSs usually don't support this
- throw new RuntimeException("Method not implemented");
+ public float moveBefore(FileName currFile, FileName nextFile) throws Exception {
+ // this operation moves a file whithin it's parent. Native FSs usually don't support this
+ throw new RuntimeException("Method not implemented");
}
}
\ No newline at end of file
Modified: projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSStore.java
===================================================================
--- projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSStore.java 2009-11-23 22:18:34 UTC (rev 96763)
+++ projects/fresh/trunk/fresh-vfs/src/main/java/org/jboss/fresh/vfs/impl/mem/MemVFSStore.java 2009-11-23 22:29:15 UTC (rev 96764)
@@ -1,188 +1,193 @@
package org.jboss.fresh.vfs.impl.mem;
+import org.jboss.fresh.vfs.FileInfo;
+import org.jboss.fresh.vfs.FileName;
+import org.jboss.fresh.vfs.FileOpInfo;
+import org.jboss.fresh.vfs.FileReadInfo;
+import org.jboss.fresh.vfs.VFSException;
+import org.jboss.fresh.vfs.VFSMeta;
+import org.jboss.fresh.vfs.VFSStore;
+import org.jboss.fresh.vfs.VFSStoreCacheUpdater;
+import org.jboss.fresh.registry.RegistryContext;
+
import org.apache.log4j.Logger;
-import org.jboss.fresh.vfs.*;
import javax.naming.Context;
-import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.naming.NamingException;
+
import java.util.Date;
public class MemVFSStore implements VFSStore {
- private VFSMeta meta;
- private VFSStoreCacheUpdater cup;
- InitialContext fsroot;
+ private VFSMeta meta;
+ private VFSStoreCacheUpdater cup;
+ RegistryContext fsroot;
- private static Logger log = Logger.getLogger("org.jboss.fresh.vfs.impl.mem.MemVFSStore");
+ private static Logger log = Logger.getLogger(MemVFSStore.class);
- public MemVFSStore(VFSMeta meta, String fsname) throws Exception {
- this.meta = meta;
- fsroot = (InitialContext) new InitialContext().lookup(fsname);
- }
+ public MemVFSStore(VFSMeta meta, String fsname) throws Exception {
+ this.meta = meta;
+ fsroot = new RegistryContext(fsname);
+ }
- public void setCacheUpdater(VFSStoreCacheUpdater updater) {
- cup = updater;
- }
+ public void setCacheUpdater(VFSStoreCacheUpdater updater) {
+ cup = updater;
+ }
- public VFSStoreCacheUpdater getCacheUpdater() {
- return cup;
- }
+ public VFSStoreCacheUpdater getCacheUpdater() {
+ return cup;
+ }
- public Object getResolvedNode(String name) throws VFSException, NamingException {
- Object node = null;
+ public Object getResolvedNode(String name) throws VFSException, NamingException {
+ Object node = null;
- for (int i = 0; i < 256; i++) {
- node = fsroot.lookup(name);
- if (node instanceof FNode) {
- FNode fnode = (FNode) node;
- if (fnode.getType() == FNode.LINK) {
- name = fnode.getLinkRef();
- } else {
- return node;
- }
- } else {
- return node;
- }
- }
+ for(int i=0; i<256; i++) {
+ node = fsroot.lookup(name);
+ if(node instanceof FNode) {
+ FNode fnode = (FNode) node;
+ if(fnode.getType() == FNode.LINK) {
+ name = fnode.getLinkRef();
+ } else {
+ return node;
+ }
+ } else {
+ return node;
+ }
+ }
- throw new VFSException("Link resolution infinitely looped: " + name);
- }
+ throw new VFSException("Link resolution infinitely looped: " + name);
+ }
- /**
- * FileName must not be null, it can point to inexisting file.
- */
- public boolean hasContent(FileName filename) throws Exception {
+ /** FileName must not be null, it can point to inexisting file.
+ */
+ public boolean hasContent(FileName filename) throws Exception {
- // lookup if it is a file
- Object node = null;
- try {
- node = getResolvedNode(filename.toString());
- } catch (NameNotFoundException ex) {
- }
+ // lookup if it is a file
+ Object node = null;
+ try {
+ node = getResolvedNode(filename.toString());
+ } catch(NameNotFoundException ex) {
+ }
- if (node == null)
- return false;
+ if(node == null)
+ return false;
- if (node instanceof FNode) {
- return ((FNode) node).getLength() > 0;
- } else if (node instanceof Context) {
- return false;
- } else {
- throw new RuntimeException("Internal error: child of illegal type: " + node.getClass().getName());
- }
- }
+ if(node instanceof FNode) {
+ return ((FNode) node).getLength() > 0;
+ } else if(node instanceof Context) {
+ return false;
+ } else {
+ throw new RuntimeException("Internal error: child of illegal type: " + node.getClass().getName());
+ }
+ }
- /**
- * Writes a chunk of content data.
- * FileOpInfo must be filled filename (file doesn't need to exist), filepos, and len.
- */
- public void writeContent(FileOpInfo info) throws Exception {
- try {
+ /** Writes a chunk of content data.
+ * FileOpInfo must be filled filename (file doesn't need to exist), filepos, and len.
+ */
+ public void writeContent(FileOpInfo info) throws Exception {
+ try {
- Object node = null;
- try {
- node = getResolvedNode(info.filename.toString());
- } catch (NameNotFoundException ex) {
- }
+ Object node = null;
+ try {
+ node = getResolvedNode(info.filename.toString());
+ } catch(NameNotFoundException ex) {
+ }
- if (node == null) {
- // file doesn't exist
- // create it
- FileInfo finf = new FileInfo(info.filename);
- finf.setCreateDate(new Date());
- finf.setLastModified(new Date());
- finf.setFileType(FileInfo.TYPE_FILE);
- finf.setLength(0);
- finf.setMime("application/octet-stream");
- meta.create(finf);
- node = getResolvedNode(info.filename.toString());
- }
+ if(node == null) {
+ // file doesn't exist
+ // create it
+ FileInfo finf = new FileInfo(info.filename);
+ finf.setCreateDate(new Date());
+ finf.setLastModified(new Date());
+ finf.setFileType(FileInfo.TYPE_FILE);
+ finf.setLength(0);
+ finf.setMime("application/octet-stream");
+ meta.create(finf);
+ node = getResolvedNode(info.filename.toString());
+ }
- RAF raf = null;
- if (node instanceof FNode) {
- raf = ((FNode) node).getFileContent().getRAF();
- } else if (node instanceof Context) {
- throw new VFSException(info.filename.toString() + " is a directory.");
- }
+ RAF raf = null;
+ if(node instanceof FNode) {
+ raf = ((FNode) node).getFileContent().getRAF();
+ } else if(node instanceof Context) {
+ throw new VFSException(info.filename.toString() + " is a directory.");
+ }
- if (info.append) {
- raf.seek(raf.getLength());
- } else {
- raf.seek(info.offset);
- }
- raf.write(info.buf, 0, info.buf.length);
- raf.close();
+ if(info.append) {
+ raf.seek(raf.getLength());
+ } else {
+ raf.seek(info.offset);
+ }
+ raf.write(info.buf, 0, info.buf.length);
+ raf.close();
- } catch (Exception e) {
- log.error("Could not write content", e);
- throw e;
- }
+ } catch (Exception e) {
+ log.error("Could not write content", e);
+ throw e;
+ }
- }
+ }
- /**
- * Reads a chunk of content data and returns it as FileRetInfo object.
- * FileOpInfo must be filled filename (file must exist), filepos and buf.
- */
- public FileReadInfo readContent(FileOpInfo info) throws Exception {
+ /** Reads a chunk of content data and returns it as FileRetInfo object.
+ * FileOpInfo must be filled filename (file must exist), filepos and buf.
+ */
+ public FileReadInfo readContent(FileOpInfo info) throws Exception {
- FileReadInfo result = new FileReadInfo();
- long count;
+ FileReadInfo result = new FileReadInfo();
+ long count;
- Object node = null;
- try {
- node = getResolvedNode(info.filename.toString());
- } catch (NameNotFoundException ex) {
- }
+ Object node = null;
+ try {
+ node = getResolvedNode(info.filename.toString());
+ } catch(NameNotFoundException ex) {
+ }
- if (node == null) throw new VFSException("File not found: " + info.filename);
+ if(node == null) throw new VFSException("File not found: " + info.filename);
- RAF raf = null;
- if (node instanceof FNode) {
- raf = ((FNode) node).getFileContent().getRAF();
- } else if (node instanceof Context) {
- throw new VFSException(info.filename.toString() + " is a directory.");
- }
+ RAF raf = null;
+ if(node instanceof FNode) {
+ raf = ((FNode) node).getFileContent().getRAF();
+ } else if(node instanceof Context) {
+ throw new VFSException(info.filename.toString() + " is a directory.");
+ }
- raf.seek(info.offset);
- int size = 8192;
- int togo = (int) (raf.getLength() - info.offset);
- if (togo <= 0) {
- result.buf = new byte[]{};
- result.more = false;
- } else if (togo > 0 && togo <= size) {
- result.buf = new byte[togo];
- result.more = false;
- } else {
- result.buf = new byte[size];
- result.more = true;
- }
+ raf.seek(info.offset);
+ int size = 8192;
+ int togo = (int) (raf.getLength() - info.offset);
+ if(togo <= 0) {
+ result.buf = new byte[] {};
+ result.more = false;
+ } else if( togo > 0 && togo <= size) {
+ result.buf = new byte[togo];
+ result.more = false;
+ } else {
+ result.buf = new byte[size];
+ result.more = true;
+ }
- raf.read(result.buf);
+ raf.read(result.buf);
- return result;
- }
+ return result;
+ }
- /**
- * Removes content data for specified file from persistence.
- */
- public void removeContent(FileName name) throws Exception {
+ /** Removes content data for specified file from persistence.
+ */
+ public void removeContent(FileName name) throws Exception {
- // ves content je v podatkovni strukturi, ki bo odstranjena
- // skupaj z metainfom
- }
+ // ves content je v podatkovni strukturi, ki bo odstranjena
+ // skupaj z metainfom
+ }
- public void rename(FileName oldPath, FileName newPath) throws Exception {
- // v content delu ni ni� za postoriti na to temo
+ public void rename(FileName oldPath, FileName newPath) throws Exception {
+ // v content delu ni ni� za postoriti na to temo
}
More information about the jboss-cvs-commits
mailing list