WikiAttachment

paul s <[email protected]> Sun, 05 Nov 2006 16:48:48 -0500
Newsgroups gmane.comp.java.webmacro.user
Message-ID <[email protected]>
This is a multi-part message in MIME format.
--------------080607050302090403090509
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 7bit

got it working... added a getInstance method to the WikiServlet for the 
WikiSystem... also change the WikiSystem to be static... any dangers in 
this?

but all in all its working fantastic on tomcat5... oh webmacro joy!!!

cheers
paul






so attached is a servlet that handles attachments for a page. everything
works great however i can't get at the current WikiSystem object. any
thoughts? reason being new page creation doesn't seem to load into the
current WikiSystem and i would imagine that i am writing the new page to
a new WikiSystem by going through a servlet. any help would be appreciated.


as for lucene when i updated the add.doc fields for 2.0 i had them
un_tockenized, that seems to be working now.

it seems i can't delete a admin user, reagular users i can delete and
add and change passwords...

cheers
paul







hi everyone - long time... has the WikiAttachment been implemented? if
so, how? code snip? similarly with lucene, indexing works, but the find
textbox doesn't seem to use the index. had an opportunity to roll out a
fresh one and its running under tomcat5. there also seems to be a bug in
the update password? willing to help sort these out...

cheers
paul





--------------080607050302090403090509
Content-Type: text/x-java;
 name="SavePageMulitpart.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="SavePageMulitpart.java"


package org.tcdi.opensource.wiki.servlet;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.tcdi.opensource.wiki.WikiAttachment;
import org.tcdi.opensource.wiki.WikiPage;
import org.tcdi.opensource.wiki.WikiSystem;
import org.tcdi.opensource.wiki.WikiUser;
import org.tcdi.opensource.wiki.WikiUtil;
import org.webmacro.servlet.WebContext;

/**
 * Saves the WikiPage that the user modified. If the page doesn't exist, it is
 * created. Otherwise, the existing page is saved as <PageName>.<oldversion>
 * and this page is saved in its place as <PageName>.
 * 
 * @author e_ridge
 */
public class SavePageMulitpart extends HttpServlet implements Servlet {

	private WikiServlet ws = new WikiServlet();
	
	private WikiSystem _wiki;
	
	public void init(ServletConfig arg0) throws ServletException {
		super.init(arg0);
		try {
			ws.init(arg0);
			_wiki = WikiServlet.getInstance();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		WebContext ctx = ws.getWebContext(req, res);
		try {
			FileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			List items = upload.parseRequest(req);
			Iterator iter = items.iterator();

			HashMap FormField = new HashMap();
			List attachments = new ArrayList();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					FormField.put(item.getFieldName(), item.getString());
				} else {
					long sizeInBytes = item.getSize();
					if (sizeInBytes > 0) {
						attachments.add(item);
					}
				}
			}
			ctx.put("Form", FormField);
			ctx.put("PageAttachments", attachments);
			String pageName = getWikiPageName(_wiki, ctx);
			WikiPage wikiPage = _wiki.getPage( pageName );
			WikiUser user = getUser(ctx);
			stuffContext(ctx, wikiPage, user, pageName);

			perform(_wiki, ctx, user, wikiPage);

			ctx.getResponse().sendRedirect(pageName);
			// throw new PageAction.RedirectException(pageName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
    public String getWikiPageName(WikiSystem wiki, WebContext ctx) {
        String pageName = (String) ((HashMap) ctx.get("Form")).get("save");
        pageName = WikiUtil.formatAsWikiTitle(pageName);
        return pageName;
    }

    /**
	 * can only save a page if the request is POST and "?save=<pagename>" is in
	 * the request
	 */
	public boolean accept(WikiSystem wiki, WebContext wc, WikiUser user) {
		// and then only accept if this is a get request
		return wc.getRequest().getMethod().equalsIgnoreCase("POST") && wc.getForm("save") != null;
	}

	/**
	 * do the saving of the page. When we're done, we redirect to the page so
	 * the user can view his changes.
	 */
	public void perform(WikiSystem wiki, WebContext wc, WikiUser user, WikiPage page) throws PageAction.PageActionException {
		if (page != null && page.getIsModerated() && !user.getIsModerator()) {
			System.out.println("This page can only be saved by moderators");
		}

		try {
			if (page == null)
				page = createNewPage(wiki, wc, user);
			else
				modifyExistingPage(wiki, wc, user, page);
		} catch (Exception e) {
			e.printStackTrace();
			throw new PageAction.PageActionException(e.toString());
		}
	}

	protected WikiPage createNewPage(WikiSystem wiki, WebContext ctx, WikiUser user) throws Exception {
		// get the page elements from the request
		String text = (String) ((HashMap) ctx.get("Form")).get("TEXT");
		String editor = user.getIdentifier();
		boolean moderated = ((HashMap) ctx.get("Form")).get("MODERATED") != null && ((HashMap) ctx.get("Form")).get("MODERATED").toString().equals("true");
		String keywords = (String) ((HashMap) ctx.get("Form")).get("RELATED_TITLES");
		String pageName = getWikiPageName(_wiki, ctx);

		// create the page
		WikiPage newPage = wiki.createPage(pageName, editor, text);
		newPage.setRelatedTitles(keywordsToStringArray(keywords));
		newPage.setIsModerated(moderated);

		storeattachments(ctx, newPage, pageName);

		// make sure to save the page
		wiki.parsePage(newPage);
		wiki.savePage(newPage);

		return newPage;
	}

	protected void modifyExistingPage(WikiSystem wiki, WebContext ctx, WikiUser user, WikiPage page) throws Exception {
		// get the page elements from the request
		String text = (String) ((HashMap) ctx.get("Form")).get("TEXT");
		String editor = user.getIdentifier();
		boolean moderated = ((HashMap) ctx.get("Form")).get("MODERATED") != null && ((HashMap) ctx.get("Form")).get("MODERATED").toString().equals("true");
		String keywords = (String) ((HashMap) ctx.get("Form")).get("RELATED_TITLES");
		String pageName = getWikiPageName(_wiki, ctx);

		// make sure the page wasn't modified by somebody else
		// System.out.println("==================" + (String) ((HashMap) ctx.get("Form")).get("VERSION"));
		long version = Long.parseLong((String) ((HashMap) ctx.get("Form")).get("VERSION"));
		if (version != page.getVersion())
			throw new ConcurrentModificationException(text);

		page.addEditor(editor);
		page.setUnparsedData(text);
		page.setIsModerated(moderated);
		page.setRelatedTitles(keywordsToStringArray(keywords));

		storeattachments(ctx, page, pageName);

		// parse the page and save it
		wiki.parsePage(page);
		wiki.savePage(page);
	}

	private synchronized void storeattachments(WebContext ctx, WikiPage page, String pageName) throws Exception {
		String dir = _wiki.getProperties().getProperty ("PageStore.Attachments").trim();
		File f = new File(dir);
		if(!f.canRead()) { f.mkdir(); }
		List attachments = (List) ctx.get("PageAttachments");
		for (Iterator iterator = attachments.iterator(); iterator.hasNext();) {
			FileItem item = (FileItem) iterator.next();
			WikiAttachment wa = new WikiAttachment(item.getName(), item.getContentType(), item.getName(), pageName);
			page.addAttachment( wa );
			item.write(new File(dir + wa.getIdentifier()));
		}
	}

	private String[] keywordsToStringArray(String input) {
		List titles = new ArrayList();
		StringTokenizer st = new StringTokenizer(input);
		StringBuffer keyword = new StringBuffer();
		while (st.hasMoreElements()) {
			String tmp = (String) st.nextElement();
			int size = tmp.length();
			for (int x = 0; x < size; x++) {
				char ch = tmp.charAt(x);
				if (Character.isLetterOrDigit(ch))
					keyword.append(ch);
			}
			titles.add(keyword.toString());
			keyword.setLength(0);
		}

		return (String[]) titles.toArray(new String[0]);
	}

	/**
     * stuff the context with objects required by most templates
	 * @param user 
     */
    public void stuffContext (WebContext wc, WikiPage page, WikiUser user, String pageName) {
        wc.put ("Wiki", _wiki);
        wc.put ("WikiUtil", WikiUtil.getInstance());
        wc.put ("Renderer", _wiki.getPageRenderer());
        wc.put ("Page", page);
        wc.put ("User", user);
        wc.put ("PageName", pageName);
    }

    /**
     * @return a WikiUser object from cookie.  null if no cookie or if user not found
     */
    private WikiUser getUser (WebContext wc) {
        try {
            Cookie cookie = wc.getCookie(_wiki.getProperties().getProperty ("CookieName").trim());
            String uid = null;
            String password = null;
            
            if (cookie != null) {
                String val = cookie.getValue();
                int idx = val.indexOf('|');
                uid = val.substring(0, idx);
                password = val.substring(idx+1);
            }
            
            WikiUser user = (WikiUser) ((uid == null) ? null : _wiki.getUser(uid));
            if (user != null) {
                // update the last accessed attribute for this user
                user.setAttribute("LastAccessed", new Date().toString());
                user.setAttribute("IPAddress", wc.getRequest().getRemoteAddr());
            }
            
            return user;
        }
        catch (Exception e) {
            return null;
        }
    }
}

--------------080607050302090403090509
Content-Type: text/x-java;
 name="WikiServlet.java"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
 filename="WikiServlet.java"

/**
 * The contents of this file are subject to the Mozilla Public
 * License Version 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS
 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
 * implied. See the License for the specific language governing
 * rights and limitations under the License.
 *
 * The Original Code is Wiki.
 *
 * The Initial Developer of the Original Code is Technology Concepts
 * and Design, Inc.
 * Copyright (C) 2000 Technology Concepts and Design, Inc.  All
 * Rights Reserved.
 *
 * Contributor(s): Lane Sharman (OpenDoors Software)
 *                 Justin Wells (Semiotek Inc.)
 *                 Eric B. Ridge (Technology Concepts and Design, Inc.)
 *
 * Alternatively, the contents of this file may be used under the
 * terms of the GNU General Public License Version 2 or later (the
 * "GPL"), in which case the provisions of the GPL are applicable
 * instead of those above.  If you wish to allow use of your
 * version of this file only under the terms of the GPL and not to
 * allow others to use your version of this file under the MPL,
 * indicate your decision by deleting the provisions above and
 * replace them with the notice and other provisions required by
 * the GPL.  If you do not delete the provisions above, a recipient
 * may use your version of this file under either the MPL or the
 * GPL.
 *
 *
 * This product includes sofware developed by OpenDoors Software.
 *
 * This product includes software developed by Justin Wells and Semiotek Inc.
 * for use in the WebMacro ServletFramework (http://www.webmacro.org).
 */

package org.tcdi.opensource.wiki.servlet;

import javax.servlet.http.*;
import javax.servlet.*;

import java.util.*;
import java.io.*;

import org.webmacro.*;
import org.webmacro.servlet.*;

import org.tcdi.opensource.wiki.*;

/**
 * The main servlet for Wiki
 *
 * @author Eric B. Ridge
 */
public class WikiServlet extends WMServlet {

    private static String COOKIE_NAME;
    private static long COOKIE_TIMEOUT;
    
    /** a log we can use */
    private Log _log;

    /** the Wiki instance we're to use */
    private static WikiSystem _wiki;
    
    /** the PageActionManager we should use for each page request */
    private PageActionManager _actionManager;

    public WebMacro initWebMacro() throws InitException {
        return super.initWebMacro();    //To change body of overriden methods use Options | File Templates.
    }

    /**
     * do necessary statup work like creating a Log and configuring
     * the various options of WikiServet
     */
    public void start () throws ServletException {
        super.start ();
        _log = this.getLog ("WikiServlet");

        try {
            configure();
        } catch (Exception e) {
            throw new ServletException (e);
        }      
    }
    
    
    /**
     * Respond to a request by getting the proper PageAction from
     * our PageActionManager
     */
    public final Template handle(WebContext wc) throws HandlerException {
        String pageName = null;
        WikiPage wikiPage = null;

        // who is trying to do something?
        WikiUser user = getUser (wc);
        
        // which action wants to respond to this request?
        PageAction action = _actionManager.getAction (wc, user);
        
        
        // use the action to determine which WikiPage
        // we should be dealing with
        if (action != null)
            pageName = action.getWikiPageName (_wiki, wc);
        if (pageName != null)
            wikiPage = _wiki.getPage (pageName);

        // stuff the webcontext with useful stuff
        stuffContext (wc, wikiPage, user, pageName);
        
        //Query the wiki system for a redirect page
        //in case we are running in private mode or
        //approved mode. 
        //todo: Capture one time the first requested page
        //so that on a successful login, the user is taken
        //there instead of the default home page.
        String redirectURL = _wiki.authorizeAction(user, action, pageName);
        if (redirectURL != null)
        {
           try {
               wc.getResponse().sendRedirect (redirectURL);
           }
           catch (IOException ioe) {
               throw new HandlerException ("Cannot redirect to " 
                               + redirectURL, ioe);
           }
           return null;
        }
        
        if (action == null)
            throw new HandlerException ("Unable to find a PageAction to handle"
                                      + " this request.");
        try {
            // attempt to perform the action against the page
            action.perform (_wiki, wc, user, wikiPage);
        } catch (PageAction.RedirectException re) {
            // action wants us to redirect somewhere else
            try {
                wc.getResponse().sendRedirect (re.getURL());
            } catch (IOException ioe) {
                throw new HandlerException ("Cannot redirect to " 
                                          + re.getURL(), ioe);
            }
            return null;
        } catch (Exception e) {
            // something bad happened while performing the action
            // TODO: Handle error and error template ourselves
            log("Error handling request", e);
            throw new HandlerException (e.toString());
        } finally {
            if (user != null)
                _wiki.updateUser(user);
        }


        // the action performed successfully, so now return 
        // the template it wants us to use
        try {
            // determine the template name and return
            String templateName = action.getTemplateName(_wiki, wikiPage);
            return getTemplate (templateName);

        } catch (ResourceException re) {
            throw new HandlerException ("Could not get template", re);
        }
    }
    
    
    /**
     * @return a WikiUser object from cookie.  null if no cookie or if user not found
     */
    private WikiUser getUser (WebContext wc) {
        try {
            Cookie cookie = wc.getCookie(COOKIE_NAME);
            String uid = null;
            String password = null;
            
            if (cookie != null) {
                String val = cookie.getValue();
                int idx = val.indexOf('|');
                uid = val.substring(0, idx);
                password = val.substring(idx+1);
            }
            
            WikiUser user = (WikiUser) ((uid == null) ? null : _wiki.getUser(uid));
            if (user != null) {
                // update the last accessed attribute for this user
                user.setAttribute("LastAccessed", new Date().toString());
                user.setAttribute("IPAddress", wc.getRequest().getRemoteAddr());
            }
            
            return user;
        }
        catch (Exception e) {
            return null;
        }
    }
    
    /**
     * stuff the context with objects required by most templates
     */
    private void stuffContext (WebContext wc, WikiPage page, WikiUser user, String pageName) {
        wc.put ("Wiki", _wiki);
        wc.put ("WikiUtil", WikiUtil.getInstance());
        wc.put ("Renderer", _wiki.getPageRenderer());
        wc.put ("Page", page);
        wc.put ("User", user);
        wc.put ("PageName", pageName);
    }
    
    /**
     * do one-time intialization/configuration
     */
    private void configure () throws Exception {
        _wiki = new Wiki (this.getInitParameter ("properties"));
        
        _actionManager = new PageActionManager (_wiki, _log);
        COOKIE_NAME = _wiki.getProperties().getProperty ("CookieName").trim();
        COOKIE_TIMEOUT = Long.parseLong (_wiki.getProperties().getProperty ("CookieTimeout").trim());
        _log.notice ("Wiki configured successfully");
        
        boolean reindex = _wiki.getProperties().getProperty ("ReIndex") != null
                       && _wiki.getProperties().getProperty ("ReIndex").equalsIgnoreCase ("true");
        if (reindex) 
            _wiki.indexCurrentPages();        
    }

    public static WikiSystem getInstance() {
        return _wiki;
    }

}

--------------080607050302090403090509
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
--------------080607050302090403090509
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

_______________________________________________
Webmacro-user mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/webmacro-user

--------------080607050302090403090509--