Zk java代码生成器

比如你有一个index.zul页面,代码如下:

<window id="hello" use="com.yourcompany.example.Hello">
<button id="hellowWorldButton" onClick="hellow.hellowWorldButtonOnClickHandler()"/>
</window>




给这个主程序类传5个参数,就可以得到最终的java文件。
java生成器代码:

package com.yourcompany.applications;
import com.yourcompany.generators.ZKWindowFileGenerator;
public class ZKWindowFileGeneratorMain {

/**
* Method : main
*
* @param args
*/
public static void main(String[] args) {
if (args.length != 5) {
System.out.println("Usage: java ZKWindowFileGeneratorMain inputFileDir inputFileName outputFileDir outputFileName packageName");
System.exit(0);
}

String inputFileDir = args[0]; //输入路径
String inputFileName = args[1];//输入.zul文件名
String outputFileDir = args[2];//输出路径
String outputFileName = args[3]; //输出.java文件名
String packageName = args[4]; //java文件包名

ZKWindowFileGenerator generator = null;
generator = new ZKWindowFileGenerator(inputFileDir, inputFileName, outputFileDir, outputFileName, packageName);

try {
generator.generate();
} catch (Exception e) {
// Already printed out and logged in the DHgZKWindowFileGenerator
// class.
}
}
}




package com.yourcompany.generators;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ZKCodeGenerator
{
private String nl = "\n";


/**
*
* Method : generateMethodComment
* @param methodName
* @param description
* @param params
* @param hasReturnType
* @return
*/
protected String generateMethodComment(String methodName,
String description,
String params[],
boolean hasReturnType)
{
StringBuffer comment = new StringBuffer();

comment.append(" /**" + nl);
comment.append(" * Method : " + methodName + nl );
if (description.length() > 70)
{
String commentString = description;
while (commentString.length() > 0)
{
// Grab the first 50 characters
int length = commentString.length();
int endIndex = 69;
if (length < 69)
endIndex = length;
String stringToPrint = commentString.substring(0,endIndex);
comment.append(" * " + stringToPrint + nl);
// Remove the part that we just used.

commentString = commentString.substring(endIndex);
}
}
else
comment.append(" * " + description + nl);

if (params != null)
{
for (int i=0;i<params.length;i++)
{
String param = params[i];
comment.append(" * @param " + param + nl);
}
}

if (hasReturnType)
{
comment.append(" * @return " + nl);
}
comment.append(" */" + nl);
return comment.toString();
}



/**
*
* Method : readHeaderCommentsFromFile
* @param fileName - this should include full path information to the file. Ex. /home/root/headers/headerFile.txt
* @return
* @throws IOException
*/
protected String readHeaderCommentsFromFile(String fileName) throws IOException
{
BufferedReader in = new BufferedReader(new FileReader(fileName));
StringBuffer header = new StringBuffer();
String currentLine;
while ((currentLine = in.readLine()) != null)
{
header.append(currentLine + "\n");
}
in.close();
return header.toString();
}



/**
*
* Method : getHeaderComments
* @param project
* @param fileName
* @param packageName
* @param className
* @param author
* @param locationOfUse
* @param type
* @param description
* @return
*/
protected String getHeaderComments(String project,
String fileName,
String packageName,
String className,
String author,
String locationOfUse,
String type,
String description)
{
String nl = new String("\n");
StringBuffer buff = new StringBuffer();

buff.append("/**" + nl);
buff.append("* _YourCompany_ Copyright 2007. All Rights Reserved." + nl);
buff.append("* " + nl);
buff.append("* Project : " + project + nl);
buff.append("* Filename : " + fileName + nl);
buff.append("* Package : " + packageName + nl);
buff.append("* Class : " + className + nl);
buff.append("* Create Date : " + nl);
buff.append("* Author : " + author + nl);
buff.append("*" + nl);
buff.append("* Location of Use : " + locationOfUse + nl);
buff.append("*" + nl);
buff.append("* Type : " + type + nl);
buff.append("* " + nl);
buff.append("* Description: " + description + nl);
buff.append("* " + nl);
buff.append("*/" + nl);

return buff.toString();
}

/**
*
* Method : getHeaderComments
* @return
*/
protected String getHeaderComments()
{
String nl = new String("\n");
StringBuffer buff = new StringBuffer();

buff.append("/**" + nl);
buff
.append("* _YourCompany_ Copyright 2007. All Rights Reserved."
+ nl);
buff.append("* " + nl);
buff.append("* Project : " + nl);
buff.append("* Filename : " + nl);
buff.append("* Package : " + nl);
buff.append("* Class : " + nl);
buff.append("* Create Date : " + nl);
buff.append("* Author : " + nl);
buff.append("*" + nl);
buff.append("* Location of Use : " + nl);
buff.append("*" + nl);
buff.append("* Type : " + nl);
buff.append("* " + nl);
buff.append("* Description: TODO" + nl);
buff.append("* " + nl);
buff.append("*/" + nl);

return buff.toString();
}


}




/**
* Description:
*
* This class will take in a ZK .zul file and from that file generate the class that
* extends the zk Window class. It will generate the member variables, the widget lookups in the
* onCreate method, and all callback methods that are defined in the .zul file. This will save alot
* of time dealing with the very tedious part of creating .zul files and the corresponding java file.
*
*/
package com.yourcompany.generators;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ZKWindowFileGenerator extends ZKCodeGenerator {
private static Logger logger = Logger.getLogger(ZKWindowFileGenerator.class);

private String className = null;

private String zkFileName = null;

private String zkFileDirectory = null;

private String outputFilePackage = null;

private String outputFileName = null;

private String outputDirectory = null;

private FileWriter writer = null;

private Vector components = new Vector();

/**
* Constructor
*
* @param zkFileName
*/
public ZKWindowFileGenerator(String zkFileDirectory, String zkFileName, String outputDirectory,
String outputFileName, String outputFilePackage) {
super();
this.zkFileName = zkFileName;
this.zkFileDirectory = zkFileDirectory;
this.outputFileName = outputFileName;
this.outputDirectory = outputDirectory;
this.outputFilePackage = outputFilePackage;

}

public void generate() throws Exception {
parseInputFile();
generateOutputFile();
}

/**
* Method : parseInputFile
*
*/
private void parseInputFile() throws Exception {
String fileName = null;
fileName = zkFileDirectory + zkFileName;

SAXBuilder builder = new SAXBuilder();

try {
Document doc = builder.build(fileName);
Element root = doc.getRootElement();
this.processDocument(root, 0);

}
// indicates a well-formedness error
catch (JDOMException e) {
System.out.println(fileName + " is not well-formed.");
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e);
}

}

/**
* Method: processDocument Processes the the zul file as DOM tree to get the
* components with theire id's and callBackMethod
*
* @param current
* node
* @param depth
* Used to go deeper in DOM tree (recursive)
*/
public void processDocument(Element current, int depth) {

// if component has no id then ignore it
if (current.getAttributeValue("id") != null) {
String idString = current.getAttributeValue("id");
String componentName = current.getName();
String callbackMethod = "";

// Get callBackMethod if there is any

if (componentName.equals("button")) {
if (current.getAttributeValue("onClick") != null) {
String callBackString = current.getAttributeValue("onClick");
int indexOfDotInCallBack = callBackString.indexOf(".");
callbackMethod = callBackString.substring(indexOfDotInCallBack + 1);
}

}
if (componentName.equals("listbox")) {
if (current.getAttributeValue("onSelect") != null) {
String callBackString = current.getAttributeValue("onSelect");
int indexOfDotInCallBack = callBackString.indexOf(".");
callbackMethod = callBackString.substring(indexOfDotInCallBack + 1);
}

}
if (componentName.equals("checkbox") || componentName.equals("radiogroup")) {
if (current.getAttributeValue("onCheck") != null) {
String callBackString = current.getAttributeValue("onCheck");
int indexOfDotInCallBack = callBackString.indexOf(".");
callbackMethod = callBackString.substring(indexOfDotInCallBack + 1);
}
}

ZKComponentHolder componentHolder = new ZKComponentHolder(componentName, idString, callbackMethod);
components.add(componentHolder);
}

List children = current.getChildren();
Iterator iterator = children.iterator();
while (iterator.hasNext()) {
Element child = (Element) iterator.next();

processDocument(child, depth + 1);

}

}

/**
*
* Method : generateOutputFile
*/
private void generateOutputFile() throws Exception {
setClassName();
String fileName = outputDirectory + outputFileName;
writer = new FileWriter(fileName);

writer.write(getHeaderComments() + "\n\n\n");

writer.write("package " + outputFilePackage + ";\n\n\n");

writer.write(generateImportStatements() + "\n\n\n");

writer.write("class " + className + " extends Window\n");
writer.write("{\n\n");

generateMemberVariables();
generateOnCreateMethod();
generateCallbackMethods();
generateInitializeComponentsMethod();
generateInitializeListBoxMethods();

writer.write("}\n");
writer.flush();
writer.close();
}

/**
*
* Method : setClassName
*/
private void setClassName() {
// int indexOfDot = zkFileName.indexOf(".");
// Use the name of output (java) file instead of zul file as class name
int indexOfDot = outputFileName.indexOf(".");
className = outputFileName.substring(0, indexOfDot);
}

/**
*
* Method : generateImportStatemens
*
* @return
*/
private String generateImportStatements() {
StringBuffer buff = new StringBuffer();
buff.append("import org.apache.log4j.Logger;\n");
buff.append("import org.zkoss.zk.ui.Executions;\n");
buff.append("import org.zkoss.zul.Button;\n");
buff.append("import org.zkoss.zul.Messagebox;\n");
buff.append("import org.zkoss.zul.Textbox;\n");
buff.append("import org.zkoss.zul.Intbox;\n");
buff.append("import org.zkoss.zul.Window;\n");
buff.append("import org.zkoss.zul.Listbox;\n");
buff.append("import org.zkoss.zul.Radiogroup;\n");
buff.append("import org.zkoss.zul.Checkbox;\n\n");
return buff.toString();
}

/**
*
* Method : generateMemberVariables
*
* @throws Exception
*/
private void generateMemberVariables() throws Exception {
writer.write(" private static Logger logger = Logger.getLogger(" + className + ".class);\n");

Iterator it = components.iterator();
while (it.hasNext()) {
ZKComponentHolder holder = (ZKComponentHolder) it.next();
System.out.println("Type = " + holder.type + " Id = " + holder.id + " Callback = " + holder.callbackMethod);
if (holder.type.compareTo("listbox") == 0) {
writer.write(" private Listbox " + holder.id + " = null;\n");
} else if (holder.type.compareTo("textbox") == 0) {
writer.write(" private Textbox " + holder.id + " = null;\n");
} else if (holder.type.compareTo("intbox") == 0) {
writer.write(" private Intbox " + holder.id + " = null;\n");
} else if (holder.type.compareTo("button") == 0) {
writer.write(" private Button " + holder.id + " = null;\n");
} else if (holder.type.compareTo("radiogroup") == 0) {
writer.write(" private Radiogroup " + holder.id + " = null;\n");
} else if (holder.type.compareTo("checkbox") == 0) {
writer.write(" private Checkbox " + holder.id + " = null;\n");
}
}
writer.write("\n\n\n");
}

/**
*
* Method : generateOnCreateMethod
*
* @throws Exception
*/
private void generateOnCreateMethod() throws Exception {
writer.write(generateMethodComment("onCreate", "", null, false));
writer.write(" public void onCreate()\n");
writer.write(" {\n");
writer.write(" initializeComponents();\n");

Iterator it = components.iterator();
while (it.hasNext()) {
ZKComponentHolder holder = (ZKComponentHolder) it.next();

if (holder.type.compareTo("listbox") == 0) {
String id = holder.id;
String firstChar = id.substring(0, 1);
id = firstChar.toUpperCase() + id.substring(1);
writer.write(" initialize" + id + "ListBox();\n");
}

}

writer.write(" }\n\n\n\n");
}

/**
*
* Method : generateInitializeComponentsMethod
*
* @throws Exception
*/
private void generateInitializeComponentsMethod() throws Exception {
writer.write(generateMethodComment("initializeComponents", "", null, false));
writer.write(" public void initializeComponents()\n");
writer.write(" {\n");
Iterator it = components.iterator();
while (it.hasNext()) {
ZKComponentHolder holder = (ZKComponentHolder) it.next();

if (holder.type.compareTo("listbox") == 0) {
writer.write(" " + holder.id + " = (Listbox)this.getFellow(\"" + holder.id + "\");\n");
} else if (holder.type.compareTo("textbox") == 0) {
writer.write(" " + holder.id + " = (Textbox)this.getFellow(\"" + holder.id + "\");\n");
} else if (holder.type.compareTo("intbox") == 0) {
writer.write(" " + holder.id + " = (Intbox)this.getFellow(\"" + holder.id + "\");\n");
} else if (holder.type.compareTo("button") == 0) {
writer.write(" " + holder.id + " = (Button)this.getFellow(\"" + holder.id + "\");\n");
} else if (holder.type.compareTo("radiogroup") == 0) {
writer.write(" " + holder.id + " = (Radiogroup)this.getFellow(\"" + holder.id + "\");\n");
} else if (holder.type.compareTo("checkbox") == 0) {
writer.write(" " + holder.id + " = (Checkbox)this.getFellow(\"" + holder.id + "\");\n");
}
}

writer.write(" }\n\n\n\n");
}

/**
*
* Method : generateInitializeListBoxMethods
*
* @throws Exception
*/
private void generateInitializeListBoxMethods() throws Exception {
Iterator it = components.iterator();
while (it.hasNext()) {
ZKComponentHolder holder = (ZKComponentHolder) it.next();

if (holder.type.compareTo("listbox") == 0) {
String id = holder.id;
String firstChar = id.substring(0, 1);
id = firstChar.toUpperCase() + id.substring(1);
writer.write(generateMethodComment("initialize" + id + "ListBox", "", null, false));
writer.write(" public void initialize" + id + "ListBox()\n");
writer.write(" {\n");

writer.write(" }\n\n\n\n");
}

}

}

/**
*
* Method : generateCallbackMethods
*
* @throws Exception
*/
private void generateCallbackMethods() throws Exception {
Iterator it = components.iterator();
while (it.hasNext()) {
ZKComponentHolder holder = (ZKComponentHolder) it.next();
if (holder.callbackMethod.length() > 0) {
writer.write(generateMethodComment(holder.callbackMethod, "", null, false));
writer.write(" public void " + holder.callbackMethod + "\n");
writer.write(" {\n\n");
writer.write(" }\n\n");
}
}
}

/**
* Embedded class for holding component info
*/
protected class ZKComponentHolder {
public String type;

public String id;

public String callbackMethod;

/**
* Constructor
*
* @param type
* @param id
* @param callbackMethod
*/
public ZKComponentHolder(String type, String id, String callbackMethod) {
super();
this.type = type;
this.id = id;
this.callbackMethod = callbackMethod;
}

}

/**
* Getter for outputFileName
*
* @return Returns the outputFileName.
*/
public String getOutputFileName() {
return this.outputFileName;
}

/**
* Setter for outputFileName
*
* @param outputFileName
* The outputFileName to set.
*/
public void setOutputFileName(String outputFileName) {
this.outputFileName = outputFileName;
}

/**
* Getter for writer
*
* @return Returns the writer.
*/
public FileWriter getWriter() {
return this.writer;
}

/**
* Setter for writer
*
* @param writer
* The writer to set.
*/
public void setWriter(FileWriter writer) {
this.writer = writer;
}

}



指定5个参数分别是:
args[0] = "D:/javacreator/zul/example/";
args[1] = "index.zul";
args[2] = "D:/javacreator/java/example/";
args[3] = "Hello.java";
args[4] = "com.yourcompany.example";

最后D:/javacreator/java/example/目录下生成的Hello.java文件代码:

/**
* _YourCompany_ Copyright 2007. All Rights Reserved.
*
* Project :
* Filename :
* Package :
* Class :
* Create Date :
* Author :
*
* Location of Use :
*
* Type :
*
* Description: TODO
*
*/

package com.yourcompany.example;

import org.apache.log4j.Logger;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zul.Button;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Window;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Radiogroup;
import org.zkoss.zul.Checkbox;

class Hello extends Window
{

private static Logger logger = Logger.getLogger(Hello.class);
private Button hellowWorldButton = null;

/**
* Method : onCreate
*
*/
public void onCreate()
{
initializeComponents();
}


/**
* Method : hellowWorldButtonOnClickHandler()
*
*/
public void hellowWorldButtonOnClickHandler()
{

}

/**
* Method : initializeComponents
*
*/
public void initializeComponents()
{
hellowWorldButton = (Button)this.getFellow("hellowWorldButton");
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个基于 ZooKeeper 实现的分布式锁的 Java 代码示例: ```java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.Stat; public class DistributedLock { private static final String LOCK_ROOT_PATH = "/locks"; private static final String LOCK_NODE_PREFIX = "lock-"; private final String lockPath; private final ZooKeeper zk; private String lockNode; private CountDownLatch lockAcquiredSignal; public DistributedLock(String zookeeperUrl, String lockPath) throws Exception { this.lockPath = LOCK_ROOT_PATH + "/" + lockPath; this.zk = new ZooKeeper(zookeeperUrl, 3000, null); ensureLockPathExists(); } public void lock() throws Exception { while (true) { try { lockNode = zk.create(lockPath + "/" + LOCK_NODE_PREFIX, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); lockAcquiredSignal = new CountDownLatch(1); waitForLock(); return; } catch (KeeperException.NodeExistsException e) { // node already exists, wait for the previous holder to release the lock waitForPreviousLock(); } } } public void unlock() throws Exception { zk.delete(lockNode, -1); lockNode = null; lockAcquiredSignal.countDown(); } private void ensureLockPathExists() throws Exception { if (zk.exists(lockPath, false) == null) { zk.create(lockPath, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } } private void waitForPreviousLock() throws Exception { List<String> lockNodes = zk.getChildren(lockPath, false); Collections.sort(lockNodes); int currentLockIndex = lockNodes.indexOf(lockNode.substring(lockPath.length() + 1)); if (currentLockIndex <= 0) { throw new IllegalStateException("Lock node not found: " + lockNode); } String previousLockNode = lockPath + "/" + lockNodes.get(currentLockIndex - 1); Stat previousLockStat = zk.exists(previousLockNode, new LockWatcher()); if (previousLockStat != null) { lockAcquiredSignal.await(); } } private void waitForLock() throws Exception { List<String> lockNodes = zk.getChildren(lockPath, false); Collections.sort(lockNodes); int currentLockIndex = lockNodes.indexOf(lockNode.substring(lockPath.length() + 1)); if (currentLockIndex == 0) { // this is the first lock node, lock acquired return; } String previousLockNode = lockPath + "/" + lockNodes.get(currentLockIndex - 1); Stat previousLockStat = zk.exists(previousLockNode, new LockWatcher()); if (previousLockStat == null) { // previous lock node has been deleted, lock acquired return; } lockAcquiredSignal.await(); } private class LockWatcher implements Watcher { @Override public void process(WatchedEvent event) { if (event.getType() == Event.EventType.NodeDeleted) { lockAcquiredSignal.countDown(); } } } } ``` 使用示例: ```java DistributedLock lock = new DistributedLock("localhost:2181", "my-lock"); lock.lock(); try { // critical section } finally { lock.unlock(); } ``` 该示例代码使用了 ZooKeeper 的临时顺序节点来实现分布式锁。当多个节点同时请求锁时,它们会在 ZooKeeper 中创建一个临时顺序节点,并按照节点名称的顺序等待前面的节点释放锁。当锁被释放时,它会通知等待的节点,让它们尝试重新获得锁。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值