Create the JvmOperation for the given JDT method.

@param method the JDT method.
@param context the context of the constructor.
@return the JvmOperation
@throws JavaModelException if the Java model is invalid.
171849
private JvmOperation getJvmOperation(IMethod method, JvmType context)
			throws JavaModelException {
		if (context instanceof JvmDeclaredType) {
			final JvmDeclaredType declaredType = (JvmDeclaredType) context;
			final ActionParameterTypes jdtSignature = this.actionPrototypeProvider.createParameterTypes(
					Flags.isVarargs(method.getFlags()),
					getFormalParameterProvider(method));
			for (final JvmOperation jvmOperation : declaredType.getDeclaredOperations()) {
				final ActionParameterTypes jvmSignature = this.actionPrototypeProvider.createParameterTypesFromJvmModel(
						jvmOperation.isVarArgs(),
						jvmOperation.getParameters());
				if (jvmSignature.equals(jdtSignature)) {
					return jvmOperation;
				}
			}
		}
		return null;
	}
569865
public static Set<ApiParamDoc> buildQueryParams(Method method) {
		Set<ApiParamDoc> apiParamDocs = new LinkedHashSet<ApiParamDoc>();
		Class<?> controller = method.getDeclaringClass();

		if (isAnnotated(controller, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(controller, RequestMapping.class);
			addRequestMappingParamDoc(apiParamDocs, requestMapping);
		}

		if (isAnnotated(method, RequestMapping.class)) {
			RequestMapping requestMapping = getAnnotation(method, RequestMapping.class);
			addRequestMappingParamDoc(apiParamDocs, requestMapping);
		}

		Annotation[][] parametersAnnotations = method.getParameterAnnotations();
		for (int i = 0; i < parametersAnnotations.length; i++) {
			RequestParam requestParam = null;
			ModelAttribute modelAttribute = null;
			ApiQueryParam apiQueryParam = null;
			ApiParamDoc apiParamDoc = null;
			
			for (Annotation annotation : parametersAnnotations[i]) {
				if (annotation instanceof RequestParam) {
					requestParam = (RequestParam) annotation;
				}
				if(annotation instanceof ModelAttribute) {
					modelAttribute = (ModelAttribute) annotation;
				}
				if (annotation instanceof ApiQueryParam) {
					apiQueryParam = (ApiQueryParam) annotation;
				}
				
				if (requestParam != null) {
					apiParamDoc = new ApiParamDoc(requestParam.value().isEmpty() ? requestParam.name() : requestParam.value(), "", JSONDocTypeBuilder.build(new JSONDocType(), method.getParameterTypes()[i], method.getGenericParameterTypes()[i]), String.valueOf(requestParam.required()), new String[] {}, null, requestParam.defaultValue().equals(ValueConstants.DEFAULT_NONE) ? "" : requestParam.defaultValue());
					mergeApiQueryParamDoc(apiQueryParam, apiParamDoc);
				}
				if(modelAttribute != null) {
					apiParamDoc = new ApiParamDoc(modelAttribute.value(), "", JSONDocTypeBuilder.build(new JSONDocType(), method.getParameterTypes()[i], method.getGenericParameterTypes()[i]), "false", new String[] {}, null, null);
					mergeApiQueryParamDoc(apiQueryParam, apiParamDoc);
				}
				
			}
			
			if(apiParamDoc != null) {
				apiParamDocs.add(apiParamDoc);
			}
		}
		
		return apiParamDocs;
	}
172748
public ClassBuilder<T> withMethod(Method method, Expression expression) {
		methods.put(method, expression);
		return this;
	}
61086
private void generateJavaDoc(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder, boolean updateMode, String whereCondition, Pair<String, List<Pair<String, TypeName>>> where,
			List<Pair<String, TypeName>> methodParams) {

		final List<SQLProperty> updatedProperties = new ArrayList<>();
		final One<Boolean> onWhereStatement = new One<Boolean>(false);

		String sqlModify = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public void onWhereStatementBegin(Where_stmtContext ctx) {
				onWhereStatement.value0 = true;
			}

			@Override
			public void onWhereStatementEnd(Where_stmtContext ctx) {
				onWhereStatement.value0 = false;
			}

			@Override
			public String onColumnNameToUpdate(String columnName) {
				SQLProperty tempProperty = currentEntity.get(columnName);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				updatedProperties.add(tempProperty);

				return tempProperty.columnName;
			}

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = currentEntity.get(columnName);

				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onBindParameter(String bindParameterName, boolean inStatement) {
				String resolvedParamName = method.findParameterNameByAlias(bindParameterName);
				AssertKripton.assertTrueOrUnknownParamInJQLException(resolvedParamName != null, method, bindParameterName);

				if (onWhereStatement.value0) {
					return SqlAnalyzer.PARAM_PREFIX + bindParameterName + SqlAnalyzer.PARAM_SUFFIX;
				} else {
					return SqlAnalyzer.PARAM_PREFIX + bindParameterName + SqlAnalyzer.PARAM_SUFFIX;
				}

			}

		});

		if (updateMode) {
			methodBuilder.addJavadoc("<h2>SQL update</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>\n", sqlModify);
			methodBuilder.addJavadoc("\n");

			// list of updated fields
			methodBuilder.addJavadoc("<h2>Updated columns:</h2>\n");
			methodBuilder.addJavadoc("<ul>\n");
			for (SQLProperty property : updatedProperties) {
				methodBuilder.addJavadoc("\t<li>$L</li>\n", property.columnName);
			}
			methodBuilder.addJavadoc("</ul>");
			methodBuilder.addJavadoc("\n\n");

		} else {
			methodBuilder.addJavadoc("<h2>SQL delete</h2>\n");
			methodBuilder.addJavadoc("<pre>$L</pre>", sqlModify);
			methodBuilder.addJavadoc("\n\n");
		}

		// list of where parameter
		if (where.value1.size() > 0) {
			methodBuilder.addJavadoc("<h2>Where parameters:</h2>\n");
			methodBuilder.addJavadoc("<dl>\n");
			for (Pair<String, TypeName> property : where.value1) {
				String rawName = method.findParameterNameByAlias(property.value0);
				methodBuilder.addJavadoc("\t<dt>$L</dt>", SqlAnalyzer.PARAM_PREFIX + property.value0 + SqlAnalyzer.PARAM_SUFFIX);
				methodBuilder.addJavadoc("<dd>is mapped to method's parameter <strong>$L</strong></dd>\n", rawName);
			}
			methodBuilder.addJavadoc("</dl>");
		} else {
			methodBuilder.addJavadoc("<p>No where parameters were found.</p>");
		}
		methodBuilder.addJavadoc("\n\n");

		if (method.hasDynamicWhereConditions()) {
			methodBuilder.addJavadoc("<dl>\n");
			methodBuilder.addJavadoc("<dt>$L</dt><dd>is part of where conditions resolved at runtime. In above SQL it is displayed as #{$L}</dd>", method.dynamicWhereParameterName,
					JQLDynamicStatementType.DYNAMIC_WHERE);
			methodBuilder.addJavadoc("\n</dl>");
			methodBuilder.addJavadoc("\n\n");
		}

		// dynamic conditions
		if (method.hasDynamicWhereConditions()) {
			methodBuilder.addJavadoc("<h2>Method's parameters and associated dynamic parts:</h2>\n");
			methodBuilder.addJavadoc("<dl>\n");

			if (method.hasDynamicWhereConditions()) {
				methodBuilder.addJavadoc("<dt>$L</dt><dd>is part of where conditions resolved at runtime. In above SQL it is displayed as #{$L}</dd>", method.dynamicWhereParameterName,
						JQLDynamicStatementType.DYNAMIC_WHERE);
			}

			methodBuilder.addJavadoc("</dl>");
			methodBuilder.addJavadoc("\n\n");
		}

		// method parameters
		if (methodParams.size() > 0) {
			for (Pair<String, TypeName> param : methodParams) {
				String resolvedName = method.findParameterAliasByName(param.value0);
				methodBuilder.addJavadoc("@param $L", param.value0);
				if (method.isThisDynamicWhereConditionsName(param.value0)) {
					methodBuilder.addJavadoc("\n\tis used as dynamic where conditions\n");
				} else if (where.value1.contains(new Pair<>(resolvedName, param.value1))) {
					methodBuilder.addJavadoc("\n\tis used as where parameter <strong>$L</strong>\n", SqlAnalyzer.PARAM_PREFIX + resolvedName + SqlAnalyzer.PARAM_SUFFIX);
				} else {
					methodBuilder.addJavadoc("\n\tis used as updated field <strong>$L</strong>\n", resolvedName);
				}
			}
		}

		// if true, field must be associate to ben attributes
		TypeName returnType = method.getReturnClass();
		// define return value
		if (returnType == TypeName.VOID) {

		} else {
			methodBuilder.addJavadoc("\n");
			if (isIn(returnType, Boolean.TYPE, Boolean.class)) {
				if (updateMode) {
					methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise");
				} else {
					methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise");
				}
				// methodBuilder.addCode("return result!=0;\n");
			} else if (isIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) {
				if (updateMode) {
					methodBuilder.addJavadoc("@return number of updated records");
				} else {
					methodBuilder.addJavadoc("@return number of deleted records");
				}

				// methodBuilder.addCode("return result;\n");
			} else {
				// more than one listener found
				throw (new InvalidMethodSignException(method, "invalid return type"));
			}
			methodBuilder.addJavadoc("\n");
		}

	}
72158
private void doMethod(CtBehavior method) throws NotFoundException, CannotCompileException {

        String signature = JavassistHelper.getSignature(method);
        String returnValue = JavassistHelper.returnValue(method);

        if (addEntryExit) {
            String messagePattern = "if ({}.{}()) {}.{}(\">> {}\");";
            Object[] arg1 = new Object[] { loggerName, levelEnabled, loggerName, level, signature };
            String before = MessageFormatter.arrayFormat(messagePattern, arg1).getMessage();
            // System.out.println(before);
            method.insertBefore(before);

            String messagePattern2 = "if ({}.{}()) {}.{}(\"<< {}{}\");";
            Object[] arg2 = new Object[] { loggerName, levelEnabled, loggerName, level, signature, returnValue };
            String after = MessageFormatter.arrayFormat(messagePattern2, arg2).getMessage();
            // System.out.println(after);
            method.insertAfter(after);
        }
    }
563889
final public void MethodParameters() throws ParseException {
                                             /*@bgen(jjtree) MethodParameters */
  AstMethodParameters jjtn000 = new AstMethodParameters(JJTMETHODPARAMETERS);
  boolean jjtc000 = true;
  jjtree.openNodeScope(jjtn000);
    try {
      jj_consume_token(LPAREN);
      switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
      case START_SET_OR_MAP:
      case INTEGER_LITERAL:
      case FLOATING_POINT_LITERAL:
      case STRING_LITERAL:
      case TRUE:
      case FALSE:
      case NULL:
      case LPAREN:
      case LBRACK:
      case NOT0:
      case NOT1:
      case EMPTY:
      case MINUS:
      case IDENTIFIER:
        Expression();
        label_15:
        while (true) {
          switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
          case COMMA:
            ;
            break;
          default:
            jj_la1[37] = jj_gen;
            break label_15;
          }
          jj_consume_token(COMMA);
          Expression();
        }
        break;
      default:
        jj_la1[38] = jj_gen;
        ;
      }
      jj_consume_token(RPAREN);
    } catch (Throwable jjte000) {
      if (jjtc000) {
        jjtree.clearNodeScope(jjtn000);
        jjtc000 = false;
      } else {
        jjtree.popNode();
      }
      if (jjte000 instanceof RuntimeException) {
        {if (true) throw (RuntimeException)jjte000;}
      }
      if (jjte000 instanceof ParseException) {
        {if (true) throw (ParseException)jjte000;}
      }
      {if (true) throw (Error)jjte000;}
    } finally {
      if (jjtc000) {
        jjtree.closeNodeScope(jjtn000, true);
      }
    }
  }
5708
private void defineJavadocForContentUri(MethodSpec.Builder builder, SQLiteModelMethod method) {
		String contentUri = method.contentProviderUri().replace("*", "[*]");

		classBuilder.addJavadoc("<tr><td><pre>$L</pre></td><td>{@link $LImpl#$L}</td></tr>\n", contentUri, method.getParent().getName(), method.contentProviderMethodName);
		builder.addJavadoc("<tr><td><pre>$L</pre></td><td>{@link $LImpl#$L}</td></tr>\n", contentUri, method.getParent().getName(), method.contentProviderMethodName);

	}
334232
public static boolean isGeneratedOperation(JvmOperation method) {
		for (final JvmAnnotationReference annotation : method.getAnnotations()) {
			if (Objects.equals(SyntheticMember.class.getName(), annotation.getAnnotation().getIdentifier())
					|| Objects.equals(Generated.class.getName(), annotation.getAnnotation().getIdentifier())) {
				return true;
			}
		}
		return false;
	}
946610
public Optional<? extends MethodExecutionHandle<?, Object>> findFallbackMethod(MethodInvocationContext<Object, Object> context) {
        Class<?> declaringType = context.getDeclaringType();
        Optional<? extends MethodExecutionHandle<?, Object>> result = beanContext
                .findExecutionHandle(declaringType, Qualifiers.byStereotype(Fallback.class), context.getMethodName(), context.getArgumentTypes());
        if (!result.isPresent()) {
            Set<Class> allInterfaces = ReflectionUtils.getAllInterfaces(declaringType);
            for (Class i : allInterfaces) {
                result = beanContext
                    .findExecutionHandle(i, Qualifiers.byStereotype(Fallback.class), context.getMethodName(), context.getArgumentTypes());
                if (result.isPresent()) {
                    return result;
                }
            }
        }
        return result;
    }
38777
public static SourceLineAnnotation forEntireMethod(JavaClass javaClass, @CheckForNull Method method) {
        String sourceFile = javaClass.getSourceFileName();
        if (method == null) {
            return createUnknown(javaClass.getClassName(), sourceFile);
        }
        Code code = method.getCode();
        LineNumberTable lineNumberTable = method.getLineNumberTable();
        if (code == null || lineNumberTable == null) {
            return createUnknown(javaClass.getClassName(), sourceFile);
        }

        return forEntireMethod(javaClass.getClassName(), sourceFile, lineNumberTable, code.getLength());
    }
868903
private void createQueryFutureMethod(JavaClass jClass,
                                       Method method)
  {
    Class<?> []parameterTypes = method.getParameterTypes();
    Annotation [][]parameterAnns = method.getParameterAnnotations();

    int paramLength = parameterTypes.length;
    
    addMethod(method);
    
    CodeWriterAttribute code = createMethodHeader(jClass, method);
    
    code.setMaxLocals(1 + 2 * parameterTypes.length);
    code.setMaxStack(10 + 2 * parameterTypes.length);
    
    code.pushObjectVar(0);
    code.getField(jClass.getThisClass(),
                  "_messageFactory",
                  MessageFactoryAmp.class);
    
    // code.pushObjectVar(getLength(parameterTypes, resultOffset) + 1);
    
    Timeout timeoutAnn = method.getAnnotation(Timeout.class);
    
    if (timeoutAnn != null) {
      long timeout = timeoutAnn.unit().toMillis(timeoutAnn.value());
      code.pushConstant(timeout);
    }
    
    
    code.pushObjectVar(0);
    code.getField(jClass.getThisClass(),
                  "_serviceRef",
                  ServiceRefAmp.class);
    
    code.pushObjectVar(0);
    code.getField(jClass.getThisClass(),
                  fieldName(method),
                  MethodAmp.class);
    
    partitionMethod(code, parameterTypes, parameterAnns);
    
    pushParameters(code, parameterTypes, parameterAnns,
                   1, 0, paramLength, -1);

    if (timeoutAnn != null) {
      code.invokeInterface(MessageFactoryAmp.class,
                           "queryFuture",
                           Object.class, // QueryWithResultMessage.class,
                           long.class,
                           ServiceRefAmp.class,
                           MethodAmp.class,
                           Object[].class);
    }
    else {
      code.invokeInterface(MessageFactoryAmp.class,
                           "queryFuture",
                           Object.class, // QueryWithResultMessage.class,
                           ServiceRefAmp.class,
                           MethodAmp.class,
                           Object[].class);
    }

    popReturn(code, method.getReturnType());

    code.close();
  }
325108
@Override
    public JMSContext createContext() throws JMSRuntimeException, JMSSecurityRuntimeException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "createContext");

        JMSContext jmsContext = null;
        try {

            // Pass sessionMode as AUTO_ACKNOWLEDGE. The sessionMode is used to create a session.In simplified
            // API(JMS 2.0), AUTO_ACKNOWLEDGE is the default sessionMode  
            jmsContext = createContext(null, null, JMSContext.AUTO_ACKNOWLEDGE);

        } finally {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "createContext");
        }
        return jmsContext;
    }
219577
public static XMethod createXMethod(JavaClass javaClass, Method method) {
        if (method == null) {
            throw new NullPointerException("method must not be null");
        }
        XMethod xmethod = createXMethod(javaClass.getClassName(), method);
        assert xmethod.isResolved();
        return xmethod;
    }
622417
public static Object create(ActionParameter argument, Context context,
                                ParameterFactories engine) {
        RouteParameterHandler handler = BINDINGS.get(argument.getSource());
        if (handler != null) {
            return handler.create(argument, context, engine);
        } else {
            LoggerFactory.getLogger(Bindings.class).warn("Unsupported route parameter in method : {}",
                    argument.getSource().name());
            return null;
        }
    }
1263640
public SipServletRequest createRequest(final String method) {
		if(logger.isDebugEnabled()) {
			logger.debug("createRequest - method="+ method);
			logger.debug("createRequest - getId()="+ getId());
		}
		if(method.equalsIgnoreCase(Request.ACK) || method.equalsIgnoreCase(Request.PRACK)
				|| method.equalsIgnoreCase(Request.CANCEL)) {
			throw new IllegalArgumentException(
					"Can not create ACK, PRACK or CANCEL requests with this method");
		}
		if(!isValid()) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is invalid");
		}
		if(State.TERMINATED.equals(state)) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " is in TERMINATED state");
		}
		// Issue 2440 : http://code.google.com/p/mobicents/issues/detail?id=2440
		// SipSession.createRequest on proxy SipSession does not throw IllegalStateException
		if(proxy != null) {
			throw new IllegalStateException("cannot create a subsequent request " + method + " because the session " + key + " has been used for proxying. See JSR289 Section 6.2.2.1.");
		}
//		if((State.INITIAL.equals(state) && hasOngoingTransaction())) {
//			throw new IllegalStateException("cannot create a request because the session is in INITIAL state with ongoing transactions");
//		}
		if(logger.isDebugEnabled()) {
			logger.debug("dialog associated with this session to create the new request " + method + " within that dialog "+
					sessionCreatingDialog);
			if(sessionCreatingDialog != null) {
				logger.debug("dialog state " + sessionCreatingDialog.getState() + " for that dialog "+ sessionCreatingDialog);
			}
		}
		SipServletRequestImpl sipServletRequest = null;
		// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
		// MSS should throw an IllegalStateException when a subsequent request is being created on a TERMINATED dialog
		// don't do it on the BYE method as a 408 within a dialog could have make the dialog TERMINATED and MSS should allow the app to create the subsequent BYE from any thread
		if(sessionCreatingDialog != null && DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && !method.equalsIgnoreCase(Request.BYE)) {
			// don't do it for authentication as the dialog will go back to TERMINATED state, so we should allow to create challenge requests
			if(sessionCreatingTransactionRequest == null || sessionCreatingTransactionRequest.getLastFinalResponse() == null ||
					(sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 401 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != 407 &&
						// http://code.google.com/p/sipservlets/issues/detail?id=143 RFC 4028 Session Timer : Allow sending retry INVITE after receiving 422 response
						sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() != SipServletResponse.SC_SESSION_INTERVAL_TOO_SMALL)) {
				throw new IllegalStateException("cannot create a subsequent request " + method + " because the dialog " + sessionCreatingDialog + " for session " + key + " is in TERMINATED state");
			}
		}
		// Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP BYE can be sent on a TERMINATED Dialog
		if(this.sessionCreatingDialog != null &&
				(!DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) ||
						(DialogState.TERMINATED.equals(sessionCreatingDialog.getState()) && method.equalsIgnoreCase(Request.BYE)))) {

			if(logger.isDebugEnabled()) {
				logger.debug("dialog " + sessionCreatingDialog + " used to create the new request " + method);
			}
			try {
				final Request methodRequest = this.sessionCreatingDialog.createRequest(method);

				if(methodRequest.getHeader(ContactHeader.NAME) != null) {
					// if a sip load balancer is present in front of the server, the contact header is the one from the sip lb
					// so that the subsequent requests can be failed over
					try {
						ContactHeader contactHeader = null;
						FromHeader from = (FromHeader) methodRequest.getHeader(FromHeader.NAME);
						String displayName = from.getAddress().getDisplayName();
						String userName = null;
						javax.sip.address.URI uri = from.getAddress().getURI();
						if(uri.isSipURI()) {
							userName = ((javax.sip.address.SipURI)uri).getUser();
						}
						if(sipFactory.isUseLoadBalancer()) {
							// https://github.com/RestComm/sip-servlets/issues/111
							MobicentsExtendedListeningPoint listeningPoint = JainSipUtils.findListeningPoint(sipFactory.getSipNetworkInterfaceManager(), methodRequest, outboundInterface);
							if(listeningPoint != null && listeningPoint.isUseLoadBalancer()) {
								// https://github.com/RestComm/sip-servlets/issues/137
								SipLoadBalancer loadBalancerToUse = null;
								if(listeningPoint.getLoadBalancer() == null) {
									loadBalancerToUse = sipFactory.getLoadBalancerToUse();
									if(logger.isDebugEnabled()) {
										logger.debug("Using listeningPoint " + listeningPoint + " for global load balancer " + sipFactory.getLoadBalancerToUse());
									}
								} else {
									loadBalancerToUse = listeningPoint.getLoadBalancer();
									if(logger.isDebugEnabled()) {
										logger.debug("Using listeningPoint " + listeningPoint + " for connector specific load balancer " + listeningPoint.getLoadBalancer());
									}
								}

								javax.sip.address.SipURI sipURI = SipFactoryImpl.addressFactory.createSipURI(userName, loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setHost(loadBalancerToUse.getAddress().getHostAddress());
								sipURI.setPort(loadBalancerToUse.getSipPort());

								// TODO: Is this enough or we must specify the transport somewhere?
								// We can leave it like this. It will be updated if needed in the send() method
								sipURI.setTransportParam(ListeningPoint.UDP);

								javax.sip.address.Address contactAddress = SipFactoryImpl.addressFactory.createAddress(sipURI);
								contactHeader = SipFactoryImpl.headerFactory.createContactHeader(contactAddress);
							} else {
								if(logger.isDebugEnabled()) {
									logger.debug("Not Using load balancer as it is not enabled for listeningPoint " + listeningPoint);
								}
								contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface);
							}
						} else {
							contactHeader = JainSipUtils.createContactHeader(sipFactory.getSipNetworkInterfaceManager(), methodRequest, displayName, userName, outboundInterface);
						}
						methodRequest.setHeader(contactHeader);
					} catch (Exception e) {
						logger.error("Can not create contact header for subsequent request " + method + " for session " + key, e);
					}
				}
				// Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) :
				// NullPointerException when sending request to client which support both UDP and TCP transport
				// before removing the via header we store the transport into its app data
				ListIterator<ViaHeader> viaHeaders = methodRequest.getHeaders(ViaHeader.NAME);
				if(viaHeaders != null && viaHeaders.hasNext()) {
					ViaHeader viaHeader = viaHeaders.next();
					((MessageExt)methodRequest).setApplicationData(viaHeader.getTransport());
				}
				//Issue 112 fix by folsson
				methodRequest.removeHeader(ViaHeader.NAME);

				// cater to http://code.google.com/p/sipservlets/issues/detail?id=31 to be able to set the rport in applications
				final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher();
				final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(),  sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName()));
				ViaHeader viaHeader = JainSipUtils.createViaHeader(
	    				sipFactory.getSipNetworkInterfaceManager(), methodRequest, branch, outboundInterface);
				methodRequest.addHeader(viaHeader);

				//if a SUBSCRIBE or BYE is sent for exemple, it will reuse the prexisiting dialog
				sipServletRequest = (SipServletRequestImpl) sipFactory.getMobicentsSipServletMessageFactory().createSipServletRequest(
						methodRequest, this, null, sessionCreatingDialog,
						false);
			} catch (SipException e) {
				logger.error("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog,e);
				throw new IllegalArgumentException("Cannot create the " + method + " request from the dialog " + sessionCreatingDialog + " for sip session " + key,e);
			}
		} else {
			boolean treatAsInitialRequest = false;
			// http://code.google.com/p/sipservlets/issues/detail?id=19
			// Retried Request are not considered as initial
			if(sessionCreatingTransactionRequest != null && sessionCreatingTransactionRequest.getLastFinalResponse() != null &&
					sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() >= 400 && sessionCreatingTransactionRequest.getLastFinalResponse().getStatus() < 500) {
				if(logger.isDebugEnabled()) {
					logger.debug("Treating as Initial Request");
				}
				treatAsInitialRequest = true;
			}
			//case where other requests are sent with the same session like REGISTER or for challenge requests
			if(sessionCreatingTransactionRequest != null) {
				if(logger.isDebugEnabled()) {
					logger.debug("createRequest - sessionCreatingTransactionRequest is not null - id:" + this.getId());
				}

				if(!isSessionCreatingTransactionServer) {
					if(logger.isDebugEnabled()) {
						logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Client Tx");
					}
					Request request = (Request) sessionCreatingTransactionRequest.getMessage().clone();
					// Issue 1524 :	Caused by: java.text.ParseException: CSEQ method mismatch with Request-Line
					javax.sip.address.URI requestUri = (javax.sip.address.URI) request.getRequestURI().clone();
					try {
						request.setMethod(method);
					} catch (ParseException e) {
						throw new IllegalArgumentException("Unexpected exception happened on setting method " + method, e);
					}
					request.setRequestURI(requestUri);
					((MessageExt)request).setApplicationData(null);

					final CSeqHeader cSeqHeader = (CSeqHeader) request.getHeader((CSeqHeader.NAME));
					try {
						cSeqHeader.setSeqNumber(cSeqHeader.getSeqNumber() + 1l);
						cSeqHeader.setMethod(method);
					} catch (InvalidArgumentException e) {
						logger.error("Cannot increment the Cseq header to the new " + method + " on the susbequent request to create on session " + key,e);
						throw new IllegalArgumentException("Cannot create the " + method + " on the susbequent request to create on session " + key,e);
					} catch (ParseException e) {
						throw new IllegalArgumentException("Cannot set the " + method + " on the susbequent request to create on session " + key,e);
					}
					// Fix for Issue 1130 (http://code.google.com/p/mobicents/issues/detail?id=1130) :
					// NullPointerException when sending request to client which support both UDP and TCP transport
					// before removing the ViaHeader we store the transport into its app data
					ListIterator<ViaHeader> viaHeaders = request.getHeaders(ViaHeader.NAME);
					if(viaHeaders != null && viaHeaders.hasNext()) {
						ViaHeader viaHeader = viaHeaders.next();
						((MessageExt)request).setApplicationData(viaHeader.getTransport());
					}
					request.removeHeader(ViaHeader.NAME);

					final SipNetworkInterfaceManager sipNetworkInterfaceManager = sipFactory.getSipNetworkInterfaceManager();
					final SipProvider sipProvider = sipNetworkInterfaceManager.findMatchingListeningPoint(
							JainSipUtils.findTransport(request), false).getSipProvider();
					final SipApplicationDispatcher sipApplicationDispatcher = sipFactory.getSipApplicationDispatcher();
					final String branch = JainSipUtils.createBranch(getSipApplicationSession().getKey().getId(),  sipApplicationDispatcher.getHashFromApplicationName(getKey().getApplicationName()));

					ViaHeader viaHeader = JainSipUtils.createViaHeader(
		    				sipNetworkInterfaceManager, request, branch, outboundInterface);
		    		request.addHeader(viaHeader);

		    		// https://code.google.com/p/sipservlets/issues/detail?id=278
		    		request.removeContent();
		    		// http://code.google.com/p/sipservlets/issues/detail?id=161
		    		// Don't reuse the dialog for challenge requests as it can lead to the JAIN SIP Stack
		    		// reusing the Terminated dialog and drop 200 OK
		    		Dialog dialogToUse = sessionCreatingDialog;
		    		if(treatAsInitialRequest) {
		    			dialogToUse = null;
		    		}

					sipServletRequest = (SipServletRequestImpl) sipFactory.getMobicentsSipServletMessageFactory().createSipServletRequest(
							request, this, null, dialogToUse,
							true);

					// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
					if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) {
						SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone();
						sipUri.clearUriParms();
						if(logger.isDebugEnabled()) {
							logger.debug("setting request uri to " + sipUri);
						}
						request.setRequestURI(sipUri);
					}
					// http://code.google.com/p/sipservlets/issues/detail?id=130
					// removes the Route and Path Headers added previously for requests that the container originated
					// when the Load Balancer is used to avoid adding them again with each request going out.
					request.removeHeader(RouteHeader.NAME);
					request.removeHeader(PathHeader.NAME);
				} else {
					if(logger.isDebugEnabled()) {
						logger.debug("orignal tx for creating susbequent request " + method + " on session " + key +" was a Server Tx");
					}
					try {
						// copying original params and call id
						final Request originalRequest = (Request) sessionCreatingTransactionRequest.getMessage();
						final FromHeader fromHeader = (FromHeader) originalRequest.getHeader(FromHeader.NAME);
						final ToHeader toHeader = (ToHeader) originalRequest.getHeader(ToHeader.NAME);
						final AddressImpl currentLocalParty = (AddressImpl)this.getLocalParty().clone();
						final AddressImpl currentRemoteParty = (AddressImpl)this.getRemoteParty().clone();
						((Parameters)currentRemoteParty .getAddress().getURI()).removeParameter("tag");
						((Parameters)currentLocalParty .getAddress().getURI()).removeParameter("tag");
						final String originalCallId = ((CallIdHeader)originalRequest.getHeader(CallIdHeader.NAME)).getCallId();
						sipServletRequest =(SipServletRequestImpl) sipFactory.createRequest(
							getSipApplicationSession(),
							method,
							currentLocalParty,
							currentRemoteParty,
							handlerServlet,
							originalCallId,
							fromHeader.getTag());
						final Request request = ((Request)sipServletRequest.getMessage());
						sipServletRequest.getSipSession().setCseq(((CSeqHeader)request.getHeader(CSeqHeader.NAME)).getSeqNumber());
						final Map<String, String> fromParameters = new HashMap<String, String>();
						final Iterator<String> fromParameterNames = fromHeader.getParameterNames();
						while (fromParameterNames.hasNext()) {
							String parameterName = (String) fromParameterNames.next();
							if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) {
								fromParameters.put(parameterName, fromHeader.getParameter(parameterName));
							}
						}
						final Map<String, String> toParameters = new HashMap<String, String>();
						final Iterator<String> toParameterNames = toHeader.getParameterNames();
						while (toParameterNames.hasNext()) {
							String parameterName = (String) toParameterNames.next();
							if(sessionCreatingDialog != null || !SipFactoryImpl.FORBIDDEN_PARAMS.contains(parameterName)) {
								toParameters.put(parameterName, toHeader.getParameter(parameterName));
							}
						}

						final ToHeader newTo = (ToHeader) request.getHeader(ToHeader.NAME);
						for (Entry<String, String> fromParameter : fromParameters.entrySet()) {
							String value = fromParameter.getValue();
							if(value == null) {
								value = "";
							}
							newTo.setParameter(fromParameter.getKey(),  value);
						}
						final FromHeader newFrom = (FromHeader) request.getHeader(FromHeader.NAME);
						for (Entry<String, String> toParameter : toParameters.entrySet()) {
							String value = toParameter.getValue();
							if(value == null) {
								value = "";
							}
							newFrom.setParameter(toParameter.getKey(),  value);
						}
						// Fix for Issue http://code.google.com/p/mobicents/issues/detail?id=2230 BYE is routed to unexpected IP
						if(sessionCreatingDialog != null && sessionCreatingDialog.getRemoteTarget() != null) {
							SipUri sipUri = (SipUri) sessionCreatingDialog.getRemoteTarget().getURI().clone();
							sipUri.clearUriParms();
							if(logger.isDebugEnabled()) {
								logger.debug("setting request uri to " + sipUri);
							}
							request.setRequestURI(sipUri);
						}
					} catch (ParseException e) {
						throw new IllegalArgumentException("Problem setting param on the newly created susbequent request " + sipServletRequest,e);
					}
				}

				if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) {
					sipServletRequest.updateAuthorizationHeaders(true);
				}
				else if (sipSessionSecurity != null) {
					sipServletRequest.updateAuthorizationHeaders(false);
				}
				if(treatAsInitialRequest) {
					sipServletRequest.setRoutingState(RoutingState.INITIAL);
				}

				return sipServletRequest;
			} else {
				String errorMessage = "Couldn't create the subsequent request " + method + " for this session " + key + ", isValid " + isValid() + ", session state " + state + " , sessionCreatingDialog = " + sessionCreatingDialog;
				if(sessionCreatingDialog != null) {
					errorMessage += " , dialog state " + sessionCreatingDialog.getState();
				}
				errorMessage += " , sessionCreatingTransactionRequest = " + sessionCreatingTransactionRequest;
				throw new IllegalStateException(errorMessage);
			}
		}
		//Application Routing :
		//removing the route headers and adding them back again except the one
		//corresponding to the app that is creating the subsequent request
		//avoid going through the same app that created the subsequent request

		Request request = (Request) sipServletRequest.getMessage();
		final ListIterator<RouteHeader> routeHeaders = request.getHeaders(RouteHeader.NAME);
		request.removeHeader(RouteHeader.NAME);
		while (routeHeaders.hasNext()) {
			RouteHeader routeHeader = routeHeaders.next();
			String routeServerId = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()).
					getParameter(MessageDispatcher.RR_PARAM_SERVER_NAME);
			String routeAppNameHashed = ((javax.sip.address.SipURI)routeHeader .getAddress().getURI()).
				getParameter(MessageDispatcher.RR_PARAM_APPLICATION_NAME);
			String routeAppName = null;
			if(routeAppNameHashed != null) {
				routeAppName = sipFactory.getSipApplicationDispatcher().getApplicationNameFromHash(routeAppNameHashed);
			}
			if(routeAppName == null || !sipFactory.getSipApplicationDispatcher().getApplicationServerId().equals(routeServerId) ||
					!routeAppName.equals(getKey().getApplicationName())) {
				request.addHeader(routeHeader);
			}
		}

		if(sipSessionSecurity != null && sipSessionSecurity.getNextNonce() != null) {
			sipServletRequest.updateAuthorizationHeaders(true);
		}
		else if (sipSessionSecurity != null) {
			sipServletRequest.updateAuthorizationHeaders(false);
		}

		return sipServletRequest;
	}
380820
@Override
    protected void createForwardingMethodBody(ClassMethod classMethod, final MethodInformation methodInfo, ClassMethod staticConstructor) {
        final Method method = methodInfo.getMethod();
        // we can only use bytecode based invocation for some methods
        // at the moment we restrict it solely to public methods with public
        // return and parameter types
        boolean bytecodeInvocationAllowed = Modifier.isPublic(method.getModifiers()) && Modifier.isPublic(method.getReturnType().getModifiers());
        for (Class<?> paramType : method.getParameterTypes()) {
            if (!Modifier.isPublic(paramType.getModifiers())) {
                bytecodeInvocationAllowed = false;
                break;
            }
        }
        if (!bytecodeInvocationAllowed) {
            createInterceptorBody(classMethod, methodInfo, staticConstructor);
            return;
        }

        // create a new interceptor invocation context whenever we invoke a method on a client proxy
        // we use a try-catch block in order to make sure that endInterceptorContext() is invoked regardless whether
        // the method has succeeded or not

        new RunWithinInterceptionDecorationContextGenerator(classMethod, this) {

            @Override
            void doWork(CodeAttribute b, ClassMethod classMethod) {
                loadBeanInstance(classMethod.getClassFile(), methodInfo, b);
                //now we should have the target bean instance on top of the stack
                // we need to dup it so we still have it to compare to the return value
                b.dup();

                //lets create the method invocation
                String methodDescriptor = methodInfo.getDescriptor();
                b.loadMethodParameters();
                if (method.getDeclaringClass().isInterface()) {
                    b.invokeinterface(methodInfo.getDeclaringClass(), methodInfo.getName(), methodDescriptor);
                } else {
                    b.invokevirtual(methodInfo.getDeclaringClass(), methodInfo.getName(), methodDescriptor);
                }
            }

            @Override
            void doReturn(CodeAttribute b, ClassMethod classMethod) {
                // assumes doWork() result is on top of the stack
                // if this method returns a primitive we just return
                if (method.getReturnType().isPrimitive()) {
                    b.returnInstruction();
                } else {
                    // otherwise we have to check that the proxy is not returning 'this;
                    // now we need to check if the proxy has return 'this' and if so return
                    // an
                    // instance of the proxy.
                    // currently we have result, beanInstance on the stack.
                    b.dupX1();
                    // now we have result, beanInstance, result
                    // we need to compare result and beanInstance

                    // first we need to build up the inner conditional that just returns
                    // the
                    // result
                    final BranchEnd returnInstruction = b.ifAcmpeq();
                    b.returnInstruction();
                    b.branchEnd(returnInstruction);

                    // now add the case where the proxy returns 'this';
                    b.aload(0);
                    b.checkcast(methodInfo.getMethod().getReturnType().getName());
                    b.returnInstruction();
                }
            }
        }.runStartIfNotEmpty();
    }
1068079
public static void generateJavaDocForContentProvider(final SQLiteModelMethod method, MethodSpec.Builder methodBuilder) {

		// javadoc
		String operation = method.jql.operationType.toString();
		methodBuilder.addJavadoc("<h1>Content provider URI ($L operation):</h1>\n", operation);
		methodBuilder.addJavadoc("<pre>$L</pre>\n\n", method.contentProviderUriTemplate.replace("*", "[*]"));

		methodBuilder.addJavadoc("<h2>JQL $L for Content Provider</h2>\n", operation);
		methodBuilder.addJavadoc("<pre>$L</pre>\n\n", method.jql.value);
		methodBuilder.addJavadoc("<h2>SQL $L for Content Provider</h2>\n", operation);
		String sql = JQLChecker.getInstance().replace(method, method.jql, new JQLReplacerListenerImpl(method) {

			@Override
			public String onColumnName(String columnName) {
				SQLProperty tempProperty = currentEntity.get(columnName);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, columnName);

				return tempProperty.columnName;
			}

			@Override
			public String onColumnAlias(String alias) {
				SQLProperty tempProperty = currentEntity.findPropertyByName(alias);
				AssertKripton.assertTrueOrUnknownPropertyInJQLException(tempProperty != null, method, alias);

				return tempProperty.columnName;
			}

		});
		methodBuilder.addJavadoc("<pre>$L</pre>\n\n", sql);

		if (method.contentProviderUriVariables.size() > 0) {
			methodBuilder.addJavadoc("<h3>Path variables defined:</h3>\n<ul>\n");
			for (ContentUriPlaceHolder variable : method.contentProviderUriVariables) {
				methodBuilder.addJavadoc("<li><strong>" + SqlAnalyzer.PARAM_PREFIX + "$L" + SqlAnalyzer.PARAM_SUFFIX + "</strong> at path segment $L</li>\n", variable.value,
						variable.pathSegmentIndex);
			}
			methodBuilder.addJavadoc("</ul>\n\n");
		}

		if (!method.hasDynamicWhereConditions()) {
			methodBuilder.addJavadoc("<p><strong>Dynamic where statement is ignored, due no param with @$L was added.</strong></p>\n\n", BindSqlDynamicWhere.class.getSimpleName());
		}

		methodBuilder.addJavadoc("<p><strong>In URI, * is replaced with [*] for javadoc rapresentation</strong></p>\n\n");
	}