translatorreader.java

来自「JSPWiki,100%Java开发的一套完整WIKI程序」· Java 代码 · 共 2,275 行 · 第 1/5 页

JAVA
2,275
字号
        for( Iterator i = list.iterator(); i.hasNext(); )        {            StringTransmutator m = (StringTransmutator) i.next();            text = m.mutate( m_context, text );        }        return text;    }    private void callHeadingListenerChain( Heading param )    {        List list = m_headingListenerChain;        for( Iterator i = list.iterator(); i.hasNext(); )        {            HeadingListener h = (HeadingListener) i.next();                        h.headingAdded( m_context, param );        }    }    /**     *  Write a HTMLized link depending on its type.     *  The link mutator chain is processed.     *     *  @param type Type of the link.     *  @param link The actual link.     *  @param text The user-visible text for the link.     */    public String makeLink( int type, String link, String text )    {        if( text == null ) text = link;        text = callMutatorChain( m_linkMutators, text );        return m_renderer.makeLink( type, link, text );    }        /**     *  Just like makeLink, but also adds the section reference (#sect...)     */    private String makeLink( int type, String link, String text, String sectref )    {        if( text == null ) text = link;        text = callMutatorChain( m_linkMutators, text );        return m_renderer.makeLink( type, link, text, sectref );    }    /**     *  Cleans a Wiki name.     *  <P>     *  [ This is a link ] -&gt; ThisIsALink     *     *  @param link Link to be cleared. Null is safe, and causes this to return null.     *  @return A cleaned link.     *     *  @since 2.0     */    public static String cleanLink( String link )    {        StringBuffer clean = new StringBuffer();        if( link == null ) return null;        //        //  Compress away all whitespace and capitalize        //  all words in between.        //        StringTokenizer st = new StringTokenizer( link, " -" );        while( st.hasMoreTokens() )        {            StringBuffer component = new StringBuffer(st.nextToken());            component.setCharAt(0, Character.toUpperCase( component.charAt(0) ) );            //            //  We must do this, because otherwise compiling on JDK 1.4 causes            //  a downwards incompatibility to JDK 1.3.            //            clean.append( component.toString() );        }        //        //  Remove non-alphanumeric characters that should not        //  be put inside WikiNames.  Note that all valid        //  Unicode letters are considered okay for WikiNames.        //  It is the problem of the WikiPageProvider to take        //  care of actually storing that information.        //        for( int i = 0; i < clean.length(); i++ )        {            char ch = clean.charAt(i);            if( !(Character.isLetterOrDigit(ch) ||                  PUNCTUATION_CHARS_ALLOWED.indexOf(ch) != -1 ))            {                clean.deleteCharAt(i);                --i; // We just shortened this buffer.            }        }        return clean.toString();    }    /**     *  Figures out if a link is an off-site link.  This recognizes     *  the most common protocols by checking how it starts.     */    // FIXME: Should really put the external link types to a sorted set,    //        then searching for them would be faster.    private boolean isExternalLink( String link )    {        for( int i = 0; i < c_externalLinks.length; i++ )        {            if( link.startsWith( c_externalLinks[i] ) ) return true;        }        return false;    }    /**     *  Returns true, if the link in question is an access     *  rule.     */    private static boolean isAccessRule( String link )    {        return link.startsWith("{ALLOW") || link.startsWith("{DENY");    }    /**     *  Matches the given link to the list of image name patterns     *  to determine whether it should be treated as an inline image     *  or not.     */    private boolean isImageLink( String link )    {        for( Iterator i = m_inlineImagePatterns.iterator(); i.hasNext(); )        {            if( m_inlineMatcher.matches( link, (Pattern) i.next() ) )                return true;        }        return false;    }    private static boolean isMetadata( String link )    {        return link.startsWith("{SET");    }    /**     *  Returns true, if the argument contains a number, otherwise false.     *  In a quick test this is roughly the same speed as Integer.parseInt()     *  if the argument is a number, and roughly ten times the speed, if     *  the argument is NOT a number.     */    private boolean isNumber( String s )    {        if( s == null ) return false;        if( s.length() > 1 && s.charAt(0) == '-' )            s = s.substring(1);        for( int i = 0; i < s.length(); i++ )        {            if( !Character.isDigit(s.charAt(i)) )                return false;        }        return true;    }    /**     *  Checks for the existence of a traditional style CamelCase link.     *  <P>     *  We separate all white-space -separated words, and feed it to this     *  routine to find if there are any possible camelcase links.     *  For example, if "word" is "__HyperLink__" we return "HyperLink".     *     *  @param word A phrase to search in.     *  @return The match within the phrase.  Returns null, if no CamelCase     *          hyperlink exists within this phrase.     */    private String checkForCamelCaseLink( String word )    {        PatternMatcherInput input;        input = new PatternMatcherInput( word );        if( m_matcher.contains( input, m_camelCasePtrn ) )        {            MatchResult res = m_matcher.getMatch();              int start = res.beginOffset(2);            int end   = res.endOffset(2);            String link = res.group(2);            if( res.group(1) != null )            {                if( res.group(1).equals("~") ||                    res.group(1).indexOf('[') != -1 )                {                    // Delete the (~) from beginning.                    // We'll make '~' the generic kill-processing-character from                    // now on.                    return null;                }            }            return link;        } // if match        return null;    }    /**     *  When given a link to a WikiName, we just return     *  a proper HTML link for it.  The local link mutator     *  chain is also called.     */    private String makeCamelCaseLink( String wikiname )    {        String matchedLink;        String link;        callMutatorChain( m_localLinkMutatorChain, wikiname );        if( (matchedLink = linkExists( wikiname )) != null )        {            link = makeLink( READ, matchedLink, wikiname );        }        else        {            link = makeLink( EDIT, wikiname, wikiname );        }        return link;    }    private String makeDirectURILink( String url )    {        String last = "";        String result;        if( url.endsWith(",") || url.endsWith(".") )        {            last = url.substring( url.length()-1 );            url  = url.substring( 0, url.length()-1 );        }        callMutatorChain( m_externalLinkMutatorChain, url );        if( isImageLink( url ) )        {            result = handleImageLink( url, url, false );        }        else        {            result = makeLink( EXTERNAL, url, url ) + m_renderer.outlinkImage();        }        result += last;        return result;    }    /**     *  Image links are handled differently:     *  1. If the text is a WikiName of an existing page,     *     it gets linked.     *  2. If the text is an external link, then it is inlined.       *  3. Otherwise it becomes an ALT text.     *     *  @param reallink The link to the image.     *  @param link     Link text portion, may be a link to somewhere else.     *  @param hasLinkText If true, then the defined link had a link text available.     *                  This means that the link text may be a link to a wiki page,     *                  or an external resource.     */        private String handleImageLink( String reallink, String link, boolean hasLinkText )    {        String possiblePage = cleanLink( link );        String matchedLink;        String res = "";        if( isExternalLink( link ) && hasLinkText )        {            res = makeLink( IMAGELINK, reallink, link );        }        else if( (matchedLink = linkExists( possiblePage )) != null &&                 hasLinkText )        {            // System.out.println("Orig="+link+", Matched: "+matchedLink);            callMutatorChain( m_localLinkMutatorChain, possiblePage );                        res = makeLink( IMAGEWIKILINK, reallink, link );        }        else        {            res = makeLink( IMAGE, reallink, link );        }        return res;    }    private String handleAccessRule( String ruleLine )    {        if( !m_parseAccessRules ) return "";        AccessControlList acl;        WikiPage          page = m_context.getPage();        UserManager       mgr  = m_context.getEngine().getUserManager();        if( ruleLine.startsWith( "{" ) )            ruleLine = ruleLine.substring( 1 );        if( ruleLine.endsWith( "}" ) )            ruleLine = ruleLine.substring( 0, ruleLine.length() - 1 );        log.debug("page="+page.getName()+", ACL = "+ruleLine);                try        {            acl = PageAuthorizer.parseAcl( page, mgr, ruleLine );            page.setAcl( acl );            log.debug( acl.toString() );        }        catch( WikiSecurityException wse )        {            return m_renderer.makeError( wse.getMessage() );        }        return "";    }    /**     *  Handles metadata setting [{SET foo=bar}]     */    private String handleMetadata( String link )    {        try        {            String args = link.substring( link.indexOf(' '), link.length()-1 );                        String name = args.substring( 0, args.indexOf('=') );            String val  = args.substring( args.indexOf('=')+1, args.length() );            name = name.trim();            val  = val.trim();            if( val.startsWith("'") ) val = val.substring( 1 );            if( val.endsWith("'") )   val = val.substring( 0, val.length()-1 );            // log.debug("SET name='"+name+"', value='"+val+"'.");            if( name.length() > 0 && val.length() > 0 )            {                m_context.getPage().setAttribute( name, val );            }        }        catch( Exception e )        {            m_renderer.makeError(" Invalid SET found: "+link);        }        return "";    }    /**     *  Gobbles up all hyperlinks that are encased in square brackets.     */    private String handleHyperlinks( String link )    {        StringBuffer sb        = new StringBuffer();        String       reallink;        int          cutpoint;        if( isAccessRule( link ) )        {            return handleAccessRule( link );        }        if( isMetadata( link ) )        {            return handleMetadata( link );        }        if( PluginManager.isPluginLink( link ) )        {            String included = "";            try            {                if( m_enablePlugins )                {                    included = m_engine.getPluginManager().execute( m_context, link );                }            }            catch( PluginException e )            {                log.info( "Failed to insert plugin", e );                log.info( "Root cause:",e.getRootThrowable() );                included = m_renderer.makeError("Plugin insertion failed: "+e.getMessage());            }                                        sb.append( included );            return sb.toString();        }        link = TextUtil.replaceEntities( link );        if( (cutpoint = link.indexOf('|')) != -1 )        {                                reallink = link.substring( cutpoint+1 ).trim();            link = link.substring( 0, cutpoint );        }        else        {            reallink = link.trim();        }        int interwikipoint = -1;        //        //  Yes, we now have the components separated.        //  link     = the text the link should have        //  reallink = the url or page name.        //        //  In many cases these are the same.  [link|reallink].        //          if( VariableManager.isVariableLink( link ) )        {            String value;                        try            {                value = m_engine.getVariableManager().parseAndGetValue( m_context, link );            }            catch( NoSuchVariableException e )            {                value = m_renderer.makeError(e.getMessage());            }            catch( IllegalArgumentException e )

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?