Package center.app.common

Source Code of center.app.common.HTTPQueryProcessor

package center.app.common;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import ru.vassaev.core.base.Null;
import ru.vassaev.core.exception.SysException;
import ru.vassaev.core.io.OutputByteBuffer;
import ru.vassaev.core.thread.Process;
import ru.vassaev.core.util.Strings;
import ru.vassaev.core.xml.XMLFileWaiter;
import center.task.AProcessor;
import center.task.CalculateException;
import center.task.Context;
import center.task.State;
import center.task.TaskException;
import center.task.prm.Type;
/**
* Процессор запроса данных по http
* @author Vassaev A.V.
* @version 1.1
*/
public class HTTPQueryProcessor extends AProcessor {
  private boolean need_send;
  private String urls;
  private String grp_in;
  private String grp_out;
  private Proxy proxy;
  private SocketAddress proxy_sa;

  public State paramsValidateAndPrepare(Context cntx) throws SysException {
    need_send = Strings.parseBoolean(cntx.getPrmNvl("need_send", "true"));
    if (!need_send)
      return State.DONE_OK;
    urls = cntx.getPrmString("url");
    if (Null.equ(urls))
        throw new SysException("Parameter \"url\" isn't set");
    grp_in = cntx.getPrmNvl("grp_in", "in");
    grp_out = cntx.getPrmNvl("grp_out", "out");
    String tpx = cntx.getPrmString("proxy_type");
    if (tpx == null)
      proxy = null;
    else {
      if (!"SOCKS".equals(tpx) && !"DIRECT".equals(tpx) && !"HTTP".equals(tpx))
        throw new SysException("Parameter \"proxy_type\" is incorrect. Use: DIRECT, SOCKS, HTTP");
      Proxy.Type type_proxy = Proxy.Type.valueOf(tpx);
      if (Proxy.Type.DIRECT.equals(type_proxy))
        proxy = null;
      else {
        String proxy_host = cntx.getPrmString("proxy_host");
        int proxy_port = cntx.getPrmNvl("proxy_port", 8080);
        proxy_sa = new InetSocketAddress(proxy_host, proxy_port);
        proxy = new Proxy(type_proxy, proxy_sa);
      }
    }
    return null;
  }
 
  public State process(Context cntx) throws TaskException, SysException, InterruptedException {
    State st = paramsValidateAndPrepare(cntx);
    if (st != null)
      return st;
    Process prc = Process.currentProcess();
    URL url = null;
    URLConnection con = null;
    try {
      url = new URL(urls);
      if (proxy != null) {
        con = url.openConnection(proxy);
      } else
        con = url.openConnection();
    } catch (MalformedURLException e) {
      throw new TaskException(State.DONE_ERR, e);
    } catch (IOException e) {
      throw new TaskException(State.DONE_ERR, e);
    }
    Map<String, Object> headers = cntx.getGroupParams(grp_in + ".header");
    String encode = cntx.getPrmNvl("charset", "UTF8");

    Object body = cntx.getPrmByFullName(grp_in + "/body");
    if (body != null) {
      long length = -1;
      con.setDoOutput(true);
      InputStream is = null;
      OutputByteBuffer obb = null;
      if (body instanceof InputStream) {
        try {
          obb = Process.getByteBuffer(8000, (InputStream) body);
          is = obb.getIS();
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else if (body instanceof OutputByteBuffer) {
        obb = (OutputByteBuffer)body;
        is = obb.getIS();
      } else if (body instanceof Element) {
        Element e = (Element) body;
        if (Strings.parseBooleanNvl(cntx.getPrmByFullName("skip-header-xml-body"), false)) {
          String n = e.getNodeName();
          try {
            obb = Process.getByteBuffer(8000, ("<"+n).getBytes(encode));
          } catch (UnsupportedEncodingException e1) {
            throw new TaskException(State.DONE_ERR, e1);
          }
        } else
          obb = Process.getByteBuffer(8000);
        XMLFileWaiter.putStream(e, obb, encode);
        try {
          obb.close();
          length = obb.getLength();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
        is = obb.getIS();
      } else if (body instanceof Document) {
        Document e = (Document) body;
        if (Strings.parseBooleanNvl(cntx.getPrmByFullName("skip-header-xml-body"), false)) {
          String n = e.getDocumentElement().getNodeName();
          try {
            obb = Process.getByteBuffer(8000, ("<"+n).getBytes(encode));
          } catch (UnsupportedEncodingException e1) {
            throw new TaskException(State.DONE_ERR, e1);
          }
        } else
          obb = Process.getByteBuffer(8000);
        XMLFileWaiter.putStream(e, obb, encode);
        try {
          obb.close();
          length = obb.getLength();
        } catch (IOException e1) {
          e1.printStackTrace();
        }
        is = obb.getIS();
      } else {
        String r = Strings.getString(body);
        byte[] b = null;
        try {
          b = r.getBytes(encode);
          length = b.length;
        } catch (UnsupportedEncodingException e) {
          throw new TaskException(State.DONE_ERR, e);
        }
        is = new ByteArrayInputStream(b);
      }
      System.out.println("=============Request=============");
      if (length >= 0) {
        prc.regResourceName(obb, "query.body.length");
        String n = "Content-Length";
        String v = Long.toString(length);
        con.addRequestProperty(n, v);
        System.out.println(((n == null) ? "" : n + ":") + v);
      }
      for(Map.Entry<String, Object> i : headers.entrySet()) {
        String n = i.getKey();
        n = n.substring((grp_in + ".header/").length());
        Object v = i.getValue();
        if (v != null) {
          if (v instanceof Type)
            try {
              v = ((Type)v).getValue(cntx);
            } catch (CalculateException e) {
              v = null;
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          con.addRequestProperty(n, Strings.getString(v));
          System.out.println(((n == null) ? "" : n + ":") + Strings.getString(v));
        } else
          con.setRequestProperty(n, null);
      }

      {
        int ch = 0;
        try {
          OutputStream os = con.getOutputStream();
          while((ch = is.read()) != -1) {
            System.out.print((char)ch);
            os.write(ch);
          }
          os.write("\r\n".getBytes());
          System.out.print("\r\n");
        } catch (IOException e) {
          throw new TaskException(State.DONE_ERR, e);
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }
    } else {
      for(Map.Entry<String, Object> i : headers.entrySet()) {
        String n = i.getKey();
        n = n.substring((grp_in + ".header/").length());
        Object v = i.getValue();
        if (v != null)
          con.addRequestProperty(n, Strings.getString(v));
        else
          con.setRequestProperty(n, null);
      }
    }

    System.out.println("=============Response=============");
    InputStream is = null;
    try {
      Map<String, List<String>> flds = con.getHeaderFields();
      for(Map.Entry<String, List<String>> fld : flds.entrySet()) {
        List<String> val = fld.getValue();
        StringBuffer sb = new StringBuffer();
        for(String v:val) { 
          sb.append(v).append("\r\n");
        }
        if (sb.length() > 0)
          sb.setLength(sb.length() - 2);
        String n = fld.getKey();
        System.out.println(((n == null)? "" : n + ":") + sb.toString());
        cntx.ta.setParamObject(cntx.id_task, grp_out+".header/" + fld.getKey(), sb.toString());
      }
      is = con.getInputStream();
      int l = con.getContentLength();
      int l_b = l >= 0 ? (l < 1024*1024 ? l : 1024*1024) : 8000;
      OutputByteBuffer obb = new OutputByteBuffer(l_b);
      obb.write(is);
      obb.close();
      prc.regResourceName(obb, "msg.body");
      if (Strings.parseBooleanNvl(cntx.getPrmString("save-out-body"), true)) {
        String fn = cntx.getPrmString("filename");
        if (fn == null)
          cntx.ta.setParamObject(cntx.id_task, grp_out + "/body", obb);
        else {
          File f = new File(fn);
          FileOutputStream fos = new FileOutputStream(f.getCanonicalPath());
          InputStream isb = obb.getIS();
          try {
            byte[] buf = new byte[l_b];
            int lr = 0;
            while ((lr = isb.read(buf)) > 0)
              fos.write(buf, 0, lr);
          } finally {
            isb.close();
            fos.close();
          }
          cntx.ta.setParamObject(cntx.id_task, grp_out + "/body", f);
        }
      }
     
    } catch (IOException e) {
      throw new TaskException(State.DONE_ERR, e);
    } finally {
      if (is != null)
        try {
          is.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
    return State.DONE_OK;
  }

  @Override
  public Set<String> dependentOn() {
    // TODO Auto-generated method stub
    return null;
  }

  @Override
  public Set<String> loopDependentOn() {
    // TODO Auto-generated method stub
    return null;
  }

}
TOP

Related Classes of center.app.common.HTTPQueryProcessor

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.