下面列出了怎么用org.apache.commons.lang.ObjectUtils的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 两层循环实现建树
*
* @param sysMenus
* @return
*/
public static List<SysMenu> treeBuilder(List<SysMenu> sysMenus) {
List<SysMenu> menus = new ArrayList<>();
for (SysMenu sysMenu : sysMenus) {
if (ObjectUtils.equals(-1L, sysMenu.getParentId())) {
menus.add(sysMenu);
}
for (SysMenu menu : sysMenus) {
if (menu.getParentId().equals(sysMenu.getId())) {
if (sysMenu.getSubMenus() == null) {
sysMenu.setSubMenus(new ArrayList<>());
}
sysMenu.getSubMenus().add(menu);
}
}
}
return menus;
}
public int compare(ResolvedArtifact artifact1, ResolvedArtifact artifact2) {
int diff = artifact1.getName().compareTo(artifact2.getName());
if (diff != 0) {
return diff;
}
diff = ObjectUtils.compare(artifact1.getClassifier(), artifact2.getClassifier());
if (diff != 0) {
return diff;
}
diff = artifact1.getExtension().compareTo(artifact2.getExtension());
if (diff != 0) {
return diff;
}
diff = artifact1.getType().compareTo(artifact2.getType());
if (diff != 0) {
return diff;
}
// Use an arbitrary ordering when the artifacts have the same public attributes
return artifact1.hashCode() - artifact2.hashCode();
}
/**
* Owners of the given calendar and users with full and read-only access have update access to the given calendar: obj.getCalendar().
* @see org.projectforge.user.UserRightAccessCheck#hasHistoryAccess(org.projectforge.user.PFUserDO, java.lang.Object)
*/
@Override
public boolean hasHistoryAccess(final PFUserDO user, final TeamEventDO obj)
{
if (obj == null) {
return true;
}
final TeamCalDO calendar = obj.getCalendar();
if (calendar == null) {
return false;
}
if (ObjectUtils.equals(user.getId(), calendar.getOwnerId()) == true) {
// User has full access to it's own calendars.
return true;
}
final Integer userId = user.getId();
if (teamCalRight.hasFullAccess(calendar, userId) == true || teamCalRight.hasReadonlyAccess(calendar, userId) == true) {
return true;
}
return false;
}
@Override
public boolean equals(final Object o)
{
if (o instanceof KostZuweisungDO) {
final KostZuweisungDO other = (KostZuweisungDO) o;
if (ObjectUtils.equals(this.getIndex(), other.getIndex()) == false)
return false;
if (ObjectUtils.equals(this.getRechnungsPositionId(), other.getRechnungsPositionId()) == false)
return false;
if (ObjectUtils.equals(this.getEingangsrechnungsPositionId(), other.getEingangsrechnungsPositionId()) == false)
return false;
if (ObjectUtils.equals(this.getEmployeeSalaryId(), other.getEmployeeSalaryId()) == false)
return false;
return true;
}
return false;
}
public void deleteData(String schemaName, String tableName, DBObject obj) {
int i = 0;
String path = "/" + schemaName + "/" + tableName + "/" + CanalEntry.EventType.DELETE.getNumber();
DBObject newObj = (DBObject) ObjectUtils.clone(obj);
DBObject logObj = (DBObject) ObjectUtils.clone(obj);
//保存原始数据
try {
i++;
if (obj.containsField("id")) {
naiveMongoTemplate.getCollection(tableName).remove(new BasicDBObject("_id", obj.get("id")));
}
i++;
SpringUtil.doEvent(path, newObj);
} catch (MongoClientException | MongoSocketException clientException) {
//客户端连接异常抛出,阻塞同步,防止mongodb宕机
throw clientException;
} catch (Exception e) {
logError(schemaName, tableName, 3, i, logObj, e);
}
}
private void initCommonTypes() {
commonTypes.put(int.class, ObjectUtils.NULL);
commonTypes.put(Integer.class, ObjectUtils.NULL);
commonTypes.put(short.class, ObjectUtils.NULL);
commonTypes.put(Short.class, ObjectUtils.NULL);
commonTypes.put(long.class, ObjectUtils.NULL);
commonTypes.put(Long.class, ObjectUtils.NULL);
commonTypes.put(boolean.class, ObjectUtils.NULL);
commonTypes.put(Boolean.class, ObjectUtils.NULL);
commonTypes.put(byte.class, ObjectUtils.NULL);
commonTypes.put(Byte.class, ObjectUtils.NULL);
commonTypes.put(char.class, ObjectUtils.NULL);
commonTypes.put(Character.class, ObjectUtils.NULL);
commonTypes.put(float.class, ObjectUtils.NULL);
commonTypes.put(Float.class, ObjectUtils.NULL);
commonTypes.put(double.class, ObjectUtils.NULL);
commonTypes.put(Double.class, ObjectUtils.NULL);
commonTypes.put(BigDecimal.class, ObjectUtils.NULL);
commonTypes.put(BigInteger.class, ObjectUtils.NULL);
}
@Override
public boolean equals(Object o)
{
if (o instanceof HRPlanningEntryDO) {
HRPlanningEntryDO other = (HRPlanningEntryDO) o;
if (this.getId() != null || other.getId() != null) {
return ObjectUtils.equals(this.getId(), other.getId());
}
if (ObjectUtils.equals(this.getPlanningId(), other.getPlanningId()) == false)
return false;
if (ObjectUtils.equals(this.getProjektId(), other.getProjektId()) == false)
return false;
if (ObjectUtils.equals(this.getStatus(), other.getStatus()) == false)
return false;
return true;
}
return false;
}
public void test7() {
String input = "a b c \"d e\" f ";
StrTokenizer tok = new StrTokenizer(input);
tok.setDelimiterMatcher(StrMatcher.spaceMatcher());
tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
tok.setIgnoredMatcher(StrMatcher.noneMatcher());
tok.setIgnoreEmptyTokens(false);
String tokens[] = tok.getTokenArray();
String expected[] = new String[]{"a", "", "", "b", "c", "d e", "f", "",};
assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
for (int i = 0; i < expected.length; i++) {
assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
ObjectUtils.equals(expected[i], tokens[i]));
}
}
/**
* Replaces the token with properties of the weather LocationConfig object.
*/
private String replaceConfig(Token token) {
LocationConfig locationConfig = WeatherContext.getInstance().getConfig().getLocationConfig(locationId);
if (locationConfig == null) {
throw new RuntimeException("Weather locationId '" + locationId + "' does not exist");
}
if ("latitude".equals(token.name)) {
return locationConfig.getLatitude().toString();
} else if ("longitude".equals(token.name)) {
return locationConfig.getLongitude().toString();
} else if ("name".equals(token.name)) {
return locationConfig.getName();
} else if ("language".equals(token.name)) {
return locationConfig.getLanguage();
} else if ("updateInterval".equals(token.name)) {
return ObjectUtils.toString(locationConfig.getUpdateInterval());
} else if ("locationId".equals(token.name)) {
return locationConfig.getLocationId();
} else if ("providerName".equals(token.name)) {
return ObjectUtils.toString(locationConfig.getProviderName());
} else {
throw new RuntimeException("Invalid weather token: " + token.full);
}
}
@Override
public void setDatapointValue(HmDatapoint dp, String datapointName, Object value) throws HomematicClientException {
HmInterface hmInterface = dp.getChannel().getDevice().getHmInterface();
if (hmInterface == HmInterface.VIRTUALDEVICES) {
String groupName = HmInterface.VIRTUALDEVICES + "." + dp.getChannel().getAddress() + "." + datapointName;
if (dp.isIntegerValue() && value instanceof Double) {
value = ((Number) value).intValue();
}
String strValue = ObjectUtils.toString(value);
if (dp.isStringValue()) {
strValue = "\"" + strValue + "\"";
}
HmResult result = sendScriptByName("setVirtualGroup", HmResult.class,
new String[] { "group_name", "group_state" }, new String[] { groupName, strValue });
if (!result.isValid()) {
throw new HomematicClientException("Unable to set CCU group " + groupName);
}
} else {
super.setDatapointValue(dp, datapointName, value);
}
}
public static CalendarObject getCalendarObject(final TeamCalDO src)
{
if (src == null) {
return null;
}
final Integer userId = PFUserContext.getUserId();
final CalendarObject cal = new CalendarObject();
DOConverter.copyFields(cal, src);
cal.setTitle(src.getTitle());
cal.setDescription(src.getDescription());
cal.setExternalSubscription(src.isExternalSubscription());
final TeamCalRight right = (TeamCalRight) UserRights.instance().getRight(TeamCalDao.USER_RIGHT_ID);
cal.setMinimalAccess(right.hasMinimalAccess(src, userId));
cal.setReadonlyAccess(right.hasReadonlyAccess(src, userId));
cal.setFullAccess(right.hasFullAccess(src, userId));
cal.setOwner(ObjectUtils.equals(userId, src.getOwnerId()));
return cal;
}
public void test5() {
String input = "a;b; c;\"d;\"\"e\";f; ; ;";
StrTokenizer tok = new StrTokenizer(input);
tok.setDelimiterChar(';');
tok.setQuoteChar('"');
tok.setIgnoredMatcher(StrMatcher.trimMatcher());
tok.setIgnoreEmptyTokens(false);
tok.setEmptyTokenAsNull(true);
String tokens[] = tok.getTokenArray();
String expected[] = new String[]{"a", "b", "c", "d;\"e", "f", null, null, null,};
assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
for (int i = 0; i < expected.length; i++) {
assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
ObjectUtils.equals(expected[i], tokens[i]));
}
}
/**
* Replaces static reference to the symbols by the dynamic ones.
*/
protected void replaceStaticRefs() {
for (IProxyReference<IModulaSymbol> proxyRef : symbolReferences) {
Assert.isTrue(proxyRef.getReference() instanceof IStaticModulaSymbolReference<?>);
IModulaSymbol staticSymbol = proxyRef.resolve();
IModulaSymbolReference<IModulaSymbol> dynamicRef = ReferenceFactory.createRef(staticSymbol);
proxyRef.setReference(dynamicRef);
if (CHECK_REFERENCE_INTEGRITY) {
IModulaSymbol dynamicSymbol = ReferenceUtils.resolve(dynamicRef);
if (!(staticSymbol instanceof IInvalidModulaSymbol) && !ObjectUtils.equals(staticSymbol, dynamicSymbol)) {
System.out.println("-- staticSymbol: " + staticSymbol.getQualifiedName() );
String message = String.format(
REFERENCE_IS_RESOLVED_INCORRECTLY_MSG_BASE + REFERENCE_IS_RESOLVED_INCORRECTLY_MSG_DETAILS,
dynamicRef, staticSymbol, dynamicSymbol
);
error(staticSymbol.getPosition(), staticSymbol.getName().length(), message);
}
}
}
symbolReferences.clear();
}
public void test8() {
String input = "a b c \"d e\" f ";
StrTokenizer tok = new StrTokenizer(input);
tok.setDelimiterMatcher(StrMatcher.spaceMatcher());
tok.setQuoteMatcher(StrMatcher.doubleQuoteMatcher());
tok.setIgnoredMatcher(StrMatcher.noneMatcher());
tok.setIgnoreEmptyTokens(true);
String tokens[] = tok.getTokenArray();
String expected[] = new String[]{"a", "b", "c", "d e", "f",};
assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
for (int i = 0; i < expected.length; i++) {
assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
ObjectUtils.equals(expected[i], tokens[i]));
}
}
/**
* Looks up a property on the criteria object and sets it as a key/value pair in the values Map
* @param criteria the DocumentSearchCriteria
* @param property the DocumentSearchCriteria property name
* @param fieldName the destination field name
* @param values the map of values to update
*/
protected static void convertCriteriaPropertyToField(DocumentSearchCriteria criteria, String property, String fieldName, Map<String, String[]> values) {
try {
Object val = PropertyUtils.getProperty(criteria, property);
if (val != null) {
values.put(fieldName, new String[] { ObjectUtils.toString(val) });
}
} catch (NoSuchMethodException nsme) {
LOG.error("Error reading property '" + property + "' of criteria", nsme);
} catch (InvocationTargetException ite) {
LOG.error("Error reading property '" + property + "' of criteria", ite);
} catch (IllegalAccessException iae) {
LOG.error("Error reading property '" + property + "' of criteria", iae);
}
}
@SuppressWarnings("unchecked")
public T bind() {
if (__bound == null) {
__bound = (T) ClassUtils.wrapper(__source).duplicate(Enhancer.create(__targetClass, new MethodInterceptor() {
@Override
public Object intercept(Object targetObject, Method targetMethod, Object[] methodParams, MethodProxy methodProxy) throws Throwable {
PropertyStateMeta _meta = __propertyStates.get(targetMethod.getName());
if (_meta != null && ArrayUtils.isNotEmpty(methodParams) && !ObjectUtils.equals(_meta.getOriginalValue(), methodParams[0])) {
if (__ignoreNull && methodParams[0] == null) {
methodParams[0] = _meta.getOriginalValue();
}
_meta.setNewValue(methodParams[0]);
}
return methodProxy.invokeSuper(targetObject, methodParams);
}
}));
}
return __bound;
}
public int compare(ResolvedArtifact artifact1, ResolvedArtifact artifact2) {
int diff = artifact1.getName().compareTo(artifact2.getName());
if (diff != 0) {
return diff;
}
diff = ObjectUtils.compare(artifact1.getClassifier(), artifact2.getClassifier());
if (diff != 0) {
return diff;
}
diff = artifact1.getExtension().compareTo(artifact2.getExtension());
if (diff != 0) {
return diff;
}
diff = artifact1.getType().compareTo(artifact2.getType());
if (diff != 0) {
return diff;
}
// Use an arbitrary ordering when the artifacts have the same public attributes
return artifact1.hashCode() - artifact2.hashCode();
}
public void test3() {
String input = "a;b; c;\"d;\"\"e\";f; ; ;";
StrTokenizer tok = new StrTokenizer(input);
tok.setDelimiterChar(';');
tok.setQuoteChar('"');
tok.setIgnoredMatcher(StrMatcher.noneMatcher());
tok.setIgnoreEmptyTokens(false);
String tokens[] = tok.getTokenArray();
String expected[] = new String[]{"a", "b", " c", "d;\"e", "f", " ", " ", "",};
assertEquals(ArrayUtils.toString(tokens), expected.length, tokens.length);
for (int i = 0; i < expected.length; i++) {
assertTrue("token[" + i + "] was '" + tokens[i] + "' but was expected to be '" + expected[i] + "'",
ObjectUtils.equals(expected[i], tokens[i]));
}
}
@Override
public boolean hasAccess(final PFUserDO user, final SkillRatingDO obj, final SkillRatingDO oldObj, final OperationType operationType)
{
final SkillRatingDO skill = (oldObj != null) ? oldObj : obj;
if (skill == null) {
return true; // General insert and select access given by default.
}
switch (operationType) {
case SELECT:
case INSERT:
// Everyone is allowed to read and create skillratings
return true;
case UPDATE:
case DELETE:
// Only owner is allowed to edit his skillratings
return ObjectUtils.equals(user.getId(), skill.getUserId());
default:
return false;
}
}
@Override
public int compare(RangerBaseModelObject o1, RangerBaseModelObject o2) {
String val1 = null;
String val2 = null;
if(o1 != null) {
if(o1 instanceof RangerServiceDef) {
val1 = ((RangerServiceDef)o1).getName();
} else if(o1 instanceof RangerService) {
val1 = ((RangerService)o1).getType();
}
}
if(o2 != null) {
if(o2 instanceof RangerServiceDef) {
val2 = ((RangerServiceDef)o2).getName();
} else if(o2 instanceof RangerService) {
val2 = ((RangerService)o2).getType();
}
}
return ObjectUtils.compare(val1, val2);
}
private void initCommonTypes() {
commonTypes.put(int.class, ObjectUtils.NULL);
commonTypes.put(Integer.class, ObjectUtils.NULL);
commonTypes.put(short.class, ObjectUtils.NULL);
commonTypes.put(Short.class, ObjectUtils.NULL);
commonTypes.put(long.class, ObjectUtils.NULL);
commonTypes.put(Long.class, ObjectUtils.NULL);
commonTypes.put(boolean.class, ObjectUtils.NULL);
commonTypes.put(Boolean.class, ObjectUtils.NULL);
commonTypes.put(byte.class, ObjectUtils.NULL);
commonTypes.put(Byte.class, ObjectUtils.NULL);
commonTypes.put(char.class, ObjectUtils.NULL);
commonTypes.put(Character.class, ObjectUtils.NULL);
commonTypes.put(float.class, ObjectUtils.NULL);
commonTypes.put(Float.class, ObjectUtils.NULL);
commonTypes.put(double.class, ObjectUtils.NULL);
commonTypes.put(Double.class, ObjectUtils.NULL);
commonTypes.put(BigDecimal.class, ObjectUtils.NULL);
commonTypes.put(BigInteger.class, ObjectUtils.NULL);
}
/**
* Determine if they have the same values in the specified fields
*
* @param targetObject the target object
* @param sourceObject the source object
* @param keyFields the specified fields
* @return true if the two objects have the same values in the specified fields; otherwise, false
*/
public static boolean equals(Object targetObject, Object sourceObject, List<String> keyFields) {
if (targetObject == sourceObject) {
return true;
}
if (targetObject == null || sourceObject == null) {
return false;
}
for (String propertyName : keyFields) {
try {
Object propertyValueOfSource = PropertyUtils.getProperty(sourceObject, propertyName);
Object propertyValueOfTarget = PropertyUtils.getProperty(targetObject, propertyName);
if (!ObjectUtils.equals(propertyValueOfSource, propertyValueOfTarget)) {
return false;
}
}
catch (Exception e) {
LOG.info(e);
return false;
}
}
return true;
}
@Override
public boolean equals(final Object o)
{
if (o instanceof KontoDO) {
final KontoDO other = (KontoDO) o;
if (ObjectUtils.equals(this.getNummer(), other.getNummer()) == false) {
return false;
}
return ObjectUtils.equals(this.getBezeichnung(), other.getBezeichnung());
}
return false;
}
/**
* Set the value of stateChangeFromOptionId.
* @param v Value to assign to stateChangeFromOptionId.
*/
public void setStateChangeFromOptionId(NumberKey v)
{
if (!ObjectUtils.equals(v, this.stateChangeFromOptionId))
{
modified = true;
this.stateChangeFromOptionId = v;
}
}
private void parseConfiguration(final Map<String, Object> configuration) {
port = ObjectUtils.toString(configuration.get("port"), null);
network = Integer.valueOf(ObjectUtils.toString(configuration.get("network"), "0")).byteValue();
logger.debug("Parsed UPB configuration:");
logger.debug("Serial port: {}", port);
logger.debug("UPB Network: {}", network & 0xff);
}
@Override
protected void onSave(final ToDoDO obj)
{
if (ObjectUtils.equals(PFUserContext.getUserId(), obj.getAssigneeId()) == false) {
// To-do is changed by other user than assignee, so set recent flag for this to-do for the assignee.
obj.setRecent(true);
}
}
/**
* Set the value of sortPolarity.
* @param v Value to assign to sortPolarity.
*/
public void setSortPolarity(String v)
{
if (!ObjectUtils.equals(v, this.sortPolarity))
{
modified = true;
this.sortPolarity = v;
}
}
@Test
public void testSaveBulkLargeTextNodeWithBlockingDisabled() throws Exception {
when(removerConfiguration.getBlockPercentage()).thenReturn(0);
Table table = tableMetadataManager.get(TestUtils.TEST_TABLE_NAME);
Document originalDocument = createLargeDummyDocument();
Document translatedDocument = TestUtils.translatedDocumentWithRowKeyVersion1(table, originalDocument);
doReturn(translatedDocument).when(dataStore)
.save(table, originalDocument);
queryStore.save(TestUtils.TEST_TABLE_NAME, originalDocument);
val currentIndex = ElasticsearchUtils.getCurrentIndex(TestUtils.TEST_TABLE_NAME, originalDocument.getTimestamp());
val response = elasticsearchConnection.getClient()
.prepareGet(currentIndex, ElasticsearchUtils.DOCUMENT_TYPE_NAME, originalDocument.getId())
.setStoredFields(ElasticsearchUtils.DOCUMENT_META_TIMESTAMP_FIELD_NAME, "testField", "testLargeField")
.execute()
.actionGet();
assertTrue(response.isExists());
val request = new GetFieldMappingsRequest();
request.indices(currentIndex);
request.fields("*");
val mappings = elasticsearchConnection.getClient()
.admin()
.indices()
.getFieldMappings(request)
.get();
Set<String> expectedFields = Sets.newHashSet("_index", "date.minuteOfHour", "date.year",
"date.dayOfMonth", "testField", "testField.analyzed",
"testLargeField",
"testLargeField.analyzed",
"_all", "date.dayOfWeek", "date.minuteOfDay",
"_parent", "date.monthOfYear", "__FOXTROT_METADATA__.time",
"time.date", "_version", "date.weekOfYear",
"_routing", "__FOXTROT_METADATA__.rawStorageId",
"_type", "__FOXTROT_METADATA__.id", "date.hourOfDay",
"_seq_no", "_field_names", "_source", "_id", "time", "_uid");
assertTrue(ObjectUtils.equals(expectedFields, mappings.mappings().get(currentIndex).get(ElasticsearchUtils.DOCUMENT_TYPE_NAME).keySet()));
}
@Override
public Void parse(Object[] message) throws IOException {
message = (Object[]) message[0];
for (int i = 0; i < message.length; i++) {
String scriptName = ObjectUtils.toString(message[i]);
HmDatapoint dpScript = new HmDatapoint(scriptName, scriptName, HmValueType.BOOL, Boolean.FALSE, false,
HmParamsetType.VALUES);
dpScript.setInfo(scriptName);
channel.addDatapoint(dpScript);
}
return null;
}
/**
* Set the value of commentQuery.
* @param v Value to assign to commentQuery.
*/
public void setCommentQuery(String v)
{
if (!ObjectUtils.equals(v, this.commentQuery))
{
modified = true;
this.commentQuery = v;
}
}