/* ------------------------------------------------------------ */ public int setProps(Object obj, Map<?, ?> props) { int count = 0; for (Iterator<?> iterator = props.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) iterator.next(); Setter setter = getSetter((String) entry.getKey()); if (setter != null) { try { setter.invoke(obj, entry.getValue()); count++; } catch (Exception e) { // TODO throw exception? LOG.warn( _pojoClass.getName() + "#" + setter.getPropertyName() + " not set from " + (entry.getValue().getClass().getName()) + "=" + entry.getValue().toString()); log(e); } } } return count; }
public static Bundle convertToBundle(JSONObject jsonObject) throws JSONException { Bundle bundle = new Bundle(); @SuppressWarnings("unchecked") Iterator<String> jsonIterator = jsonObject.keys(); while (jsonIterator.hasNext()) { String key = jsonIterator.next(); Object value = jsonObject.get(key); if (value == null || value == JSONObject.NULL) { // Null is not supported. continue; } // Special case JSONObject as it's one way, on the return it would be Bundle. if (value instanceof JSONObject) { bundle.putBundle(key, convertToBundle((JSONObject) value)); continue; } Setter setter = SETTERS.get(value.getClass()); if (setter == null) { throw new IllegalArgumentException("Unsupported type: " + value.getClass()); } setter.setOnBundle(bundle, key, value); } return bundle; }
String setTreeFieldsAndSave(String formName, Setter... setters) throws InterruptedException { String currentNode = selenium.getAttribute("//input[@name='currentNode']@value"); assertTrue(currentNode.startsWith(formName + ".")); String prefix = currentNode.replace(formName + ".", ""); for (Setter setter : setters) { setter.setField(prefix); } selenium.click("//input[contains(@onclick, '" + currentNode + "') and @value='Save']"); return currentNode; }
public RibbonCommand( String commandKey, RestClient restClient, HttpClientRequest.Verb verb, String uri, MultivaluedMap<String, String> headers, MultivaluedMap<String, String> params, InputStream requestEntity) throws URISyntaxException { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandKey)) .andCommandPropertiesDefaults( // we want to default to semaphore-isolation since this wraps // 2 others commands that are already thread isolated HystrixCommandProperties.Setter() .withExecutionIsolationStrategy( HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE) .withExecutionIsolationSemaphoreMaxConcurrentRequests( DynamicPropertyFactory.getInstance() .getIntProperty( ZuulConstants.ZUUL_EUREKA + commandKey + ".semaphore.maxSemaphores", 100) .get()))); this.restClient = restClient; this.verb = verb; this.uri = new URI(uri); this.headers = headers; this.params = params; this.requestEntity = requestEntity; }
private void set(String paramName, Setter s) throws DataLinkException { for (int i = 0; i < params.length; i++) { if (params[i] != null && params[i].equals(paramName)) { s.set(i + 1); } } }
public TimeOutCommand(int timeout, DataBaseManager resource, String productId) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(COMMAND_GROUP)) .andCommandPropertiesDefaults( HystrixCommandProperties.Setter() .withExecutionIsolationThreadTimeoutInMilliseconds((timeout)))); this.resource = resource; this.productId = productId; }
private SecondaryCommand(int id) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX")) .andCommandKey(HystrixCommandKey.Factory.asKey("SecondaryCommand")) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey("SecondaryCommand")) .andCommandPropertiesDefaults( // we default to a 100ms timeout for secondary HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(100))); this.id = id; }
/** * A failsafe GET request which takes the client, request and response handler to use to send the * request and send a response * * @param client the http client * @param request the request to make using the client * @param responseHandler the response handler */ public FailSafeGetRequest( HttpClient client, HttpGet request, ResponseHandler<Address> responseHandler) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(PERSON_GROUP)) .andCommandKey(HystrixCommandKey.Factory.asKey(ADDRESS_GET_COMMAND)) .andThreadPoolKey(HystrixThreadPoolKey.Factory.asKey(ADDRESS_CLIENT_POOL))); this.client = client; this.responseHandler = responseHandler; this.request = request; }
public GetLogsCommand(String key) { super( Setter.withGroupKey( HystrixCommandGroupKey.Factory.asKey(FluxConstants.MIDDLETIER_HYSTRIX_GROUP)) .andCommandKey( HystrixCommandKey.Factory.asKey( FluxConstants.MIDDLETIER_HYSTRIX_GET_LOGS_COMMAND_KEY)) .andThreadPoolKey( HystrixThreadPoolKey.Factory.asKey(FluxConstants.MIDDLETIER_HYSTRIX_THREAD_POOL))); this.key = key; }
public CommandFacadeWithPrimarySecondary(int id) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("SystemX")) .andCommandKey(HystrixCommandKey.Factory.asKey("PrimarySecondaryCommand")) .andCommandPropertiesDefaults( // we want to default to semaphore-isolation since this wraps // 2 others commands that are already thread isolated HystrixCommandProperties.Setter() .withExecutionIsolationStrategy( HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE))); this.id = id; }
public static JSONObject convertToJSON(Bundle bundle) throws JSONException { JSONObject json = new JSONObject(); for (String key : bundle.keySet()) { Object value = bundle.get(key); if (value == null) { // Null is not supported. continue; } // Special case List<String> as getClass would not work, since List is an interface if (value instanceof List<?>) { JSONArray jsonArray = new JSONArray(); @SuppressWarnings("unchecked") List<String> listValue = (List<String>) value; for (String stringValue : listValue) { jsonArray.put(stringValue); } json.put(key, jsonArray); continue; } // Special case Bundle as it's one way, on the return it will be JSONObject if (value instanceof Bundle) { json.put(key, convertToJSON((Bundle) value)); continue; } Setter setter = SETTERS.get(value.getClass()); if (setter == null) { throw new IllegalArgumentException("Unsupported type: " + value.getClass()); } setter.setOnJSON(json, key, value); } return json; }
/** * Constructor for REST WebService HystrixCommand class, passing in all the parameters to execute * the call. * * @param commandName String the web service call name used to create the Hystrix Command Key * @param groupKeyName The group key under which this web service call falls * @param httpRequest Request method to be executed * @param httpClient HttpClient that executes the request * @param httpContext Http request execution context */ public CommandRestResourceCall( final String groupKeyName, final String commandName, final HttpRequestBase httpRequest, final HttpClient httpClient, final HttpContext httpContext) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKeyName)) .andCommandKey(HystrixCommandKey.Factory.asKey(commandName))); checkNullArguments(groupKeyName, commandName, httpRequest, httpClient, httpContext); this.commandName = commandName; this.httpRequest = httpRequest; this.httpClient = httpClient; this.httpContext = httpContext; }
public ShedLoadInventoryRequestCommand( final InventoryRequester inventoryRequester, final Store store, final Product product) { super( Setter.withGroupKey( HystrixCommandGroupKey.Factory.asKey( ShedLoadInventoryRequestCommand.class.getSimpleName())) .andCommandKey( HystrixCommandKey.Factory.asKey( ShedLoadInventoryRequestCommand.class.getSimpleName())) .andCommandPropertiesDefaults( HystrixCommandProperties.Setter() .withCircuitBreakerRequestVolumeThreshold(10) .withCircuitBreakerForceClosed(true) .withExecutionTimeoutInMilliseconds(200)), inventoryRequester, store, product); }
public Command( String commandKey, boolean shouldFail, boolean shouldFailWithBadRequest, long latencyToAdd, int sleepWindow, int requestVolumeThreshold) { super( Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("Command")) .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey)) .andCommandPropertiesDefaults( HystrixCommandPropertiesTest.getUnitTestPropertiesSetter() .withExecutionTimeoutInMilliseconds(500) .withCircuitBreakerRequestVolumeThreshold(requestVolumeThreshold) .withCircuitBreakerSleepWindowInMilliseconds(sleepWindow))); this.shouldFail = shouldFail; this.shouldFailWithBadRequest = shouldFailWithBadRequest; this.latencyToAdd = latencyToAdd; }
public void setValue(I obj, T value) { setter.set(obj, value); }
@SuppressWarnings({"unchecked", "rawtypes"}) public Object jsonToObject(final JSonNode json, Type type) throws MapperException { final ClassCache cc; try { Class<?> clazz = null; if (type instanceof ParameterizedType) { Type typ = ((ParameterizedType) type).getRawType(); if (typ instanceof Class) { clazz = (Class<?>) typ; } } else if (type instanceof Class) { clazz = (Class) type; } else if (type instanceof GenericArrayType) { // this is for 1.6 // for 1.7 we do not get GenericArrayTypeImpl here but the // actual array class type = clazz = Array.newInstance((Class<?>) ((GenericArrayType) type).getGenericComponentType(), 0) .getClass(); } if (clazz == null || clazz == Object.class) { if (json instanceof JSonArray) { type = clazz = LinkedList.class; } else if (json instanceof JSonObject) { type = clazz = HashMap.class; } else if (json instanceof JSonValue) { switch (((JSonValue) json).getType()) { case BOOLEAN: type = clazz = boolean.class; break; case DOUBLE: type = clazz = double.class; break; case LONG: type = clazz = long.class; break; case NULL: case STRING: type = clazz = String.class; } } } final TypeMapper<?> tm = typeMapper.get(clazz); if (tm != null) { return tm.reverseMap(json); } if (json instanceof JSonValue) { if (!Clazz.isPrimitive(type) && !Clazz.isString(type) && type != Object.class && ((JSonValue) json).getValue() != null && !Clazz.isEnum(type)) { // throw new MapperException(json + " cannot be mapped to " + type); } switch (((JSonValue) json).getType()) { case BOOLEAN: case DOUBLE: case LONG: if (type instanceof Class) { return JSonMapper.cast(((JSonValue) json).getValue(), (Class) type); } else { return ((JSonValue) json).getValue(); } case STRING: if (type instanceof Class && ((Class<?>) type).isEnum()) { try { return Enum.valueOf((Class<Enum>) type, ((JSonValue) json).getValue() + ""); } catch (final IllegalArgumentException e) { if (isIgnoreIllegalArgumentMappings() || isIgnoreIllegalEnumMappings()) { return null; } throw e; } } else { return ((JSonValue) json).getValue(); } case NULL: return null; } } if (type instanceof ParameterizedType) { final ParameterizedType pType = (ParameterizedType) type; Type raw = pType.getRawType(); if (raw instanceof Class && Collection.class.isAssignableFrom((Class) raw)) { final Collection<Object> inst = (Collection<Object>) mapClasses((Class) raw).newInstance(); final JSonArray obj = (JSonArray) json; for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, pType.getActualTypeArguments()[0])); } return inst; } else if (raw instanceof Class && Map.class.isAssignableFrom((Class) raw)) { final Map<String, Object> inst = (Map<String, Object>) mapClasses((Class) raw).newInstance(); final JSonObject obj = (JSonObject) json; Entry<String, JSonNode> next; for (final Iterator<Entry<String, JSonNode>> it = obj.entrySet().iterator(); it.hasNext(); ) { next = it.next(); inst.put( next.getKey(), this.jsonToObject(next.getValue(), pType.getActualTypeArguments()[1])); } return inst; } } if (clazz != null) { if (clazz == Object.class) { // guess type if (json instanceof JSonArray) { type = LinkedList.class; } else if (json instanceof JSonObject) { type = HashMap.class; } } if (Collection.class.isAssignableFrom(clazz)) { final Collection<Object> inst = (Collection<Object>) mapClasses(clazz).newInstance(); final JSonArray obj = (JSonArray) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[0]; } else { gType = void.class; } for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, gType)); } return inst; } else if (Map.class.isAssignableFrom(clazz)) { final Map<String, Object> inst = (Map<String, Object>) mapClasses(clazz).newInstance(); final JSonObject obj = (JSonObject) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[1]; } else { gType = void.class; } Entry<String, JSonNode> next; for (final Iterator<Entry<String, JSonNode>> it = obj.entrySet().iterator(); it.hasNext(); ) { next = it.next(); inst.put(next.getKey(), this.jsonToObject(next.getValue(), gType)); } return inst; } else if (clazz.isArray()) { final JSonArray obj = (JSonArray) json; final Object arr = Array.newInstance(mapClasses(clazz.getComponentType()), obj.size()); for (int i = 0; i < obj.size(); i++) { final Object v = this.jsonToObject(obj.get(i), clazz.getComponentType()); Array.set(arr, i, v); } return arr; } else { if (json instanceof JSonArray) { final java.util.List<Object> inst = new ArrayList<Object>(); final JSonArray obj = (JSonArray) json; final Type gs = clazz.getGenericSuperclass(); final Type gType; if (gs instanceof ParameterizedType) { gType = ((ParameterizedType) gs).getActualTypeArguments()[0]; } else { gType = Object.class; } for (final JSonNode n : obj) { inst.add(this.jsonToObject(n, gType)); } return inst; } else { final JSonObject obj = (JSonObject) json; if (Clazz.isPrimitive(clazz)) { // if (isIgnoreIllegalArgumentMappings()) { return null; } else { throw new IllegalArgumentException("Cannot Map " + obj + " to " + clazz); } } cc = ClassCache.getClassCache(clazz); final Object inst = cc.getInstance(); JSonNode value; Object v; for (final Setter s : cc.getSetter()) { value = obj.get(s.getKey()); if (value == null) { continue; } // Type fieldType = s.getType(); // special handling for generic fields if (fieldType instanceof TypeVariable) { final Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments(); final TypeVariable<?>[] genericTypes = clazz.getTypeParameters(); for (int i = 0; i < genericTypes.length; i++) { if (StringUtils.equals( ((TypeVariable) fieldType).getName(), genericTypes[i].getName())) { fieldType = actualTypes[i]; break; } } } v = this.jsonToObject(value, fieldType); try { s.setValue(inst, v); } catch (final IllegalArgumentException e) { if (isIgnoreIllegalArgumentMappings()) { continue; } else if (v == null && isIgnorePrimitiveNullMapping()) { continue; } throw e; } } return inst; } } } else { System.err.println("TYPE?!"); } } catch (final SecurityException e) { e.printStackTrace(); } catch (final NoSuchMethodException e) { e.printStackTrace(); } catch (final IllegalArgumentException e) { e.printStackTrace(); } catch (final InstantiationException e) { e.printStackTrace(); } catch (final IllegalAccessException e) { e.printStackTrace(); } catch (final InvocationTargetException e) { e.printStackTrace(); } return null; }
void testA(Setter s1, Setter s2, SelfBoundSetter sbs) { s1.set(s2); // s1.set(sbs); // Error: // set(Setter) in SelfBoundSetter<Setter> // cannot be applied to (SelfBoundSetter) }
public AbstractNode decode( org.w3c.dom.Element xmlElement, java.util.Map<Integer, AbstractDeclaration> map) { AbstractNode rv; if (xmlElement.hasAttribute(CodecConstants.TYPE_ATTRIBUTE)) { String clsName = getClassName(xmlElement); if (clsName.equals(JavaType.class.getName())) { rv = JavaType.getInstance(decodeType(xmlElement, "type")); } else if (clsName.equals(UserArrayType.class.getName())) { rv = decodeUserArrayType(xmlElement, map); } else if (clsName.equals(JavaConstructor.class.getName())) { rv = JavaConstructor.getInstance(decodeConstructor(xmlElement, "constructor")); } else if (clsName.equals(JavaMethod.class.getName())) { MethodReflectionProxy methodReflectionProxy = decodeMethod(xmlElement, "method"); MethodReflectionProxy varArgsReplacement = MethodReflectionProxy.getReplacementIfNecessary(methodReflectionProxy); if (varArgsReplacement != null) { edu.cmu.cs.dennisc.java.util.logging.Logger.errln( "replacing", methodReflectionProxy, "with", varArgsReplacement); methodReflectionProxy = varArgsReplacement; } rv = JavaMethod.getInstance(methodReflectionProxy); } else if (clsName.equals(Getter.class.getName()) || clsName.equals(Setter.class.getName())) { org.w3c.dom.Node xmlFirstChild = xmlElement.getFirstChild(); if (xmlFirstChild instanceof org.w3c.dom.Element) { org.w3c.dom.Element xmlFirstChildElement = (org.w3c.dom.Element) xmlFirstChild; if (xmlFirstChildElement.hasAttribute(CodecConstants.UNIQUE_KEY_ATTRIBUTE)) { int getterOrSetterUniqueKey = getUniqueKey(xmlElement); int fieldUniqueKey = getUniqueKey(xmlFirstChildElement); java.util.Map<Integer, Integer> mapToFieldKey; if (clsName.equals(Getter.class.getName())) { mapToFieldKey = EPIC_HACK_mapGetterKeyToFieldKey; } else { mapToFieldKey = EPIC_HACK_mapSetterKeyToFieldKey; } mapToFieldKey.put(getterOrSetterUniqueKey, fieldUniqueKey); } } org.w3c.dom.NodeList nodeList = xmlElement.getChildNodes(); assert nodeList.getLength() == 1; org.w3c.dom.Element xmlField = (org.w3c.dom.Element) nodeList.item(0); UserField field = (UserField) decode(xmlField, map); if (clsName.equals(Getter.class.getName())) { rv = field.getGetter(); } else { rv = field.getSetter(); } } else if (clsName.equals(SetterParameter.class.getName())) { org.w3c.dom.NodeList nodeList = xmlElement.getChildNodes(); assert nodeList.getLength() == 1; org.w3c.dom.Element xmlSetter = (org.w3c.dom.Element) nodeList.item(0); Setter setter = (Setter) decode(xmlSetter, map); rv = setter.getRequiredParameters().get(0); } else if (clsName.equals(JavaField.class.getName())) { rv = JavaField.getInstance(decodeField(xmlElement, "field")); } else if (clsName.equals(AnonymousUserConstructor.class.getName())) { rv = decodeAnonymousConstructor(xmlElement, map); } else if (clsName.equals(JavaConstructorParameter.class.getName())) { org.w3c.dom.NodeList nodeList = xmlElement.getChildNodes(); assert nodeList.getLength() == 2; org.w3c.dom.Element xmlConstructor = (org.w3c.dom.Element) nodeList.item(0); JavaConstructor constructorDeclaredInJava = (JavaConstructor) decodeValue(xmlConstructor, map); org.w3c.dom.Element xmlIndex = (org.w3c.dom.Element) nodeList.item(1); int index = Integer.parseInt(xmlIndex.getTextContent()); final int REQUIRED_N = constructorDeclaredInJava.getRequiredParameters().size(); if (index < REQUIRED_N) { rv = constructorDeclaredInJava.getRequiredParameters().get(index); } else { if (index == REQUIRED_N) { rv = constructorDeclaredInJava.getVariableLengthParameter(); if (rv != null) { // pass; } else { rv = constructorDeclaredInJava.getKeyedParameter(); } } else { rv = null; } } } else if (clsName.equals(JavaMethodParameter.class.getName())) { org.w3c.dom.NodeList nodeList = xmlElement.getChildNodes(); assert nodeList.getLength() == 2; org.w3c.dom.Element xmlMethod = (org.w3c.dom.Element) nodeList.item(0); JavaMethod methodDeclaredInJava = (JavaMethod) decodeValue(xmlMethod, map); org.w3c.dom.Element xmlIndex = (org.w3c.dom.Element) nodeList.item(1); int index = Integer.parseInt(xmlIndex.getTextContent()); final int REQUIRED_N = methodDeclaredInJava.getRequiredParameters().size(); if (index < REQUIRED_N) { rv = methodDeclaredInJava.getRequiredParameters().get(index); } else { if (index == REQUIRED_N) { rv = methodDeclaredInJava.getVariableLengthParameter(); if (rv != null) { // pass; } else { rv = methodDeclaredInJava.getKeyedParameter(); } } else { rv = null; } } } else { rv = (AbstractNode) newInstance(xmlElement); assert rv != null; } if (rv instanceof AbstractDeclaration) { map.put(getUniqueKey(xmlElement), (AbstractDeclaration) rv); } rv.decodeNode(this, xmlElement, map); if (xmlElement.hasAttribute(CodecConstants.ID_ATTRIBUTE)) { if (this.policy.isIdPreserved()) { rv.setId(java.util.UUID.fromString(xmlElement.getAttribute(CodecConstants.ID_ATTRIBUTE))); } } } else { int key = getUniqueKey(xmlElement); rv = map.get(key); if (rv != null) { // pass } else { if (EPIC_HACK_mapArrayTypeKeyToLeafTypeKey.containsKey(key)) { int leafTypeKey = EPIC_HACK_mapArrayTypeKeyToLeafTypeKey.get(key); AbstractDeclaration leafDeclaration = map.get(leafTypeKey); if (leafDeclaration instanceof UserType<?>) { UserType<?> leafType = (UserType<?>) leafDeclaration; edu.cmu.cs.dennisc.java.util.logging.Logger.outln(leafTypeKey, leafType); rv = leafType.getArrayType(); } else { assert false : leafDeclaration; } } else if (EPIC_HACK_mapGetterKeyToFieldKey.containsKey(key)) { int fieldKey = EPIC_HACK_mapGetterKeyToFieldKey.get(key); AbstractDeclaration fieldDeclaration = map.get(fieldKey); if (fieldDeclaration instanceof UserField) { UserField userField = (UserField) fieldDeclaration; rv = userField.getGetter(); } } else if (EPIC_HACK_mapSetterKeyToFieldKey.containsKey(key)) { int fieldKey = EPIC_HACK_mapSetterKeyToFieldKey.get(key); AbstractDeclaration fieldDeclaration = map.get(fieldKey); if (fieldDeclaration instanceof UserField) { UserField userField = (UserField) fieldDeclaration; rv = userField.getSetter(); } } else { assert false : Integer.toHexString(key) + " " + map; } } } return rv; }