Java 类org.apache.commons.beanutils.PropertyUtils 实例源码

项目:automat    文件:InstanceUtil.java   
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:Pogamut3    文件:ReflectionUtils.java   
public static <T extends java.lang.annotation.Annotation, E extends Throwable>  void processEachAnnotatedDeclaredField(final Object targetObject, final Class rootClass, final Class<T> annotationClass, final ProcessAnnotatedFieldCallback<T, E> callBack) throws E{

        processEachDeclaredNonStaticField(targetObject, rootClass, new ProcessFieldCallback<E>() {

            @Override
            public void processField(Field f) throws E {
                if(f.isAnnotationPresent(annotationClass)){
                    Object fieldValue;
                    try {
                         fieldValue = PropertyUtils.getProperty(targetObject, f.getName());
                    } catch (Exception ex) {
                        throw new IllegalStateException("Could not read property value for annotated property '" + f.getName() + "' in class" + f.getDeclaringClass().getName() + "\nThe property should have public getter.", ex);
                    }
                    callBack.processField(f, fieldValue, f.getAnnotation(annotationClass));
                }
            }
        });


    }
项目:weixin_api    文件:MpMsgApi.java   
/**
 * 群发消息预览
 * 
 * @param towxname
 * @param msg
 * @return
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws ClientProtocolException
 * @throws URISyntaxException
 * @throws IOException
 * @throws AccessTokenFailException
 */
public BaseResp apiMessageMassPreview(String towxname, MassMsg msg)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClientProtocolException,
        URISyntaxException, IOException, AccessTokenFailException {
    MpAccessToken token = mpApi.apiToken();
    String path = String.format("/message/mass/preview?access_token=%s", token.getAccessToken());

    Map<String, Object> reqMap = PropertyUtils.describe(msg);
    reqMap.put("towxname", towxname);
    String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
    BaseResp resp = new Gson().fromJson(respText, BaseResp.class);
    if (mpApi.log.isInfoEnabled()) {
        mpApi.log.info(String.format("apiMessageMassDelete %s", new Gson().toJson(resp)));
    }
    return resp;
}
项目:iBase4J-Common    文件:InstanceUtil.java   
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:YiDu-Novel    文件:ReviewListAction.java   
@Override
protected void loadData() {

    initCollections(new String[] { "collectionProperties.review.searchkey" });
    ReviewSearchBean searchBean = new ReviewSearchBean();
    BeanUtils.copyProperties(this, searchBean, new String[] { "articleno" });

    try {
        PropertyUtils.setProperty(searchBean, option, key);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }

    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn(TReview.PROP_POSTDATE);
        pagination.setSortOrder("DESC");
    }

    // 总件数设置
    pagination.setPreperties(reviewService.getCount(searchBean));
    searchBean.setPagination(pagination);
    reviewList = reviewService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(reviewList.size());
}
项目:nixmash-blog    文件:SiteOptions.java   
public void setSiteOptionProperty(String property, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    if (PropertyUtils.isWriteable(this, property)) {

        switch (PropertyUtils
                .getPropertyDescriptor(this, property).getPropertyType().getSimpleName()) {
            case OPTION_VALUE_TYPE_BOOLEAN:
                value = Boolean.valueOf(value.toString());
                break;
            case OPTION_VALUE_TYPE_INTEGER:
                value = Integer.parseInt(value.toString());
                break;
            case OPTION_VALUE_TYPE_USERREGISTRATION:
                value = UserRegistration.valueOf(value.toString());
                break;
            default:
                break;
        }
        PropertyUtils.setProperty(this, property, value);
    }
}
项目:urule    文件:PackageServletHandler.java   
private void instanceChildObject(Object obj,String propertyName){
    int pointIndex=propertyName.indexOf(".");
    if(pointIndex==-1){
        return;
    }
    String name=propertyName.substring(0,pointIndex);
    propertyName=propertyName.substring(pointIndex+1);
    try {
        Object instance=PropertyUtils.getProperty(obj, name);
        if(instance!=null){
            instanceChildObject(instance,propertyName);
            return;
        }
        Object targetEntity=new GeneralEntity(name);
        PropertyUtils.setProperty(obj, name, targetEntity);
        instanceChildObject(targetEntity,propertyName);
    } catch (Exception e) {
        throw new RuleException(e);
    }
}
项目:esup-ecandidat    文件:TableFormating.java   
/** Ajoute une case a cocher a la place de O et N
 * @param property
 */
public void addBooleanColumn(String property, Boolean alignCenter){
    addGeneratedColumn(property, new Table.ColumnGenerator() {
           /**serialVersionUID**/
        private static final long serialVersionUID = -3483685206189347289L;

        @Override
           public Object generateCell(Table source, Object itemId, Object columnId) {               
            try {
                Object value = PropertyUtils.getProperty(itemId,(String)columnId);
                if (value instanceof Boolean){
                    return new IconLabel((Boolean)value,alignCenter);
                }else{
                    return value;
                }
            } catch (Exception e) {
                return null;
            }               
           }            
       });
}
项目:mumu    文件:InstanceUtil.java   
/**
 * 封装实体
 * 
 * @param cls 实体类
 * @param list 数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:delivery-sdk-java    文件:ThymeleafTemplateEngine.java   
private String getContentTypeFromModel(Object model) {
    if (model instanceof ContentItem) {
        ContentItem contentItem = (ContentItem) model;
        return contentItem.getSystem().getType();
    }
    ContentItemMapping contentItemMapping = model.getClass().getAnnotation(ContentItemMapping.class);
    if (contentItemMapping != null) {
        return contentItemMapping.value();
    }
    try {
        Object system = PropertyUtils.getProperty(model, "system");
        if (system instanceof System) {
            return ((System) system).getType();
        }
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        logger.debug("Unable to find System property on model", e);
    }
    return null;
}
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, SurveyConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
SurveyForm existForm = (SurveyForm) sessionMap.get(SurveyConstants.ATTR_SURVEY_FORM);

SurveyForm surveyForm = (SurveyForm) form;
try {
    PropertyUtils.copyProperties(surveyForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(SurveyConstants.SUCCESS);
   }
项目:lams    文件:AnswerDTO.java   
public AnswerDTO(SurveyQuestion question) {
try {
    PropertyUtils.copyProperties(this, question);
} catch (Exception e) {
    logger.error("Error occurs during creating AnswerDTO");
}

// clone options
Set<SurveyOption> optList = question.getOptions();
if (optList != null) {
    SortedSet<SurveyOption> newOptions = new TreeSet<SurveyOption>(new SurveyOptionComparator());
    for (SurveyOption option : optList) {
    SurveyOption newOption = (SurveyOption) option.clone();
    // clone does not copy the UID, here copy it back
    newOption.setUid(option.getUid());
    newOptions.add(newOption);
    }
    this.setOptions(newOptions);
}

String desc = this.getDescription();
desc = desc.replaceAll("<(.|\n)*?>", "");
this.setShortTitle(StringUtils.abbreviate(desc, SHORT_TITLE_LENGTH));

   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, AssessmentConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
    .getAttribute(sessionMapID);
AssessmentForm existForm = (AssessmentForm) sessionMap.get(AssessmentConstants.ATTR_ASSESSMENT_FORM);

AssessmentForm assessmentForm = (AssessmentForm) form;
try {
    PropertyUtils.copyProperties(assessmentForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(AssessmentConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, PeerreviewConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
    .getAttribute(sessionMapID);
PeerreviewForm existForm = (PeerreviewForm) sessionMap.get(PeerreviewConstants.ATTR_PEERREVIEW_FORM);

PeerreviewForm peerreviewForm = (PeerreviewForm) form;
try {
    PropertyUtils.copyProperties(peerreviewForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(PeerreviewConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, ResourceConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
ResourceForm existForm = (ResourceForm) sessionMap.get(ResourceConstants.ATTR_RESOURCE_FORM);

ResourceForm resourceForm = (ResourceForm) form;
try {
    PropertyUtils.copyProperties(resourceForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(ResourceConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, CommonCartridgeConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
CommonCartridgeForm existForm = (CommonCartridgeForm) sessionMap
    .get(CommonCartridgeConstants.ATTR_RESOURCE_FORM);

CommonCartridgeForm commonCartridgeForm = (CommonCartridgeForm) form;
try {
    PropertyUtils.copyProperties(commonCartridgeForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(CommonCartridgeConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, DokumaranConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
DokumaranForm existForm = (DokumaranForm) sessionMap.get(DokumaranConstants.ATTR_RESOURCE_FORM);

DokumaranForm dokumaranForm = (DokumaranForm) form;
try {
    PropertyUtils.copyProperties(dokumaranForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(DokumaranConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    * 
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   protected ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, DacoConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
DacoForm existForm = (DacoForm) sessionMap.get(DacoConstants.ATTR_DACO_FORM);

DacoForm dacoForm = (DacoForm) form;
try {
    PropertyUtils.copyProperties(dacoForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(DacoConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, ImageGalleryConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
ImageGalleryForm existForm = (ImageGalleryForm) sessionMap.get(ImageGalleryConstants.ATTR_IMAGE_GALLERY_FORM);

ImageGalleryForm imageGalleryForm = (ImageGalleryForm) form;
try {
    PropertyUtils.copyProperties(imageGalleryForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(ImageGalleryConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, ScratchieConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
    .getAttribute(sessionMapID);
ScratchieForm existForm = (ScratchieForm) sessionMap.get(ScratchieConstants.ATTR_RESOURCE_FORM);

ScratchieForm scratchieForm = (ScratchieForm) form;
try {
    PropertyUtils.copyProperties(scratchieForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(ScratchieConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, SpreadsheetConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
SpreadsheetForm existForm = (SpreadsheetForm) sessionMap.get(SpreadsheetConstants.ATTR_RESOURCE_FORM);

SpreadsheetForm spreadsheetForm = (SpreadsheetForm) form;
try {
    PropertyUtils.copyProperties(spreadsheetForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(SpreadsheetConstants.SUCCESS);
   }
项目:lams    文件:AuthoringAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward initPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, TaskListConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
TaskListForm existForm = (TaskListForm) sessionMap.get(TaskListConstants.ATTR_TASKLIST_FORM);

TaskListForm taskListForm = (TaskListForm) form;
try {
    PropertyUtils.copyProperties(taskListForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

ToolAccessMode mode = WebUtil.readToolAccessModeAuthorDefaulted(request);
request.setAttribute(AttributeNames.ATTR_MODE, mode.toString());

return mapping.findForward(TaskListConstants.SUCCESS);
   }
项目:lams    文件:AuthoringTaskListConditionAction.java   
/**
    * Display same entire authoring page content from HttpSession variable.
    *
    * @param mapping
    * @param form
    * @param request
    * @param response
    * @return
    * @throws ServletException
    */
   private ActionForward showConditions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws ServletException {
String sessionMapID = WebUtil.readStrParam(request, TaskListConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession().getAttribute(sessionMapID);
TaskListForm existForm = (TaskListForm) sessionMap.get(TaskListConstants.ATTR_TASKLIST_FORM);

TaskListForm taskListForm = (TaskListForm) form;
try {
    PropertyUtils.copyProperties(taskListForm, existForm);
} catch (Exception e) {
    throw new ServletException(e);
}

return mapping.findForward(TaskListConstants.SUCCESS);
   }
项目:iBase4J    文件:InstanceUtil.java   
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:Biliomi    文件:XmlElementPathBeanPredicate.java   
private static boolean testCollectionAgainsString(Collection<?> a, String b, RestFilterOperator operator) {
  switch (operator) {
    case CONTAINS:
      if (!a.isEmpty()) {
        return a.stream().anyMatch(o -> {
          if (String.class.isAssignableFrom(o.getClass())) {
            return StringUtils.containsIgnoreCase((CharSequence) o, b);
          } else {
            return EStream.from(o.getClass().getDeclaredFields())
                .filter(field -> String.class.isAssignableFrom(field.getType()))
                .map(field -> PropertyUtils.getProperty(o, field.getName()))
                .filter(Objects::nonNull)
                .anyMatch(v -> StringUtils.containsIgnoreCase((CharSequence) v, b));
          }
        });
      }
    default:
      return false;
  }
}
项目:Biliomi    文件:XmlElementPathBeanComparator.java   
@Override
public int compare(T o1, T o2) {
  Comparable obj1 = null;
  Comparable obj2 = null;

  try {
    obj1 = (Comparable) PropertyUtils.getProperty(o1, this.propertyPath);
    obj2 = (Comparable) PropertyUtils.getProperty(o2, this.propertyPath);
  } catch (NestedNullException ignored) {
    // Ignored, als het property NULL is, dan vergelijken met NULL
  } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
    throw new IllegalArgumentException("Could not retrieve property " + this.propertyPath, e);
  }

  Comparator<Comparable<Object>> objectComparator = null;
  if ((obj1 != null && obj2 != null) && obj1 instanceof String) {
    obj1 = ((String) obj1).toLowerCase().trim();
    obj2 = ((String) obj2).toLowerCase().trim();

    if (!StringUtils.isEmpty((String) obj1) && !StringUtils.isEmpty((String) obj2)) {
      if (StringUtils.isNumeric((String) obj1) && StringUtils.isNumeric((String) obj2)) {
        objectComparator = Comparator.comparingDouble(o -> new Double(String.valueOf(o)));
      }
    }
  }

  if (objectComparator == null) {
    objectComparator = Comparator.naturalOrder();
  }

  //noinspection unchecked
  return Comparator.nullsLast(objectComparator).compare(obj1, obj2);
}
项目:Biliomi    文件:UserSettingsProducer.java   
@Produces
@CoreSetting("PRODUCER")
public String getUserSetting(InjectionPoint injectionPoint) {
  Annotated annotated = injectionPoint.getAnnotated();

  if (annotated.isAnnotationPresent(CoreSetting.class)) {
    String settingPath = annotated.getAnnotation(CoreSetting.class).value();
    Object object = yamlCoreSettings;
    String[] split = settingPath.split("\\.");
    int c = 0;

    while (c < split.length) {
      try {
        object = PropertyUtils.getProperty(object, split[c]);
        c++;
      } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        LogManager.getLogger(getClass()).error("Failed retrieving setting " + settingPath, e);
        return null;
      }
    }

    return String.valueOf(object);
  }

  return null;
}
项目:Yidu    文件:ReviewListAction.java   
@Override
protected void loadData() {

    initCollections(new String[] { "collectionProperties.review.searchkey" });
    ReviewSearchBean searchBean = new ReviewSearchBean();
    BeanUtils.copyProperties(this, searchBean, new String[] { "articleno" });

    try {
        PropertyUtils.setProperty(searchBean, option, key);
    } catch (Exception e) {
        logger.warn(e.getMessage());
    }

    if (StringUtils.isEmpty(pagination.getSortColumn())) {
        pagination.setSortColumn(TReview.PROP_POSTDATE);
        pagination.setSortOrder("DESC");
    }

    // 总件数设置
    pagination.setPreperties(reviewService.getCount(searchBean));
    searchBean.setPagination(pagination);
    reviewList = reviewService.find(searchBean);
    // Setting number of records in the particular page
    pagination.setPageRecords(reviewList.size());
}
项目:bird-java    文件:InstanceHelper.java   
/**
 * 封装实体
 *
 * @param cls
 *            实体类
 * @param rs
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:uckefu    文件:UKResultMapper.java   
public <T> T mapEntity(String source , SearchHit hit , Class<T> clazz) {
    T t = mapEntity(source , clazz) ;

    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
    HighlightField highlightNameField = highlightFields.get("title");
    HighlightField contentHightlightField = highlightFields.get("content");
    try {
        if(highlightNameField!=null&&highlightNameField.fragments()!=null){
            PropertyUtils.setProperty(t, "title" , highlightNameField.fragments()[0].string());
        }
        if(contentHightlightField!=null){
            PropertyUtils.setProperty(t, "content" , contentHightlightField.fragments()[0].string());
        }
        PropertyUtils.setProperty(t, "id" , hit.getId());
    } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
        e.printStackTrace();
    } 
    return t;
}
项目:xDoc    文件:MarkdownFormat.java   
@Override
public String format(ApiModule apiModule) {
    VelocityTemplater templater = new VelocityTemplater("org/treeleafj/xdoc/spring/format/api.vm");

    for (ApiAction apiAction : apiModule.getApiActions()) {
        SpringApiAction saa = (SpringApiAction) apiAction;
        if (saa.isJson() && StringUtils.isNotBlank(saa.getRespbody())) {
            saa.setRespbody(JsonFormatUtils.formatJson(saa.getRespbody()));
        }
    }

    try {
        Map<String, Object> map = PropertyUtils.describe(apiModule);
        return templater.parse(map);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
项目:QLExpress    文件:ExpressUtil.java   
public static Object getProperty(Object bean, Object name) {
    try {
        if(bean.getClass().isArray() && name.equals("length")){
           return Array.getLength(bean);
        }else if (bean instanceof Class) {
            if(name.equals("class")){
                return bean;
            }else{
                Field f = ((Class<?>) bean).getDeclaredField(name.toString());
                return f.get(null);
            }
        }else if(bean instanceof Map ){
            return ((Map<?,?>)bean).get(name);
        }else {
            Object obj = PropertyUtils.getProperty(bean, name.toString());
            return obj;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:QLExpress    文件:ExpressUtil.java   
public static Class<?> getPropertyClass(Object bean, Object name) {
    try {
        if(bean.getClass().isArray() && name.equals("length")){
           return int.class;
        }else if (bean instanceof Class) {
            if(name.equals("class")){
                return Class.class;
            }else{
                Field f = ((Class<?>) bean).getDeclaredField(name.toString());
                return f.getType();
            }
        }else if(bean instanceof Map ){
            Object o = ((Map<?,?>)bean).get(name);
            if(o == null){
                return null;
            }else{
                return o.getClass();
            }
        }else {
            return PropertyUtils.getPropertyDescriptor(bean, name.toString()).getPropertyType();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
项目:JAVA-    文件:InstanceUtil.java   
/**
 * 封装实体
 * 
 * @param cls
 *            实体类
 * @param list
 *            数据查询结果集
 * @return
 */
public static final <E> List<E> getInstanceList(Class<E> cls, ResultSet rs) {
    List<E> resultList = newArrayList();
    try {
        E object = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        while (rs.next()) {
            object = cls.newInstance();
            for (int i = 0; i < fields.length; i++) {
                String fieldName = fields[i].getName();
                PropertyUtils.setProperty(object, fieldName, rs.getObject(fieldName));
            }
            resultList.add(object);
        }
    } catch (Exception e) {
        throw new InstanceException(e);
    }
    return resultList;
}
项目:angit    文件:Collections3.java   
/**
 * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
 *
 * @param collection        来源集合.
 * @param keyPropertyName   要提取为Map中的Key值的属性名.
 * @param valuePropertyName 要提取为Map中的Value值的属性名.
 * @return the map
 */
@SuppressWarnings("unchecked")
public static Map extractToMap(final Collection collection, final String keyPropertyName,
                               final String valuePropertyName) {
    Map map = new HashMap(collection.size());

    try {
        for (Object obj : collection) {
            map.put(PropertyUtils.getProperty(obj, keyPropertyName),
                PropertyUtils.getProperty(obj, valuePropertyName));
        }
    } catch (Exception e) {
        throw Reflections.convertReflectionExceptionToUnchecked(e);
    }

    return map;
}
项目:weibo    文件:UserServiceImpl.java   
public void register(UserToken userToken) throws Exception {

        // 检查用户名和邮箱
        this.chickUserNameExist(userToken.getUsername());
        this.chickEmailExist(userToken.getEmail());

        // 判定密码相同与否
        if(!(userToken.getPassword().equals(userToken.getRpassword()))){
            throw new WeiboException("两次密码不一致");
        }

        // 整理数据,插入数据库
        User user = new User();
        PropertyUtils.copyProperties(user, userToken);
        user.setWeibo(0);
        user.setFollow(0);
        user.setFollower(0);
        user.setDeleted((byte) 0);
        user.setStatus(DC.STATUS_NORMAL);
        user.setPassword(MD5.getMD5(user.getPassword()));
        userMapper.insertSelective(user);
    }
项目:spring-data-mapdb    文件:PropertyComparator.java   
/**
 *
 * @param o1
 *            An entry in a map
 * @param o2
 *            Another entry in the map
 * @return Comparison result
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public int compare(Object o1, Object o2) {

    try {
        Object o1Field = PropertyUtils.getProperty(o1, this.attributeName);
        Object o2Field = PropertyUtils.getProperty(o2, this.attributeName);

        if (o1Field == null) {
            return this.direction;
        }
        if (o2Field == null) {
            return -1 * this.direction;
        }
        if (o1Field instanceof Comparable && o2Field instanceof Comparable) {
            return this.direction * ((Comparable) o1Field).compareTo((Comparable) o2Field);
        }

    } catch (Exception ignore) {
        return 0;
    }

    return 0;
}
项目:UtilsMaven    文件:CommonUtils.java   
/**
 * 将一个JavaBean对象的所有属性封装在Map中并返回,
 * 注意只能将拥有Getter方法的属性才能取出并封装到Map中
 *
 * @param bean 需要转换的Bean对象
 * @return 返回一个Map , 失败返回null
 */
public static <T extends Object> Map<String, Object> toMap(T bean) {
    Map<String, Object> map = null;
    try {
        map = PropertyUtils.describe(bean);
        map.remove("class");
        StringBuilder methodName = new StringBuilder("get");
        for (String property : map.keySet()) {
            methodName.delete(3, methodName.length()).append(property.substring(0, 1).toUpperCase())
                    .append(property.substring(1));
            Object o = MethodUtils.invokeMethod(bean, methodName.toString(), null);
            map.put(property, o);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return map;
}
项目:microservice    文件:WorkflowTraceService.java   
/**
 * 获取当前节点信息
 *
 * @param processInstance
 * @return
 */
private Task getCurrentTaskInfo(ProcessInstance processInstance) {
    Task currentTask = null;
    try {
        String activitiId = (String) PropertyUtils.getProperty(processInstance, "activityId");
        logger.debug("current activity id: {}", activitiId);

        currentTask = taskService.createTaskQuery().processInstanceId(processInstance.getId()).taskDefinitionKey(activitiId)
                .singleResult();
        logger.debug("current task for processInstance: {}", ToStringBuilder.reflectionToString(currentTask));

    } catch (Exception e) {
        logger.error("can not get property activityId from processInstance: {}", processInstance);
    }
    return currentTask;
}
项目:ureport    文件:DatasourceServletAction.java   
public void buildClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String clazz=req.getParameter("clazz");
    List<Field> result=new ArrayList<Field>();
    try{
        Class<?> targetClass=Class.forName(clazz);
        PropertyDescriptor[] propertyDescriptors=PropertyUtils.getPropertyDescriptors(targetClass);
        for(PropertyDescriptor pd:propertyDescriptors){
            String name=pd.getName();
            if("class".equals(name)){
                continue;
            }
            result.add(new Field(name));
        }
        writeObjectToJson(resp, result);
    }catch(Exception ex){
        throw new ReportDesignException(ex);
    }
}