Invoke the object with the request from the input stream.

@param in the Hessian input stream
@param out the Hessian output stream
506864
public void invoke(InputStream is, OutputStream os,
                       SerializerFactory serializerFactory)
        throws Exception
    {
        boolean isDebug = false;

        if (isDebugInvoke()) {
            isDebug = true;

            PrintWriter dbg = createDebugPrintWriter();
            HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);
            dIs.startTop2();
            is = dIs;
            HessianDebugOutputStream dOs = new HessianDebugOutputStream(os, dbg);
            dOs.startTop2();
            os = dOs;
        }

        HessianInputFactory.HeaderType header = _inputFactory.readHeader(is);

        AbstractHessianInput in;
        AbstractHessianOutput out;

        switch (header) {
            case CALL_1_REPLY_1:
                in = _hessianFactory.createHessianInput(is);
                out = _hessianFactory.createHessianOutput(os);
                break;

            case CALL_1_REPLY_2:
                in = _hessianFactory.createHessianInput(is);
                out = _hessianFactory.createHessian2Output(os);
                break;

            case HESSIAN_2:
                in = _hessianFactory.createHessian2Input(is);
                in.readCall();
                out = _hessianFactory.createHessian2Output(os);
                break;

            default:
                throw new IllegalStateException(header + " is an unknown Hessian call");
        }

        if (serializerFactory != null) {
            in.setSerializerFactory(serializerFactory);
            out.setSerializerFactory(serializerFactory);
        }

        try {
            invoke(_service, in, out);
        } finally {
            in.close();
            out.close();

            if (isDebug)
                os.close();
        }
    }
505901
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable
    {
        String mangleName;

        synchronized (_mangleMap) {
            mangleName = _mangleMap.get(method);
        }

        if (mangleName == null) {
            String methodName = method.getName();
            Class<?>[] params = method.getParameterTypes();

            // equals and hashCode are special cased
            if (methodName.equals("equals")
                && params.length == 1 && params[0].equals(Object.class)) {
                Object value = args[0];
                if (value == null || !Proxy.isProxyClass(value.getClass()))
                    return Boolean.FALSE;

                Object proxyHandler = Proxy.getInvocationHandler(value);

                if (!(proxyHandler instanceof HessianProxy))
                    return Boolean.FALSE;

                HessianProxy handler = (HessianProxy) proxyHandler;

                return new Boolean(_url.equals(handler.getURL()));
            }
            else if (methodName.equals("hashCode") && params.length == 0)
                return new Integer(_url.hashCode());
            else if (methodName.equals("getHessianType"))
                return proxy.getClass().getInterfaces()[0].getName();
            else if (methodName.equals("getHessianURL"))
                return _url.toString();
            else if (methodName.equals("toString") && params.length == 0)
                return "HessianProxy[" + _url + "]";

            if (!_factory.isOverloadEnabled())
                mangleName = method.getName();
            else
                mangleName = mangleName(method);

            synchronized (_mangleMap) {
                _mangleMap.put(method, mangleName);
            }
        }

        InputStream is = null;
        HessianConnection conn = null;

        try {
            if (log.isLoggable(Level.FINER))
                log.finer("Hessian[" + _url + "] calling " + mangleName);

            conn = sendRequest(mangleName, args);

            is = getInputStream(conn);

            if (log.isLoggable(Level.FINEST)) {
                PrintWriter dbg = new PrintWriter(new LogWriter(log));
                HessianDebugInputStream dIs = new HessianDebugInputStream(is, dbg);

                dIs.startTop2();

                is = dIs;
            }

            AbstractHessianInput in;

            int code = is.read();

            if (code == 'H') {
                int major = is.read();
                int minor = is.read();

                in = _factory.getHessian2Input(is);

                Object value = in.readReply(method.getReturnType());

                return value;
            }
            else if (code == 'r') {
                int major = is.read();
                int minor = is.read();

                in = _factory.getHessianInput(is);

                in.startReplyBody();

                Object value = in.readObject(method.getReturnType());

                if (value instanceof InputStream) {
                    value = new ResultInputStream(conn, is, in, (InputStream) value);
                    is = null;
                    conn = null;
                }
                else
                    in.completeReply();

                return value;
            }
            else
                throw new HessianProtocolException("'" + (char) code + "' is an unknown code");
        } catch (HessianProtocolException e) {
            throw new HessianRuntimeException(e);
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (Exception e) {
                log.log(Level.FINE, e.toString(), e);
            }

            try {
                if (conn != null)
                    conn.destroy();
            } catch (Exception e) {
                log.log(Level.FINE, e.toString(), e);
            }
        }
    }
1030034
public void writeObject (ObjectOutputStream out)
        throws IOException
    {
        out.writeInt(size());
        for (E value : this) {
            out.writeObject(value);
        }
    }
682385
public void invoke(InputStream is, OutputStream os)
        throws Exception
    {
        invoke(is, os, null);
    }
703281
@Override
  public Object invoke(final ELContext context, final Object base, final Object method,
      Class<?>[] paramTypes, final Object[] params) {
    if ((base == null) || (method == null)) {
      return null;
    }

    final MethodDescriptor[] methodDescriptors = getMethodDescriptors(context, base);

    if (methodDescriptors != null) {
      final Method m =
          findMethodOrThrow(method.toString(), paramTypes, params, false, methodDescriptors);
      paramTypes = m.getParameterTypes();
    }

    return super.invoke(context, base, method, paramTypes, params);
  }
162209
public static void writeObjectToStream(final Object o, OutputStream out) {
    out = new BufferedOutputStream(out);
    try {
      final ObjectOutputStream oos = new ObjectOutputStream(out);
      oos.writeObject(o);
      oos.flush();
    } catch (final IOException e) {
      e.printStackTrace();
    }
  }
648714
private static void inflater(InputStream in, OutputStream out) {
		final InflaterOutputStream ios = (out instanceof InflaterOutputStream) ? (InflaterOutputStream) out : new InflaterOutputStream(out, new Inflater(true));
		IoUtil.copy(in, ios);
		try {
			ios.finish();
		} catch (IOException e) {
			throw new IORuntimeException(e);
		}
	}
707819
protected Thread copy(final InputStream in, final Writer out)
	{
		Runnable r = () -> {
			try
			{
				StreamUtil.streamCopy(in, out);
			}
			catch (IOException e)
			{
				try
				{
					out.flush();
				}
				catch (Throwable t)
				{
				}

				unexpectedFailure(e);
			}
		};

		Thread t = new Thread(r);
		t.setName(this + " - IOCopy " + in + " to " + out);
		t.setDaemon(true);
		t.start();

		return t;
	}
142647
public static void write(InputStream in, int bufferSize) {
		ServletOutputStream out = null;
		try {
			out = getOutputStream();
			IoUtil.copy(in, out, bufferSize);
		} catch (IOException e) {
			throw new RenderException("Error when output to client!", e);
		} finally {
			IoUtil.close(out);
			IoUtil.close(in);
		}
	}
202679
public void invokeRequest (ClientObject caller, byte[] serializedAction,
        InvocationService.ResultListener listener)
    {
        NodeRequest request = null;
        try {
            ObjectInputStream oin =
                new ObjectInputStream(new ByteArrayInputStream(serializedAction));
            request = (NodeRequest)oin.readObject();
            _injector.injectMembers(request);
            request.invoke(listener);

        } catch (Exception e) {
            log.warning("Failed to execute node request",
                        "from", (caller == null) ? "self" : caller.who(),
                        "request", request, "serializedSize", serializedAction.length, e);
            listener.requestFailed("Failed to execute node request");
        }
    }
1263697
@Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        return connectionHandler.remoteInvocation(proxy, method, args);
    }
1175489
public static void copyBytes(final InputStream in, final OutputStream out) throws IOException {
		copyBytes(in, out, BLOCKSIZE, true);
	}
418654
private void sendStream(InputStream in) {
        new Thread(() -> {
            try {
                con.sendData(in);
                con.sendResponse(226, "File sent!");
            } catch(ResponseException ex) {
                con.sendResponse(ex.getCode(), ex.getMessage());
            } catch(Exception ex) {
                con.sendResponse(451, ex.getMessage());
            }
        }).start();
    }
90563
@Override
    public String invoke(Object inConn, String request, int timeout, Map<String, String> headers)
    throws ConnectionException, AdapterException {
        HttpHelper httpHelper = null;
        Object conn = inConn;
        try {
            httpHelper = getHttpHelper(conn);

            if (headers != null)
                httpHelper.setHeaders(headers);

            String response = performHttpAction(httpHelper, request);

            // Check if received a 401 if using an AuthTokenProvider, refresh token in case it expired and try again
            if (response != null && getAuthProvider() instanceof AuthTokenProvider && super.getResponse(conn, response).getStatusCode() == Status.UNAUTHORIZED.getCode()) {
                String user = getAttribute(AUTH_USER);
                String password = getAttribute(AUTH_PASSWORD);
                URL endpoint = new URL(getEndpointUri());
                AuthTokenProvider authProvider = (AuthTokenProvider)getAuthProvider();
                authProvider.invalidateToken(endpoint, user);
                String token = new String(authProvider.getToken(endpoint, user, password));
                headers.put("Authorization", "Bearer " + token);
                conn = openConnection();
                httpHelper = getHttpHelper(conn);
                httpHelper.setHeaders(headers);
                response = performHttpAction(httpHelper, request);
            }

            if (response != null) {
                // HTTP code threshold for retries
                int codeThreshold = DEFAULT_RETRY_HTTP_CODE;
                String retryCodes = getAttributeValueSmart(RETRY_HTTP_CODES);
                if (retryCodes != null) {
                    try {
                        codeThreshold = Integer.parseInt(retryCodes);
                    }
                    catch (NumberFormatException ex) {} // Use default in this case
                }
                // HTTP code threshold for error
                int errorCodeThreshold = DEFAULT_ERROR_HTTP_CODE;
                String errorCodes = getAttributeValueSmart(ERROR_HTTP_CODES);
                if (errorCodes != null) {
                    try {
                        errorCodeThreshold = Integer.parseInt(errorCodes);
                    }
                    catch (NumberFormatException ex) {} // Use default in this case
                }
                Response httpResponse = super.getResponse(conn, response);
                if (httpResponse.getStatusCode() >= codeThreshold)
                    throw new IOException("Server returned HTTP response code: " + httpResponse.getStatusCode());  // Retryable
                else if (httpResponse.getStatusCode() >= errorCodeThreshold)
                    throw new AdapterException("Server returned HTTP response code: " + httpResponse.getStatusCode());   // Non-Retryable
            }
            return response;
        }
        catch (IOException ex) {
            if (httpHelper != null && httpHelper.getResponse() != null) {
                Response response = new Response(httpHelper.getResponse());
                response.setStatusCode(httpHelper.getResponseCode());
                response.setStatusMessage(httpHelper.getResponseMessage());
                response.setPath(ServicePaths.getOutboundResponsePath(httpHelper.getConnection().getUrl(),
                        httpHelper.getConnection().getMethod()));
                logResponse(response);
            }
            /**
             * Plugs into automatic retrying
             */
            logexception(ex.getMessage(), ex);
            throw new ConnectionException(-1, ex.getMessage(), ex);
        }
        catch (Exception ex) {
            int responseCode = -1;
            if (httpHelper != null) {
                responseCode = httpHelper.getResponseCode();
                if (httpHelper.getResponse() != null) {
                    Response response = new Response(httpHelper.getResponse());
                    response.setStatusCode(responseCode);
                    response.setStatusMessage(httpHelper.getResponseMessage());
                    response.setPath(ServicePaths.getOutboundResponsePath(httpHelper.getConnection().getUrl(),
                            httpHelper.getConnection().getMethod()));
                    logResponse(response);
                }
            }
            throw new AdapterException(responseCode, ex.getMessage() , ex);
        }
        finally {
            if (httpHelper != null) {
                setResponseHeaders(httpHelper.getHeaders());
                // We have to override the response from original connection if token was expired
                if (!httpHelper.getConnection().equals(inConn))
                    ((HttpConnection)inConn).setResponse(httpHelper.getConnection().getResponse());
            }
        }
    }
1245737
public Object invoke(MethodInvocation mi) throws Throwable {
		if (!Modifier.isPublic(mi.getMethod().getModifiers())) {
			return mi.proceed();
		}

		Method daoMethod = mi.getMethod();
		Object[] args = mi.getArguments();
		String appid = AOPUtils.getFirstArgOfString(args);

		Method superMethod = null;
		Indexed indexedAnno = null;
		Cached cachedAnno = null;

		try {
			superMethod = DAO.class.getMethod(daoMethod.getName(), daoMethod.getParameterTypes());
			indexedAnno = Config.isSearchEnabled() ? superMethod.getAnnotation(Indexed.class) : null;
			cachedAnno = Config.isCacheEnabled() ? superMethod.getAnnotation(Cached.class) : null;
			detectNestedInvocations(daoMethod);
		} catch (Exception e) {
			logger.error("Error in AOP layer!", e);
		}

		Set<IOListener> ioListeners = Para.getIOListeners();
		for (IOListener ioListener : ioListeners) {
			ioListener.onPreInvoke(superMethod, args);
			logger.debug("Executed {}.onPreInvoke().", ioListener.getClass().getName());
		}

		Object result = handleIndexing(indexedAnno, appid, daoMethod, args, mi);
		Object cachingResult = handleCaching(cachedAnno, appid, daoMethod, args, mi);

		// we have a read operation without any result but we get back objects from cache
		if (result == null && cachingResult != null) {
			result = cachingResult;
		}

		// both searching and caching are disabled - pass it through
		if (indexedAnno == null && cachedAnno == null) {
			result = invokeDAO(appid, daoMethod, mi);
		}

		for (IOListener ioListener : ioListeners) {
			ioListener.onPostInvoke(superMethod, result);
			logger.debug("Executed {}.onPostInvoke().", ioListener.getClass().getName());
		}

		return result;
	}
962335
public void sendRequest (
        int invOid, int invCode, int methodId, Object[] args, Transport transport)
    {
        if (_clobj == null) {
            log.warning("Dropping invocation request on shutdown director", "code", invCode,
                        "methodId", methodId);
            return;
        }

        // configure any invocation listener marshallers among the arguments
        int acount = args.length;
        for (int ii = 0; ii < acount; ii++) {
            Object arg = args[ii];
            if (arg instanceof ListenerMarshaller) {
                ListenerMarshaller lm = (ListenerMarshaller)arg;
                lm.requestId = nextRequestId();
                lm.mapStamp = System.currentTimeMillis();
                // create a mapping for this marshaller so that we can properly dispatch responses
                // sent to it
                _listeners.put(lm.requestId, lm);
            }
        }

        // create an invocation request event
        InvocationRequestEvent event = new InvocationRequestEvent(invOid, invCode, methodId, args);
        event.setTransport(transport);

        // because invocation directors are used on the server, we set the source oid here so that
        // invocation requests are properly attributed to the right client object when created by
        // server-side entities only sort of pretending to be a client
        event.setSourceOid(_clobj.getOid());

//         Log.info("Sending invreq " + event + ".");

        // now dispatch the event
        _omgr.postEvent(event);
    }
433653
public Object invoke(MethodInvocation mi) throws Throwable {
		if (!Modifier.isPublic(mi.getMethod().getModifiers())) {
			return mi.proceed();
		}

		Method searchMethod = mi.getMethod();
		Object[] args = mi.getArguments();
		String appid = AOPUtils.getFirstArgOfString(args);

		Method superMethod = null;
		Measured measuredAnno = null;

		try {
			superMethod = Search.class.getMethod(searchMethod.getName(), searchMethod.getParameterTypes());
			measuredAnno = superMethod.getAnnotation(Measured.class);
		} catch (Exception e) {
			logger.error("Error in search AOP layer!", e);
		}

		Set<IOListener> ioListeners = Para.getSearchQueryListeners();
		for (IOListener ioListener : ioListeners) {
			ioListener.onPreInvoke(superMethod, args);
			logger.debug("Executed {}.onPreInvoke().", ioListener.getClass().getName());
		}

		Object result = null;
		if (measuredAnno != null) {
			result = invokeTimedSearch(appid, searchMethod, mi);
		} else {
			result = mi.proceed();
		}

		for (IOListener ioListener : ioListeners) {
			ioListener.onPostInvoke(superMethod, result);
			logger.debug("Executed {}.onPostInvoke().", ioListener.getClass().getName());
		}

		return result;
	}