org.apache.commons.beanutils.BeanMap Java Examples

The following examples show how to use org.apache.commons.beanutils.BeanMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: StramWebServices.java    From Bats with Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/properties")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getOperatorProperties(@PathParam("operatorName") String operatorName, @QueryParam("propertyName") String propertyName) throws IOException, JSONException
{
  init();
  OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName);
  BeanMap operatorProperties = null;
  if (logicalOperator == null) {
    ModuleMeta logicalModule = dagManager.getModuleMeta(operatorName);
    if (logicalModule == null) {
      throw new NotFoundException();
    }
    operatorProperties = LogicalPlanConfiguration.getObjectProperties(logicalModule.getOperator());
  } else {
    operatorProperties = LogicalPlanConfiguration.getObjectProperties(logicalOperator.getOperator());
  }

  Map<String, Object> m = getPropertiesAsMap(propertyName, operatorProperties);
  return new JSONObject(objectMapper.writeValueAsString(m));
}
 
Example #2
Source File: StramWebServices.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getPropertiesAsMap(@QueryParam("propertyName") String propertyName, BeanMap operatorProperties)
{
  Map<String, Object> m = new HashMap<>();
  @SuppressWarnings("rawtypes")
  Iterator entryIterator = operatorProperties.entryIterator();
  while (entryIterator.hasNext()) {
    try {
      @SuppressWarnings("unchecked")
      Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryIterator.next();
      if (propertyName == null) {
        m.put(entry.getKey(), entry.getValue());
      } else if (propertyName.equals(entry.getKey())) {
        m.put(entry.getKey(), entry.getValue());
        break;
      }
    } catch (Exception ex) {
      LOG.warn("Caught exception", ex);
    }
  }
  return m;
}
 
Example #3
Source File: StramWebServices.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/properties")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getOperatorProperties(@PathParam("operatorName") String operatorName, @QueryParam("propertyName") String propertyName) throws IOException, JSONException
{
  init();
  OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName);
  BeanMap operatorProperties = null;
  if (logicalOperator == null) {
    ModuleMeta logicalModule = dagManager.getModuleMeta(operatorName);
    if (logicalModule == null) {
      throw new NotFoundException();
    }
    operatorProperties = LogicalPlanConfiguration.getObjectProperties(logicalModule.getOperator());
  } else {
    operatorProperties = LogicalPlanConfiguration.getObjectProperties(logicalOperator.getOperator());
  }

  Map<String, Object> m = getPropertiesAsMap(propertyName, operatorProperties);
  return new JSONObject(objectMapper.writeValueAsString(m));
}
 
Example #4
Source File: ConfigBean.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
public void onApplyEnvParams() {
    logger.info("onApplyEnvParams: start");
    try {

    	EnvironmentSettings environmentSettings = BeanUtil.getSfContext().getEnvironmentManager().getEnvironmentSettings();
    	BeanMap environmentBeanMap = new BeanMap(environmentSettings);

        for (EnvironmentEntity entry : environmentParamsList) {
        	Class<?> type = environmentBeanMap.getType(entry.getParamName());
        	Object convertedValue = BeanUtilsBean.getInstance().getConvertUtils().convert(entry.getParamValue(), type);
            environmentBeanMap.put(entry.getParamName(), convertedValue);
        }
        BeanUtil.getSfContext().getEnvironmentManager().updateEnvironmentSettings((EnvironmentSettings) environmentBeanMap.getBean());
        BeanUtil.showMessage(FacesMessage.SEVERITY_INFO, "INFO", "Successfully saved. Some options will be applied only after Sailfish restart");
    } catch (Exception e){
        logger.error(e.getMessage(), e);
        BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, "ERROR", e.getMessage());
    }
    logger.info("onApplyEnvParams: end");
}
 
Example #5
Source File: ServiceResource.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
private Element marshal(IServiceSettings settings) throws Exception {
 BeanMap beanMap = new BeanMap(settings);
 
 DOMElement rootElement = new DOMElement(new QName("settings"));
 
 for (Object key : beanMap.keySet()) {
         Object value = beanMap.get(key);
         if (value != null) {
             DOMElement domElement = new DOMElement(new QName(key.toString()));
             domElement.setText(value.toString());
             rootElement.add(domElement);
         }
    }
 
 return rootElement;
}
 
Example #6
Source File: StramToNodeGetPropertyRequest.java    From attic-apex-core with Apache License 2.0 6 votes vote down vote up
@Override
public StatsListener.OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException
{
  BeanMap beanMap = new BeanMap(operator);
  Map<String, Object> propertyValue = new HashMap<>();
  if (propertyName != null) {
    if (beanMap.containsKey(propertyName)) {
      propertyValue.put(propertyName, beanMap.get(propertyName));
    }
  } else {
    Iterator entryIterator = beanMap.entryIterator();
    while (entryIterator.hasNext()) {
      Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryIterator.next();
      propertyValue.put(entry.getKey(), entry.getValue());
    }
  }
  logger.debug("Getting property {} on operator {}", propertyValue, operator);
  OperatorResponse response = new OperatorResponse(requestId, propertyValue);
  return response;
}
 
Example #7
Source File: Output.java    From red5-io with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected Method getGetter(Class<?> objectClass, BeanMap beanMap, String keyName) {
    //check element to prevent null pointer
    Element element = getGetterCache().get(objectClass);
    Map<String, Method> getterMap = (element == null ? null : (Map<String, Method>) element.getObjectValue());
    if (getterMap == null) {
        getterMap = new HashMap<String, Method>();
        getGetterCache().put(new Element(objectClass, getterMap));
    }
    Method getter;
    if (getterMap.containsKey(keyName)) {
        getter = getterMap.get(keyName);
    } else {
        getter = beanMap.getReadMethod(keyName);
        getterMap.put(keyName, getter);
    }
    return getter;
}
 
Example #8
Source File: StramToNodeGetPropertyRequest.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public StatsListener.OperatorResponse execute(Operator operator, int operatorId, long windowId) throws IOException
{
  BeanMap beanMap = new BeanMap(operator);
  Map<String, Object> propertyValue = new HashMap<>();
  if (propertyName != null) {
    if (beanMap.containsKey(propertyName)) {
      propertyValue.put(propertyName, beanMap.get(propertyName));
    }
  } else {
    Iterator entryIterator = beanMap.entryIterator();
    while (entryIterator.hasNext()) {
      Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryIterator.next();
      propertyValue.put(entry.getKey(), entry.getValue());
    }
  }
  logger.debug("Getting property {} on operator {}", propertyValue, operator);
  OperatorResponse response = new OperatorResponse(requestId, propertyValue);
  return response;
}
 
Example #9
Source File: StramWebServices.java    From Bats with Apache License 2.0 6 votes vote down vote up
private Map<String, Object> getPropertiesAsMap(@QueryParam("propertyName") String propertyName, BeanMap operatorProperties)
{
  Map<String, Object> m = new HashMap<>();
  @SuppressWarnings("rawtypes")
  Iterator entryIterator = operatorProperties.entryIterator();
  while (entryIterator.hasNext()) {
    try {
      @SuppressWarnings("unchecked")
      Map.Entry<String, Object> entry = (Map.Entry<String, Object>)entryIterator.next();
      if (propertyName == null) {
        m.put(entry.getKey(), entry.getValue());
      } else if (propertyName.equals(entry.getKey())) {
        m.put(entry.getKey(), entry.getValue());
        break;
      }
    } catch (Exception ex) {
      LOG.warn("Caught exception", ex);
    }
  }
  return m;
}
 
Example #10
Source File: ClassUtils.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> convertBeanToMap(Object ciObj, DynamicEntityMeta entityMeta, boolean includeNullVal, List<String> requestFields) {
    Map<String, Object> ciMap = new HashMap<>();
    BeanMap ciObjMap = new BeanMap(ciObj);
    Collection<FieldNode> nodes = entityMeta.getAllFieldNodes(false);
    for (FieldNode node : nodes) {
        String name = node.getName();
        if (isRequestField(requestFields, name)) {
            Object val = ciObjMap.get(name);
            if (includeNullVal) {
                ciMap.put(name, val);
            } else {
                if (val != null) {
                    ciMap.put(name, val);
                }
            }
        }
    }
    return ciMap;
}
 
Example #11
Source File: CiTypeServiceImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
@Override
    public void updateCiType(int ciTypeId, CiTypeDto ciType) {
        if (!ciTypeRepository.existsById(ciTypeId)) {
            throw new InvalidArgumentException("Can not find out CiType with given argument.", "ciTypeId", ciTypeId);
        }

        Map<String, Object> updateMap = new HashMap<>();
        BeanMap ciTypeMap = new BeanMap(ciType);
        Field[] feilds = CiTypeDto.class.getDeclaredFields();
        for (Field field : feilds) {
            DtoField dtoField = field.getAnnotation(DtoField.class);
            if (ciTypeMap.get(field.getName()) != null && (dtoField == null || (dtoField != null && dtoField.updatable()))) {
                updateMap.put(field.getName(), ciTypeMap.get(field.getName()));
            }
        }
//		AdmCiType existingAdmCiType = ciTypeRepository.getOne(ciTypeId);
        staticDtoService.update(CiTypeDto.class, ciTypeId, updateMap);

        // AdmCiType updatedAdmCiType = ciType.updateTo(existingAdmCiType);
        // ciTypeRepository.saveAndFlush(updatedAdmCiType);

        logger.info(String.format("Updated CI type sucessfully. (CI type id:%d)", ciTypeId));
    }
 
Example #12
Source File: Output.java    From red5-io with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void writeObject(Map<Object, Object> map) {
    if (!checkWriteReference(map)) {
        storeReference(map);
        buf.put(AMF.TYPE_OBJECT);
        boolean isBeanMap = (map instanceof BeanMap);
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            if (isBeanMap && "class".equals(entry.getKey())) {
                continue;
            }
            putString(entry.getKey().toString());
            Serializer.serialize(this, entry.getValue());
        }
        buf.put(AMF.END_OF_OBJECT_SEQUENCE);
    }
}
 
Example #13
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
public <T> T createDynamicEntityBean(Class<T> domainClazz, List<Field> fields, Object[] attrVals) {
    if (fields.size() != attrVals.length) {
        throw new IllegalArgumentException("Domain class properties and attribute values should be same count.");
    }

    T entityBean;
    try {
        entityBean = domainClazz.newInstance();
    } catch (Exception e) {
        throw new ServiceException(String.format("Fail to create domain [%s] entity bean.", domainClazz.toString()));
    }
    BeanMap beanMap = new BeanMap(entityBean);

    final AtomicInteger i = new AtomicInteger(0);
    fields.forEach(x -> {
        String attrName = x.getName();
        Class<?> attrType = x.getType();
        beanMap.put(attrName, ClassUtils.toObject(attrType, attrVals[i.getAndIncrement()]));
    });

    return entityBean;
}
 
Example #14
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
/**
    * 1. clone current ci to a new one and assign a new guid to it 2. assign the
    * new guid as pguid to current ci
    */
   @Override
   public Object cloneCiAsParent(EntityManager entityManager, int ciTypeId, String guid) {
       DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciTypeId);
       Object fromBean = JpaQueryUtils.findEager(entityManager, entityMeta.getEntityClazz(), guid);
       if (fromBean == null) {
           throw new InvalidArgumentException(String.format("Can not find CI (ciTypeId:%d, guid:%s)", ciTypeId, guid));
       }
       String newGuid = sequenceService.getNextGuid(entityMeta.getTableName(), ciTypeId);

       BeanMap fromBeanMap = new BeanMap(fromBean);
       DynamicEntityHolder toEntityHolder = DynamicEntityHolder.cloneDynamicEntityBean(entityMeta, fromBean);
       MultiValueFeildOperationUtils.processMultValueFieldsForCloneCi(entityManager, entityMeta, newGuid, fromBeanMap, toEntityHolder, this);

       toEntityHolder.put(CmdbConstants.DEFAULT_FIELD_GUID, newGuid);

       List<AdmCiTypeAttr> refreshableAttrs = ciTypeAttrRepository.findByCiTypeIdAndIsRefreshable(ciTypeId, 1);
       refreshableAttrs.forEach(attr -> {
           fromBeanMap.put(attr.getPropertyName(), null);
       });
fromBeanMap.put(CmdbConstants.DEFAULT_FIELD_PARENT_GUID, newGuid);

       entityManager.merge(fromBean);
       entityManager.persist(toEntityHolder.getEntityObj());
       return fromBean;
   }
 
Example #15
Source File: CiDataInterceptorService.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
private void validateRequiredFieldForCreation(DynamicEntityHolder entityHolder, BeanMap ciBeanMap) {
    List<AdmCiTypeAttr> attrs = ciTypeAttrRepository.findWithNullableAndIsAuto(entityHolder.getEntityMeta().getCiTypeId(), 0, 0);
    for (AdmCiTypeAttr attr : attrs) {
        if (systemFillFields.contains(attr.getPropertyName())) {
            continue;
        }

        if (CiStatus.Decommissioned.getCode().equals(attr.getStatus()) || CiStatus.NotCreated.getCode().equals(attr.getStatus()) ) {
            continue;
        }
        
        Object val = ciBeanMap.get(attr.getPropertyName());
        if (val == null || ((val instanceof String) && "".equals(val))) {
            Integer ciTypeId = entityHolder.getEntityMeta().getCiTypeId();
            throw new InvalidArgumentException(String.format("Field [%s] is required for creation of CiType [%s(%d)].", attr.getPropertyName(), getCiTypeName(ciTypeId), ciTypeId));
        }
    }
}
 
Example #16
Source File: StaticEntityRepositoryImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
@Transactional
@Override
public <D> D update(Class<D> domainClzz, int id, Map<String, Object> domainVals) {

    D domainBean = validateDomain(domainClzz, id);

    BeanMap domainBeanMap = new BeanMap(domainBean);

    domainVals.forEach((name, value) -> {
        domainBeanMap.put(name, value);
    });

    D updatedBean = entityManager.merge(domainBean);
    entityManager.flush();

    return updatedBean;
}
 
Example #17
Source File: CiDataInterceptorService.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
public void preCreate(DynamicEntityHolder entityHolder, Map<String, ?> ci) {
    Map cloneCi = Maps.newHashMap(ci);
    cloneCi.remove("guid");

    BeanMap ciBeanMap = new BeanMap(entityHolder.getEntityObj());

    validateCiTypeStatus(entityHolder);
    validateCiTypeAttrStatus(entityHolder, ciBeanMap);
    validateRequiredFieldForCreation(entityHolder, ciBeanMap);
    validateSelectInputType(entityHolder, cloneCi);
    validateRefInputType(entityHolder, cloneCi);
    validateUniqueField(entityHolder.getEntityMeta().getCiTypeId(), cloneCi);
    validateIsAutoField(entityHolder, cloneCi);
    validateRegularExpressionRule(entityHolder, ciBeanMap);

    authorizationService.authorizeCiData(entityHolder.getEntityMeta().getCiTypeId(), entityHolder.getEntityObj(), ACTION_CREATION);
}
 
Example #18
Source File: CiDataInterceptorService.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
private void validateCiTypeAttrStatus(DynamicEntityHolder entityHolder, BeanMap ciBeanMap) {
    int ciTypeId = entityHolder.getEntityMeta().getCiTypeId();
    List<AdmCiTypeAttr> attrs = ciTypeAttrRepository.findAllByCiTypeId(ciTypeId);
    if (attrs != null && !attrs.isEmpty()) {
        attrs.forEach(attr -> {
            Object val = ciBeanMap.get(attr.getPropertyName());
            if (val == null || ((val instanceof String) && "".equals(val))) {
                return;
            } else { // auto filled field should be rejected
                CiStatus ciStatus = CiStatus.fromCode(attr.getStatus());
                if (!(CiStatus.Created.equals(ciStatus) || CiStatus.Dirty.equals(ciStatus))) {
                    throw new InvalidArgumentException(String.format("The attribute [%s] status is [%s]", attr.getPropertyName(), attr.getStatus()));
                }
            }
        });
    }

}
 
Example #19
Source File: MultiValueFeildOperationUtils.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
public static void processMultValueFieldsForCloneCi(EntityManager entityManager, DynamicEntityMeta entityMeta, String newGuid, BeanMap fromBeanMap, DynamicEntityHolder toEntityHolder, CiService ciService) {
    Collection<FieldNode> fieldNodes = entityMeta.getAllFieldNodes(true);
    fieldNodes.forEach(fn -> {
        if (DynamicEntityType.MultiSelection.equals(fn.getEntityType())) {
            int attrId = fn.getAttrId();
            DynamicEntityMeta multSelMeta = ciService.getMultSelectMetaMap().get(attrId);
            Set multSelSet = (Set) fromBeanMap.get(fn.getName());
            if (multSelSet != null ) {
                Set newMultiSet = new HashSet();
                multSelSet.forEach(item -> {
                    DynamicEntityHolder newMultiSelItem = DynamicEntityHolder.cloneDynamicEntityBean(multSelMeta, item);
                    newMultiSelItem.put("from_guid", newGuid);
                    // newMultiSelItem.put("from_guid_guid", toEntityHolder.getEntityObj());
                    entityManager.persist(newMultiSelItem.getEntityObj());
                    newMultiSet.add(newMultiSelItem.getEntityObj());
                });
                toEntityHolder.put(fn.getName(), newMultiSet);
            }
        } else if (DynamicEntityType.MultiReference.equals(fn.getEntityType())) {
            Set newMultiRefSet = new HashSet();
            Set fromMultiRefSet = (Set) fromBeanMap.get(fn.getName());
            if (fromMultiRefSet != null && !fromMultiRefSet.isEmpty()) {
                newMultiRefSet.addAll(fromMultiRefSet);
            }

            toEntityHolder.put(fn.getName(), newMultiRefSet);
        }
    });
}
 
Example #20
Source File: AbstractIOTest.java    From red5-io with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings({ "rawtypes" })
public void testJavaBean() {
    log.debug("\ntestJavaBean");
    TestJavaBean beanIn = new TestJavaBean();
    beanIn.setTestString("test string here");
    beanIn.setTestBoolean((System.currentTimeMillis() % 2 == 0) ? true : false);
    beanIn.setTestBooleanObject((System.currentTimeMillis() % 2 == 0) ? Boolean.TRUE : Boolean.FALSE);
    beanIn.setTestNumberObject(Integer.valueOf((int) System.currentTimeMillis() / 1000));
    Serializer.serialize(out, beanIn);
    dumpOutput();
    Object mapOrBean = Deserializer.deserialize(in, Object.class);
    assertEquals(beanIn.getClass().getName(), mapOrBean.getClass().getName());
    Map<?, ?> map = (mapOrBean instanceof Map) ? (Map<?, ?>) mapOrBean : new BeanMap(mapOrBean);
    Set<?> entrySet = map.entrySet();
    Iterator<?> it = entrySet.iterator();
    Map beanInMap = new BeanMap(beanIn);
    assertEquals(beanInMap.size(), map.size());
    while (it.hasNext()) {
        Map.Entry entry = (Map.Entry) it.next();
        String propOut = (String) entry.getKey();
        Object valueOut = entry.getValue();
        assertTrue(beanInMap.containsKey(propOut));
        assertEquals(valueOut, beanInMap.get(propOut));
    }
    resetOutput();
}
 
Example #21
Source File: HttpParameterConverter.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public HttpParameterConverter(Object bean) {
    if (bean instanceof Map) {
        beanMap = ((Map) bean);
    } else {
        beanMap = new HashMap<>((Map) new BeanMap(bean));
        beanMap.remove("class");
        beanMap.remove("declaringClass");
    }
}
 
Example #22
Source File: CollectionUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 对象转map集合
 */
public static Map<?, ?> object2Map(Object obj) {
    if (obj == null) {
        return null;
    }
    return new BeanMap(obj);
}
 
Example #23
Source File: DBusUtils.java    From DBus with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> object2map(Object obj) {
    if (obj == null)
        return null;
    Map<?, ?> map = new BeanMap(obj);
    Map<String, Object> resultMap = new HashMap<>(map.size());
    for (Object key : map.keySet()) {
        resultMap.put(key.toString(), map.get(key));
    }
    return resultMap;
}
 
Example #24
Source File: ServiceActions.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@CommonColumns(@CommonColumn(value = Column.ServiceName, required = true))
@ActionMethod
   public void initService(IActionContext actionContext, HashMap<?, ?> message) throws IllegalAccessException, InvocationTargetException, InterruptedException, IOException {
	ServiceName serviceName = ServiceName.parse(actionContext.getServiceName());
	IActionServiceManager serviceManager = actionContext.getServiceManager();

	try {
           IServiceSettings serviceSettings = serviceManager.getServiceSettings(serviceName);
		BeanMap beanMap = new BeanMap(serviceSettings);
		Set<String> editedProperty = new HashSet<>();
		Set<String> incorrectProperty = new HashSet<>();
		for (Entry<?, ?> entry : message.entrySet()) {
			String property = convertProperty(entry.getKey().toString());
			if (beanMap.containsKey(property)){
				BeanUtils.setProperty(serviceSettings, property, converter.get().convert((Object)unwrapFilters(entry.getValue()), beanMap.getType(property)));
                   editedProperty.add(property);
			} else {
				incorrectProperty.add(property);
			}
		}

		if (!incorrectProperty.isEmpty()) {
			throw new EPSCommonException(serviceSettings.getClass().getName() + " does not contain properties: " + incorrectProperty);
		}

           serviceManager.updateService(serviceName, serviceSettings, null).get();

		try (FileOutputStream out = new FileOutputStream(actionContext.getReport().createFile(StatusType.NA, servicesFolder, changingSettingFolder, serviceName + FORMATTER.format(DateTimeUtility.nowLocalDateTime()) + servicesFileExpression))) {
               actionContext.getServiceManager().serializeServiceSettings(serviceName, out);
           }
       } catch (ExecutionException e) {
           ExceptionUtils.rethrow(ObjectUtils.defaultIfNull(e.getCause(), e));
       }
}
 
Example #25
Source File: ConverterBean.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
public void convertMatrix() {
    logger.debug("convert started");
    try {
        TestToolsAPI testToolsAPI = TestToolsAPI.getInstance();
        IMatrixConverter converter = testToolsAPI.getMatrixConverter(converterUri);
        ConversionMonitor monitor = new ConversionMonitor();
        IMatrixConverterSettings settings = testToolsAPI
                .prepareConverterSettings(matrixId, environment, converterUri, outputMatrixName);
        BeanMap beanMap = new BeanMap(settings);

        for (ConverterNode setting : currentSettings.getNodes()){
            if(beanMap.get(setting.getName()) instanceof Map){
                ConverterFormMapAdapter adapter = (ConverterFormMapAdapter) setting.getValue();
                adapter.toMap();
                BeanUtils.setProperty(settings, setting.getName(), adapter);
            } else {
                BeanUtils.setProperty(settings, setting.getName(), setting.getValue());
            }
        }

        Future<Boolean> converterTask = BeanUtil.getSfContext().getTaskExecutor().addTask(new ConversionTask(converter, settings, monitor));
        task = new MatrixConverterFeature(monitor, converterTask, settings.getOutputFile());
    } catch(RuntimeException |  IOException | IllegalAccessException | InvocationTargetException e) {
        BeanUtil.showMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
        logger.error(e.getMessage(), e);
    }
}
 
Example #26
Source File: Serializer.java    From red5-io with Apache License 2.0 5 votes vote down vote up
/**
 * Write typed object to the output
 * 
 * @param out
 *            Output writer
 * @param obj
 *            Object type to write
 * @return true if the object has been written, otherwise false
 */
@SuppressWarnings("all")
protected static boolean writeObjectType(Output out, Object obj) {
    if (obj instanceof ObjectMap || obj instanceof BeanMap) {
        out.writeObject((Map) obj);
    } else if (obj instanceof Map) {
        out.writeMap((Map) obj);
    } else if (obj instanceof RecordSet) {
        out.writeRecordSet((RecordSet) obj);
    } else {
        out.writeObject(obj);
    }
    return true;
}
 
Example #27
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
private List getSortedMultRefList(Set<Object> referCis, Map<String, Integer> sortMap) {
    List ciList = Lists.newLinkedList();
    for (Object ci : referCis) {
        ciList.add(ci);
    }
    ciList.sort((ci1, ci2) -> {
        String refGuid1 = (String) new BeanMap(ci1).get("guid");
        String refGuid2 = (String) new BeanMap(ci2).get("guid");

        return sortMap.get(refGuid1) - sortMap.get(refGuid2);
    });
    return ciList;
}
 
Example #28
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> getCi(int ciTypeId, String guid) {
    validateCiType(ciTypeId);
    DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciTypeId);
    // Object entityBean = entityManager.find(entityMeta.getEntityClazz(), guid);
    PriorityEntityManager priEntityManager = getEntityManager();
    EntityManager entityManager = priEntityManager.getEntityManager();
    try {
        Object entityBean = JpaQueryUtils.findEager(entityManager, entityMeta.getEntityClazz(), guid);
        if (entityBean == null) {
            throw new InvalidArgumentException(String.format("Can not find CI (ciTypeId:%d, guid:%s)", ciTypeId, guid));
        }
        Map<String, Object> resultMap = Maps.newHashMap();
        BeanMap ciObjMap = new BeanMap(entityBean);
        for (Map.Entry kv : ciObjMap.entrySet()) {
            String fieldName = kv.getKey().toString();
            FieldNode fieldNode = entityMeta.getFieldNode(fieldName);
            Object value = kv.getValue();
            if (fieldNode != null) {
                if (!fieldNode.isJoinNode()) {
                    resultMap.put(fieldName, value);
                }
            }
        }
        if (!authorizationService.isCiDataPermitted(ciTypeId, entityBean, ACTION_ENQUIRY)) {
            resultMap = CollectionUtils.retainsEntries(resultMap, Sets.newHashSet("guid", "key_name"));
            logger.info("Access denied - {}, returns guid and key_name only.", resultMap);
        }
        return resultMap;
    } finally {
        priEntityManager.close();
    }
}
 
Example #29
Source File: CollectionUtils.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
static public List clone(List src, List dest) throws CloneNotSupportedException {
    for (Object obj : src) {
        BeanMap cloneBM = (BeanMap) (new BeanMap(obj).clone());
        dest.add(cloneBM.getBean());
    }
    return dest;
}
 
Example #30
Source File: JpaQueryUtils.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
public static Map<String, Integer> getSortedMapForMultiRef(EntityManager entityManager, AdmCiTypeAttr attr, DynamicEntityMeta multRefMeta) {
    Map<String, Integer> sortMap = new HashMap<>();
    String joinTable = attr.retrieveJoinTalbeName();
    String querySql = "select id,from_guid,to_guid, seq_no from " + joinTable;
    Query query = entityManager.createNativeQuery(querySql, multRefMeta.getEntityClazz());
    List results = query.getResultList();

    for (Object bean : results) {
        BeanMap beanMap = new BeanMap(bean);
        sortMap.put((String) beanMap.get("to_guid"), (Integer) beanMap.get("seq_no"));
    }
    return sortMap;
}