Search in sources :

Example 6 with WikiException

use of org.apache.wiki.api.exceptions.WikiException in project jspwiki by apache.

the class AttachmentServlet method executeUpload.

/**
 * @param context the wiki context
 * @param data the input stream data
 * @param filename the name of the file to upload
 * @param errorPage the place to which you want to get a redirection
 * @param parentPage the page to which the file should be attached
 * @param changenote The change note
 * @param contentLength The content length
 * @return <code>true</code> if upload results in the creation of a new page;
 * <code>false</code> otherwise
 * @throws RedirectException If the content needs to be redirected
 * @throws IOException       If there is a problem in the upload.
 * @throws ProviderException If there is a problem in the backend.
 */
protected boolean executeUpload(WikiContext context, InputStream data, String filename, String errorPage, String parentPage, String changenote, long contentLength) throws RedirectException, IOException, ProviderException {
    boolean created = false;
    try {
        filename = AttachmentManager.validateFileName(filename);
    } catch (WikiException e) {
        // here we have the context available, so we can internationalize it properly :
        throw new RedirectException(Preferences.getBundle(context, InternationalizationManager.CORE_BUNDLE).getString(e.getMessage()), errorPage);
    }
    if (!context.hasAdminPermissions()) {
        if (contentLength > m_maxSize) {
            // FIXME: Does not delete the received files.
            throw new RedirectException("File exceeds maximum size (" + m_maxSize + " bytes)", errorPage);
        }
        if (!isTypeAllowed(filename)) {
            throw new RedirectException("Files of this type may not be uploaded to this wiki", errorPage);
        }
    }
    Principal user = context.getCurrentUser();
    AttachmentManager mgr = m_engine.getAttachmentManager();
    log.debug("file=" + filename);
    if (data == null) {
        log.error("File could not be opened.");
        throw new RedirectException("File could not be opened.", errorPage);
    }
    // 
    // Check whether we already have this kind of a page.
    // If the "page" parameter already defines an attachment
    // name for an update, then we just use that file.
    // Otherwise we create a new attachment, and use the
    // filename given.  Incidentally, this will also mean
    // that if the user uploads a file with the exact
    // same name than some other previous attachment,
    // then that attachment gains a new version.
    // 
    Attachment att = mgr.getAttachmentInfo(context.getPage().getName());
    if (att == null) {
        att = new Attachment(m_engine, parentPage, filename);
        created = true;
    }
    att.setSize(contentLength);
    // 
    // Check if we're allowed to do this?
    // 
    Permission permission = PermissionFactory.getPagePermission(att, "upload");
    if (m_engine.getAuthorizationManager().checkPermission(context.getWikiSession(), permission)) {
        if (user != null) {
            att.setAuthor(user.getName());
        }
        if (changenote != null && changenote.length() > 0) {
            att.setAttribute(WikiPage.CHANGENOTE, changenote);
        }
        try {
            m_engine.getAttachmentManager().storeAttachment(att, data);
        } catch (ProviderException pe) {
            // here we have the context available, so we can internationalize it properly :
            throw new ProviderException(Preferences.getBundle(context, InternationalizationManager.CORE_BUNDLE).getString(pe.getMessage()));
        }
        log.info("User " + user + " uploaded attachment to " + parentPage + " called " + filename + ", size " + att.getSize());
    } else {
        throw new RedirectException("No permission to upload a file", errorPage);
    }
    return created;
}
Also used : WikiException(org.apache.wiki.api.exceptions.WikiException) ProviderException(org.apache.wiki.api.exceptions.ProviderException) Permission(java.security.Permission) Principal(java.security.Principal) RedirectException(org.apache.wiki.api.exceptions.RedirectException)

Example 7 with WikiException

use of org.apache.wiki.api.exceptions.WikiException in project jspwiki by apache.

the class GroupManager method initialize.

/**
 * Initializes the group cache by initializing the group database and
 * obtaining a list of all of the groups it stores.
 * @param engine the wiki engine
 * @param props the properties used to initialize the wiki engine
 * @see GroupDatabase#initialize(org.apache.wiki.WikiEngine,
 *      java.util.Properties)
 * @see GroupDatabase#groups()
 * @throws WikiSecurityException if GroupManager cannot be initialized
 */
public void initialize(WikiEngine engine, Properties props) throws WikiSecurityException {
    m_engine = engine;
    try {
        m_groupDatabase = getGroupDatabase();
    } catch (WikiException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    }
    // Load all groups from the database into the cache
    Group[] groups = m_groupDatabase.groups();
    synchronized (m_groups) {
        for (Group group : groups) {
            // Add new group to cache; fire GROUP_ADD event
            m_groups.put(group.getPrincipal(), group);
            fireEvent(WikiSecurityEvent.GROUP_ADD, group);
        }
    }
    // Make the GroupManager listen for WikiEvents (WikiSecurityEvents for changed user profiles)
    engine.getUserManager().addWikiEventListener(this);
    // Success!
    log.info("Authorizer GroupManager initialized successfully; loaded " + groups.length + " group(s).");
}
Also used : WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) WikiException(org.apache.wiki.api.exceptions.WikiException)

Example 8 with WikiException

use of org.apache.wiki.api.exceptions.WikiException in project jspwiki by apache.

the class PageRenamer method renamePage.

/**
 *  Renames a page.
 *
 *  @param context The current context.
 *  @param renameFrom The name from which to rename.
 *  @param renameTo The new name.
 *  @param changeReferrers If true, also changes all the referrers.
 *  @return The final new name (in case it had to be modified)
 *  @throws WikiException If the page cannot be renamed.
 */
public String renamePage(final WikiContext context, final String renameFrom, final String renameTo, final boolean changeReferrers) throws WikiException {
    // 
    if (renameFrom == null || renameFrom.length() == 0) {
        throw new WikiException("From name may not be null or empty");
    }
    if (renameTo == null || renameTo.length() == 0) {
        throw new WikiException("To name may not be null or empty");
    }
    // 
    // Clean up the "to" -name so that it does not contain anything illegal
    // 
    String renameToClean = MarkupParser.cleanLink(renameTo.trim());
    if (renameToClean.equals(renameFrom)) {
        throw new WikiException("You cannot rename the page to itself");
    }
    // 
    // Preconditions: "from" page must exist, and "to" page must not yet exist.
    // 
    WikiEngine engine = context.getEngine();
    WikiPage fromPage = engine.getPage(renameFrom);
    if (fromPage == null) {
        throw new WikiException("No such page " + renameFrom);
    }
    WikiPage toPage = engine.getPage(renameToClean);
    if (toPage != null) {
        throw new WikiException("Page already exists " + renameToClean);
    }
    // 
    // Options
    // 
    m_camelCase = TextUtil.getBooleanProperty(engine.getWikiProperties(), JSPWikiMarkupParser.PROP_CAMELCASELINKS, m_camelCase);
    Set<String> referrers = getReferencesToChange(fromPage, engine);
    // 
    // Do the actual rename by changing from the frompage to the topage, including
    // all of the attachments
    // 
    // Remove references to attachments under old name
    @SuppressWarnings("unchecked") Collection<Attachment> attachmentsOldName = engine.getAttachmentManager().listAttachments(fromPage);
    for (Attachment att : attachmentsOldName) {
        WikiPage fromAttPage = engine.getPage(att.getName());
        engine.getReferenceManager().pageRemoved(fromAttPage);
    }
    engine.getPageManager().getProvider().movePage(renameFrom, renameToClean);
    if (engine.getAttachmentManager().attachmentsEnabled()) {
        engine.getAttachmentManager().getCurrentProvider().moveAttachmentsForPage(renameFrom, renameToClean);
    }
    // 
    // Add a comment to the page notifying what changed.  This adds a new revision
    // to the repo with no actual change.
    // 
    toPage = engine.getPage(renameToClean);
    if (toPage == null)
        throw new InternalWikiException("Rename seems to have failed for some strange reason - please check logs!");
    toPage.setAttribute(WikiPage.CHANGENOTE, fromPage.getName() + " ==> " + toPage.getName());
    toPage.setAuthor(context.getCurrentUser().getName());
    engine.getPageManager().putPageText(toPage, engine.getPureText(toPage));
    // 
    // Update the references
    // 
    engine.getReferenceManager().pageRemoved(fromPage);
    engine.updateReferences(toPage);
    // 
    if (changeReferrers) {
        updateReferrers(context, fromPage, toPage, referrers);
    }
    // 
    // re-index the page including its attachments
    // 
    engine.getSearchManager().reindexPage(toPage);
    @SuppressWarnings("unchecked") Collection<Attachment> attachmentsNewName = engine.getAttachmentManager().listAttachments(toPage);
    for (Attachment att : attachmentsNewName) {
        WikiPage toAttPage = engine.getPage(att.getName());
        // add reference to attachment under new page name
        engine.updateReferences(toAttPage);
        engine.getSearchManager().reindexPage(att);
    }
    // Currently not used internally by JSPWiki itself, but you can use it for something else.
    WikiEventManager.fireEvent(this, new WikiPageRenameEvent(this, renameFrom, renameToClean));
    // 
    return renameToClean;
}
Also used : InternalWikiException(org.apache.wiki.InternalWikiException) WikiException(org.apache.wiki.api.exceptions.WikiException) WikiPage(org.apache.wiki.WikiPage) Attachment(org.apache.wiki.attachment.Attachment) WikiEngine(org.apache.wiki.WikiEngine) InternalWikiException(org.apache.wiki.InternalWikiException) WikiPageRenameEvent(org.apache.wiki.event.WikiPageRenameEvent)

Example 9 with WikiException

use of org.apache.wiki.api.exceptions.WikiException in project jspwiki by apache.

the class AtomAPIServlet method doPost.

/**
 *  Implements the PostURI of the Atom spec.
 *  <p>
 *  Implementation notes:
 *  <ul>
 *   <li>Only fetches the first content.  All other contents are ignored.
 *   <li>Assumes that incoming code is plain text or WikiMarkup, not html.
 *  </ul>
 *
 *  @param request {@inheritDoc}
 *  @param response {@inheritDoc}
 *  @throws ServletException {@inheritDoc}
 */
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    log.debug("Received POST to AtomAPIServlet");
    try {
        String blogid = getPageName(request);
        WikiPage page = m_engine.getPage(blogid);
        if (page == null) {
            throw new ServletException("Page " + blogid + " does not exist, cannot add blog post.");
        }
        // FIXME: Do authentication here
        Entry entry = Sandler.unmarshallEntry(request.getInputStream());
        // 
        // Fetch the obligatory parts of the content.
        // 
        Content title = entry.getTitle();
        Content content = entry.getContent(0);
        Person author = entry.getAuthor();
        // FIXME: Sandler 0.5 does not support generator
        // 
        // Generate new blog entry.
        // 
        WeblogEntryPlugin plugin = new WeblogEntryPlugin();
        String pageName = plugin.getNewEntryPage(m_engine, blogid);
        String username = author.getName();
        WikiPage entryPage = new WikiPage(m_engine, pageName);
        entryPage.setAuthor(username);
        WikiContext context = new WikiContext(m_engine, request, entryPage);
        StringBuilder text = new StringBuilder();
        text.append("!" + title.getBody());
        text.append("\n\n");
        text.append(content.getBody());
        log.debug("Writing entry: " + text);
        m_engine.saveText(context, text.toString());
    } catch (FeedMarshallException e) {
        log.error("Received faulty Atom entry", e);
        throw new ServletException("Faulty Atom entry", e);
    } catch (IOException e) {
        log.error("I/O exception", e);
        throw new ServletException("Could not get body of request", e);
    } catch (WikiException e) {
        log.error("Provider exception while posting", e);
        throw new ServletException("JSPWiki cannot save the entry", e);
    }
}
Also used : ServletException(javax.servlet.ServletException) Entry(org.intabulas.sandler.elements.Entry) WikiContext(org.apache.wiki.WikiContext) WikiException(org.apache.wiki.api.exceptions.WikiException) Content(org.intabulas.sandler.elements.Content) WikiPage(org.apache.wiki.WikiPage) FeedMarshallException(org.intabulas.sandler.exceptions.FeedMarshallException) IOException(java.io.IOException) WeblogEntryPlugin(org.apache.wiki.plugin.WeblogEntryPlugin) Person(org.intabulas.sandler.elements.Person)

Example 10 with WikiException

use of org.apache.wiki.api.exceptions.WikiException in project jspwiki by apache.

the class UserManager method setUserProfile.

/**
 * <p>
 * Saves the {@link org.apache.wiki.auth.user.UserProfile}for the user in
 * a wiki session. This method verifies that a user profile to be saved
 * doesn't collide with existing profiles; that is, the login name
 * or full name is already used by another profile. If the profile
 * collides, a <code>DuplicateUserException</code> is thrown. After saving
 * the profile, the user database changes are committed, and the user's
 * credential set is refreshed; if custom authentication is used, this means
 * the user will be automatically be logged in.
 * </p>
 * <p>
 * When the user's profile is saved successfully, this method fires a
 * {@link WikiSecurityEvent#PROFILE_SAVE} event with the WikiSession as the
 * source and the UserProfile as target. For existing profiles, if the
 * user's full name changes, this method also fires a "name changed"
 * event ({@link WikiSecurityEvent#PROFILE_NAME_CHANGED}) with the
 * WikiSession as the source and an array containing the old and new
 * UserProfiles, respectively. The <code>NAME_CHANGED</code> event allows
 * the GroupManager and PageManager can change group memberships and
 * ACLs if needed.
 * </p>
 * <p>
 * Note that WikiSessions normally attach event listeners to the
 * UserManager, so changes to the profile will automatically cause the
 * correct Principals to be reloaded into the current WikiSession's Subject.
 * </p>
 * @param session the wiki session, which may not be <code>null</code>
 * @param profile the user profile, which may not be <code>null</code>
 * @throws DuplicateUserException if the proposed profile's login name or full name collides with another
 * @throws WikiException if the save fails for some reason. If the current user does not have
 * permission to save the profile, this will be a {@link org.apache.wiki.auth.WikiSecurityException};
 * if if the user profile must be approved before it can be saved, it will be a
 * {@link org.apache.wiki.workflow.DecisionRequiredException}. All other WikiException
 * indicate a condition that is not normal is probably due to mis-configuration
 */
public void setUserProfile(WikiSession session, UserProfile profile) throws DuplicateUserException, WikiException {
    // Verify user is allowed to save profile!
    final Permission p = new WikiPermission(m_engine.getApplicationName(), WikiPermission.EDIT_PROFILE_ACTION);
    if (!m_engine.getAuthorizationManager().checkPermission(session, p)) {
        throw new WikiSecurityException("You are not allowed to save wiki profiles.");
    }
    // Check if profile is new, and see if container allows creation
    final boolean newProfile = profile.isNew();
    // Check if another user profile already has the fullname or loginname
    final UserProfile oldProfile = getUserProfile(session);
    final boolean nameChanged = (oldProfile == null || oldProfile.getFullname() == null) ? false : !(oldProfile.getFullname().equals(profile.getFullname()) && oldProfile.getLoginName().equals(profile.getLoginName()));
    UserProfile otherProfile;
    try {
        otherProfile = getUserDatabase().findByLoginName(profile.getLoginName());
        if (otherProfile != null && !otherProfile.equals(oldProfile)) {
            throw new DuplicateUserException("security.error.login.taken", profile.getLoginName());
        }
    } catch (final NoSuchPrincipalException e) {
    }
    try {
        otherProfile = getUserDatabase().findByFullName(profile.getFullname());
        if (otherProfile != null && !otherProfile.equals(oldProfile)) {
            throw new DuplicateUserException("security.error.fullname.taken", profile.getFullname());
        }
    } catch (final NoSuchPrincipalException e) {
    }
    // For new accounts, create approval workflow for user profile save.
    if (newProfile && oldProfile != null && oldProfile.isNew()) {
        final WorkflowBuilder builder = WorkflowBuilder.getBuilder(m_engine);
        final Principal submitter = session.getUserPrincipal();
        final Task completionTask = new SaveUserProfileTask(m_engine, session.getLocale());
        // Add user profile attribute as Facts for the approver (if required)
        final boolean hasEmail = profile.getEmail() != null;
        final Fact[] facts = new Fact[hasEmail ? 4 : 3];
        facts[0] = new Fact(PREFS_FULL_NAME, profile.getFullname());
        facts[1] = new Fact(PREFS_LOGIN_NAME, profile.getLoginName());
        facts[2] = new Fact(FACT_SUBMITTER, submitter.getName());
        if (hasEmail) {
            facts[3] = new Fact(PREFS_EMAIL, profile.getEmail());
        }
        final Workflow workflow = builder.buildApprovalWorkflow(submitter, SAVE_APPROVER, null, SAVE_DECISION_MESSAGE_KEY, facts, completionTask, null);
        workflow.setAttribute(SAVED_PROFILE, profile);
        m_engine.getWorkflowManager().start(workflow);
        final boolean approvalRequired = workflow.getCurrentStep() instanceof Decision;
        // If the profile requires approval, redirect user to message page
        if (approvalRequired) {
            throw new DecisionRequiredException("This profile must be approved before it becomes active");
        }
        try {
            final AuthenticationManager mgr = m_engine.getAuthenticationManager();
            if (newProfile && !mgr.isContainerAuthenticated()) {
                mgr.login(session, null, profile.getLoginName(), profile.getPassword());
            }
        } catch (final WikiException e) {
            throw new WikiSecurityException(e.getMessage(), e);
        }
        // Alert all listeners that the profile changed...
        // ...this will cause credentials to be reloaded in the wiki session
        fireEvent(WikiSecurityEvent.PROFILE_SAVE, session, profile);
    } else // For existing accounts, just save the profile
    {
        // If login name changed, rename it first
        if (nameChanged && oldProfile != null && !oldProfile.getLoginName().equals(profile.getLoginName())) {
            getUserDatabase().rename(oldProfile.getLoginName(), profile.getLoginName());
        }
        // Now, save the profile (userdatabase will take care of timestamps for us)
        getUserDatabase().save(profile);
        if (nameChanged) {
            // Fire an event if the login name or full name changed
            final UserProfile[] profiles = new UserProfile[] { oldProfile, profile };
            fireEvent(WikiSecurityEvent.PROFILE_NAME_CHANGED, session, profiles);
        } else {
            // Fire an event that says we have new a new profile (new principals)
            fireEvent(WikiSecurityEvent.PROFILE_SAVE, session, profile);
        }
    }
}
Also used : Task(org.apache.wiki.workflow.Task) WikiException(org.apache.wiki.api.exceptions.WikiException) UserProfile(org.apache.wiki.auth.user.UserProfile) DecisionRequiredException(org.apache.wiki.workflow.DecisionRequiredException) Workflow(org.apache.wiki.workflow.Workflow) DuplicateUserException(org.apache.wiki.auth.user.DuplicateUserException) Fact(org.apache.wiki.workflow.Fact) Decision(org.apache.wiki.workflow.Decision) WikiPermission(org.apache.wiki.auth.permissions.WikiPermission) Permission(java.security.Permission) AllPermission(org.apache.wiki.auth.permissions.AllPermission) WorkflowBuilder(org.apache.wiki.workflow.WorkflowBuilder) WikiPermission(org.apache.wiki.auth.permissions.WikiPermission) Principal(java.security.Principal)

Aggregations

WikiException (org.apache.wiki.api.exceptions.WikiException)15 Principal (java.security.Principal)5 IOException (java.io.IOException)3 WikiPage (org.apache.wiki.WikiPage)3 File (java.io.File)2 Permission (java.security.Permission)2 WikiContext (org.apache.wiki.WikiContext)2 FilterManager (org.apache.wiki.api.engine.FilterManager)2 FilterException (org.apache.wiki.api.exceptions.FilterException)2 NoRequiredPropertyException (org.apache.wiki.api.exceptions.NoRequiredPropertyException)2 ProviderException (org.apache.wiki.api.exceptions.ProviderException)2 RedirectException (org.apache.wiki.api.exceptions.RedirectException)2 GroupPrincipal (org.apache.wiki.auth.GroupPrincipal)2 WikiPrincipal (org.apache.wiki.auth.WikiPrincipal)2 UserProfile (org.apache.wiki.auth.user.UserProfile)2 DecisionRequiredException (org.apache.wiki.workflow.DecisionRequiredException)2 Test (org.junit.Test)2 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1