urlmodule.java

来自「RESIN 3.2 最新源码」· Java 代码 · 共 961 行 · 第 1/2 页

JAVA
961
字号
/* * Copyright (c) 1998-2008 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT.  See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * *   Free Software Foundation, Inc. *   59 Temple Place, Suite 330 *   Boston, MA 02111-1307  USA * * @author Scott Ferguson */package com.caucho.quercus.lib;import com.caucho.quercus.annotation.Optional;import com.caucho.quercus.env.*;import com.caucho.quercus.lib.file.BinaryInput;import com.caucho.quercus.lib.file.BinaryStream;import com.caucho.quercus.lib.file.FileModule;import com.caucho.quercus.module.AbstractQuercusModule;import com.caucho.util.Base64;import com.caucho.util.CharBuffer;import com.caucho.util.L10N;import com.caucho.vfs.TempBuffer;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.Socket;import java.net.URL;import java.util.LinkedHashMap;import java.util.Map;import java.util.Set;import java.util.logging.Logger;/** * PHP URL */public class UrlModule extends AbstractQuercusModule {  private static final L10N L = new L10N(UrlModule.class);  private static final Logger log    = Logger.getLogger(UrlModule.class.getName());  /**   * Encodes base64   */  public static String base64_encode(InputStream is)  {    CharBuffer cb = new CharBuffer();    TempBuffer tb = TempBuffer.allocate();    byte []buffer = tb.getBuffer();    int len;    int offset = 0;        try {      while ((len = is.read(buffer, offset, buffer.length - offset)) >= 0) {        int tail = len % 3;        Base64.encode(cb, buffer, 0, len - tail);        System.arraycopy(buffer, len - tail, buffer, 0, tail);        offset = tail;      }      if (offset > 0)        Base64.encode(cb, buffer, 0, offset);    } catch (IOException e) {      throw new RuntimeException(e);    } finally {      TempBuffer.free(tb);    }    return cb.toString();  }  /**   * Decodes base64   */  public static String base64_decode(String str)  {    if (str == null)      return "";    return Base64.decode(str);  }  /**   * Connects to the given URL using a HEAD request to retreive   * the headers sent in the response.   */  public static Value get_headers(Env env, String urlString,                                  @Optional Value format)  {    Socket socket = null;    try {      URL url = new URL(urlString);      if (! url.getProtocol().equals("http") &&          ! url.getProtocol().equals("https")) {        env.warning(L.l("Not an HTTP URL"));        return null;      }      int port = 80;      if (url.getPort() < 0) {        if (url.getProtocol().equals("http"))          port = 80;        else if (url.getProtocol().equals("https"))          port = 443;      } else {        port = url.getPort();      }      socket = new Socket(url.getHost(), port);      OutputStream out = socket.getOutputStream();      InputStream in = socket.getInputStream();      StringBuilder request = new StringBuilder();      request.append("HEAD ");      if (url.getPath() != null)        request.append(url.getPath());      if (url.getQuery() != null)        request.append("?" + url.getQuery());      if (url.getRef() != null)        request.append("#" + url.getRef());      request.append(" HTTP/1.0\r\n");      if (url.getHost() != null)        request.append("Host: " + url.getHost() + "\r\n");      request.append("\r\n");      OutputStreamWriter writer = new OutputStreamWriter(out);      writer.write(request.toString());      writer.flush();      LineNumberReader reader = new LineNumberReader(new InputStreamReader(in));      ArrayValue result = new ArrayValueImpl();      if (format.toBoolean()) {        for (String line = reader.readLine();             line != null;             line = reader.readLine()) {          line = line.trim();          if (line.length() == 0)            continue;          int colon = line.indexOf(':');          ArrayValue values;          if (colon < 0)            result.put(env.createString(line.trim()));          else {            StringValue key =              env.createString(line.substring(0, colon).trim());            StringValue value;            if (colon < line.length())              value = env.createString(line.substring(colon + 1).trim());            else              value = env.getEmptyString();            if (result.get(key) != UnsetValue.UNSET)              values = (ArrayValue)result.get(key);            else {              values = new ArrayValueImpl();              result.put(key, values);            }            values.put(value);          }        }        // collapse single entries        for (Value key : result.keySet()) {          Value value = result.get(key);          if (value.isArray() && ((ArrayValue)value).getSize() == 1)            result.put(key, ((ArrayValue)value).get(LongValue.ZERO));        }      } else {        for (String line = reader.readLine();             line != null;             line = reader.readLine()) {          line = line.trim();          if (line.length() == 0)            continue;          result.put(env.createString(line.trim()));        }      }      return result;    } catch (Exception e) {      env.warning(e);      return BooleanValue.FALSE;    } finally {      try {        if (socket != null)          socket.close();      } catch (IOException e) {        env.warning(e);      }    }  }  /**   * Extracts the meta tags from a file and returns them as an array.   */  public static Value get_meta_tags(Env env, StringValue filename,                                    @Optional("false") boolean use_include_path)  {    InputStream in = null;    ArrayValue result = new ArrayValueImpl();    try {      BinaryStream stream	= FileModule.fopen(env, filename, "r", use_include_path, null);      if (stream == null || ! (stream instanceof BinaryInput))        return result;      BinaryInput input = (BinaryInput) stream;      while (! input.isEOF()) {        String tag = getNextTag(input);        if (tag.equalsIgnoreCase("meta")) {          String name = null;          String content = null;          String [] attr;          while ((attr = getNextAttribute(input)) != null) {            if (name == null && attr[0].equalsIgnoreCase("name")) {              if (attr.length > 1)                name = attr[1];            } else if (content == null && attr[0].equalsIgnoreCase("content")) {              if (attr.length > 1)                content = attr[1];            }            if (name != null && content != null) {              result.put(env.createString(name),                         env.createString(content));              break;            }          }        } else if (tag.equalsIgnoreCase("/head"))          break;      }    } catch (IOException e) {      env.warning(e);    } finally {      try {        if (in != null)          in.close();      } catch (IOException e) {        env.warning(e);      }    }    return result;  }    public static Value http_build_query(Env env,                                       Value formdata, 		                               @Optional StringValue numeric_prefix,		                               @Optional("'&'") StringValue separator)  {    StringValue result = env.createUnicodeBuilder();    httpBuildQueryImpl(env,                       result,                       formdata,                       env.getEmptyString(),                       numeric_prefix,                       separator);    return result;  }    private static void httpBuildQueryImpl(Env env,                                         StringValue result,                                         Value formdata,                                         StringValue path,                                         StringValue numeric_prefix,                                         StringValue separator)  {    Set<Map.Entry<Value,Value>> entrySet;    if (formdata.isArray())      entrySet = ((ArrayValue)formdata).entrySet();    else if (formdata.isObject()) {      Set<? extends Map.Entry<Value,Value>> stringEntrySet        = ((ObjectValue)formdata).entrySet();      LinkedHashMap<Value,Value> valueMap = new LinkedHashMap<Value,Value>();      for (Map.Entry<Value,Value> entry : stringEntrySet)        valueMap.put(entry.getKey(), entry.getValue());      entrySet = valueMap.entrySet();    } else {      env.warning(L.l("formdata must be an array or object"));      return;    }    boolean isFirst = true;    for (Map.Entry<Value,Value> entry : entrySet) {      if (! isFirst) {        if (separator != null)          result.append(separator);        else          result.append("&");      }      isFirst = false;            StringValue newPath = makeNewPath(path, entry.getKey(), numeric_prefix);      Value entryValue = entry.getValue();      if (entryValue.isArray() || entryValue.isObject()) {        // can always throw away the numeric prefix on recursive calls        httpBuildQueryImpl(env, result, entryValue, newPath, null, separator);      } else {        result.append(newPath);        result.append("=");        result.append(urlencode(entry.getValue().toStringValue()));      }    }  }  private static StringValue makeNewPath(StringValue oldPath,                                         Value key,                                         StringValue numeric_prefix)  {    StringValue path = oldPath.createStringBuilder();        if (oldPath.length() != 0) {      path.append(oldPath);      //path.append('[');      path.append("%5B");      urlencode(path, key.toStringValue());      //path.append(']');      path.append("%5D");      return path;    }    else if (key.isLongConvertible() && numeric_prefix != null) {      urlencode(path, numeric_prefix);      urlencode(path, key.toStringValue());            return path;    }    else {      urlencode(path, key.toStringValue());            return path;    }  }  /**   * Creates a http string.   */  /*  public String http_build_query(Value value,                                 @Optional String prefix)  {    StringBuilder sb = new StringBuilder();    int index = 0;    if (value instanceof ArrayValue) {      ArrayValue array = (ArrayValue) value;      for (Map.Entry<Value,Value> entry : array.entrySet()) {        Value keyValue = entry.getKey();        Value v = entry.getValue();        String key;        if (keyValue.isLongConvertible())          key = prefix + keyValue;        else          key = keyValue.toString();        if (v instanceof ArrayValue)          http_build_query(sb, key, (ArrayValue) v);        else {          if (sb.length() > 0)            sb.append('&');          sb.append(key);          sb.append('=');          urlencode(sb, v.toString());        }      }    }    return sb.toString();  }  */  /**   * Creates a http string.   */  /*  private void http_build_query(StringBuilder sb,                                String prefix,                                ArrayValue array)  {    for (Map.Entry<Value,Value> entry : array.entrySet()) {      Value keyValue = entry.getKey();      Value v = entry.getValue();      String key = prefix + '[' + keyValue + ']';      if (v instanceof ArrayValue)        http_build_query(sb, key, (ArrayValue) v);      else {        if (sb.length() > 0)          sb.append('&');        sb.append(key);        sb.append('=');        urlencode(sb, v.toString());      }    }  }  */  /**   * Parses the URL into an array.   */  public static Value parse_url(Env env, StringValue str)  {    if (str == null)      str = env.getEmptyString();    int i = 0;    int length = str.length();

⌨️ 快捷键说明

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