List of usage examples for java.lang.reflect Method getGenericParameterTypes
@Override
public Type[] getGenericParameterTypes()
From source file:org.evosuite.testcase.TestFactory.java
private boolean insertRandomReflectionCall(TestCase test, int position, int recursionDepth) throws ConstructionFailedException { logger.debug("Recursion depth: " + recursionDepth); if (recursionDepth > Properties.MAX_RECURSION) { logger.debug("Max recursion depth reached"); throw new ConstructionFailedException("Max recursion depth reached"); }/*w w w . ja v a2 s. com*/ int length = test.size(); List<VariableReference> parameters = null; Statement st = null; if (reflectionFactory.nextUseField()) { Field field = reflectionFactory.nextField(); parameters = satisfyParameters(test, null, //we need a reference to the SUT, and one to a variable of same type of chosen field Arrays.asList((Type) reflectionFactory.getReflectedClass(), (Type) field.getType()), position, recursionDepth + 1, true, false, true); try { st = new PrivateFieldStatement(test, reflectionFactory.getReflectedClass(), field.getName(), parameters.get(0), parameters.get(1)); } catch (NoSuchFieldException e) { logger.error("Reflection problem: " + e, e); throw new ConstructionFailedException("Reflection problem"); } } else { //method Method method = reflectionFactory.nextMethod(); List<Type> list = new ArrayList<>(); list.add(reflectionFactory.getReflectedClass()); list.addAll(Arrays.asList(method.getGenericParameterTypes())); parameters = satisfyParameters(test, null, list, position, recursionDepth + 1, true, false, true); VariableReference callee = parameters.remove(0); st = new PrivateMethodStatement(test, reflectionFactory.getReflectedClass(), method, callee, parameters, Modifier.isStatic(method.getModifiers())); } int newLength = test.size(); position += (newLength - length); test.addStatement(st, position); return true; }
From source file:com.meidusa.venus.client.RemotingInvocationHandler.java
protected Object invokeRemoteService(Service service, Endpoint endpoint, Method method, EndpointParameter[] params, Object[] args) throws Exception { String apiName = VenusAnnotationUtils.getApiname(method, service, endpoint); AthenaTransactionId athenaTransactionId = null; if (service.athenaFlag()) { athenaTransactionId = AthenaTransactionDelegate.getDelegate().startClientTransaction(apiName); }/* ww w . ja v a2 s . c om*/ boolean async = false; if (endpoint.async()) { async = true; } byte[] traceID = VenusTracerUtil.getTracerID(); if (traceID == null) { traceID = VenusTracerUtil.randomTracerID(); } Serializer serializer = SerializerFactory.getSerializer(serializeType); SerializeServiceRequestPacket serviceRequestPacket = new SerializeServiceRequestPacket(serializer, null); serviceRequestPacket.clientId = PacketConstant.VENUS_CLIENT_ID; serviceRequestPacket.clientRequestId = sequenceId.getAndIncrement(); serviceRequestPacket.traceId = traceID; serviceRequestPacket.apiName = apiName; serviceRequestPacket.serviceVersion = service.version(); serviceRequestPacket.parameterMap = new HashMap<String, Object>(); if (params != null) { for (int i = 0; i < params.length; i++) { if (args[i] instanceof InvocationListener) { async = true; ReferenceInvocationListener listener = new ReferenceInvocationListener(); ServicePacketBuffer buffer = new ServicePacketBuffer(16); buffer.writeLengthCodedString(args[i].getClass().getName(), "utf-8"); buffer.writeInt(System.identityHashCode(args[i])); listener.setIdentityData(buffer.toByteBuffer().array()); Type type = method.getGenericParameterTypes()[i]; if (type instanceof ParameterizedType) { ParameterizedType genericType = ((ParameterizedType) type); container.putInvocationListener((InvocationListener) args[i], genericType.getActualTypeArguments()[0]); } else { throw new InvalidParameterException("invocationListener is not generic"); } serviceRequestPacket.parameterMap.put(params[i].getParamName(), listener); } else { serviceRequestPacket.parameterMap.put(params[i].getParamName(), args[i]); } } } setTransactionId(serviceRequestPacket, athenaTransactionId); PerformanceLevel pLevel = AnnotationUtil.getAnnotation(method.getAnnotations(), PerformanceLevel.class); long start = TimeUtil.currentTimeMillis(); long borrowed = start; if (async) { if (!this.isEnableAsync()) { throw new VenusConfigException("service async call disabled"); } BackendConnection conn = null; try { if (nioConnPool instanceof RequestLoadbalanceObjectPool) { conn = (BackendConnection) ((RequestLoadbalanceObjectPool) nioConnPool) .borrowObject(serviceRequestPacket.parameterMap, endpoint); } else { conn = nioConnPool.borrowObject(); } borrowed = TimeUtil.currentTimeMillis(); conn.write(serviceRequestPacket.toByteBuffer()); VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName, JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE)); return null; } finally { if (service.athenaFlag()) { AthenaTransactionDelegate.getDelegate().completeClientTransaction(); } if (performanceLogger.isDebugEnabled()) { long end = TimeUtil.currentTimeMillis(); long time = end - borrowed; StringBuffer buffer = new StringBuffer(); buffer.append("[").append(borrowed - start).append(",").append(time) .append("]ms (*client,async*) traceID=").append(UUID.toString(traceID)).append(", api=") .append(serviceRequestPacket.apiName); performanceLogger.debug(buffer.toString()); } if (conn != null) { nioConnPool.returnObject(conn); } } } else { AbstractBIOConnection conn = null; int soTimeout = 0; int oldTimeout = 0; boolean success = true; int errorCode = 0; AbstractServicePacket packet = null; String remoteAddress = null; boolean invalided = false; try { if (bioConnPool instanceof RequestLoadbalanceObjectPool) { conn = (AbstractBIOConnection) ((RequestLoadbalanceObjectPool) bioConnPool) .borrowObject(serviceRequestPacket.parameterMap, endpoint); } else { conn = (AbstractBIOConnection) bioConnPool.borrowObject(); } remoteAddress = conn.getRemoteAddress(); borrowed = TimeUtil.currentTimeMillis(); ServiceConfig config = this.serviceFactory.getServiceConfig(method.getDeclaringClass()); oldTimeout = conn.getSoTimeout(); if (config != null) { EndpointConfig endpointConfig = config.getEndpointConfig(endpoint.name()); if (endpointConfig != null) { int eTimeOut = endpointConfig.getTimeWait(); if (eTimeOut > 0) { soTimeout = eTimeOut; } } else { if (config.getTimeWait() > 0) { soTimeout = config.getTimeWait(); } else { if (endpoint.timeWait() > 0) { soTimeout = endpoint.timeWait(); } } } } else { if (endpoint.timeWait() > 0) { soTimeout = endpoint.timeWait(); } } byte[] bts; try { if (soTimeout > 0) { conn.setSoTimeout(soTimeout); } conn.write(serviceRequestPacket.toByteArray()); VenusTracerUtil.logRequest(traceID, serviceRequestPacket.apiName, JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE)); bts = conn.read(); } catch (IOException e) { try { conn.close(); } catch (Exception e1) { // ignore } bioConnPool.invalidateObject(conn); invalided = true; Class<?>[] eClass = method.getExceptionTypes(); if (eClass != null && eClass.length > 0) { for (Class<?> clazz : eClass) { if (e.getClass().isAssignableFrom(clazz)) { throw e; } } } throw new RemoteSocketIOException("api=" + serviceRequestPacket.apiName + ", remoteIp=" + conn.getRemoteAddress() + ",(" + e.getMessage() + ")", e); } int type = AbstractServicePacket.getType(bts); switch (type) { case PacketConstant.PACKET_TYPE_ERROR: ErrorPacket error = new ErrorPacket(); error.init(bts); packet = error; Exception e = venusExceptionFactory.getException(error.errorCode, error.message); if (e == null) { throw new DefaultVenusException(error.errorCode, error.message); } else { if (error.additionalData != null) { Map<String, Type> tmap = Utils.getBeanFieldType(e.getClass(), Exception.class); if (tmap != null && tmap.size() > 0) { Object obj = serializer.decode(error.additionalData, tmap); BeanUtils.copyProperties(e, obj); } } throw e; } case PacketConstant.PACKET_TYPE_OK: OKPacket ok = new OKPacket(); ok.init(bts); packet = ok; return null; case PacketConstant.PACKET_TYPE_SERVICE_RESPONSE: ServiceResponsePacket response = new SerializeServiceResponsePacket(serializer, method.getGenericReturnType()); response.init(bts); packet = response; return response.result; default: { logger.warn("unknow response type=" + type); success = false; return null; } } } catch (Exception e) { success = false; if (e instanceof CodedException || (errorCode = venusExceptionFactory.getErrorCode(e.getClass())) != 0 || e instanceof RuntimeException) { if (e instanceof CodedException) { errorCode = ((CodedException) e).getErrorCode(); } throw e; } else { RemoteException code = e.getClass().getAnnotation(RemoteException.class); if (code != null) { errorCode = code.errorCode(); throw e; } else { ExceptionCode eCode = e.getClass().getAnnotation(ExceptionCode.class); if (eCode != null) { errorCode = eCode.errorCode(); throw e; } else { errorCode = -1; if (conn == null) { throw new DefaultVenusException(e.getMessage(), e); } else { throw new DefaultVenusException( e.getMessage() + ". remoteAddress=" + conn.getRemoteAddress(), e); } } } } } finally { if (service.athenaFlag()) { AthenaTransactionDelegate.getDelegate().completeClientTransaction(); } long end = TimeUtil.currentTimeMillis(); long time = end - borrowed; StringBuffer buffer = new StringBuffer(); buffer.append("[").append(borrowed - start).append(",").append(time) .append("]ms (*client,sync*) traceID=").append(UUID.toString(traceID)).append(", api=") .append(serviceRequestPacket.apiName); if (remoteAddress != null) { buffer.append(", remote=").append(remoteAddress); } else { buffer.append(", pool=").append(bioConnPool.toString()); } buffer.append(", clientID=").append(PacketConstant.VENUS_CLIENT_ID).append(", requestID=") .append(serviceRequestPacket.clientRequestId); if (packet != null) { if (packet instanceof ErrorPacket) { buffer.append(", errorCode=").append(((ErrorPacket) packet).errorCode); buffer.append(", message=").append(((ErrorPacket) packet).message); } else { buffer.append(", errorCode=0"); } } if (pLevel != null) { if (pLevel.printParams()) { buffer.append(", params="); buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE)); } if (time > pLevel.error() && pLevel.error() > 0) { if (performanceLogger.isErrorEnabled()) { performanceLogger.error(buffer.toString()); } } else if (time > pLevel.warn() && pLevel.warn() > 0) { if (performanceLogger.isWarnEnabled()) { performanceLogger.warn(buffer.toString()); } } else if (time > pLevel.info() && pLevel.info() > 0) { if (performanceLogger.isInfoEnabled()) { performanceLogger.info(buffer.toString()); } } else { if (performanceLogger.isDebugEnabled()) { performanceLogger.debug(buffer.toString()); } } } else { buffer.append(", params="); buffer.append(JSON.toJSONString(serviceRequestPacket.parameterMap, JSON_FEATURE)); if (time >= 30 * 1000) { if (performanceLogger.isErrorEnabled()) { performanceLogger.error(buffer.toString()); } } else if (time >= 10 * 1000) { if (performanceLogger.isWarnEnabled()) { performanceLogger.warn(buffer.toString()); } } else if (time >= 5 * 1000) { if (performanceLogger.isInfoEnabled()) { performanceLogger.info(buffer.toString()); } } else { if (performanceLogger.isDebugEnabled()) { performanceLogger.debug(buffer.toString()); } } } if (conn != null && !invalided) { if (!conn.isClosed() && soTimeout > 0) { conn.setSoTimeout(oldTimeout); } bioConnPool.returnObject(conn); } } } }
From source file:it.restrung.rest.marshalling.response.AbstractJSONResponse.java
/** * @see JSONResponse#fromJSON(org.json.JSONObject) */// w w w . j a va 2 s. c o m @Override @SuppressWarnings("unchecked") public void fromJSON(JSONObject jsonObject) throws JSONException { this.delegate = jsonObject; Method[] methods = getClass().getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 1 && method.getName().startsWith("set") && method.getName().length() > 3) { Class argType = method.getParameterTypes()[0]; String propertyName = method.getName().substring(3); propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1); try { Field foundField = getClass().getDeclaredField(propertyName); if (foundField.isAnnotationPresent(JsonProperty.class)) { propertyName = foundField.getAnnotation(JsonProperty.class).value(); } } catch (NoSuchFieldException e) { //todo log errors when field names mismatch their setter } Object result = null; if (String.class.isAssignableFrom(argType)) { result = getString(propertyName); } else if (Boolean.class.isAssignableFrom(argType) || boolean.class.isAssignableFrom(argType)) { result = getBoolean(propertyName); } else if (Double.class.isAssignableFrom(argType) || double.class.isAssignableFrom(argType)) { result = getDouble(propertyName); } else if (Long.class.isAssignableFrom(argType) || long.class.isAssignableFrom(argType)) { result = getLong(propertyName); } else if (Integer.class.isAssignableFrom(argType) || int.class.isAssignableFrom(argType)) { result = getInt(propertyName); } else if (Date.class.isAssignableFrom(argType)) { result = getDate(propertyName); } else if (JSONResponse.class.isAssignableFrom(argType)) { result = getObject(propertyName, argType); } else if (Enum.class.isAssignableFrom(argType)) { String value = getString(propertyName); if (value != null) { result = Enum.valueOf((Class<Enum>) argType, getString(propertyName)); } } else if (List.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]) .getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getList(propertyName, typeArg); } else { result = getElementCollection(propertyName); } } else if (Map.class.isAssignableFrom(argType)) { Class typeArg = (Class) ((ParameterizedType) method.getGenericParameterTypes()[0]) .getActualTypeArguments()[0]; if (JSONResponse.class.isAssignableFrom(typeArg)) { result = getMap(propertyName, typeArg); } else { result = getElementMap(propertyName); } } else { throw new UnsupportedOperationException(String.format( "%s is of type: %s which is not yet supported by the AbstractJSONResponse serialization", propertyName, argType)); } try { method.invoke(this, result); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } }
From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java
private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception { Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>(); Method[] methods = recordClass.getDeclaredMethods(); // get all get methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.equals("getProto")) { continue; }//from www. ja v a2s. c o m if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) { String propertyName = name.substring(3); Type valueType = m.getGenericReturnType(); GetSetPair p = ret.get(propertyName); if (p == null) { p = new GetSetPair(); p.propertyName = propertyName; p.type = valueType; p.getMethod = m; ret.put(propertyName, p); } else { Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName); } } } } // match get methods with set methods for (int i = 0; i < methods.length; i++) { Method m = methods[i]; int mod = m.getModifiers(); if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) { String name = m.getName(); if (name.startsWith("set") && (m.getParameterTypes().length == 1)) { String propertyName = name.substring(3); Type valueType = m.getGenericParameterTypes()[0]; GetSetPair p = ret.get(propertyName); if (p != null && p.type.equals(valueType)) { p.setMethod = m; } } } } // exclude incomplete get/set pair, and generate test value Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator(); while (itr.hasNext()) { Entry<String, GetSetPair> cur = itr.next(); GetSetPair gsp = cur.getValue(); if ((gsp.getMethod == null) || (gsp.setMethod == null)) { LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName)); itr.remove(); } else { LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type)); gsp.testValue = genTypeValue(gsp.type); LOG.info(String.format(" testValue: %s\n", gsp.testValue)); } } return ret; }
From source file:org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.java
private Type determineInferredType(Method method) { if (method == null) { return null; }//from w w w . j av a 2s . com Type genericParameterType = null; boolean hasAck = false; for (int i = 0; i < method.getParameterTypes().length; i++) { MethodParameter methodParameter = new MethodParameter(method, i); /* * We're looking for a single non-annotated parameter, or one annotated with @Payload. * We ignore parameters with type Message because they are not involved with conversion. */ if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0 || methodParameter.hasParameterAnnotation(Payload.class))) { if (genericParameterType == null) { genericParameterType = methodParameter.getGenericParameterType(); if (genericParameterType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericParameterType; if (parameterizedType.getRawType().equals(Message.class)) { genericParameterType = ((ParameterizedType) genericParameterType) .getActualTypeArguments()[0]; } else if (parameterizedType.getRawType().equals(List.class) && parameterizedType.getActualTypeArguments().length == 1) { Type paramType = parameterizedType.getActualTypeArguments()[0]; this.isConsumerRecordList = paramType.equals(ConsumerRecord.class) || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType) .getRawType().equals(ConsumerRecord.class)); this.isMessageList = paramType.equals(Message.class) || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType).getRawType().equals(Message.class)); } } } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Ambiguous parameters for target payload for method " + method + "; no inferred type available"); } break; } } else if (methodParameter.getGenericParameterType().equals(Acknowledgment.class)) { hasAck = true; } } Assert.state( !this.isConsumerRecordList || method.getParameterTypes().length == 1 || (method.getGenericParameterTypes().length == 2 && hasAck), "A parameter of type 'List<ConsumerRecord>' must be the only parameter " + "(except for an optional 'Acknowledgment')"); Assert.state( !this.isMessageList || method.getParameterTypes().length == 1 || (method.getGenericParameterTypes().length == 2 && hasAck), "A parameter of type 'List<Message<?>>' must be the only parameter " + "(except for an optional 'Acknowledgment')"); return genericParameterType; }
From source file:com.gatf.generator.core.GatfTestGeneratorMojo.java
/** * @param classes Generates all testcases for all the rest-full services found in the classes discovered *//*from w ww . j av a 2s . c o m*/ @SuppressWarnings({ "rawtypes", "unchecked" }) private void generateRestTestCases(List<Class> classes) { try { Map<String, Integer> classTypes = new HashMap<String, Integer>(); for (Class claz : classes) { classTypes.put(claz.getSimpleName(), 0); Annotation theClassPath = claz.getAnnotation(Path.class); if (theClassPath == null) theClassPath = claz.getAnnotation(RequestMapping.class); if (theClassPath != null) { List<TestCase> tcases = new ArrayList<TestCase>(); Method[] methods = claz.getMethods(); for (Method method : methods) { Annotation theMethodPath = method.getAnnotation(Path.class); if (theMethodPath == null) theMethodPath = method.getAnnotation(RequestMapping.class); if (theMethodPath != null) { TestCase tcase = new TestCase(); String completeServicePath = null; String httpMethod = ""; String consumes = "text/plain"; if (theClassPath instanceof Path && theMethodPath instanceof Path) { Path cpath = (Path) theClassPath; Path mpath = (Path) theMethodPath; completeServicePath = cpath.value() + mpath.value(); } else if (theClassPath instanceof RequestMapping && theMethodPath instanceof RequestMapping) { RequestMapping cpath = (RequestMapping) theClassPath; RequestMapping mpath = (RequestMapping) theMethodPath; completeServicePath = cpath.value()[0] + mpath.value()[0]; httpMethod = mpath.method()[0].name(); consumes = mpath.consumes()[0]; } else { throw new Exception( "Invalid Annotation found on the Service class - " + claz.getSimpleName()); } if (completeServicePath != null && completeServicePath.charAt(0) == '/') { completeServicePath = completeServicePath.substring(1); } String url = getUrl(completeServicePath); String completeServiceSubmitPath = url; Type[] argTypes = method.getGenericParameterTypes(); Annotation[][] argAnot = method.getParameterAnnotations(); boolean mayBemultipartContent = false; if (isDebugEnabled()) getLog().info( "Started looking at " + claz.getSimpleName() + " " + method.getName()); ViewField contentvf = null; Map<String, String> params = new HashMap<String, String>(); Map<String, String> hparams = new HashMap<String, String>(); for (int i = 0; i < argTypes.length; i++) { Annotation[] annotations = getRestArgAnnotation(argAnot[i]); if (annotations[0] != null) { String formpnm = null; if (annotations[0] instanceof FormParam) { formpnm = ((FormParam) annotations[0]).value(); if (annotations[1] != null) params.put(formpnm, ((DefaultValue) annotations[1]).value()); else params.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } if (annotations[0] instanceof RequestParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (((RequestParam) annotations[0]).defaultValue() != null) completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).defaultValue() + "}&"; else completeServiceSubmitPath += ((RequestParam) annotations[0]).value() + "={" + ((RequestParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof QueryParam) { if (completeServiceSubmitPath.indexOf("?") == -1) completeServiceSubmitPath += "?"; if (completeServiceSubmitPath .charAt(completeServiceSubmitPath.length() - 1) != '&') completeServiceSubmitPath += "&"; if (annotations[1] != null) completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((DefaultValue) annotations[1]).value() + "}&"; else completeServiceSubmitPath += ((QueryParam) annotations[0]).value() + "={" + ((QueryParam) annotations[0]).value() + "}&"; continue; } if (annotations[0] instanceof HeaderParam) { formpnm = ((HeaderParam) annotations[0]).value(); if (annotations[1] != null) hparams.put(formpnm, ((DefaultValue) annotations[1]).value()); else hparams.put(formpnm, String.valueOf(getPrimitiveValue(argTypes[i]))); continue; } } else { ViewField vf = getViewField(argTypes[i]); if (vf != null) { contentvf = vf; if (isDebugEnabled()) getLog().info("Done looking at " + claz.getSimpleName() + " " + method.getName()); break; } else { mayBemultipartContent = true; } } } classTypes.put(claz.getSimpleName(), classTypes.get(claz.getSimpleName()) + 1); Annotation hm = method.getAnnotation(POST.class); if (hm != null) { httpMethod = "POST"; } else { hm = method.getAnnotation(GET.class); if (hm != null) { httpMethod = "GET"; } else { hm = method.getAnnotation(PUT.class); if (hm != null) { httpMethod = "PUT"; } else { hm = method.getAnnotation(DELETE.class); if (hm != null) { httpMethod = "DELETE"; } } } } Annotation annot = method.getAnnotation(Consumes.class); if (annot != null) { consumes = ((Consumes) annot).value()[0]; } String produces = null; if ("JSON".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_JSON; } else if ("XML".equalsIgnoreCase(getOutDataType())) { produces = MediaType.APPLICATION_XML; } else { produces = MediaType.TEXT_PLAIN; } annot = method.getAnnotation(Produces.class); if (annot != null) { produces = ((Produces) annot).value()[0]; } String content = ""; try { if (!params.isEmpty() || consumes.equals(MediaType.APPLICATION_FORM_URLENCODED)) { for (Map.Entry<String, String> entry : params.entrySet()) { content += entry.getKey() + "=" + entry.getValue() + "&"; } consumes = MediaType.APPLICATION_FORM_URLENCODED; } else if (contentvf != null && contentvf.getValue() != null && contentvf.getValue() instanceof String) { content = (String) contentvf.getValue(); } else if (("JSON".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_JSON)) && contentvf != null && contentvf.getValue() != null) { content = new ObjectMapper().writerWithDefaultPrettyPrinter() .writeValueAsString(contentvf.getValue()); consumes = MediaType.APPLICATION_JSON; } else if (("XML".equalsIgnoreCase(getInDataType()) || consumes.equals(MediaType.APPLICATION_XML)) && contentvf != null && contentvf.getValue() != null) { JAXBContext context = JAXBContext.newInstance(contentvf.getValue().getClass()); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); StringWriter writer = new StringWriter(); m.marshal(contentvf.getValue(), writer); content = writer.toString(); consumes = MediaType.APPLICATION_XML; } else if ((httpMethod.equals("POST") || httpMethod.equals("PUT")) && mayBemultipartContent) { consumes = MediaType.MULTIPART_FORM_DATA; } else if (httpMethod.equals("GET") || httpMethod.equals("DELETE")) { consumes = ""; } } catch (Exception e) { getLog().error(e); } if (consumes != null && !consumes.trim().isEmpty()) { hparams.put(HttpHeaders.CONTENT_TYPE, consumes); } completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("\\?&", "?"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("&&", "&"); completeServiceSubmitPath = completeServiceSubmitPath.replaceAll("/\\?", "?"); completeServiceSubmitPath = completeServiceSubmitPath.trim(); if (completeServiceSubmitPath.charAt(completeServiceSubmitPath.length() - 1) == '&') { completeServiceSubmitPath = completeServiceSubmitPath.substring(0, completeServiceSubmitPath.length() - 1); } tcase.setUrl(completeServiceSubmitPath); tcase.setMethod(httpMethod); tcase.setContent(content); tcase.setName(claz.getName() + "." + method.getName()); tcase.setDescription(tcase.getName()); tcase.setDetailedLog(false); tcase.setSkipTest(false); tcase.setSecure(isOverrideSecure()); tcase.setSoapBase(false); tcase.setExpectedResCode(200); tcase.setExpectedResContentType(produces); if (hparams.size() > 0) tcase.setHeaders(hparams); if (tcase.getNumberOfExecutions() == null) tcase.setNumberOfExecutions(1); if (tcase.getExpectedNodes().size() == 0) tcase.setExpectedNodes(null); if (tcase.getWorkflowContextParameterMap().size() == 0) tcase.setWorkflowContextParameterMap(null); if (tcase.getSoapParameterValues().size() == 0) tcase.setSoapParameterValues(null); if (tcase.getRepeatScenarios().size() == 0) tcase.setRepeatScenarios(null); if (tcase.getMultipartContent().size() == 0) tcase.setMultipartContent(null); tcases.add(tcase); } } if (!tcases.isEmpty()) { if ("json".equalsIgnoreCase(getTestCaseFormat())) { String postManJson = new ObjectMapper().writeValueAsString(tcases); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } else if ("csv".equalsIgnoreCase(getTestCaseFormat())) { StringBuilder build = new StringBuilder(); for (TestCase testCase : tcases) { build.append(testCase.toCSV()); build.append(SystemUtils.LINE_SEPARATOR); } String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.csv"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(build.toString()); bw.close(); } else { XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new GatfPrettyPrintWriter(out, TestCase.CDATA_NODES); } }); xstream.processAnnotations(new Class[] { TestCase.class }); xstream.alias("TestCases", List.class); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_rest.xml"; xstream.toXML(tcases, new FileOutputStream(file)); } if (getPostmanCollectionVersion() > 0) { PostmanCollection postmanCollection = new PostmanCollection(); postmanCollection.setName(claz.getSimpleName()); postmanCollection.setDescription(postmanCollection.getName()); for (TestCase testCase : tcases) { postmanCollection.addTestCase(testCase, getPostmanCollectionVersion()); } String postManJson = new ObjectMapper().writeValueAsString(postmanCollection); String file = getResourcepath() + File.separator + claz.getName().replaceAll("\\.", "_") + "_testcases_postman.json"; BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(postManJson); bw.close(); } } } } } catch (Exception e) { getLog().error(e); } }
From source file:org.apache.flink.api.java.typeutils.TypeExtractor.java
/** * Checks if the given field is a valid pojo field: * - it is public// w ww.ja v a 2s . c om * OR * - there are getter and setter methods for the field. * * @param f field to check * @param clazz class of field * @param typeHierarchy type hierarchy for materializing generic types */ private boolean isValidPojoField(Field f, Class<?> clazz, ArrayList<Type> typeHierarchy) { if (Modifier.isPublic(f.getModifiers())) { return true; } else { boolean hasGetter = false, hasSetter = false; final String fieldNameLow = f.getName().toLowerCase().replaceAll("_", ""); Type fieldType = f.getGenericType(); Class<?> fieldTypeWrapper = ClassUtils.primitiveToWrapper(f.getType()); TypeVariable<?> fieldTypeGeneric = null; if (fieldType instanceof TypeVariable) { fieldTypeGeneric = (TypeVariable<?>) fieldType; fieldType = materializeTypeVariable(typeHierarchy, (TypeVariable<?>) fieldType); } for (Method m : clazz.getMethods()) { final String methodNameLow = m.getName().endsWith("_$eq") ? m.getName().toLowerCase().replaceAll("_", "").replaceFirst("\\$eq$", "_\\$eq") : m.getName().toLowerCase().replaceAll("_", ""); // check for getter if ( // The name should be "get<FieldName>" or "<fieldName>" (for scala) or "is<fieldName>" for boolean fields. (methodNameLow.equals("get" + fieldNameLow) || methodNameLow.equals("is" + fieldNameLow) || methodNameLow.equals(fieldNameLow)) && // no arguments for the getter m.getParameterTypes().length == 0 && // return type is same as field type (or the generic variant of it) (m.getGenericReturnType().equals(fieldType) || (fieldTypeWrapper != null && m.getReturnType().equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericReturnType().equals(fieldTypeGeneric)))) { if (hasGetter) { throw new IllegalStateException("Detected more than one getter"); } hasGetter = true; } // check for setters (<FieldName>_$eq for scala) if ((methodNameLow.equals("set" + fieldNameLow) || methodNameLow.equals(fieldNameLow + "_$eq")) && m.getParameterTypes().length == 1 && // one parameter of the field's type (m.getGenericParameterTypes()[0].equals(fieldType) || (fieldTypeWrapper != null && m.getParameterTypes()[0].equals(fieldTypeWrapper)) || (fieldTypeGeneric != null && m.getGenericParameterTypes()[0].equals(fieldTypeGeneric))) && // return type is void. m.getReturnType().equals(Void.TYPE)) { if (hasSetter) { throw new IllegalStateException("Detected more than one setter"); } hasSetter = true; } } if (hasGetter && hasSetter) { return true; } else { if (!hasGetter) { LOG.debug(clazz + " does not contain a getter for field " + f.getName()); } if (!hasSetter) { LOG.debug(clazz + " does not contain a setter for field " + f.getName()); } return false; } } }
From source file:com.github.helenusdriver.driver.impl.ClassInfoImpl.java
/** * Finds an initial objects factory method for the POJO if configured. * * @author paouelle/*from w w w. j ava2s .c o m*/ * * @return the initial objects factory method or <code>null</code> if none * configured * @throws IllegalArgumentException if the initial objects method is not * properly defined */ private Method findInitial() { final InitialObjects io = clazz.getAnnotation(InitialObjects.class); if (io != null) { final String mname = io.staticMethod(); try { final Method m = (suffixesByType.isEmpty() ? clazz.getMethod(mname) : clazz.getMethod(mname, Map.class)); // validate the method is static if (!Modifier.isStatic(m.getModifiers())) { throw new IllegalArgumentException("initial objects method '" + mname + "' is not static in class: " + clazz.getSimpleName()); } // validate the return type is compatible with this class and is an array final Class<?> type = m.getReturnType(); if (!type.isArray()) { throw new IllegalArgumentException("initial objects method '" + mname + "' doesn't return an array in class: " + clazz.getSimpleName()); } final Class<?> ctype = type.getComponentType(); if (!ctype.isAssignableFrom(clazz)) { throw new IllegalArgumentException("incompatible returned class '" + ctype.getName() + "' for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } // validate that if suffixes are defined, the method expects a Map<String, String> // to provide the values for the suffixes when initializing objects final Class<?>[] cparms = m.getParameterTypes(); if (suffixesByType.isEmpty()) { // should always be 0 as we used no classes in getMethod() if (cparms.length != 0) { throw new IllegalArgumentException("expecting no parameters for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } } else { // should always be 1 as we used only 1 class in getMethod() if (cparms.length != 1) { throw new IllegalArgumentException( "expecting one Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } // should always be a map as we used a Map to find the method if (!Map.class.isAssignableFrom(cparms[0])) { throw new IllegalArgumentException("expecting parameter for initial objects method '" + mname + "' to be of type Map<String, String> in class: " + clazz.getSimpleName()); } final Type[] tparms = m.getGenericParameterTypes(); // should always be 1 as we used only 1 class in getMethod() if (tparms.length != 1) { // should always be 1 as it was already tested above throw new IllegalArgumentException( "expecting one Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } if (tparms[0] instanceof ParameterizedType) { final ParameterizedType ptype = (ParameterizedType) tparms[0]; // maps will always have 2 arguments for (final Type atype : ptype.getActualTypeArguments()) { final Class<?> aclazz = ReflectionUtils.getRawClass(atype); if (String.class != aclazz) { throw new IllegalArgumentException( "expecting a Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } } } else { throw new IllegalArgumentException( "expecting a Map<String, String> parameter for initial objects method '" + mname + "' in class: " + clazz.getSimpleName()); } } return m; } catch (NoSuchMethodException e) { throw new IllegalArgumentException( "missing initial objects method '" + mname + "' in class: " + clazz.getSimpleName(), e); } } return null; }
From source file:org.apache.axis2.description.java2wsdl.DefaultSchemaGenerator.java
protected Method[] processMethods(Method[] declaredMethods) throws Exception { ArrayList<Method> list = new ArrayList<Method>(); //short the elements in the array Arrays.sort(declaredMethods, new MathodComparator()); // since we do not support overload HashMap<String, Method> uniqueMethods = new LinkedHashMap<String, Method>(); XmlSchemaComplexType methodSchemaType; XmlSchemaSequence sequence = null;/*from w w w . j a va2s . c o m*/ for (Method jMethod : declaredMethods) { if (jMethod.isBridge()) { continue; } WebMethodAnnotation methodAnnon = JSR181Helper.INSTANCE.getWebMethodAnnotation(jMethod); String methodName = jMethod.getName(); if (methodAnnon != null) { if (methodAnnon.isExclude()) { continue; } if (methodAnnon.getOperationName() != null) { methodName = methodAnnon.getOperationName(); } } // no need to think abt this method , since that is system // config method if (excludeMethods.contains(methodName)) { continue; } if (!Modifier.isPublic(jMethod.getModifiers())) { // no need to generate Schema for non public methods continue; } if (uniqueMethods.get(methodName) != null) { log.warn("We don't support method overloading. Ignoring [" + methodName + "]"); continue; } boolean addToService = false; AxisOperation axisOperation = service.getOperation(new QName(methodName)); if (axisOperation == null) { axisOperation = Utils.getAxisOperationForJmethod(jMethod); // if (WSDL2Constants.MEP_URI_ROBUST_IN_ONLY.equals( // axisOperation.getMessageExchangePattern())) { // AxisMessage outMessage = axisOperation.getMessage( // WSDLConstants.MESSAGE_LABEL_OUT_VALUE); // if (outMessage != null) { // outMessage.setName(methodName + RESPONSE); // } // } addToService = true; } // by now axis operation should be assigned but we better recheck & add the paramether if (axisOperation != null) { axisOperation.addParameter("JAXRSAnnotaion", JAXRSUtils.getMethodModel(this.classModel, jMethod)); } // Maintain a list of methods we actually work with list.add(jMethod); processException(jMethod, axisOperation); uniqueMethods.put(methodName, jMethod); Class<?>[] parameters = jMethod.getParameterTypes(); String parameterNames[] = null; AxisMessage inMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_IN_VALUE); if (inMessage != null) { inMessage.setName(methodName + Java2WSDLConstants.MESSAGE_SUFFIX); } if (parameters.length > 0) { parameterNames = methodTable.getParameterNames(methodName); // put the parameter names to use it for parsing service.addParameter(methodName, parameterNames); } // we need to add the method opration wrapper part even to // empty parameter operations sequence = new XmlSchemaSequence(); String requestElementSuffix = getRequestElementSuffix(); String requestLocalPart = methodName; if (requestElementSuffix != null) { requestLocalPart += requestElementSuffix; } methodSchemaType = createSchemaTypeForMethodPart(requestLocalPart); methodSchemaType.setParticle(sequence); inMessage.setElementQName(typeTable.getQNamefortheType(requestLocalPart)); Parameter param = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (param != null) { inMessage.setPartName((String) param.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); Annotation[][] parameterAnnotation = jMethod.getParameterAnnotations(); Type[] genericParameterTypes = jMethod.getGenericParameterTypes(); for (int j = 0; j < parameters.length; j++) { Class<?> methodParameter = parameters[j]; String parameterName = getParameterName(parameterAnnotation, j, parameterNames); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, jMethod.getName()); break; } else { Type genericParameterType = genericParameterTypes[j]; Type genericType = null; if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); genericType = parameterArgTypes[0]; generateSchemaForType(sequence, genericType, parameterName, true); } else { generateSchemaForType(sequence, methodParameter, parameterName); } } } // for its return type Class<?> returnType = jMethod.getReturnType(); if (!"void".equals(jMethod.getReturnType().getName())) { String partQname = methodName + RESPONSE; methodSchemaType = createSchemaTypeForMethodPart(partQname); sequence = new XmlSchemaSequence(); methodSchemaType.setParticle(sequence); WebResultAnnotation returnAnnon = JSR181Helper.INSTANCE.getWebResultAnnotation(jMethod); String returnName = "return"; if (returnAnnon != null) { returnName = returnAnnon.getName(); if (returnName == null || "".equals(returnName)) { returnName = "return"; } } Type genericParameterType = jMethod.getGenericReturnType(); if (nonRpcMethods.contains(jMethod.getName())) { generateSchemaForType(sequence, null, returnName); } else if (genericParameterType instanceof ParameterizedType) { ParameterizedType aType = (ParameterizedType) genericParameterType; Type[] parameterArgTypes = aType.getActualTypeArguments(); generateSchemaForType(sequence, parameterArgTypes[0], returnName, true); } else { generateSchemaForType(sequence, returnType, returnName); } AxisMessage outMessage = axisOperation.getMessage(WSDLConstants.MESSAGE_LABEL_OUT_VALUE); outMessage.setElementQName(typeTable.getQNamefortheType(partQname)); outMessage.setName(partQname); Parameter outparam = service.getParameter(Java2WSDLConstants.MESSAGE_PART_NAME_OPTION_LONG); if (outparam != null) { outMessage.setPartName((String) outparam.getValue()); } service.addMessageElementQNameToOperationMapping(methodSchemaType.getQName(), axisOperation); } if (addToService) { service.addOperation(axisOperation); } } return list.toArray(new Method[list.size()]); }
From source file:plugins.PlayReader.java
private Operation parseMethod(Class<?> cls, Method method, List<Parameter> globalParameters) { Operation operation = new Operation(); ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class); ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class); String operationId = method.getName(); String responseContainer = null; Type responseType = null;//from w w w . j a v a 2s .com Map<String, Property> defaultResponseHeaders = new HashMap<String, Property>(); if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!"".equals(apiOperation.nickname())) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); if (apiOperation.response() != null && !isVoid(apiOperation.response())) { responseType = apiOperation.response(); } if (!"".equals(apiOperation.responseContainer())) { responseContainer = apiOperation.responseContainer(); } if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) { operation.security(sec); } } } if (apiOperation.consumes() != null && !apiOperation.consumes().isEmpty()) { operation.consumes(apiOperation.consumes()); } if (apiOperation.produces() != null && !apiOperation.produces().isEmpty()) { operation.produces(apiOperation.produces()); } } if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) { Response response = new Response().description(SUCCESSFUL_OPERATION); response.schema(new RefProperty(apiOperation.responseReference())); operation.addResponse(String.valueOf(apiOperation.code()), response); } else if (responseType == null) { // pick out response from method declaration Logger.debug("picking up response class from method " + method); responseType = method.getGenericReturnType(); } if (isValidResponse(responseType)) { final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property); final int responseCode = apiOperation == null ? 200 : apiOperation.code(); operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION) .schema(responseProperty).headers(defaultResponseHeaders)); appendModels(responseType); } } operation.operationId(operationId); if (apiOperation != null && apiOperation.consumes() != null && apiOperation.consumes().isEmpty()) { final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) { operation.consumes(mediaType); } } } if (apiOperation != null && apiOperation.produces() != null && apiOperation.produces().isEmpty()) { final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : ReaderUtils.splitContentValues(produces.value())) { operation.produces(mediaType); } } } List<ApiResponse> apiResponses = new ArrayList<ApiResponse>(); if (responseAnnotation != null) { for (ApiResponse apiResponse : responseAnnotation.value()) { Map<String, Property> responseHeaders = parseResponseHeaders(apiResponse.responseHeaders()); Response response = new Response().description(apiResponse.message()).headers(responseHeaders); if (apiResponse.code() == 0) { operation.defaultResponse(response); } else { operation.response(apiResponse.code(), response); } if (StringUtils.isNotEmpty(apiResponse.reference())) { response.schema(new RefProperty(apiResponse.reference())); } else if (!isVoid(apiResponse.response())) { responseType = apiResponse.response(); final Property property = ModelConverters.getInstance().readAsProperty(responseType); if (property != null) { response.schema(ContainerWrapper.wrapContainer(apiResponse.responseContainer(), property)); appendModels(responseType); } } } } if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) { operation.setDeprecated(true); } // process parameters for (Parameter globalParameter : globalParameters) { operation.parameter(globalParameter); } Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); for (int i = 0; i < genericParameterTypes.length; i++) { final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls); List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i])); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { Response response = new Response().description(SUCCESSFUL_OPERATION); operation.defaultResponse(response); } return operation; }