001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.plugin;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Context;
024import org.apache.wiki.api.core.Engine;
025import org.apache.wiki.api.core.Page;
026import org.apache.wiki.api.exceptions.PluginException;
027import org.apache.wiki.api.exceptions.RedirectException;
028import org.apache.wiki.api.exceptions.WikiException;
029import org.apache.wiki.api.plugin.Plugin;
030import org.apache.wiki.api.spi.Wiki;
031import org.apache.wiki.pages.PageManager;
032import org.apache.wiki.parser.MarkupParser;
033import org.apache.wiki.preferences.Preferences;
034import org.apache.wiki.util.Synchronizer;
035import org.apache.wiki.util.TextUtil;
036
037import java.io.PrintWriter;
038import java.io.StringWriter;
039import java.security.Principal;
040import java.text.MessageFormat;
041import java.text.SimpleDateFormat;
042import java.util.Date;
043import java.util.Map;
044import java.util.Properties;
045import java.util.ResourceBundle;
046import java.util.StringTokenizer;
047import java.util.concurrent.locks.ReentrantLock;
048
049/**
050 *  Provides a handler for bug reports.  Still under construction.
051 *
052 *  <p>Parameters : </p>
053 *  <ul>
054 *  <li><b>title</b> -  title of the bug, this is required.  If it is empty (as in "")  it is a signal to the handler to return quietly.</li>
055 *  <li><b>description</b> - description of the bug.</li>
056 *  <li><b>version</b> - version</li>
057 *  <li><b>map</b> - I have no idea </li>
058 *  <li><b>page</b> - The name of the page to be created for this bug report </li>
059 *  </ul>
060 *
061 */
062public class BugReportHandler implements Plugin {
063
064    private static final Logger LOG = LogManager.getLogger( BugReportHandler.class );
065    private static final String DEFAULT_DATEFORMAT = "dd-MMM-yyyy HH:mm:ss zzz";
066
067    /** Parameter name for setting the title.  Value is <tt>{@value}</tt>. */
068    public static final String PARAM_TITLE          = "title";
069    /** Parameter name for setting the description.  Value is <tt>{@value}</tt>. */
070    public static final String PARAM_DESCRIPTION    = "description";
071    /** Parameter name for setting the version.  Value is <tt>{@value}</tt>. */
072    public static final String PARAM_VERSION        = "version";
073    /** Parameter name for setting the map.  Value is <tt>{@value}</tt>. */
074    public static final String PARAM_MAPPINGS       = "map";
075    /** Parameter name for setting the page.  Value is <tt>{@value}</tt>. */
076    public static final String PARAM_PAGE           = "page";
077
078    /**
079     * A lock used to ensure thread safety when accessing shared resources.
080     * This lock provides more flexibility and capabilities than the intrinsic locking mechanism,
081     * such as the ability to attempt to acquire a lock with a timeout, or to interrupt a thread
082     * waiting to acquire a lock.
083     *
084     * @see java.util.concurrent.locks.ReentrantLock
085     */
086    private final ReentrantLock lock = new ReentrantLock();
087
088    /**
089     *  {@inheritDoc}
090     */
091    @Override
092    public String execute( final Context context, final Map< String, String > params ) throws PluginException {
093        final String title = params.get( PARAM_TITLE );
094        String description = params.get( PARAM_DESCRIPTION );
095        String version = params.get( PARAM_VERSION );
096        String submitter = null;
097        final SimpleDateFormat format = new SimpleDateFormat( DEFAULT_DATEFORMAT );
098        final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE );
099        final Principal wup = context.getCurrentUser();
100
101        if( wup != null ) {
102            submitter = wup.getName();
103        }
104
105        if( title == null ) {
106            throw new PluginException(rb.getString("bugreporthandler.titlerequired"));
107        }
108        if( title.isEmpty() ) {
109            return "";
110        }
111
112        if( description == null ) {
113            description = "";
114        }
115        if( version == null ) {
116            version = "unknown";
117        }
118
119        final Properties mappings = parseMappings( params.get( PARAM_MAPPINGS ) );
120
121        //  Start things
122        try {
123            final StringWriter str = new StringWriter();
124            final PrintWriter out = new PrintWriter( str );
125            final Date d = new Date();
126
127            //  Outputting of basic data
128            out.println( "|" + mappings.getProperty(PARAM_TITLE,"Title" ) + "|" + title );
129            out.println( "|" + mappings.getProperty("date","Date" ) + "|" + format.format( d ) );
130            out.println( "|" + mappings.getProperty(PARAM_VERSION,"Version" ) + "|" + version );
131            if( submitter != null ) {
132                out.println("|"+mappings.getProperty("submitter","Submitter") + "|" + submitter );
133            }
134
135            //  Outputting the other parameters added to this.
136            for( final Map.Entry< String, String > entry : params.entrySet() ) {
137                if( !( entry.getKey().equals( PARAM_TITLE ) ||
138                       entry.getKey().equals( PARAM_DESCRIPTION ) ||
139                       entry.getKey().equals( PARAM_VERSION ) ||
140                       entry.getKey().equals( PARAM_MAPPINGS ) ||
141                       entry.getKey().equals( PARAM_PAGE ) ||
142                       entry.getKey().startsWith( "_" )
143                     ) ) {
144                    //  If no mapping has been defined, just ignore it.
145                    final String head = mappings.getProperty( entry.getKey(), entry.getKey() );
146                    if( !head.isEmpty() ) {
147                        out.println( "|" + head + "|" + entry.getValue() );
148                    }
149                }
150            }
151
152            out.println();
153            out.println( description );
154            out.close();
155
156            //  Now create a new page for this bug report
157            final String pageName = findNextPage( context, title, TextUtil.replaceEntities(params.get( PARAM_PAGE )) );
158            final Page newPage = Wiki.contents().page( context.getEngine(), pageName );
159            final Context newContext = context.clone();
160            newContext.setPage( newPage );
161            context.getEngine().getManager( PageManager.class ).saveText( newContext, str.toString() );
162
163            final MessageFormat formatter = new MessageFormat("");
164            formatter.applyPattern( rb.getString("bugreporthandler.new") );
165            final String[] args = { "<a href=\""+context.getViewURL(pageName)+"\">"+pageName+"</a>" };
166
167            return formatter.format( args );
168        } catch( final RedirectException e ) {
169            LOG.info("Saving not allowed, reason: '"+e.getMessage()+"', can't redirect to "+e.getRedirect());
170            throw new PluginException("Saving not allowed, reason: "+e.getMessage());
171        } catch( final WikiException e ) {
172            LOG.error( "Unable to save page!", e );
173            return rb.getString("bugreporthandler.unable" );
174        }
175    }
176
177    /**
178     *  Finds a free page name for adding the bug report.  Tries to construct a page, and if it's found, adds a number to it
179     *  and tries again.
180     */
181    private String findNextPage( final Context context, final String title, final String baseName ) {
182        return Synchronizer.synchronize(lock, () -> {
183            final String basicPageName = ( ( baseName != null ) ? baseName : "Bug" ) + MarkupParser.cleanLink( title );
184            final Engine engine = context.getEngine();
185
186            String pageName = basicPageName;
187            long   lastbug  = 2;
188            while( engine.getManager( PageManager.class ).wikiPageExists( pageName ) ) {
189                pageName = basicPageName + lastbug++;
190            }
191            return pageName;
192        });
193    }
194
195    /**
196     *  Just parses a mappings list in the form of "a=b;b=c;c=d".
197     *  <p>
198     *  FIXME: Should probably be in TextUtil or somewhere.
199     */
200    private Properties parseMappings( final String mappings ) {
201        final Properties props = new Properties();
202        if( mappings == null ) {
203            return props;
204        }
205
206        final StringTokenizer tok = new StringTokenizer( mappings, ";" );
207        while( tok.hasMoreTokens() ) {
208            final String t = tok.nextToken();
209            final int colon = t.indexOf("=");
210            final String key;
211            final String value;
212
213            if( colon > 0 ) {
214                key = t.substring(0,colon);
215                value = t.substring(colon+1);
216            } else {
217                key = t;
218                value = "";
219            }
220
221            props.setProperty( key, value );
222        }
223        return props;
224    }
225
226}