Skip to content

Instantly share code, notes, and snippets.

@mccxj
Created January 12, 2014 03:50
Show Gist options
  • Save mccxj/8380572 to your computer and use it in GitHub Desktop.
Save mccxj/8380572 to your computer and use it in GitHub Desktop.
moco stub server
package com.github.mccxj.stub;
import com.github.dreamhead.moco.internal.ActualHttpServer;
import com.github.dreamhead.moco.internal.MocoHttpServer;
import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import static com.github.dreamhead.moco.Moco.*;
public class HelloStubServer {
public static void main(String[] args) throws Exception {
final String adir = "adir";
ChangeCallBack callback = new ChangeCallBack() {
MocoHttpServer httpServer = null;
@Override
public void callback() {
if(httpServer != null)
httpServer.stop();
ActualHttpServer server = (ActualHttpServer) httpserver(12306);
httpServer = new MocoHttpServer(server);
File[] files = new File(adir).listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith("txt");
}
});
for (File f : files) {
server.post(and(by(uri("/foo")), eq(xpath("/request/parameters/id/text()"), f.getName().substring(0, f.getName().length() - 4)))).response(file(f.getAbsolutePath()));
}
server.response("foo");
httpServer.start();
}
};
DirWatcher watcher = new DirWatcher(adir, callback);
watcher.start();
}
}
interface ChangeCallBack {
public void callback();
}
class DirWatcher extends Thread {
private final ChangeCallBack callback;
private final String dir;
private String[] prevFiles;
public DirWatcher(String dir, ChangeCallBack callback) {
this.dir = dir;
this.callback = callback;
}
@Override
public void run() {
while (true) {
String[] files1 = new File(dir).list();
Arrays.sort(files1);
if (prevFiles == null){
prevFiles = files1;
callback.callback();
}
if (!sameFiles(prevFiles, files1)) {
prevFiles = files1;
callback.callback();
}
try {
Thread.sleep(5L);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
private boolean sameFiles(String[] f1, String[] f2) {
if (f1.length != f2.length)
return false;
for (int i = 0; i < f1.length; i++)
if (!f1[i].equals(f2[i]))
return false;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment