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.wiki.ajax.WikiAjaxServlet;
022import org.apache.wiki.api.core.Context;
023import org.apache.wiki.api.exceptions.PluginException;
024import org.apache.wiki.api.plugin.Plugin;
025import org.apache.wiki.util.TextUtil;
026
027import jakarta.servlet.ServletException;
028import jakarta.servlet.http.HttpServletRequest;
029import jakarta.servlet.http.HttpServletResponse;
030import java.io.IOException;
031import java.util.List;
032import java.util.Map;
033
034/**
035 * @since 2.10.2-svn10
036 *
037 * updated according to https://issues.apache.org/jira/browse/JSPWIKI-1195
038 */
039
040public class SampleAjaxPlugin implements Plugin, WikiAjaxServlet {
041    
042    private static final String SERVLET_MAPPING = "SampleAjaxPlugin";
043
044    @Override
045    public String execute( final Context context, final Map<String, String> params) throws PluginException {
046            var id = Long.toString(System.currentTimeMillis());
047
048        var url = "/" + SERVLET_MAPPING + "/ajaxAction";
049
050        var ajaxParams = jsStringEscape( params.get("params") );
051
052        var js = String.format("$('result%s').value='Loading…';"+
053            "var token = Wiki.CsrfProtection;"+
054            "new Request.HTML({"+
055                "url: Wiki.JsonUrl + '%s', "+
056                "update:$('result%s'),"+
057                "onSuccess: function(data){console.log('Success',data);},"+
058                "onError: function(err){console.log('Error',err);}"+
059            "}).post('params=%s&X-XSRF-TOKEN='+token)", id, url, id, ajaxParams);
060
061        return String.format("<div onclick='%s' style='color: blue; cursor: pointer'>Press Me</div><div id='result%s'></div>", js, id);
062    }
063
064    /**
065     * Escapes a value for safe embedding inside a single-quoted javascript string that itself
066     * lives inside a single-quoted HTML event-handler attribute: every character other than an
067     * ASCII letter or digit is emitted as a javascript unicode escape, so the result can
068     * terminate neither the enclosing javascript string nor the enclosing attribute.
069     *
070     * @param s the raw parameter value, may be {@code null}.
071     * @return the escaped value, or an empty string if {@code s} was {@code null}.
072     */
073    static String jsStringEscape( final String s ) {
074        if( s == null ) {
075            return "";
076        }
077        final StringBuilder sb = new StringBuilder( s.length() );
078        for( int i = 0; i < s.length(); i++ ) {
079            final char c = s.charAt( i );
080            if( ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) || ( c >= '0' && c <= '9' ) ) {
081                sb.append( c );
082            } else {
083                sb.append( String.format( "\\u%04x", ( int )c ) );
084            }
085        }
086        return sb.toString();
087    }
088
089    @Override
090    public String getServletMapping() {
091        return SERVLET_MAPPING;
092    }
093
094    @Override
095    public void service( final HttpServletRequest request, final HttpServletResponse response, final String actionName, final List< String > params )
096            throws ServletException, IOException {
097        try {
098            Thread.sleep( 5000 ); // Wait 5 seconds
099        } catch( final Exception e ) {
100        }
101        response.getWriter().print( "You called! actionName=" + TextUtil.replaceEntities( actionName )
102                + " params=" + TextUtil.replaceEntities( String.valueOf( params ) ) );
103    }
104
105}