urltag.java

来自「jakarta-taglibs」· Java 代码 · 共 299 行

JAVA
299
字号
/*
 * Copyright 1999,2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.taglibs.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.Tag;

/** A JSP Custom tag to make a URL request and output the response.
  *
  * @author <a href="mailto:james.strachan@metastuff.com">James Strachan</a>
  * @version $Revision: 1.7 $
  */
public class URLTag extends AbstractTag implements PipeProducer, PipeConsumer {

    /** URL property to request */
    private String url;
    
    /** The current full URL including any <io:param> tags */
    private String fullURL;
    
    /** The encoding to use (defaults to JVM encoding) */
    private String encoding;
    
    /** URL connection */
    private URLConnection connection;
    
    /** Writer to output to */
    private Writer writer;
    
    /** Reader used as source of data written or POSTed to the URL */
    private Reader reader;
    
    /** Buffer used to pipe output to JSP writer */
    private byte[] buffer = new byte[ 32*1024 ];

    /** Whether or not we should read from the URL */
    private boolean output = true;

    /** Whether or not we should write to the URL */
    private boolean input = false;

    public URLTag() {
    }
    

    /** Adds a HTTP header to the current request 
      */
    public void addHeader( String name, String value ) throws JspException {
        if ( TRACE ) {
            log( "Setting header: " + name + ": " + value );
        }
        try {        
            getConnection().setRequestProperty( name, value );
        }
        catch (IOException e) {
            handleException(e);
        }
    }

    /** Adds a HTTP query parameter to the current url
      */
    public void addParameter( String name, String value ) {
        if ( fullURL == null ) {
            fullURL = url;
        }
        String prefix = ( fullURL.indexOf( '?' ) < 0 ) ? "?" : "&";
        fullURL += prefix + name + "=" + value;
        
        // XXXX: may wish to add some encoding code here...
        
        if ( TRACE ) {
            log( "Adding parameter: " + name + ": " + value );
            log( "URL is now: " + fullURL );
        }
    }

    
    // PipeProducer interface
    //-------------------------------------------------------------------------                        
    public void setWriter(Writer writer) {
        this.writer = writer;
    }
    
    // PipeConsumer interface
    //-------------------------------------------------------------------------                            
    public void setReader(Reader reader) {
        this.reader = reader;
        this.input = true;
    }

    
    // Tag interface
    //-------------------------------------------------------------------------                        
    public int doStartTag() throws JspException {
        fullURL = null;
        connection = null;
        return EVAL_BODY_INCLUDE;
    }
    
    public int doEndTag() throws JspException {
        Writer writer = null;
        try {
            if ( reader != null ) {
                writer = getURLWriter();
                PipeHelper.pipe( reader, writer );
                reader.close();
                writer.close();
            }
            if ( output ) {
                readURL();
            }
            else {
                getConnection().connect();
            }
        }
        catch (IOException e) {
            handleException(e);
        }
        finally {
            // we don't disconnect as our outer tag may read us after the doEndTag()
            // disconnect( connection );
            if ( writer != null ) {
                try {
                    writer.close();
                }
                catch (Exception e) {
                }
            }
            reader = null;
            writer = null;
        }
        return EVAL_PAGE;
    }
    
    public void release() {
        super.release();
        url = null;
        fullURL = null;
        connection = null;
        buffer = null;
        input = false;
        output = true;
        reader = null;
        writer = null;
    }
    
    
    // Properties
    //-------------------------------------------------------------------------                    
    public void setUrl(String url) {
        this.url = url;
    }
    
    public void setOutput(boolean output) {
        this.output = output;
    }
    
    public void setInput(boolean input) {
        this.input = input;
        
        //log( "input has been set to: " + this.input );
    }
    
    /** Sets the character encoding */
    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }
    
    public Writer getURLWriter() throws IOException {
        OutputStream out = getURLOutputStream();
        if ( out != null ) {
            if ( encoding != null ) {
                return new OutputStreamWriter( out, encoding );
            }
            else {
                return new OutputStreamWriter( out );
            }
        }
        return null;
    }
    
    public OutputStream getURLOutputStream() throws IOException {
        URLConnection connection = getConnection();
        return connection.getOutputStream();
    }

    public Reader getURLReader() throws IOException {
        InputStream in = getURLInputStream();
        if ( in != null ) {
            if ( encoding != null ) {
                return new InputStreamReader( in, encoding );
            }
            else {
                return new InputStreamReader( in );
            }
        }
        return null;
    }
    
    public InputStream getURLInputStream() throws IOException {
        URLConnection connection = getConnection();
        connection.connect();
        return connection.getInputStream();
    }

    
    // Implementation methods
    //-------------------------------------------------------------------------                    
    protected URLConnection getConnection() throws IOException {
        if ( connection == null ) {            
            if ( fullURL == null ) {
                fullURL = url;
            }
            URL theURL = URLHelper.createURL(fullURL, pageContext);
            
            if ( TRACE ) {
                log( "Reading URL: " + theURL.toString() );
            }
            
            connection = theURL.openConnection();
            configureConnection( connection );
        }
        return connection;
    }

    protected void configureConnection( URLConnection connection ) throws IOException {
        //log( "#### configureConnection(): output: " + output + " input: " + input );
        
        connection.setAllowUserInteraction(false);
        connection.setDoInput(output);
        connection.setDoOutput(input);
    }
    
    protected void disconnect( URLConnection connection ) {
        try {
            if ( connection instanceof HttpURLConnection ) {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.disconnect();
            }
        }
        catch (Exception e) {
            // ignore errors, we are just trying to close gracefully
        }
    }
    
    protected void readURL() throws IOException, JspException {
        Tag parent = getParent();
        if ( writer == null && parent instanceof PipeConsumer ) {
            PipeConsumer consumer = (PipeConsumer) parent;
            consumer.setReader( getURLReader() );
        }
        else {
            if ( writer == null ) {
                writer = pageContext.getOut();
            }
            Reader reader = getURLReader();
            try {
                PipeHelper.pipe( reader, writer );
            }
            finally {
                try {
                    reader.close();
                }
                catch (Exception e) {
                }
            }
        }
    }
}

⌨️ 快捷键说明

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