use velocity template engine

This commit is contained in:
Peter Hormanns 2013-02-20 17:24:23 +01:00
parent 62a66e6859
commit 6208e0ec8c
30 changed files with 464 additions and 1081 deletions

View File

@ -28,5 +28,6 @@
<classpathentry kind="lib" path="lib/xmlrpc-common-3.1.3.jar"/>
<classpathentry kind="lib" path="lib/xmlrpc-server-3.1.3.jar"/>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/>
<classpathentry kind="lib" path="lib/velocity-1.7.jar"/>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -47,7 +47,7 @@
<fileset dir="build/cls"/>
<fileset dir="src">
<include name="**/*.properties"/>
<include name="**/*.jtpl"/>
<include name="**/*.vm"/>
</fileset>
<fileset dir="conf">
<include name="**/*.xml"/>
@ -77,7 +77,7 @@
<classes dir="build/cls" />
<classes dir="src">
<include name="**/*.properties"/>
<include name="**/*.jtpl"/>
<include name="**/*.vm"/>
</classes>
<classes dir="conf">
<include name="**/*.xml"/>

Binary file not shown.

View File

@ -1,26 +1,28 @@
package de.hsadmin.core.qserv;
import java.util.Iterator;
import java.util.Map;
import de.hsadmin.mods.dom.Domain;
import de.hsadmin.mods.pac.Hive;
public class CreateFileProcessor extends AbstractProcessor {
private static final long serialVersionUID = -2947609532975712444L;
private Processor compoundProcessor;
public CreateFileProcessor(String templateName, Map<String, String> templateValues, String targetPath, String owner, String group, String modeMask, boolean overwriteTarget) throws ProcessorException {
TemplateProcessor templateProcessor = new TemplateProcessor(templateName, templateValues, targetPath, overwriteTarget);
public CreateFileProcessor(String templateName, Map<String, Object> templateValues, Domain dom, String targetPath, String owner, String group, String modeMask, boolean overwriteTarget) throws ProcessorException {
VelocityProcessor templateProcessor = new VelocityProcessor(templateName, templateValues, dom, targetPath, overwriteTarget);
compoundProcessor = createCompound(targetPath, owner, group, modeMask, templateProcessor);
}
public CreateFileProcessor(String templateName, Map<String, String> templateValues, Iterator<Map<String, String>> iterateValues, String targetPath, String owner, String group, String modeMask, boolean overwriteTarget) throws ProcessorException {
TemplateProcessor templateProcessor = new TemplateProcessor(templateName, templateValues, iterateValues, targetPath, overwriteTarget);
public CreateFileProcessor(String templateName, Hive hive, String targetPath, String owner, String group, String modeMask, boolean overwriteTarget) throws ProcessorException {
VelocityProcessor templateProcessor = new VelocityProcessor(templateName, hive, targetPath, overwriteTarget);
compoundProcessor = createCompound(targetPath, owner, group, modeMask, templateProcessor);
}
private Processor createCompound(String targetPath, String owner, String group,
String modeMask, TemplateProcessor templateProcessor) {
String modeMask, Processor templateProcessor) {
ShellProcessor shellProcessor =
new ShellProcessor(
"chown " + owner + ":" + group + " " + targetPath + " && " +

View File

@ -1,56 +0,0 @@
package de.hsadmin.core.qserv;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Map;
import net.sf.jtpl.Template;
import de.hsadmin.core.model.HSAdminException;
import de.hsadmin.core.util.Config;
public class MailerProcessor extends AbstractProcessor {
private static final long serialVersionUID = 1L;
private String aTo;
private String aSubject;
private String aBody;
public MailerProcessor(String aTo, String aSubject, String aBody) {
this.aTo = aTo;
this.aSubject = aSubject;
this.aBody = aBody;
}
public MailerProcessor(String aTo, String aSubject, String templateName, Map<String, String> templateValues) throws ProcessorException {
this.aTo = aTo;
this.aSubject = aSubject;
try {
InputStream stream = MailerProcessor.class.getClassLoader().getResourceAsStream(templateName);
Template template = new Template(new InputStreamReader(stream));
for (String key : templateValues.keySet()) {
template.assign(key, templateValues.get(key));
}
template.parse("main");
this.aBody = template.out();
} catch (IllegalArgumentException e) {
throw new ProcessorException(e);
} catch (IOException e) {
throw new ProcessorException(e);
}
}
public Object process() throws ProcessorException {
try {
Config config = Config.getInstance();
String aFrom = config.getProperty("hsadmin.smtp.from", "unconfigured_from@example.com");
String aCC = config.getProperty("hsadmin.smtp.cc", "unconfigured_cc@example.com");
SmtpHelper.send(aFrom, aTo, aCC, aSubject, aBody);
return null;
} catch (HSAdminException e) {
throw new ProcessorException(e);
}
}
}

View File

@ -1,81 +0,0 @@
package de.hsadmin.core.qserv;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;
import net.sf.jtpl.Template;
public class TemplateProcessor extends AbstractProcessor {
private static final long serialVersionUID = 2L;
private String content = null;
private String targetPath = null;
private boolean overwriteTarget = false;
public TemplateProcessor(String templateName, Map<String, String> templateValues, String targetPath, boolean overwriteTarget) throws ProcessorException {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
try {
InputStream stream = TemplateProcessor.class.getClassLoader().getResourceAsStream(templateName);
Template template = new Template(new InputStreamReader(stream));
for (String key : templateValues.keySet()) {
template.assign(key, templateValues.get(key));
}
template.parse("main");
content = template.out();
} catch (IOException e) {
throw new ProcessorException(e);
}
}
public TemplateProcessor(String templateName, Map<String, String> mainValues, Iterator<Map<String, String>> iterateValues, String targetPath, boolean overwriteTarget) throws ProcessorException {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
try {
InputStream stream = TemplateProcessor.class.getClassLoader().getResourceAsStream(templateName);
Template template = new Template(new InputStreamReader(stream));
for (String key : mainValues.keySet()) {
template.assign(key, mainValues.get(key));
}
while (iterateValues.hasNext()) {
Map<String, String> iterationValues = iterateValues.next();
for (String key : iterationValues.keySet()) {
template.assign(key, iterationValues.get(key));
}
template.parse("main.iterate");
}
template.parse("main");
content = template.out();
} catch (IOException e) {
throw new ProcessorException(e);
}
}
@Override
public Object process() throws ProcessorException {
try {
File file = new File(targetPath);
if (file.exists() && !overwriteTarget) {
return null;
}
if (!file.exists() || file.canWrite()) {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.append(content);
writer.close();
} else {
throw new ProcessorException("could not write file " + targetPath);
}
return null;
} catch (IOException e) {
throw new ProcessorException(e);
}
}
}

View File

@ -0,0 +1,144 @@
package de.hsadmin.core.qserv;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.CharEncoding;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import de.hsadmin.mods.dom.Domain;
import de.hsadmin.mods.pac.BasePac;
import de.hsadmin.mods.pac.Hive;
import de.hsadmin.mods.pac.INetAddress;
import de.hsadmin.mods.pac.Pac;
public class VelocityProcessor extends AbstractProcessor {
private static final long serialVersionUID = 1L;
static {
Properties props = new Properties();
props.getProperty("resource.loader", "file");
props.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
Velocity.init(props);
}
private String content;
private String targetPath;
private boolean overwriteTarget;
public VelocityProcessor(String templateName, Hive hive, String targetPath, boolean overwriteTarget) {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
VelocityContext context = new VelocityContext();
context.put("hive", hive);
mergeTemplate(templateName, context);
}
public VelocityProcessor(String templateName, Pac pac, String targetPath, boolean overwriteTarget) {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
VelocityContext context = new VelocityContext();
context.put("pac", pac);
context.put("hive", pac.getHive());
mergeTemplate(templateName, context);
}
public VelocityProcessor(String templateName, Domain dom, String targetPath, boolean overwriteTarget) {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
VelocityContext context = new VelocityContext();
context.put("dom", dom);
Pac pac = dom.getUser().getPac();
context.put("pac", pac);
context.put("hive", pac.getHive());
mergeTemplate(templateName, context);
}
public VelocityProcessor(String templateName, Map<String, Object> templateVars, Domain dom, String targetPath, boolean overwriteTarget) {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
VelocityContext context = new VelocityContext();
context.put("dom", dom);
Pac pac = dom.getUser().getPac();
context.put("pac", pac);
context.put("hive", pac.getHive());
for (String key : templateVars.keySet()) {
context.put(key, templateVars.get(key));
}
mergeTemplate(templateName, context);
}
public VelocityProcessor(String templateName, HashMap<String, Object> templateVars,
String targetPath, boolean overwriteTarget) {
this.targetPath = targetPath;
this.overwriteTarget = overwriteTarget;
VelocityContext context = new VelocityContext();
for (String key : templateVars.keySet()) {
context.put(key, templateVars.get(key));
}
mergeTemplate(templateName, context);
}
private void mergeTemplate(String templateName, VelocityContext context) {
StringWriter writer = new StringWriter();
Velocity.mergeTemplate(templateName, CharEncoding.UTF_8, context, writer);
this.content = writer.toString();
}
@Override
public Object process() throws ProcessorException {
try {
File file = new File(targetPath);
if (file.exists() && !overwriteTarget) {
return "did not overwrite existing file " + targetPath;
}
if (!file.exists() || file.canWrite()) {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.append(content);
writer.close();
} else {
throw new ProcessorException("could not write file " + targetPath);
}
return "wrote file " + targetPath;
} catch (IOException e) {
throw new ProcessorException(e);
}
}
public static void main(String[] args) {
Hive h = new Hive("h01", new INetAddress("192.168.1.100"));
HashSet<Pac> pacsSet = new HashSet<Pac>();
h.setPacs(pacsSet);
Pac p1 = new Pac("pac01", null, new BasePac(), h);
pacsSet.add(p1);
Pac p2 = new Pac("pac02", null, new BasePac(), h);
pacsSet.add(p2);
p1.setCurINetAddr(new INetAddress("192.168.2.11"));
p2.setCurINetAddr(new INetAddress("192.168.2.12"));
VelocityProcessor procHosts = new VelocityProcessor("/de/hsadmin/mods/pac/hosts.vm", h, "/tmp/etc-hosts", true);
VelocityProcessor procVirtual = new VelocityProcessor("/de/hsadmin/mods/pac/httpd-virtual.vm", h, "/tmp/httpd-virtual.conf", true);
VelocityProcessor procInterfaces = new VelocityProcessor("/de/hsadmin/mods/pac/interfaces.vm", h, "/tmp/net-interfaces", true);
VelocityProcessor procProFtpd = new VelocityProcessor("/de/hsadmin/mods/pac/proftpd-conf.vm", h, "/tmp/proftpd.conf", true);
VelocityProcessor procSudoers = new VelocityProcessor("/de/hsadmin/mods/pac/sudoers.vm", h, "/tmp/sudoers", true);
try {
System.out.println(procHosts.process());
System.out.println(procVirtual.process());
System.out.println(procInterfaces.process());
System.out.println(procProFtpd.process());
System.out.println(procSudoers.process());
} catch (ProcessorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@ -16,12 +16,11 @@ import de.hsadmin.core.qserv.EntityProcessorFactory;
import de.hsadmin.core.qserv.Processor;
import de.hsadmin.core.qserv.ProcessorException;
import de.hsadmin.core.qserv.ShellProcessor;
import de.hsadmin.core.qserv.TemplateProcessor;
import de.hsadmin.core.qserv.VelocityProcessor;
import de.hsadmin.core.qserv.WaitingTasksProcessor;
import de.hsadmin.core.util.Config;
import de.hsadmin.mods.email.EMailAddress;
import de.hsadmin.mods.email.EMailAddressProcessorFactory;
import de.hsadmin.mods.pac.INetAddress;
import de.hsadmin.mods.pac.Pac;
import de.hsadmin.mods.user.UnixUser;
@ -40,39 +39,17 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
Domain dom = (Domain) entity;
UnixUser domUser = dom.getUser();
Pac pac = domUser.getPac();
String pacName = pac.getName();
String domName = dom.getName();
Map<String, String> templateVars = new HashMap<String, String>();
templateVars.put("SIO", Long.toString(System.currentTimeMillis()/1000L));
templateVars.put("PAC", pacName);
templateVars.put("HIVE", pac.getHiveName());
templateVars.put("DOM_HOSTNAME", domName);
templateVars.put("DOM_USERNAME", domUser.getName());
templateVars.put("PAC_HOSTNAME", pacName + ".hostsharing.net");
templateVars.put("DOM_IPNUMBER", getCurrentIPAddress(pac));
templateVars.put("DOM_IPNUMBEREX", getOldIPAddress(pac));
WaitingTasksProcessor mainProcessor = new WaitingTasksProcessor(createHiveDNSSetupProcessor(domName, templateVars));
mainProcessor.appendProcessor(hiveName, createHiveEMailSetupProcessor(em, domName), "Setup EMail");
String hiveInetAddr = pac.getHive().getInetAddr().getInetAddr();
WaitingTasksProcessor mainProcessor = new WaitingTasksProcessor(createHiveDNSSetupProcessor(dom));
mainProcessor.appendProcessor(hiveName, createHiveEMailSetupProcessor(em, dom), "Setup EMail");
Config config = Config.getInstance();
for (String queueName : config.getProperty("queues.dns").split(",")) {
mainProcessor.appendProcessor(queueName, createDNSServerSetupProcessor(domName, hiveInetAddr), queueName + ".hostsharing.net");
mainProcessor.appendProcessor(queueName, createDNSServerSetupProcessor(dom.getName(), pac.getHive().getInetAddr().getInetAddr()), queueName + ".hostsharing.net");
}
for (String queueName : config.getProperty("queues.mail").split(",")) {
mainProcessor.appendProcessor(queueName, createMailinSetupProcessor(em, dom, pac), queueName + ".hostsharing.net");
}
templateVars = new HashMap<String, String>();
templateVars.put("PAC", pacName);
templateVars.put("HIVE", pac.getHiveName());
templateVars.put("DOM_HOSTNAME", domName);
templateVars.put("DOM_USERNAME", domUser.getName());
templateVars.put("PAC_HOSTNAME", pacName + ".hostsharing.net");
templateVars.put("DOM_IPNUMBER", getCurrentIPAddress(pac));
templateVars.put("DOM_IPNUMBEREX", getOldIPAddress(pac));
templateVars.put("DOMAIN", domName);
templateVars.put("USER_NAME", domUser.getComment());
mainProcessor.appendProcessor(hiveName, createDomainDirectoriesProcessor(dom, templateVars), "Setup Domain Directories");
mainProcessor.appendProcessor(hiveName, createApacheVHostSetupProcessor(em, dom, templateVars), "Setup Apache VHost");
mainProcessor.appendProcessor(hiveName, createDomainDirectoriesProcessor(dom), "Setup Domain Directories");
mainProcessor.appendProcessor(hiveName, createApacheVHostSetupProcessor(em, dom), "Setup Apache VHost");
return mainProcessor;
}
@ -80,19 +57,7 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
Domain dom = (Domain) entity;
UnixUser domUser = dom.getUser();
Pac pac = domUser.getPac();
String pacName = pac.getName();
String domName = dom.getName();
Map<String, String> templateVars = new HashMap<String, String>();
templateVars.put("PAC", pacName);
templateVars.put("HIVE", pac.getHiveName());
templateVars.put("DOM_HOSTNAME", domName);
templateVars.put("DOM_USERNAME", domUser.getName());
templateVars.put("PAC_HOSTNAME", pacName + ".hostsharing.net");
templateVars.put("DOM_IPNUMBER", getCurrentIPAddress(pac));
templateVars.put("DOM_IPNUMBEREX", getOldIPAddress(pac));
templateVars.put("DOMAIN", domName);
templateVars.put("USER_NAME", domUser.getComment());
WaitingTasksProcessor processor = new WaitingTasksProcessor(createApacheVHostSetupProcessor(em, dom, templateVars));
WaitingTasksProcessor processor = new WaitingTasksProcessor(createApacheVHostSetupProcessor(em, dom));
Config config = Config.getInstance();
for (String queueName : config.getProperty("queues.mail").split(",")) {
processor.appendProcessor(queueName, createMailinSetupProcessor(em, dom, pac), queueName + ".hostsharing.net");
@ -117,11 +82,13 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
return mainProcessor;
}
private Processor createHiveDNSSetupProcessor(String domName, Map<String, String> templateVars)
throws ProcessorException {
private Processor createHiveDNSSetupProcessor(Domain dom) throws ProcessorException {
Map<String, Object> templateVars = new HashMap<String, Object>();
templateVars.put("sio", Long.toString(System.currentTimeMillis()/1000L));
String domName = dom.getName();
String zonefileTargetPath = "/etc/bind/pri." + domName;
Processor zonefileTemplateProcessor =
new TemplateProcessor("/de/hsadmin/mods/dom/zonefile.jtpl", templateVars, zonefileTargetPath, false);
new VelocityProcessor("/de/hsadmin/mods/dom/zonefile.vm", templateVars, dom, zonefileTargetPath, false);
Processor zonefileACLProcessor =
new ShellProcessor("chown root:bind " + zonefileTargetPath + " && chmod 644 " + zonefileTargetPath);
// TODO Use templates and regenerate the file.
@ -142,13 +109,13 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
" && invoke-rc.d bind9 reload");
}
private CompoundProcessor createHiveEMailSetupProcessor(EntityManager em, String domName) {
private CompoundProcessor createHiveEMailSetupProcessor(EntityManager em, Domain dom) {
EMailAddressProcessorFactory eMailAddressProcessorFactory = new EMailAddressProcessorFactory();
CompoundProcessor emailAdrProcessor = new CompoundProcessor();
Query query = em.createQuery(
"SELECT adr FROM " +
EMailAddress.class.getAnnotation(javax.persistence.Entity.class).name() + " adr " +
"WHERE adr.domain.name='" + domName + "'");
"WHERE adr.domain.name='" + dom.getName() + "'");
List<?> resultList = query.getResultList();
for (Object obj : resultList) {
EMailAddress eMailAddress = (EMailAddress) obj;
@ -202,7 +169,7 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
}
private Processor createPostgreyConfiguration(EntityManager em) throws ProcessorException {
ArrayList<Map<String, String>> domsMaps = new ArrayList<Map<String, String>>();
List<Domain> whitelistDoms = new ArrayList<Domain>();
Query query = em.createQuery("SELECT DISTINCT dom FROM Domains dom WHERE NOT EXISTS " +
"( SELECT postgreyDom FROM Domains postgreyDom " +
" WHERE postgreyDom.domainoptions.name = :option" +
@ -211,15 +178,14 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
List<?> result = query.getResultList();
for (Object dom : result) {
if (dom instanceof Domain) {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("DOM", ((Domain) dom).getName());
domsMaps.add(hashMap);
whitelistDoms.add((Domain) dom);
}
}
HashMap<String, Object> templateVars = new HashMap<String, Object>();
templateVars.put("whitelist", whitelistDoms);
return new CompoundProcessor(
new TemplateProcessor("/de/hsadmin/mods/dom/postgrey-whitelist-recipients.jtpl",
new HashMap<String, String>(),
domsMaps.iterator(), "/etc/postgrey/whitelist_recipients.tmp", true),
new VelocityProcessor("/de/hsadmin/mods/dom/postgrey-whitelist-recipients.vm",
templateVars, "/etc/postgrey/whitelist_recipients.tmp", true),
new ShellProcessor(" ( diff -q /etc/postgrey/whitelist_recipients.tmp /etc/postgrey/whitelist_recipients && rm /etc/postgrey/whitelist_recipients.tmp ) " +
"|| ( mv /etc/postgrey/whitelist_recipients.tmp /etc/postgrey/whitelist_recipients && invoke-rc.d postgrey reload )")
);
@ -236,7 +202,8 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
return mailQueueProcessor;
}
private CompoundProcessor createDomainDirectoriesProcessor(Domain dom, Map<String, String> templateVars) throws ProcessorException {
private CompoundProcessor createDomainDirectoriesProcessor(Domain dom) throws ProcessorException {
Map<String, Object> templateVars = new HashMap<String, Object>();
UnixUser domUser = dom.getUser();
String domName = dom.getName();
Pac pac = domUser.getPac();
@ -269,26 +236,26 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
"chown " + userName + ":" + pacName + " " + domainDir + "/" + subDir
));
}
templateVars.put("PROTOCOL", "http");
templateVars.put("protocol", "http");
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/htaccess.jtpl", templateVars, domainDir + "/htdocs/.htaccess", userName, pacName, "644", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/htaccess.vm", templateVars, dom, domainDir + "/htdocs/.htaccess", userName, pacName, "644", false)
);
templateVars.put("PROTOCOL", "https");
templateVars.put("protocol", "https");
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/htaccess.jtpl", templateVars, domainDir + "/htdocs-ssl/.htaccess", userName, pacName, "644", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/htaccess.vm", templateVars, dom, domainDir + "/htdocs-ssl/.htaccess", userName, pacName, "644", false)
);
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/index.html.jtpl", templateVars, domainDir + "/subs/www/index.html", userName, pacName, "644", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/index.html.vm", templateVars, dom, domainDir + "/subs/www/index.html", userName, pacName, "644", false)
);
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/index.html.jtpl", templateVars, domainDir + "/subs-ssl/www/index.html", userName, pacName, "644", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/index.html.vm", templateVars, dom, domainDir + "/subs-ssl/www/index.html", userName, pacName, "644", false)
);
if (dynamicWeb) {
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/test.cgi.jtpl", templateVars, domainDir + "/cgi/test.cgi", userName, pacName, "755", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/test.cgi.vm", templateVars, dom, domainDir + "/cgi/test.cgi", userName, pacName, "755", false)
);
domDirsProcessor.appendProcessor(
new CreateFileProcessor("/de/hsadmin/mods/dom/test.cgi.jtpl", templateVars, domainDir + "/cgi-ssl/test.cgi", userName, pacName, "755", false)
new CreateFileProcessor("/de/hsadmin/mods/dom/test.cgi.vm", templateVars, dom, domainDir + "/cgi-ssl/test.cgi", userName, pacName, "755", false)
);
domDirsProcessor.appendProcessor(
new CopyFileProcessor("/usr/local/src/phpstub/phpstub", domainDir + "/fastcgi/phpstub", userName, pacName, "755")
@ -305,57 +272,20 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
return domDirsProcessor;
}
private Processor createApacheVHostSetupProcessor(EntityManager em, Domain dom, Map<String, String> templateVars)
throws ProcessorException {
private Processor createApacheVHostSetupProcessor(EntityManager em, Domain dom) throws ProcessorException {
Map<String, Object> templateVars = new HashMap<String, Object>();
String domName = dom.getName();
int level = domName.split("\\.").length;
String linkPrefix = Integer.toString(100 - level);
String pac = dom.getUser().getPac().getName();
Query query = em.createQuery("SELECT d FROM Domains d WHERE d.domainoptions.name = :option AND d.name = :domname");
query.setParameter("domname", dom.getName());
// TODO: This code should be cleaned up after switching to the velocity template engine.
query.setParameter("option", "indexes");
if (query.getResultList().isEmpty()) {
templateVars.put("INDEXES", "-Indexes");
} else {
templateVars.put("INDEXES", "+Indexes");
}
// TODO: This code should be cleaned up after switching to the velocity template engine.
query.setParameter("option", "includes");
if (query.getResultList().isEmpty()) {
templateVars.put("INCLUDES", "-Includes");
} else {
templateVars.put("INCLUDES", "+IncludesNoExec");
}
// TODO: This code should be cleaned up after switching to the velocity template engine.
query.setParameter("option", "multiviews");
if (query.getResultList().isEmpty()) {
templateVars.put("MULTIVIEWS", "-MultiViews");
} else {
templateVars.put("MULTIVIEWS", "+MultiViews");
}
// TODO: This code should be cleaned up after switching to the velocity template engine.
query.setParameter("option", "htdocsfallback");
if (query.getResultList().isEmpty()) {
templateVars.put("NOHTDOCSFALLBACKHTTP",
" RewriteCond %{REQUEST_URI} !^/cgi-bin/\n" +
" RewriteCond %{REQUEST_URI} !^/fastcgi-bin/\n" +
" RewriteCond %{HTTP_HOST} ^(.+)\\.{DOM_HOSTNAME}\\.?(:80)?$ [novary]\n" +
" RewriteCond /home/doms/{DOM_HOSTNAME}/subs/${tolower:%1} !-d\n" +
" RewriteRule ^(.*) - [redirect=404,last]\n");
templateVars.put("NOHTDOCSFALLBACKHTTPS",
" RewriteCond %{REQUEST_URI} !^/cgi-bin/\n" +
" RewriteCond %{REQUEST_URI} !^/fastcgi-bin/\n" +
" RewriteCond %{HTTP_HOST} ^(.+)\\.{DOM_HOSTNAME}\\.?(:443)?$ [novary]\n" +
" RewriteCond /home/doms/{DOM_HOSTNAME}/subs-ssl/${tolower:%1} !-d\n" +
" RewriteRule ^(.*) - [redirect=404,last]\n");
} else {
templateVars.put("NOHTDOCSFALLBACKHTTP", "\n");
templateVars.put("NOHTDOCSFALLBACKHTTPS", "\n");
}
ifOption(templateVars, query, "indexes", "+Indexes", "-Indexes");
ifOption(templateVars, query, "includes", "+IncludesNoExec", "-Includes");
ifOption(templateVars, query, "multiviews", "+MultiViews", "-MultiViews");
ifOption(templateVars, query, "htdocsfallback", Boolean.TRUE, Boolean.FALSE);
Processor domSetupProcessor = new CompoundProcessor(
new CreateFileProcessor(selectVHostTemplate(dom), templateVars, "/etc/apache2/sites-available/" + domName + ".tmp", "root", "root", "644", true),
new CreateFileProcessor("/de/hsadmin/mods/dom/httpd-vhost.vm", templateVars, dom, "/etc/apache2/sites-available/" + domName + ".tmp", "root", "root", "644", true),
new ShellProcessor("ls /etc/apache2/pems/" + pac + ".pem >/dev/null 2>&1" +
" && sed -i '/SSLCertificate.*default/d' " + "/etc/apache2/sites-available/" + domName + ".tmp" +
" && (ls /etc/apache2/pems/" + pac + ".chain.pem >/dev/null 2>&1 || sed -i '/SSLCertificateChain.*" + pac + "/d' " + "/etc/apache2/sites-available/" + domName + ".tmp )" +
@ -370,6 +300,15 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
return domSetupProcessor;
}
private void ifOption(Map<String, Object> templateVars, Query query, String option, Object optIsTrue, Object optIsFalse) {
query.setParameter("option", option);
if (query.getResultList().isEmpty()) {
templateVars.put(option, optIsFalse);
} else {
templateVars.put(option, optIsTrue);
}
}
private Processor createApacheVHostDeleteProcessor(Domain dom) {
String domName = dom.getName();
int level = domName.split("\\.").length;
@ -383,30 +322,4 @@ public class DomainProcessorFactory implements EntityProcessorFactory {
return vhostDelProcessor;
}
private String selectVHostTemplate(Domain dom) {
String domName = dom.getName();
UnixUser user = dom.getUser();
Pac pac = user.getPac();
if (domName.equals(pac.getName() + ".hostsharing.net")) {
return "/de/hsadmin/mods/dom/httpd-vhost-dynamic.jtpl";
}
if (pac.isDynamicWeb() || dom.isPacDomain()) {
return "/de/hsadmin/mods/dom/httpd-vhost-dynamic.jtpl";
}
return "/de/hsadmin/mods/dom/httpd-vhost-static.jtpl";
}
private String getCurrentIPAddress(Pac pac) {
return pac.getCurINetAddr().getInetAddr();
}
private String getOldIPAddress(Pac pac) {
INetAddress oldINetAddr = pac.getOldINetAddr();
if (oldINetAddr != null) {
return oldINetAddr.getInetAddr();
} else {
return getCurrentIPAddress(pac);
}
}
}

View File

@ -1,2 +0,0 @@
<!-- BEGIN: main -->Redirect permanent / {PROTOCOL}://www.{DOMAIN}/
<!-- END: main -->

View File

@ -0,0 +1 @@
Redirect permanent / ${protocol}://www.{domain.name}/

View File

@ -1,106 +0,0 @@
<!-- BEGIN: main -->#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
<VirtualHost {DOM_IPNUMBER}:80 {DOM_IPNUMBEREX}:80>
ServerName {DOM_HOSTNAME}
ServerAlias *.{DOM_HOSTNAME}
ServerAdmin webmaster@{DOM_HOSTNAME}
SuexecUserGroup {DOM_USERNAME} {PAC}
DocumentRoot /home/doms/{DOM_HOSTNAME}/htdocs
Alias /cgi-bin/ /home/doms/{DOM_HOSTNAME}/cgi/
Alias /fastcgi-bin/ /home/doms/{DOM_HOSTNAME}/fastcgi/
<Directory />
Options -ExecCGI {INCLUDES} {INDEXES} {MULTIVIEWS} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/{DOM_HOSTNAME}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
<Location /cgi-bin/>
SetHandler cgi-script
Options +ExecCGI {INCLUDES} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
<Location /fastcgi-bin/>
SetHandler fcgid-script
Options +ExecCGI {INCLUDES} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.{DOM_HOSTNAME}\.?(:[0-9]+)?$ [novary]
RewriteCond /home/doms/{DOM_HOSTNAME}/subs/${tolower:%1} -d
RewriteRule ^(.*) /home/doms/{DOM_HOSTNAME}/subs/${tolower:%1}$1 [last]
{NOHTDOCSFALLBACKHTTP}
AddType application/x-httpd-php .php .php5 .php4 .php3
Action application/x-httpd-php /fastcgi-bin/phpstub
</VirtualHost>
<VirtualHost {DOM_IPNUMBER}:443 {DOM_IPNUMBEREX}:443>
ServerName {DOM_HOSTNAME}
ServerAlias *.{DOM_HOSTNAME}
ServerAdmin {DOM_USERNAME}@{HIVE}.hostsharing.net
SuexecUserGroup {DOM_USERNAME} {PAC}
SSLEngine On
SSLCertificateFile /etc/apache2/pems/default.pem
SSLCertificateChainFile /etc/apache2/pems/default.chain.pem
SSLCertificateFile /etc/apache2/pems/{PAC}.pem
SSLCertificateChainFile /etc/apache2/pems/{PAC}.chain.pem
DocumentRoot /home/doms/{DOM_HOSTNAME}/htdocs-ssl
Alias /cgi-bin/ /home/doms/{DOM_HOSTNAME}/cgi-ssl/
Alias /fastcgi-bin/ /home/doms/{DOM_HOSTNAME}/fastcgi-ssl/
<Directory />
SSLRequireSSL On
Options -ExecCGI {INCLUDES} {INDEXES} {MULTIVIEWS} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/{DOM_HOSTNAME}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
<Location /cgi-bin/>
SetHandler cgi-script
Options +ExecCGI {INCLUDES} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
<Location /fastcgi-bin/>
SetHandler fcgid-script
Options +ExecCGI {INCLUDES} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.{DOM_HOSTNAME}\.?(:[0-9]+)?$ [novary]
RewriteCond /home/doms/{DOM_HOSTNAME}/subs-ssl/${tolower:%1} -d
RewriteRule ^(.*) /home/doms/{DOM_HOSTNAME}/subs-ssl/${tolower:%1}$1 [last]
{NOHTDOCSFALLBACKHTTPS}
AddType application/x-httpd-php .php .php5 .php4 .php3
Action application/x-httpd-php /fastcgi-bin/phpstub
</VirtualHost>
<!-- END: main -->

View File

@ -1,90 +0,0 @@
<!-- BEGIN: main -->#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
<VirtualHost {DOM_IPNUMBER}:80 {DOM_IPNUMBEREX}:80>
ServerName {DOM_HOSTNAME}
ServerAlias *.{DOM_HOSTNAME}
ServerAdmin webmaster@{DOM_HOSTNAME}
SuexecUserGroup {DOM_USERNAME} {PAC}
DocumentRoot /home/doms/{DOM_HOSTNAME}/htdocs
<Directory />
Options -ExecCGI {INCLUDES} {INDEXES} {MULTIVIEWS} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/{DOM_HOSTNAME}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
<Location /cgi-bin/>
Redirect 501 /
</Location>
<Location /fastcgi-bin/>
Redirect 501 /
</Location>
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.{DOM_HOSTNAME}\.?(:[0-9]+)?$ [novary]
RewriteCond /home/doms/{DOM_HOSTNAME}/subs/${tolower:%1} -d
RewriteRule ^(.*) /home/doms/{DOM_HOSTNAME}/subs/${tolower:%1}$1 [last]
{NOHTDOCSFALLBACKHTTP}
</VirtualHost>
<VirtualHost {DOM_IPNUMBER}:443 {DOM_IPNUMBEREX}:443>
ServerName {DOM_HOSTNAME}
ServerAlias *.{DOM_HOSTNAME}
ServerAdmin {DOM_USERNAME}@{HIVE}.hostsharing.net
SuexecUserGroup {DOM_USERNAME} {PAC}
SSLEngine On
SSLCertificateFile /etc/apache2/pems/default.pem
SSLCertificateChainFile /etc/apache2/pems/default.chain.pem
SSLCertificateFile /etc/apache2/pems/{PAC}.pem
SSLCertificateChainFile /etc/apache2/pems/{PAC}.chain.pem
DocumentRoot /home/doms/{DOM_HOSTNAME}/htdocs-ssl
<Directory />
SSLRequireSSL On
Options -ExecCGI {INCLUDES} {INDEXES} {MULTIVIEWS} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/{DOM_HOSTNAME}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
<Location /cgi-bin/>
Redirect 501 /
</Location>
<Location /fastcgi-bin/>
Redirect 501 /
</Location>
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.{DOM_HOSTNAME}\.?(:[0-9]+)?$ [novary]
RewriteCond /home/doms/{DOM_HOSTNAME}/subs-ssl/${tolower:%1} -d
RewriteRule ^(.*) /home/doms/{DOM_HOSTNAME}/subs-ssl/${tolower:%1}$1 [last]
{NOHTDOCSFALLBACKHTTPS}
</VirtualHost>
<!-- END: main -->

View File

@ -0,0 +1,145 @@
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
<VirtualHost ${pac.curINetAddr.inetAddr}:80 ${pac.oldINetAddr.inetAddr}:80>
ServerName ${dom.name}
ServerAlias *.${dom.name}
ServerAdmin webmaster@${dom.name}
SuexecUserGroup ${dom.user.name} ${pac.name}
DocumentRoot /home/doms/${dom.name}/htdocs
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
Alias /cgi-bin/ /home/doms/${dom.name}/cgi/
Alias /fastcgi-bin/ /home/doms/${dom.name}/fastcgi/
#end
<Directory />
Options -ExecCGI ${includes} ${indexes} ${multiviews} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/${dom.name}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
<Location /cgi-bin/>
SetHandler cgi-script
Options +ExecCGI ${includes} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
<Location /fastcgi-bin/>
SetHandler fcgid-script
Options +ExecCGI ${includes} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
#else
<Location /cgi-bin/>
Redirect 501 /
</Location>
<Location /fastcgi-bin/>
Redirect 501 /
</Location>
#end
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.${dom.name}\.?(:[0-9]+)?\$ [novary]
RewriteCond /home/doms/${dom.name}/subs/\$\{tolower:%1\} -d
RewriteRule ^(.*) /home/doms/${dom.name}/subs/\$\{tolower:%1\}\$1 [last]
#if( !${htdocsfallback} )
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.{DOM_HOSTNAME}\.?(:80)?\$ [novary]
RewriteCond /home/doms/${dom.name}/subs/\$\{tolower:%1\} !-d
RewriteRule ^(.*) - [redirect=404,last]
#end
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
AddType application/x-httpd-php .php .php5 .php4 .php3
Action application/x-httpd-php /fastcgi-bin/phpstub
#end
</VirtualHost>
<VirtualHost ${pac.curINetAddr.inetAddr}:443 ${pac.oldINetAddr.inetAddr}:443>
ServerName ${dom.name}
ServerAlias *.${dom.name}
ServerAdmin ${dom.user.name}@${dom.name}
SuexecUserGroup ${dom.user.name} ${pac.name}
SSLEngine On
SSLCertificateFile /etc/apache2/pems/default.pem
SSLCertificateChainFile /etc/apache2/pems/default.chain.pem
SSLCertificateFile /etc/apache2/pems/${pac.name}.pem
SSLCertificateChainFile /etc/apache2/pems/${pac.name}.chain.pem
DocumentRoot /home/doms/${dom.name}/htdocs-ssl
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
Alias /cgi-bin/ /home/doms/${dom.name}/cgi-ssl/
Alias /fastcgi-bin/ /home/doms/${dom.name}/fastcgi-ssl/
#end
<Directory />
SSLRequireSSL On
Options -ExecCGI ${includes} ${indexes} ${multiviews} +SymLinksIfOwnerMatch
</Directory>
<Directory /home/doms/${dom.name}/>
AllowOverride AuthConfig FileInfo Indexes Limit
</Directory>
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
<Location /cgi-bin/>
SetHandler cgi-script
Options +ExecCGI ${includes} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
<Location /fastcgi-bin/>
SetHandler fcgid-script
Options +ExecCGI ${includes} -Indexes -MultiViews +SymLinksIfOwnerMatch
</Location>
#else
<Location /cgi-bin/>
Redirect 501 /
</Location>
<Location /fastcgi-bin/>
Redirect 501 /
</Location>
#end
RewriteEngine On
RewriteOptions Inherit
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.${dom.name}\.?(:[0-9]+)?\$ [novary]
RewriteCond /home/doms/${dom.name}/subs-ssl/\$\{tolower:%1\} -d
RewriteRule ^(.*) /home/doms/${dom.name}/subs-ssl/\$\{tolower:%1\}\$1 [last]
#if( !${htdocsfallback} )
RewriteCond %{REQUEST_URI} !^/cgi-bin/
RewriteCond %{REQUEST_URI} !^/fastcgi-bin/
RewriteCond %{HTTP_HOST} ^(.+)\.${dom.name}\.?(:443)?\$ [novary]
RewriteCond /home/doms/${dom.name}/subs-ssl/\$\{tolower:%1\} !-d
RewriteRule ^(.*) - [redirect=404,last]
#end
#if( ${pac.dynamicWeb} || ${dom.pacDomain} )
AddType application/x-httpd-php .php .php5 .php4 .php3
Action application/x-httpd-php /fastcgi-bin/phpstub
#end
</VirtualHost>

View File

@ -1,22 +1,21 @@
<!-- BEGIN: main --><html>
<html>
<head>
<title>Willkommen bei {DOMAIN}</title>
<title>Willkommen bei ${dom.name}</title>
</head>
<body bgcolor="orange">
<h1>Willkommen bei {DOMAIN}</h1>
<h1>Willkommen bei ${dom.name}</h1>
<p>Diese neue Website wurde gerade bei der
<a href="http://www.hostsharing.net">Hostsharing eG</a>
f&uuml;r {USER_NAME} eingerichtet.</p>
f&uuml;r ${dom.user.comment} eingerichtet.</p>
<p>Der Inhaber der Domain ist bereits per Email unter
<a href="mailto:webmaster(at){DOMAIN}">webmaster(at){DOMAIN}</a>
<a href="mailto:webmaster(at)${dom.name}">webmaster(at)${dom.name}</a>
zu erreichen.</p>
</body>
</html>
<!-- END: main -->

View File

@ -1,4 +1,4 @@
<!-- BEGIN: main -->#
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
@ -8,6 +8,6 @@ postmaster@
####################################################
<!-- BEGIN: iterate -->{DOM}
<!-- END: iterate -->
<!-- END: main -->
#foreach( $whitelistdom in ${whitelist} )
${whitelistdom.name}
#end

View File

@ -1,5 +1,4 @@
<!-- BEGIN: main -->#!/bin/sh
#!/bin/sh
echo Content-type: text/plain
echo
echo Hello, world
<!-- END: main -->

View File

@ -1,25 +0,0 @@
<!-- BEGIN: main -->$TTL 6H
{DOM_HOSTNAME}. IN SOA dns.hostsharing.net. hostmaster.hostsharing.net. (
{SIO} ; serial secs since Jan 1 1970
6H ; refresh (>=10000)
1H ; retry (>=1800)
1W ; expire
1H ; minimum
)
{DOM_HOSTNAME}. IN NS dns1.hostsharing.net.
{DOM_HOSTNAME}. IN NS dns2.hostsharing.net.
{DOM_HOSTNAME}. IN NS dns3.hostsharing.net.
{DOM_HOSTNAME}. IN MX 30 mailin1.hostsharing.net.
{DOM_HOSTNAME}. IN MX 30 mailin2.hostsharing.net.
{DOM_HOSTNAME}. IN MX 30 mailin3.hostsharing.net.
{DOM_HOSTNAME}. IN A {DOM_IPNUMBER}
*.{DOM_HOSTNAME}. IN MX 30 mailin1.hostsharing.net.
*.{DOM_HOSTNAME}. IN MX 30 mailin2.hostsharing.net.
*.{DOM_HOSTNAME}. IN MX 30 mailin3.hostsharing.net.
*.{DOM_HOSTNAME}. IN A {DOM_IPNUMBER}
<!-- END: main -->

View File

@ -0,0 +1,24 @@
$TTL 6H
${dom.name}. IN SOA dns.hostsharing.net. hostmaster.hostsharing.net. (
${sio} ; serial secs since Jan 1 1970
6H ; refresh (>=10000)
1H ; retry (>=1800)
1W ; expire
1H ; minimum
)
${dom.name}. IN NS dns1.hostsharing.net.
${dom.name}. IN NS dns2.hostsharing.net.
${dom.name}. IN NS dns3.hostsharing.net.
${dom.name}. IN MX 30 mailin1.hostsharing.net.
${dom.name}. IN MX 30 mailin2.hostsharing.net.
${dom.name}. IN MX 30 mailin3.hostsharing.net.
${dom.name}. IN A ${pac.curINetAddr.inetAddr}
*.${dom.name}. IN MX 30 mailin1.hostsharing.net.
*.${dom.name}. IN MX 30 mailin2.hostsharing.net.
*.${dom.name}. IN MX 30 mailin3.hostsharing.net.
*.${dom.name}. IN A ${pac.curINetAddr.inetAddr}

View File

@ -26,6 +26,7 @@ public class BasePac implements Serializable {
private static final long serialVersionUID = 1491121619195513435L;
public BasePac() {
components = new HashSet<Component>();
}
public BasePac(String name, String desc, int sortPos) {

View File

@ -21,6 +21,7 @@ import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.util.Config;
import de.hsadmin.mods.user.UnixUser;
@Entity(name = "Hives")
@ -130,4 +131,9 @@ public class Hive extends AbstractEntity implements Serializable {
public UnixUser owningUser(EntityManager em) {
return null; // TODO: kinda somebody like root needed
}
public String getDefaultGateway() {
String hiveIP = getInetAddr().getInetAddr();
return Config.getInstance().getProperty("hsadmin.default_gateway", hiveIP.substring(0, hiveIP.lastIndexOf('.')) + ".1");
}
}

View File

@ -1,27 +1,22 @@
package de.hsadmin.mods.pac;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.EntityManager;
import de.hsadmin.core.model.AbstractEntity;
import de.hsadmin.core.qserv.CompoundProcessor;
import de.hsadmin.core.qserv.CreateFileProcessor;
import de.hsadmin.core.qserv.EntityProcessorFactory;
//import de.hsadmin.core.qserv.MailerProcessor;
import de.hsadmin.core.qserv.Processor;
import de.hsadmin.core.qserv.ProcessorException;
import de.hsadmin.core.qserv.ShellProcessor;
import de.hsadmin.core.qserv.TemplateProcessor;
import de.hsadmin.core.qserv.CreateFileProcessor;
import de.hsadmin.core.qserv.VelocityProcessor;
import de.hsadmin.core.qserv.WaitingTasksProcessor;
import de.hsadmin.core.util.Config;
import de.hsadmin.core.util.PasswordTool;
import de.hsadmin.mods.user.UnixUser;
public class PacProcessorFactory implements EntityProcessorFactory {
@Override
@ -32,19 +27,17 @@ public class PacProcessorFactory implements EntityProcessorFactory {
Hive hive = pac.getHive();
UnixUser unixUser = getPacAdminUser(pac);
String password = PasswordTool.generatePassword();
Map<String, String> hiveValues = fillHiveValues(hive);
List<Map<String, String>> pacValuesList = fillPacValuesList(hive, null);
Processor priProcessor = new CompoundProcessor(
createAddUserProc(pacName, unixUser, password),
createSetQuotaProc(pac),
createEtcHostsProc(hiveValues, pacValuesList),
createNetworkInterfacesProc(hiveValues, pacValuesList),
createEtcHostsProc(hive),
createNetworkInterfacesProc(hive),
createIPTablesProc(),
createSudouersProc(hiveValues, pacValuesList),
createProftpdConfProc(hiveValues, pacValuesList),
createSudouersProc(hive),
createProftpdConfProc(hive),
createMakePacDirectoryStructure(unixUser),
createIfUp(pacName),
createHttpdVirtualProc(pacName, pacValuesList),
createHttpdVirtualProc(hive),
createAccountingRulesProc());
WaitingTasksProcessor secProcessor = new WaitingTasksProcessor(priProcessor);
return secProcessor;
@ -54,11 +47,9 @@ public class PacProcessorFactory implements EntityProcessorFactory {
return new ShellProcessor("mk-iptables-rules Accounting");
}
private Processor createHttpdVirtualProc(
String pacName, List<Map<String, String>> pacValuesList) throws ProcessorException {
private Processor createHttpdVirtualProc(Hive hive) throws ProcessorException {
Processor domSetupProcessor = new CompoundProcessor(
new CreateFileProcessor("/de/hsadmin/mods/pac/httpd-virtual.jtpl",
new HashMap<String, String>(), pacValuesList.iterator(),
new CreateFileProcessor("/de/hsadmin/mods/pac/httpd-virtual.vm", hive,
"/etc/apache2/virtual.conf.tmp", "root", "root", "644", true),
new ShellProcessor("for PEM in $( cat /etc/apache2/virtual.conf.tmp | grep SSLCertificateFile | cut -c24- ); do " +
"ls $PEM >/dev/null 2>&1 || ( " +
@ -90,46 +81,36 @@ public class PacProcessorFactory implements EntityProcessorFactory {
public <T extends AbstractEntity> Processor createDeleteProcessor(EntityManager em, T entity) throws ProcessorException {
Pac pac = (Pac) entity;
Hive hive = pac.getHive();
Map<String, String> hiveValues = fillHiveValues(hive);
List<Map<String, String>> pacValuesList = fillPacValuesList(hive, pac);
WaitingTasksProcessor waitingProcessor = new WaitingTasksProcessor(new CompoundProcessor(
createIfDown(pac.getName()),
createEtcHostsProc(hiveValues, pacValuesList),
createNetworkInterfacesProc(hiveValues, pacValuesList),
createSudouersProc(hiveValues, pacValuesList),
createProftpdConfProc(hiveValues, pacValuesList),
createHttpdVirtualProc(pac.getName(), pacValuesList),
createEtcHostsProc(hive),
createNetworkInterfacesProc(hive),
createSudouersProc(hive),
createProftpdConfProc(hive),
createHttpdVirtualProc(hive),
createAccountingRulesProc()));
waitingProcessor.appendProcessor(pac.getHiveName(), createDelUserProc(pac.getName()), "remove packet");
return waitingProcessor;
}
private Processor createEtcHostsProc(
Map<String, String> hiveValues,
List<Map<String, String>> pacValuesList) throws ProcessorException {
return new TemplateProcessor("/de/hsadmin/mods/pac/hosts.jtpl", hiveValues, pacValuesList.iterator(), "/etc/hosts", true);
private Processor createEtcHostsProc(Hive hive) throws ProcessorException {
return new VelocityProcessor("/de/hsadmin/mods/pac/hosts.vm", hive, "/etc/hosts", true);
}
private Processor createNetworkInterfacesProc(
Map<String, String> hiveValues,
List<Map<String, String>> pacValuesList) throws ProcessorException {
return new TemplateProcessor("/de/hsadmin/mods/pac/interfaces.jtpl", hiveValues, pacValuesList.iterator(), "/etc/network/interfaces", true);
private Processor createNetworkInterfacesProc(Hive hive) throws ProcessorException {
return new VelocityProcessor("/de/hsadmin/mods/pac/interfaces.vm", hive, "/etc/network/interfaces", true);
}
private Processor createIPTablesProc() {
return new ShellProcessor("mk-iptables-rules Accounting");
}
private Processor createSudouersProc(
Map<String, String> hiveValues,
List<Map<String, String>> pacValuesList) throws ProcessorException {
return new TemplateProcessor("/de/hsadmin/mods/pac/sudoers.jtpl", hiveValues, pacValuesList.iterator(), "/etc/sudoers", true);
private Processor createSudouersProc(Hive hive) throws ProcessorException {
return new VelocityProcessor("/de/hsadmin/mods/pac/sudoers.vm", hive, "/etc/sudoers", true);
}
private Processor createProftpdConfProc(
Map<String, String> hiveValues,
List<Map<String, String>> pacValuesList) throws ProcessorException {
return new TemplateProcessor("/de/hsadmin/mods/pac/proftpd-conf.jtpl", hiveValues, pacValuesList.iterator(), "/etc/proftpd/proftpd.conf", true);
private Processor createProftpdConfProc(Hive hive) throws ProcessorException {
return new VelocityProcessor("/de/hsadmin/mods/pac/proftpd-conf.vm", hive, "/etc/proftpd/proftpd.conf", true);
}
private Processor createAddUserProc(String pacName, UnixUser unixUser, String password) {
@ -203,31 +184,4 @@ public class PacProcessorFactory implements EntityProcessorFactory {
return unixUser;
}
private Map<String, String> fillHiveValues(Hive hive) {
Map<String, String> hiveValues = new HashMap<String, String>();
hiveValues.put("HIVE", hive.getName());
String hiveIP = hive.getInetAddr().getInetAddr();
hiveValues.put("HIVE_IP", hiveIP);
String defaultGateway =
Config.getInstance().getProperty("hsadmin.default_gateway", hiveIP.substring(0, hiveIP.lastIndexOf('.')) + ".1");
defaultGateway =
Config.getInstance().getProperty("hsadmin." + hive.getName() + ".default_gateway", defaultGateway);
hiveValues.put("HIVE_GATEWAY", defaultGateway);
return hiveValues;
}
private List<Map<String, String>> fillPacValuesList(Hive hive, Pac pacToSkip) {
List<Map<String, String>> pacValuesList = new ArrayList<Map<String, String>>();
Set<Pac> pacsSet = hive.getPacs();
for (Pac p : pacsSet) {
HashMap<String, String> pacValues = new HashMap<String, String>();
pacValues.put("PAC", p.getName());
pacValues.put("PAC_IP", p.getCurINetAddr().getInetAddr());
if (pacToSkip == null || !pacToSkip.getName().equals(p.getName())) {
pacValuesList.add(pacValues);
}
}
return pacValuesList;
}
}

View File

@ -1,4 +1,4 @@
<!-- BEGIN: main -->#
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
@ -12,8 +12,8 @@ ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
{HIVE_IP} {HIVE}.hostsharing.net {HIVE} localhive
${hive.inetAddr.inetAddr} ${hive.name}.hostsharing.net ${hive.name} localhive
<!-- BEGIN: iterate -->{PAC_IP} {PAC}.hostsharing.net {PAC}
<!-- END: iterate -->
<!-- END: main -->
#foreach( $pac in ${hive.pacs} )
${pac.curINetAddr.inetAddr} ${pac.name}.hostsharing.net ${pac.name}
#end

View File

@ -1,12 +0,0 @@
<!-- BEGIN: main -->#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
<!-- BEGIN: iterate -->
NameVirtualHost {PAC_IP}:80
NameVirtualHost {PAC_IP}:443
<!-- END: iterate -->
<!-- END: main -->

View File

@ -0,0 +1,11 @@
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
#foreach( $pac in ${hive.pacs} )
# ${pac.name}
NameVirtualHost ${pac.curINetAddr.inetAddr}:80
NameVirtualHost ${pac.curINetAddr.inetAddr}:443
#end

View File

@ -1,22 +0,0 @@
<!-- BEGIN: main -->#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address {HIVE_IP}
netmask 255.255.255.0
gateway {HIVE_GATEWAY}
<!-- BEGIN: iterate -->auto eth0:{PAC}
iface eth0:{PAC} inet static
address {PAC_IP}
netmask 255.255.255.0
<!-- END: iterate -->
<!-- END: main -->

View File

@ -0,0 +1,22 @@
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address ${hive.inetAddr.inetAddr}
netmask 255.255.255.0
gateway ${hive.defaultGateway}
#foreach( $pac in ${hive.pacs} )
iface eth0:${pac.name} inet static
address ${pac.curINetAddr.inetAddr}
netmask 255.255.255.0
#end

View File

@ -1,4 +1,4 @@
<!-- BEGIN: main -->#
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
@ -58,11 +58,10 @@ PassivePorts 60000 65534
AllowOverwrite on
</Directory>
<!-- BEGIN: iterate -->
####################################################
#foreach( $pac in ${hive.pacs} )
<VirtualHost {PAC_IP}>
DefaultRoot ~ {PAC}
<VirtualHost ${pac.curINetAddr.inetAddr}>
DefaultRoot ~ ${pac.name}
ServerName "Hostsharing eG"
AllowOverwrite on
AllowForeignAddress on
@ -70,14 +69,14 @@ PassivePorts 60000 65534
<Limit LOGIN>
Order allow,deny
AllowGroup {PAC}
AllowGroup ${pac.name}
DenyAll
</Limit>
<Anonymous /home/pacs/{PAC}/ftp>
User {PAC}
Group {PAC}
UserAlias anonymous {PAC}
UserAlias ftp {PAC}
<Anonymous /home/pacs/${pac.name}/ftp>
User ${pac.name}
Group ${pac.name}
UserAlias anonymous ${pac.name}
UserAlias ftp ${pac.name}
DirFakeUser on ftp
DirFakeGroup on ftp
DirFakeMode 000
@ -87,6 +86,5 @@ PassivePorts 60000 65534
</Limit>
</Anonymous>
</VirtualHost>
<!-- END: iterate -->
<!-- END: main -->
#end

View File

@ -1,4 +1,4 @@
<!-- BEGIN: main -->#
#
# This file is managed by HSAdmin.
# Do not edit manually. Changes will be overwritten.
#
@ -22,6 +22,6 @@ root ALL=(ALL) ALL
####################################################
<!-- BEGIN: iterate -->{PAC} ALL = (%{PAC}) NOPASSWD: ALL
<!-- END: iterate -->
<!-- END: main -->
#foreach( $pac in ${hive.pacs} )
${pac.name} ALL = (%${pac.name}) NOPASSWD: ALL
#end

View File

@ -1,307 +0,0 @@
/*
Copyright 2009 jtpl.sourceforge.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.sf.jtpl;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <b>Jtpl: a very simple template engine for Java</b><br>
* Contact: <a href="mailto:emmanuel.alliel@gmail.com">emmanuel.alliel@gmail.com</a><br>
* Web: <a href="http://jtpl.sourceforge.net">http://jtpl.sourceforge.net</a><br>
*
* @version $LastChangedRevision: 51 $
* @author Emmanuel ALLIEL
* @author Staffan Olsson
*
* <p>
* Template syntax:<br>
* &nbsp;&nbsp;&nbsp;Variables:<br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>{VARIABLE_NAME}</code><br>
* &nbsp;&nbsp;&nbsp;Blocks:<br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>&lt;!-- BEGIN: BlockName --&gt;</code><br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>&lt;!-- BEGIN: SubBlockName --&gt;</code><br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>&lt;!-- END: SubBlockName --&gt;</code><br>
* &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<code>&lt;!-- END: BlockName --&gt;</code><br>
* <p>
* License: Apache 2.0<br>
*/
public class Jtpl implements Serializable
{
private static final long serialVersionUID = -7175035307912229580L;
private HashMap<String, String> blocks = new HashMap<String, String>();
private HashMap<String, String> parsedBlocks = new HashMap<String, String>();
private HashMap<String, String> subBlocks = new HashMap<String, String>();
private HashMap<String, String> vars = new HashMap<String, String>();
// flag for backwards compatibility, will probably be reomved in future releases
private boolean failSilently = false;
private boolean implicitMain = false;
/**
* Constructs a Jtpl object and reads the template from a file.
* For backwards compatibility this constructor enables 'failSilently'.
* @param fileName the <code>file name</code> of the template, exemple: "java/folder/index.tpl"
* @throws IOException when an i/o error occurs while reading the template.
*/
public Jtpl(String fileName) throws IOException
{
this(new File(fileName));
// this is the old constructor so it enables the old (pre-1.3) behavior on errors
this.failSilently = true;
}
/**
* Constructs a Jtpl object and reads the template from a file.
* @param file readable file containing template source
* @throws IOException when an i/o error occurs while reading the template.
*/
public Jtpl(File file) throws IOException
{
FileReader fr = new FileReader(file);
String fileText = readFile(fr);
makeTree(fileText);
}
/**
* Constructs a Jtpl object and reads the template from arbitrary input source.
* @param template the template source
* @throws IOException when an i/o error occurs while reading the template.
*/
public Jtpl(Reader template) throws IOException
{
String fileText = readFile(template);
makeTree(fileText);
}
/**
* Assign a template variable.
* For variables that are used in blocks, the variable value
* must be set before <code>parse</code> is called.
* @param varName the name of the variable to be set.
* @param varData the new value of the variable.
*/
public void assign(String varName, String varData)
{
vars.put(varName, varData);
}
/**
* Generates the HTML page and return it into a String.
*/
public String out()
{
if (this.implicitMain) {
this.parse("main");
}
Object main = parsedBlocks.get("main");
if (main == null) {
throw new IllegalStateException("'main' block not parsed");
}
return(main.toString());
}
/**
* Parse a template block.
* If the block contains variables, these variables must be set
* before the block is added.
* If the block contains subblocks, the subblocks
* must be parsed before this block.
* @param blockName the name of the block to be parsed.
* @throws IllegalArgumentException if the block name is not found (and failSiletly==false)
*/
public void parse(String blockName) throws IllegalArgumentException
{
String copy = "";
if (implicitMain && !"main".equals(blockName) && !blockName.startsWith("main.")) {
blockName = "main." + blockName;
}
try {
copy = blocks.get(blockName).toString();
} catch (NullPointerException e) {
if (!this.failSilently) throw new IllegalArgumentException(
"Block '" + blockName + "' not found." +
" Matches " + locateBlock(blockName));
}
Pattern pattern = Pattern.compile("\\{([\\w\\.]+)\\}");
Matcher matcher = pattern.matcher(copy);
pattern = Pattern.compile("_BLOCK_\\.(.+)");
for (Matcher matcher2; matcher.find();)
{
String match = matcher.group(1);
matcher2 = pattern.matcher(match);
if (matcher2.find())
{
if (parsedBlocks.containsKey(matcher2.group(1)))
{
copy = copy.replaceFirst("\\{"+match+"\\}", escape(
parsedBlocks.get(matcher2.group(1)).toString()));
}
else
{
copy = copy.replaceFirst("\\{"+match+"\\}", "");
}
}
else
{
if (vars.containsKey(match))
{
copy = copy.replaceFirst("\\{"+match+"\\}", escape(
vars.get(match).toString()));
}
else
{
// Leave unchanged because it might be wanted in output.
// Can always be removed by assigning empty value.
//copy = copy.replaceFirst("\\{"+match+"\\}", "");
}
}
}
if (parsedBlocks.containsKey(blockName))
{
parsedBlocks.put(blockName, parsedBlocks.get(blockName) + copy);
}
else
{
parsedBlocks.put(blockName, copy);
}
if (subBlocks.containsKey(blockName))
{
parsedBlocks.put(subBlocks.get(blockName), "");
}
}
/**
* Template parsing uses regex replace to insert result text,
* which means that special characters in replacement string must be escaped.
* @param replacement The text that should appear in output.
* @return Text escaped so that it works as String.replaceFirst replacement.
*/
protected String escape(String replacement) {
return replacement.replace("\\", "\\\\").replace("$", "\\$");
}
/**
* Lists the blocks that end with the given blockName.
* @param blockName The name as used in parse
* @return Blocks where blockName is the child
* (the Set's toString lists the full names)
*/
protected Set<Object> locateBlock(final String blockName) {
Set<Object> matches = new java.util.HashSet<Object>();
for (Iterator<String> it = blocks.keySet().iterator(); it.hasNext(); ) {
Object b = it.next();
if (b.toString().endsWith('.' + blockName)) matches.add(b);
}
return matches;
}
private String readFile(Reader fr) throws IOException
{
StringBuffer content = new StringBuffer();
for (int c; (c = fr.read()) != -1; content.append((char)c));
fr.close();
return content.toString();
}
private void makeTree(String fileText)
{
// BEGIN: implicit main
if (!Pattern.compile(".*<!--\\s*BEGIN\\s*:\\s*main\\s*-->.*", Pattern.DOTALL)
.matcher(fileText).matches()) {
this.implicitMain = true; // affects parse(block) and out()
fileText = "<!-- BEGIN: main -->" + fileText + "<!-- END: main -->";
}
// END: implicit main
Pattern pattern = Pattern.compile("<!--\\s*(BEGIN|END)\\s*:\\s*(\\w+)\\s*-->(.*?)(?=(?:<!--\\s*(?:BEGIN|END)\\s*:\\s*\\w+\\s*-->)|(?:\\s*$))", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(fileText);
ArrayList<String> blockNames = new ArrayList<String>();
String parentName = "";
int lastlength = 0; // used in newline trimming to see if one block immediately follows the previous
while (matcher.find())
{
// BEGIN: newline trimming
String after = matcher.group(3); // contents after tag
if (lastlength == 0 || fileText.charAt(matcher.start() - 1) == '\n') {
after = after.replaceFirst("^\\r?\\n", "");
}
lastlength = after.length();
// END: newline trimming
if (matcher.group(1).toUpperCase().equals("BEGIN"))
{
parentName = implode(blockNames);
blockNames.add(matcher.group(2));
String currentBlockName = implode(blockNames);
if (blocks.containsKey(currentBlockName))
{
blocks.put(currentBlockName, blocks.get(currentBlockName) + after);
}
else
{
blocks.put(currentBlockName, after);
}
if (blocks.containsKey(parentName))
{
blocks.put(parentName, blocks.get(parentName) + "{_BLOCK_." + currentBlockName + "}");
}
else
{
blocks.put(parentName, "{_BLOCK_." + currentBlockName + "}");
}
subBlocks.put(parentName, currentBlockName);
subBlocks.put(currentBlockName, "");
}
else if (matcher.group(1).toUpperCase().equals("END"))
{
blockNames.remove(blockNames.size()-1);
parentName = implode(blockNames);
if (blocks.containsKey(parentName))
{
blocks.put(parentName, blocks.get(parentName) + after);
}
else
{
blocks.put(parentName, after);
}
}
}
}
private String implode(ArrayList<String> al)
{
String ret = "";
for (int i = 0; al.size() > i; i++)
{
if (i != 0)
{
ret += ".";
}
ret += al.get(i);
}
return (ret);
}
}

View File

@ -1,136 +0,0 @@
/*
Copyright 2009 jtpl.sourceforge.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package net.sf.jtpl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.jtpl.Jtpl;
/**
* The forward compatible template engine interface,
* replacing {@link Jtpl}.
*/
public class Template implements Serializable {
private static final long serialVersionUID = 3916690583929137140L;
private Jtpl t;
public Template(Reader template) throws IOException {
t = new Jtpl(template);
}
public Template(String templateSource) {
try {
t = new Jtpl(new StringReader(templateSource));
} catch (IOException e) {
throw new RuntimeException(e); // should be impossible with StringReader
}
}
public Template(File templateFile) throws FileNotFoundException {
FileReader r = new FileReader(templateFile);
try {
t = new Jtpl(templateFile);
} catch (IOException e) {
try {
r.close();
} catch (Exception nothingToDoAboutIt) {}
}
}
// proxying methods from Jtpl1
public Template assign(String varName, String varData) {
t.assign(varName, varData);
return this;
}
public Template parse(String blockName) throws IllegalArgumentException {
t.parse(blockName);
return this;
}
public String out() {
return t.out();
}
// bean properties support
public Template parse(String blockName, Object bean) {
assignAll(bean);
return parse(blockName);
}
public String out(Object bean) {
assignAll(bean);
return out();
}
protected void assignAll(Object bean) {
Map<String, Object> p = getBeanProperties(bean);
Iterator<String> i = p.keySet().iterator();
while (i.hasNext()) {
String key = (String) i.next();
assign(key.toUpperCase(), "" + p.get(key));
}
}
/**
* @param bean The instance that has properties named according to JavaBean standard.
* @return Map<String, Object> that should be considered immutable
*/
protected Map<String, Object> getBeanProperties(Object bean) {
HashMap<String, Object> values = new HashMap<String, Object>();
if (bean == null) return values;
Method[] m = bean.getClass().getMethods();
Pattern p = Pattern.compile("get([A-Z]\\w+)");
for (int i = 0; i < m.length; i++) {
if (m[i].getName().equals("getClass")) continue;
if (m[i].getParameterTypes().length > 0) continue;
Matcher r = p.matcher(m[i].getName());
if (r.matches()) {
try {
values.put(r.group(1).toLowerCase(), m[i].invoke(bean, new Object[0]));
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
return values;
}
}