Code Search for Developers
 
 
  

WootSite.java from PeerWriter at Krugle


Show WootSite.java syntax highlighted

package de.peerwriter.woot;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;

import com.thoughtworks.xstream.XStream;

import de.peerwriter.pbcast.Site;
import de.peerwriter.util.FileUtil;
import de.peerwriter.util.clock.Clock;
import de.peerwriter.util.clock.PersistentClock;
import de.peerwriter.woot.operation.Delete;
import de.peerwriter.woot.operation.Insert;
import de.peerwriter.woot.operation.Operation;
import de.peerwriter.woot.operation.Patch;
import de.peerwriter.woot.operation.Pool;

public class WootSite implements Site {

	private String id;

	private String workingDir;

	private Clock opLocalClock;

	private Pool waitingQueue;

	public static final short HUMAN_MODE = 0;

	public Object _getHumanMode() {
		return WootSite.HUMAN_MODE;
	}

	public static final short REAL_MODE = 1;

	public Object _getReadlMode() {
		return WootSite.REAL_MODE;
	}

	public WootSite(String siteId, String workingDir) throws Exception {
		this.setId(siteId);
		this.setWorkingDir(workingDir);

		File dirClocks = new File(this.getWorkingDir() + File.separator + "clocks");
		File dirPool = new File(this.getWorkingDir() + File.separator + "pool");
		File dirPages = new File(this.getWorkingDir() + File.separator + "pages");

		if (!dirClocks.exists()) {
			if (!dirClocks.mkdir()) {
				throw new RuntimeException("Can't create clocks directory: " + dirClocks);
			}
		}
		if (!dirPool.exists()) {
			if (!dirPool.mkdir()) {
				throw new RuntimeException("Can't create pool directory: " + dirPool);
			}
		}
		if (!dirPages.exists()) {
			if (!dirPages.mkdir()) {
				throw new RuntimeException("Can't create pages directory: " + dirPages);
			}
		}
		Clock patchClock = new PersistentClock(dirClocks + File.separator + "patchClock");
		Clock opClock = new PersistentClock(dirClocks + File.separator + "opClock");
		Pool pool = new Pool(dirPool + File.separator + "pool");

		// ws.setPatchLocalClock(patchClock);
		this.setOpLocalClock(opClock);
		this.setWaitingQueue(pool);
		this.WaitingQueueExec(null);
	}

	public void WaitingQueueExec(String patchPageName) throws Exception {
		getWaitingQueue().loadPool();
		if (patchPageName != null && patchPageName.trim().length() != 0) {// maybe
			WootDocument page = loadPage(patchPageName);
			int i = 0;
			while (i < getWaitingQueue().getContent().size()) {
				Operation op = (Operation) getWaitingQueue().getContent().elementAt(i);
				if (op.getPageName().equals(patchPageName)) {

					if (op instanceof Insert) {
						Insert ins = (Insert) op;
						int[] indexs = new int[2];
						indexs = ins.precond_v2(page);
						if (indexs != null) {
							ins.execute(indexs[0], indexs[1], page);
							getWaitingQueue().getContent().removeElementAt(i);
							i = 0;// rewind
							this.storePage(page);
							// unloadPage(page); storePage
							getWaitingQueue().storePool();
						} else
							i++;
					} else {// del
						Delete del = (Delete) op;
						int idx = del.precond_v2(page);
						if (idx >= 0) {
							del.setIndexRow(idx);
							del.execute(page);
							getWaitingQueue().getContent().removeElementAt(i);
							i = 0;
							this.storePage(page);
							// unloadPage(page); storePage
							getWaitingQueue().storePool();
						} else
							i++;
					}
				} else {
					i++;
				}

			}

			this.unloadPage(page);

		} else { // WaitingQueueExec called with null
			int i = 0;
			while (i < getWaitingQueue().getContent().size()) {

				Operation op = (Operation) getWaitingQueue().getContent().elementAt(i);
				WootDocument page = loadPage(patchPageName);
				if (page != null) {
					if (op instanceof Insert) {
						Insert ins = (Insert) op;
						int[] indexs = new int[2];
						indexs = ins.precond_v2(page);
						if (indexs != null) {
							ins.execute(indexs[0], indexs[1], page);
							getWaitingQueue().getContent().removeElementAt(i);
							i = 0;// rewind
							// unloadPage(page); storePage
							getWaitingQueue().storePool();
						} else
							i++;
					} else {// del
						Delete del = (Delete) op;
						int idx = del.precond_v2(page);
						if (idx >= 0) {
							del.setIndexRow(idx);
							del.execute(page);
							getWaitingQueue().getContent().removeElementAt(i);
							i = 0;
							// unloadPage(page); storePage
							getWaitingQueue().storePool();
						} else
							i++;
					}
					this.unloadPage(page);
				}
			}
		}

		getWaitingQueue().unLoadPool();
	}

	public void deliver(Object o) throws Exception {
		if (!(o instanceof Patch)) {
			System.out.println("not applicable patch...");
			return;
		}
		Patch p = (Patch) o;

		String pageName = p.getPageId();
		if (!this.pageExist(pageName)) {
			createPage(pageName);
		}
		WootDocument page = loadPage(pageName);
		synchronized (page) {
			for (Object obj : p.getData()) {
				Operation op = (Operation) obj;
				// op.setWootPage(page);
				if (op instanceof Insert) {
					Insert ins = (Insert) op;
					int[] indexs = new int[2];
					indexs = ins.precond_v2(page);
					if (indexs != null) {
						ins.execute(indexs[0], indexs[1], page);
					} else {
						this.getWaitingQueue().loadPool();
						this.getWaitingQueue().getContent().addElement(ins);
						this.getWaitingQueue().unLoadPool();

					}

				} else {// Del
					Delete del = (Delete) op;
					int idx = del.precond_v2(page);
					if (idx >= 0) {
						del.setIndexRow(idx);
						del.execute(page);
					} else {
						this.getWaitingQueue().loadPool();
						this.getWaitingQueue().getContent().addElement(op);
						this.getWaitingQueue().unLoadPool();
					}
				}
			}
		}
		unloadPage(page);
		WaitingQueueExec(pageName);
	}

	private Insert ins(WootDocument page, String alpha, int pos) throws Exception {
		if (pos <= page.size() && pos >= 0) {
			int indexP = page.indexOfVisible(pos);
			WootTag rp = (indexP != -1) ? page.elementAt(indexP) : page.elementAt(0);
			if (!rp.equals(WootTag.RE)) {
				int indexN = page.indexOfVisibleNext(indexP);
				WootTag rn = (indexN != -1) ? page.elementAt(indexN) : page.elementAt(page.size() + 1);
				int deg_c = 1;
				deg_c += (rp.getDegree() >= rn.getDegree()) ? rp.getDegree() : rn.getDegree();
				// WootTag r = new WootTag(new WootId(id,
				// getRowLocalClock().getValue()), alpha, deg_c);
				WootTag r = new WootTag(new WootId(id, getOpLocalClock().getValue()), alpha, deg_c);
				// getRowLocalClock().setValue(getRowLocalClock().getValue() +
				// 1);
				// getRowLocalClock().store();
				Operation ins = new Insert(r, rp.getWootId(), rn.getWootId());
				ins.setOpid(new WootId(id, getOpLocalClock().getValue()));
				ins.setPageName(page.getDocumentName());
				getOpLocalClock().setValue(getOpLocalClock().getValue() + 1);
				// getOpLocalClock().store();
				// ins.setSiteId(getId());
				ins.execute(page);
				return (Insert) ins;
			} else {
				throw new RuntimeException("site " + getId() + ": Il est inmpossible d'ins\u00E9rer \u00E0 la position " + pos);
			}

		} else {
			throw new RuntimeException("site " + getId() + ": Il est inmpossible d'ins\u00E9rer \u00E0 la position " + pos);
		}
	}

	private Delete del(WootDocument page, int pos) throws Exception {
		if (pos >= 0 && pos < page.size()) {
			int idxV = page.indexOfVisible(pos + 1);
			WootTag wr = page.elementAt(idxV);
			if (!wr.equals(WootTag.RE)) {
				Delete del = new Delete(page, wr.getWootId());
				del.setOpid(new WootId(id, getOpLocalClock().getValue()));
				getOpLocalClock().setValue(getOpLocalClock().getValue() + 1);
				// getOpLocalClock().store();
				// del.setSiteId(getId());
				del.setPageName(page.getDocumentName());
				del.setIndexRow(idxV);
				del.execute(page);
				return (Delete) del;
			} else {
				throw new RuntimeException("site " + getId() + ": Il est impossible de supprimer \u00E0 la position " + pos);
			}

		} else {
			throw new RuntimeException("site " + getId() + ": Il est impossible de supprimer \u00E0 la position " + pos);
		}
	}

	/*
	 * public String toString() { return "Site:" + id + " CC:" +
	 * getRowLocalClock() + " OpC:" + getOpLocalClock(); }
	 */

	private boolean pageExist(String pageId) throws Exception {
		File f = new File(this.workingDir + File.separator + "pages" + File.separator + pageId);
		return f.exists();
	}

	private synchronized WootDocument loadPage(String pageId) throws Exception {
		if ((pageId == null) || pageId.equals("") || !(this.pageExist(pageId))) {
			// throw new RuntimeException("pageId :" + pageId + " doesn't
			// exist");
			// replace it with the appropriate exception (maybe to redirect
			// to
			// page creation)
			/*
			 * if (!this.pageExist("Home")) { // create Home page
			 * this.createPage("Home"); } pageId = "Home";
			 */
			return null;
		}
		XStream xstream = new XStream();
		return (WootDocument) xstream.fromXML(new FileInputStream(this.getWorkingDir() + File.separator + "pages" + File.separator + pageId));

		/*
		 * FileInputStream fin = new FileInputStream(this.getWorkDirectory() +
		 * File.separator + "pages" + File.separator + pageId); WootDocument
		 * wootPage = null; ObjectInputStream ois = new ObjectInputStream(fin);
		 * wootPage = (WootDocument) ois.readObject(); ois.close(); return wootPage;
		 */
	}

	private void unloadPage(WootDocument wootDocument) throws Exception {
		XStream xstream = new XStream();

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(this.getWorkingDir() + File.separator + "pages" + File.separator
				+ wootDocument.getDocumentName()), Charset.forName(System.getProperty("file.encoding")));
		PrintWriter output = new PrintWriter(osw);

		output.print(xstream.toXML(wootDocument));
		// FileOutputStream fout = new FileOutputStream(this.getWorkDirectory()
		// + File.separator + "pages" + File.separator +
		// wootPage.getPageName());
		// ObjectOutputStream oos = new ObjectOutputStream(fout);
		// oos.writeObject(wootPage);
		// oos.flush();
		// oos.close();
		output.flush();
		output.close();
		wootDocument = null;
		System.runFinalization();
		System.gc();
	}

	private void storePage(WootDocument wootDocument) throws Exception {
		XStream xstream = new XStream();

		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(this.getWorkingDir() + File.separator + "pages" + File.separator
				+ wootDocument.getDocumentName()), Charset.forName(System.getProperty("file.encoding")));
		PrintWriter output = new PrintWriter(osw);

		output.print(xstream.toXML(wootDocument));
		output.flush();
		output.close();

		/*
		 * FileOutputStream fout = new FileOutputStream(this.getWorkDirectory() +
		 * File.separator + "pages" + File.separator + wootPage.getPageName());
		 * ObjectOutputStream oos = new ObjectOutputStream(fout);
		 * oos.writeObject(wootPage); oos.flush(); oos.close();
		 */

	}

	/*
	 * public String readPage(String pageName) throws Exception { WootDocument page =
	 * this.loadPage(pageName); String content = page.toHumanString(); return
	 * content; }
	 */
	public Object getPage(Object pageName, Object mode) throws Exception {
		if ((Short) mode == WootSite.HUMAN_MODE) {
			return this.loadPage((String) pageName).toHumanString();

		} else if ((Short) mode == WootSite.REAL_MODE) {
			return this.loadPage((String) pageName).toString();

		} else {
			throw new RuntimeException("Uknown mode for reading page");
		}
	}

	public String createPage(String pageName) throws Exception {
		if (pageName == null || pageName.equals("")) {
			throw new RuntimeException("Please enter a non-empty page name !");
		} else {
			String pageId = pageName.replaceAll("[^0-9a-zA-Z]", "_");
			/*
			 * while (this.pageExist(pageId)) { pageId = pageId + Math.random(); }
			 */
			if (this.pageExist(pageId)) {
				throw new RuntimeException("This page already exist !");
			}
			WootDocument wootDocument = new WootDocument(true);
			wootDocument.setDocumentName(pageId);
			wootDocument.setTitle(pageId);
			// wootPage.setTitle(pageName);
			XStream xstream = new XStream();
			PrintWriter pw = new PrintWriter(new FileOutputStream(this.getWorkingDir() + File.separator + "pages" + File.separator + pageId));
			pw.print(xstream.toXML(wootDocument));
			pw.flush();
			pw.close();

			/*
			 * FileOutputStream fout = new
			 * FileOutputStream(this.getWorkDirectory() + File.separator +
			 * "pages" + File.separator + pageId); ObjectOutputStream oos = new
			 * ObjectOutputStream(fout); oos.writeObject(wootPage); oos.flush();
			 * oos.close();
			 */
			return pageId;
		}
	}

	public String[] listPages() throws Exception {
		File dir = new File(this.workingDir + File.separator + "pages" + File.separator);
		return dir.list();
	}

	// getters
	private Pool getWaitingQueue() {
		return waitingQueue;
	}

	private String getWorkingDir() {
		return workingDir;
	}

	public Clock getOpLocalClock() {
		return opLocalClock;
	}

	public String getId() {
		return id;
	}

	public void setOpLocalClock(Clock opLocalClock) {
		this.opLocalClock = opLocalClock;
	}

	private void setWorkingDir(String workDirectory) {
		this.workingDir = workDirectory;
	}

	private void setWaitingQueue(Pool waitingQueue) {
		this.waitingQueue = waitingQueue;
	}

	private void setId(String id) {
		this.id = id;
	}

	public Object ins(Object page, String alpha, int pos) throws Exception {
		return this.ins((WootDocument) page, alpha, pos);
	}

	public Object del(Object page, int pos) throws Exception {
		return this.del((WootDocument) page, pos);
	}

	public boolean pageExist(Object pageId) throws Exception {
		return this.pageExist((String) pageId);
	}

	public Object _getPage(Object pageId) throws Exception {
		return this.loadPage((String) pageId);
	}

	public void _storePage(Object page) throws Exception {
		this.storePage((WootDocument) page);
	}

	public void settingUpState(String fZip) throws Exception {
		// unzip file, and move the content to proper location

		File pages = new File(this.getWorkingDir() + File.separator + "pages");
		if (!pages.exists()) {
			if (!pages.mkdir()) {
				throw new RuntimeException("Can't create pages directory");
			}

		} else {
			// delete the content
			for (File f : pages.listFiles()) {
				if (!f.delete()) {
					System.err.println("Can't delete: " + f);
				}
			}
		}
		File fClock = new File(this.getWorkingDir() + File.separator + "clocks");
		if (!fClock.exists()) {
			if (!fClock.mkdir()) {
				throw new RuntimeException("Can't create clock directory");
			}
		} else {

		}

		File fPoolDir = new File(this.getWorkingDir() + File.separator + "pool");
		if (!fPoolDir.exists()) {
			if (!fPoolDir.mkdir()) {
				throw new RuntimeException("Can't create pool directory");
			}
		} else {
			// delete the content
			for (File f : fPoolDir.listFiles()) {
				if (!f.delete()) {
					System.err.println("Can't delete: " + f);
				}
			}
		}

		// Clock patchClock = new PersistentClock(fClock + File.separator
		// + "patchClock");
		Clock opClock = new PersistentClock(fClock.toString() + File.separator + "opClock");
		// Pool pool = new Pool(fPool + File.separator + "pool");

		// unzip the file
		File tmpfile = File.createTempFile("state", "");
		String tmpDir = tmpfile.toString();
		tmpfile.delete();
		File fTmpDir = new File(tmpDir);

		if (!fTmpDir.mkdir()) {
			throw new Exception("Can't create tmp directory to extract files");
		}

		FileUtil.unzipDirectory(fZip, tmpDir.toString());

		File newPool = new File(tmpDir.toString() + File.separator + "pool" + File.separator + "pool");
		if (!newPool.exists()) {
			throw new RuntimeException("Can't find pool file ! " + newPool);
		}

		File fPool = new File(this.getWorkingDir() + File.separator + "pool" + File.separator + "pool");

		FileUtil.copyFile(newPool.toString(), fPool.toString());
		// File newPool = new File(tmpDir + File.separator + "pool");

		// if (newPool.exists())
		// {
		// boolean success = newPool.renameTo(oldPool);
		// if (!success)
		// {
		// throw new RuntimeException("Pool was not successfully moved");
		// }
		//
		// }

		File newPages = new File(tmpDir.toString() + File.separator);
		if (!newPages.exists()) {
			throw new RuntimeException("Can't find new pages ! " + newPages);
		}

		FileUtil.copyFiles(newPages.toString(), this.getWorkingDir() + File.separator + "pages");
		// this.setPatchLocalClock(patchClock);
		this.setOpLocalClock(opClock);
		this.setWaitingQueue(new Pool(fPool.toString()));
		this.WaitingQueueExec(null);

		// delete zip file
		fTmpDir.delete();
	}

}




See more files for this project here

PeerWriter

PeerWriter is a collaborative text editor. Multiple peers can edit the same document while they see overall changes in real-time. PeerWriter is based on a decentralized infrastructure, using a non-locking concurrency protocol ensuring global consistency.

Project homepage: http://sourceforge.net/projects/peerwriter
Programming language(s): Java,XML
License: gpl2

  operation/
    Delete.java
    Insert.java
    Operation.java
    Patch.java
    Pool.java
  State.java
  WootDocument.java
  WootId.java
  WootSite.java
  WootTag.java