连接Http Server， 准备传送serialized-object

@param httpServerParam
@return
@throws java.lang.Exception
176379
public HttpURLConnection connectService(HttpServerParam httpServerParam, String userPassword) throws Exception {
		HttpURLConnection httpURLConnection = null;
		URL url = null;
		try {

			url = new URL("http", httpServerParam.getHost(), httpServerParam.getPort(), httpServerParam.getServletPath());

			Debug.logVerbose("[JdonFramework]Service url=" + url, module);

			httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setRequestMethod("POST");
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setUseCaches(false);
			httpURLConnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");

			if ((userPassword != null) && (!userPassword.equals("null"))) {
				String encoded = "Basic " + Base64.encodeBytes(userPassword.getBytes("UTF-8"));
				httpURLConnection.setRequestProperty("Authorization", encoded);
			}
		} catch (Exception ex) {
			Debug.logError("[JdonFramework] connectServer " + url + " error: " + ex, module);
			throw new Exception(ex);
		}
		return httpURLConnection;
	}
74549
protected void checkParameters() {
        // 检查注入的ref是否接口实现类
        Class proxyClass = providerConfig.getProxyClass();
        String key = providerConfig.buildKey();
        T ref = providerConfig.getRef();
        if (!proxyClass.isInstance(ref)) {
            throw ExceptionUtils.buildRuntime("provider.ref",
                ref == null ? "null" : ref.getClass().getName(),
                "This is not an instance of " + providerConfig.getInterfaceId()
                    + " in provider config with key " + key + " !");
        }
        // server 不能为空
        if (CommonUtils.isEmpty(providerConfig.getServer())) {
            throw ExceptionUtils.buildRuntime("server", "NULL", "Value of \"server\" is not specified in provider" +
                " config with key " + key + " !");
        }
        checkMethods(proxyClass);
    }
352331
@Bean
	public RemoteServiceCaller remoteServiceCaller(Optional<EasyTransRpcConsumer> optionalConsumer,
			@Lazy Optional<EasyTransMsgPublisher> optionalPublisher, ObjectSerializer serializer,
			QueueTopicMapper queueTopicMapper) {

		EasyTransRpcConsumer consumer = optionalConsumer.orElseGet(() -> new EasyTransRpcConsumer() {

			@Override
			public <P extends EasyTransRequest<R, ?>, R extends Serializable> R call(String appId, String busCode,
					String innerMethod, Map<String, Object> header, P params) {
				throw new RuntimeException("can not find EasyTransRpcConsumer implement but try handle rpc request");
			}

			@Override
			public <P extends EasyTransRequest<R, ?>, R extends Serializable> void callWithNoReturn(String appId,
					String busCode, String innerMethod, Map<String, Object> header, P params) {
				throw new RuntimeException("can not find EasyTransRpcConsumer implement but try handle rpc request");
			}
		});

		EasyTransMsgPublisher publisher = optionalPublisher.orElseGet(() -> new EasyTransMsgPublisher() {

			@Override
			public EasyTransMsgPublishResult publish(String topic, String tag, String key, Map<String, Object> header,
					byte[] msgByte) {
				throw new RuntimeException("can not find EasyTransMsgPublisher implement but try to publish a message");
			}
		});

		return new RemoteServiceCaller(consumer, publisher, serializer, queueTopicMapper);
	}
71745
@SuppressWarnings("UnusedParameters")
    protected String serialize(String serviceName, String id, Payload payload) {
        return String.valueOf(payload);
    }
1000044
@Singleton
    HttpServerHandler<HttpRequest<?>, HttpResponse<?>> httpServerHandler(HttpTracing httpTracing) {
        return HttpServerHandler.create(httpTracing, new HttpServerAdapter<HttpRequest<?>, HttpResponse<?>>() {
            @Override
            public String method(HttpRequest<?> request) {
                return request.getMethod().name();
            }

            @Override
            public String url(HttpRequest<?> request) {
                return request.getUri().toString();
            }

            @Override
            public String requestHeader(HttpRequest<?> request, String name) {
                return request.getHeaders().get(name);
            }

            @Override
            public Integer statusCode(HttpResponse<?> response) {
                return response.getStatus().getCode();
            }

            @Override
            public String route(HttpResponse<?> response) {
                Optional<String> value = response.getAttribute(HttpAttributes.URI_TEMPLATE, String.class);
                return value.orElseGet(() -> super.route(response));
            }

            @Override
            public String methodFromResponse(HttpResponse<?> httpResponse) {
                return httpResponse.getAttribute(HttpAttributes.METHOD_NAME, String.class).orElse(null);
            }

            @Override
            public boolean parseClientAddress(HttpRequest<?> httpRequest, Endpoint.Builder builder) {
                InetSocketAddress remoteAddress = httpRequest.getRemoteAddress();
                return builder.parseIp(remoteAddress.getAddress());
            }
        });
    }
1232745
public static void registerAllToHttpServer(HttpServer server) {
    server.createContext(tracezZPageHandler.getUrlPath(), new ZPageHttpHandler(tracezZPageHandler));
    server.createContext(
        traceConfigzZPageHandler.getUrlPath(), new ZPageHttpHandler(traceConfigzZPageHandler));
    server.createContext(rpczZpageHandler.getUrlPath(), new ZPageHttpHandler(rpczZpageHandler));
    server.createContext(statszZPageHandler.getUrlPath(), new ZPageHttpHandler(statszZPageHandler));
  }
874453
private void checkSerialize(final HttpServletRequest request) {
    String reqpar = request.getParameter("serialize");

    if (reqpar == null) {
      return;
    }

    HttpSession sess = request.getSession(false);
    Enumeration en = sess.getAttributeNames();

    while (en.hasMoreElements()) {
      String attrname = (String)en.nextElement();
      ObjectOutputStream oo = null;

      info("Attempt to serialize attr " + attrname);
      Object o = sess.getAttribute(attrname);

      try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        oo = new ObjectOutputStream(bo);
        oo.writeObject(o);
        oo.flush();

        info("Serialized object " + attrname + " has size: " + bo.size());
      } catch (Throwable t) {
        t.printStackTrace();
      } finally {
        if (oo != null) {
          try {
            oo.close();
          } catch (Throwable t) {}
        }
      }
    }
  }
579385
public static JSONObject getJSONObject(HttpPost request, Integer method, HashMap<String, String> params) throws JSONException {
        switch (method) {
        case METHOD_PUT:
        case METHOD_DELETE:
        case METHOD_POST:
            return doPostRequest(request, params);
        default:
            throw new RuntimeException("Wrong http method requested");
        }
    }
1311874
public void start() throws Exception {
        // verify server is NOT null
        if (server == null) {
            throw new NullPointerException("Internal server instance was null, server not configured perhaps?");
        }

        logger.info("HttpServer [{}] version [{}] using Jetty [{}]", configuration.safeGetName(), com.cloudhopper.jetty.Version.getLongVersion(),
		    server.getVersion());
        logger.info("HttpServer [{}] on [{}] starting...", configuration.safeGetName(), configuration.getPortString());

        // try to start jetty server -- if it fails, it'll actually keep running
        // so if an exception occurs, we'll make to stop it afterwards and rethrow the exception
        try {
            server.start();
        } catch (Exception e) {
            // make sure we stop the server
            try { this.stop(); } catch (Exception ex) { }
            throw e;
        }

        logger.info("HttpServer [{}] on [{}] started", configuration.safeGetName(), configuration.getPortString());
    }
588636
public void bindServer(HttpServletRequest request, HttpServletResponse response){
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(StrUtil.isBlank(getToken()) || StrUtil.isBlank(getAESKey()) || StrUtil.isBlank(getCropId())){
            pw.write("");
            pw.flush();
            pw.close();
        }
        try {
            WXBizMsgCrypt pc = new WXBizMsgCrypt(getToken(), getAESKey(), getCropId());
            String echoStr = pc.verifyUrl(request.getParameter("msg_signature"), request.getParameter("timestamp"), request.getParameter("nonce"), request.getParameter("echostr"));
            pw.write(echoStr);
            pw.flush();
            pw.close();
        } catch (AesException e) {
            e.printStackTrace();
            pw.write("");
            pw.flush();
            pw.close();
        }
    }
238176
private WebServer loadWebServer() {
        WebServer webServer = null;
        if (!Utils.isEmpty(getParamString("webserver_class"))) {
            try {
                Class<?> serviceClass = Class.forName(getParamString("webserver_class"));
                Method instanceMethod = serviceClass.getMethod("instance", (Class<?>[])null);
                webServer = (WebServer)instanceMethod.invoke(null, (Object[])null);
                webServer.init(RESTServlet.class.getName());
            } catch (Exception e) {
                throw new RuntimeException("Error initializing WebServer: " + getParamString("webserver_class"), e);
            }
        }
        return webServer;
    }
973204
public static Map<String, Object> getParametersMap(ContainerRequestContext requestContext,HttpServletRequest request)
			throws IOException {
		
		if(isMultipartContent(request)){
			return buildQueryParamsMap(request);
		}
		
		Map<String, Object> parameters = buildQueryParamsMap(request);
		
		if (RestConst.GET_METHOD.equals(request.getMethod())) {
			return parameters;
		}else if (RestConst.POST_METHOD.equals(request.getMethod())) {
			
			byte[] byteArray = IOUtils.toByteArray(requestContext.getEntityStream());
			//reset InputStream
			requestContext.setEntityStream(new ByteArrayInputStream(byteArray));
			
			if(byteArray == null || byteArray.length == 0)return parameters;
			String content = new String(byteArray);
			//JSON 
//			try {
//				return JsonUtils.toObject(content, Map.class);
//			} catch (Exception e) {}
			if(content.contains("{")){
				content = StringUtils.left(content, 2048).trim();
				if(!content.endsWith("}"))content = content + "...\n}";
				parameters.put("data", content);
				return parameters;
			}
			
			String[] split = content.split("\\&");
			for (String s : split) {
				String[] split2 = s.split("=");
				if (split2.length == 2 && StringUtils.isNotBlank(split2[1])) {
					parameters.put(split2[0], split2[1]);
				}
			}
			return parameters;
		
		}
		return null;
	}
608334
public static HttpResponse executePost(final String url,
                                           final String entity,
                                           final Map<String, Object> parameters) {
        return executePost(url, null, null, entity, parameters);
    }
197731
protected static String serialize(Serializable serializable) throws JMSException {
        if (serializable == null) {
            return null;
        }
        String serializedString;
        ObjectOutputStream objectOutputStream = null;
        try {
            ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(bytesOut);
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            serializedString = Base64.encodeAsString(bytesOut.toByteArray());
        } catch (IOException e) {
            LOG.error("IOException: cannot serialize objectMessage", e);
            throw convertExceptionToMessageFormatException(e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    LOG.warn(e.getMessage());
                }
            }
        }
        return serializedString;
    }
713618
HttpConnection asRequest() {
        DatabaseURIHelper builder = getViewURIBuilder();
        for (Map.Entry<String, Object> queryParameter : processParameters(Parameter.Type
                .QUERY_PARAMETER).entrySet()) {
            builder.query(queryParameter.getKey(), queryParameter.getValue());
        }
        Map<String, Object> parameters = processParameters(Parameter.Type.BODY_PARAMETER);
        // if there are no parameters in the body, we do a GET, otherwise we do a POST
        if (parameters == null || parameters.isEmpty()) {
            return Http.GET(builder.build());
        }
        JsonElement body = gson.toJsonTree(parameters);
        HttpConnection conn = Http.POST(builder.build(),  "application/json");
        conn.setRequestBody(body.toString());
        return conn;
    }
553546
@Override
    public final <RQ, RS> Maybe<Response<RS>> post(String resource, RQ rq, Type type)
            throws RestEndpointIOException {
        HttpPost post = new HttpPost(spliceUrl(resource));
        Serializer serializer = getSupportedSerializer(rq);
        ByteArrayEntity httpEntity = new ByteArrayEntity(serializer.serialize(rq),
                ContentType.create(serializer.getMimeType()));
        post.setEntity(httpEntity);
        return executeInternal(post, new TypeConverterCallback<RS>(serializers, type));
    }
149507
public <T> String postObject(
                    final String url,
                    final T object,
                    final Class<T> type
                    )
    {
        _LOG_.debug( "HTTP POST: URL=" + url
                        + ", request type=" + type );

        HttpHeaders  request_headers = new HttpHeaders();
        request_headers.setContentType( getObjectMediaType() );
        HttpEntity<T> request_entity = new HttpEntity<T>( object, request_headers );

        URI  location = null;
        try {
            location= _newRestTemplate().postForLocation( url, request_entity );
            //throws RestClientException
        } catch (Exception ex) {
            throw new HttpException( ex );
        }

        return location.toString();
    }