Java Code Examples for java.util.Objects.nonNull()

The following are Jave code examples for showing how to use nonNull() of the java.util.Objects class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: quartz-manager   File: EmailService.java   View Source Code Vote up 6 votes
public void updateJob(String group, String name, JobDescriptor descriptor) {
	try {
		JobDetail oldJobDetail = scheduler.getJobDetail(jobKey(name, group));
		if(Objects.nonNull(oldJobDetail)) {
			JobDataMap jobDataMap = oldJobDetail.getJobDataMap();
			jobDataMap.put("subject", descriptor.getSubject());
			jobDataMap.put("messageBody", descriptor.getMessageBody());
			jobDataMap.put("to", descriptor.getTo());
			jobDataMap.put("cc", descriptor.getCc());
			jobDataMap.put("bcc", descriptor.getBcc());
			JobBuilder jb = oldJobDetail.getJobBuilder();
			JobDetail newJobDetail = jb.usingJobData(jobDataMap).storeDurably().build();
			scheduler.addJob(newJobDetail, true);
			log.info("Updated job with key - {}", newJobDetail.getKey());
			return;
		}
		log.warn("Could not find job with key - {}.{} to update", group, name);
	} catch (SchedulerException e) {
		log.error("Could not find job with key - {}.{} to update due to error - {}", group, name, e.getLocalizedMessage());
	}
}
 
Example 2
Project: willtest   File: SeleniumEventListener.java   View Source Code Vote up 6 votes
@Override
protected void after(Description description, Throwable testFailure) throws Throwable {
    super.after(description, testFailure);
    try {
        if (Objects.nonNull(testFailure)) {
            LOGGER.error("\n\n\nTest failed with error: ", testFailure);
            TestReportFile testReportFile = TestReportFile.forTest(description).withPostix("_action.log").build();
            FileUtils.copyFile(tempFile, testReportFile.getFile());
        }
    } finally {
        if (!tempFile.delete()) {
            LOGGER.error("Could not delete temp file at " + tempFile.getAbsolutePath());
        }
        tempFile = null;
        Logger.getLogger(LOGGER_NAME).removeAppender(APPENDER_NAME);
    }
}
 
Example 3
Project: happylifeplat-transaction   File: NettyMessageServiceImpl.java   View Source Code Vote up 6 votes
/**
 * 完成提交自身的事务
 *
 * @param txGroupId 事务组id
 * @param taskKey   子事务的taskKey
 * @param status    状态  {@linkplain com.happylifeplat.transaction.common.enums.TransactionStatusEnum}
 * @return true 成功 false 失败
 */
@Override
public Boolean completeCommitTxTransaction(String txGroupId, String taskKey, int status) {
    HeartBeat heartBeat = new HeartBeat();
    heartBeat.setAction(NettyMessageActionEnum.COMPLETE_COMMIT.getCode());
    TxTransactionGroup txTransactionGroup = new TxTransactionGroup();
    txTransactionGroup.setId(txGroupId);
    TxTransactionItem item = new TxTransactionItem();
    item.setTaskKey(taskKey);
    item.setStatus(status);
    txTransactionGroup.setItemList(Collections.singletonList(item));
    heartBeat.setTxTransactionGroup(txTransactionGroup);
    final Object object = nettyClientMessageHandler.sendTxManagerMessage(heartBeat);
    if (Objects.nonNull(object)) {
        return (Boolean) object;
    }
    return false;
}
 
Example 4
Project: willtest   File: SeleniumEventListener.java   View Source Code Vote up 5 votes
@Override
public void afterChangeValueOf(WebElement webElement, WebDriver webDriver, CharSequence[] charSequences) {
    if(Objects.nonNull(charSequences)) {
        StringBuilder stringBuilder = new StringBuilder();
        for (CharSequence charSequence : charSequences) {
            stringBuilder.append("['").append(charSequence).append("']");
        }
        LOGGER.info("Input in: " + getElementSelector(webElement) + " --- Input text: " + stringBuilder.toString());
    } else {
        LOGGER.info("Input in: " + getElementSelector(webElement) + " --- Cleared field");
    }
}
 
Example 5
Project: visitormanagement   File: EmployeeService.java   View Source Code Vote up 5 votes
private long getLatestSlackUpdatedTime() {
	Employee employee = employeeRepository.findOne(new Sort(Sort.Direction.DESC, EMPLOYEE_FIELDS.SLACK_UPDATEDTIME));
	if (Objects.nonNull(employee)) {
		return employee.getSlackUt();
	}
	return 0; 
}
 
Example 6
Project: happylifeplat-transaction   File: NettyMessageServiceImpl.java   View Source Code Vote up 5 votes
/**
 * 获取事务组状态
 *
 * @param txGroupId 事务组id
 * @return 事务组状态
 */
@Override
public int findTransactionGroupStatus(String txGroupId) {
    HeartBeat heartBeat = new HeartBeat();
    heartBeat.setAction(NettyMessageActionEnum.GET_TRANSACTION_GROUP_STATUS.getCode());
    TxTransactionGroup txTransactionGroup = new TxTransactionGroup();
    txTransactionGroup.setId(txGroupId);

    final Object object = nettyClientMessageHandler.sendTxManagerMessage(heartBeat);
    if (Objects.nonNull(object)) {
        return (Integer) object;
    }
    return TransactionStatusEnum.ROLLBACK.getCode();

}
 
Example 7
Project: ServerBrowser   File: FavouritesController.java   View Source Code Vote up 5 votes
private static String escapeFormat(final String string, final String... replacements) {
	final String[] replacementsNew = new String[replacements.length];
	for (int i = 0; i < replacements.length; i++) {
		final String replacementValue = replacements[i];
		if (Objects.nonNull(replacementValue)) {
			replacementsNew[i] = replacementValue.replace("'", "''");
		}
	}
	return MessageFormat.format(string, (Object[]) replacementsNew);
}
 
Example 8
Project: allure-java   File: AllureJunit4.java   View Source Code Vote up 5 votes
private TestResult createTestResult(final String uuid, final Description description) {
    final String className = description.getClassName();
    final String methodName = description.getMethodName();
    final String name = Objects.nonNull(methodName) ? methodName : className;
    final String fullName = Objects.nonNull(methodName) ? String.format("%s.%s", className, methodName) : className;
    final String suite = Optional.ofNullable(description.getTestClass().getAnnotation(DisplayName.class))
            .map(DisplayName::value).orElse(className);

    final TestResult testResult = new TestResult()
            .withUuid(uuid)
            .withHistoryId(getHistoryId(description))
            .withName(name)
            .withFullName(fullName)
            .withLinks(getLinks(description))
            .withLabels(
                    new Label().withName("package").withValue(getPackage(description.getTestClass())),
                    new Label().withName("testClass").withValue(className),
                    new Label().withName("testMethod").withValue(name),
                    new Label().withName("suite").withValue(suite),
                    new Label().withName("host").withValue(getHostName()),
                    new Label().withName("thread").withValue(getThreadName())
            );
    testResult.getLabels().addAll(getLabels(description));
    getDisplayName(description).ifPresent(testResult::setName);
    getDescription(description).ifPresent(testResult::setDescription);
    return testResult;
}
 
Example 9
Project: spring-boot-rocketmq-starter   File: AbstractRocketMqConsumer.java   View Source Code Vote up 5 votes
@PreDestroy
public void destroy() throws Exception {
    if (Objects.nonNull(consumer)) {
        consumer.shutdown();
    }
    logger.info("consumer shutdown, {}", this.toString());
}
 
Example 10
Project: ServerBrowser   File: OptionalUtility.java   View Source Code Vote up 5 votes
/**
 * Returns an {@link Optional} of the first non-null Object found within the given objects.
 *
 * @param objects
 *            objects to get the first non-null from
 * @return first non-null object or an empty {@link Optional}
 */
@SafeVarargs
public static <T> Optional<T> firstNonNullOrEmpty(final T... objects) {
	for (final T t : objects) {
		if (Objects.nonNull(t)) {
			return Optional.of(t);
		}
	}

	return Optional.empty();
}
 
Example 11
Project: cloudterm   File: TerminalService.java   View Source Code Vote up 5 votes
private void initializeProcess() throws Exception {

        String userHome = System.getProperty("user.home");
        Path dataDir = Paths.get(userHome).resolve(".terminalfx");
        IOHelper.copyLibPty(dataDir);

        if (Platform.isWindows()) {
            this.termCommand = "cmd.exe".split("\\s+");
        } else {
            this.termCommand = "/bin/bash -i".split("\\s+");
        }

        if(Objects.nonNull(shellStarter)){
            this.termCommand = shellStarter.split("\\s+");
        }

        Map<String, String> envs = new HashMap<>(System.getenv());
        envs.put("TERM", "xterm");

        System.setProperty("PTY_LIB_FOLDER", dataDir.resolve("libpty").toString());

        this.process = PtyProcess.exec(termCommand, envs, userHome);

        process.setWinSize(new WinSize(columns, rows));
        this.inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        this.errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        this.outputWriter = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

        ThreadHelper.start(() -> {
            printReader(inputReader);
        });

        ThreadHelper.start(() -> {
            printReader(errorReader);
        });

        process.waitFor();

    }
 
Example 12
Project: java-commons   File: Exec.java   View Source Code Vote up 5 votes
@Override
public void execute() {
    if (withTry && Objects.nonNull(recoverFunc)) {
        Try.apply(worker).recoverWith(recoverFunc);
        return;
    }

    if (withTry) {
        Try.apply(worker);
        return;
    }

    worker.execute();
}
 
Example 13
Project: sstable-adaptor   File: FileHandle.java   View Source Code Vote up 5 votes
/**
 * Provide {@link CompressionMetadata} to use when reading compressed file.
 *
 * @param metadata CompressionMetadata to use
 * @return this object
 */
public Builder withCompressionMetadata(CompressionMetadata metadata)
{
    this.compressed = Objects.nonNull(metadata);
    this.compressionMetadata = metadata;
    return this;
}
 
Example 14
Project: monarch   File: MPredicateHelper.java   View Source Code Vote up 4 votes
public static Predicate<Double> isGreaterThanOrEqual(final Double target) {
  return (null == target) ? Objects::isNull : me -> Objects.nonNull(me) && me >= target;
}
 
Example 15
Project: monarch   File: MPredicateHelper.java   View Source Code Vote up 4 votes
public static Predicate<Byte> isGreaterThanOrEqual(final Byte target) {
  return (null == target) ? Objects::isNull : me -> Objects.nonNull(me) && me >= target;
}
 
Example 16
Project: ForgeHax   File: FlyMod.java   View Source Code Vote up 4 votes
@Override
public void onDisabled() {
    if(Objects.nonNull(getLocalPlayer()))
        getLocalPlayer().noClip = false;
}
 
Example 17
Project: monarch   File: MPredicateHelper.java   View Source Code Vote up 4 votes
public static Predicate<Byte> isLessThanOrEqual(final Byte target) {
  return (null == target) ? Objects::isNull : me -> Objects.nonNull(me) && me <= target;
}
 
Example 18
Project: Cognizant-Intelligent-Test-Scripter   File: Attributes.java   View Source Code Vote up 4 votes
public boolean addAll(List<Attribute> a) {
    if (Objects.nonNull(a)) {
        return super.addAll(a);
    }
    return false;
}
 
Example 19
Project: happylifeplat-tcc   File: ZookeeperCompensationServiceImpl.java   View Source Code Vote up 4 votes
/**
 * 分页获取补偿事务信息
 *
 * @param query 查询条件
 * @return CommonPager<TransactionRecoverVO>
 */
@Override
public CommonPager<TccCompensationVO> listByPage(CompensationQuery query) {

    CommonPager<TccCompensationVO> voCommonPager = new CommonPager<>();
    final int currentPage = query.getPageParameter().getCurrentPage();
    final int pageSize = query.getPageParameter().getPageSize();

    int start = (currentPage - 1) * pageSize;

    final String rootPath = RepositoryPathUtils.buildZookeeperPathPrefix(query.getApplicationName());

    List<String> zNodePaths;

    List<TccCompensationVO> voList;

    int totalCount;

    try {
        //如果只查 重试条件的
        if (StringUtils.isBlank(query.getTransId()) && Objects.nonNull(query.getRetry())) {
            zNodePaths = zooKeeper.getChildren(rootPath, false);
            final List<TccCompensationVO> all = findAll(zNodePaths, rootPath);
            final List<TccCompensationVO> collect =
                    all.stream()
                            .filter(vo -> vo.getRetriedCount() < query.getRetry())
                            .collect(Collectors.toList());
            totalCount = collect.size();
            voList = collect.stream().skip(start).limit(pageSize).collect(Collectors.toList());

        } else if (StringUtils.isNoneBlank(query.getTransId()) && Objects.isNull(query.getRetry())) {
            zNodePaths = Lists.newArrayList(query.getTransId());
            totalCount = zNodePaths.size();
            voList = findAll(zNodePaths, rootPath);

        } else if (StringUtils.isNoneBlank(query.getTransId()) && Objects.nonNull(query.getRetry())) {
            zNodePaths = Lists.newArrayList(query.getTransId());
            totalCount = zNodePaths.size();
            voList = findAll(zNodePaths, rootPath)
                    .stream()
                    .filter(vo -> vo.getRetriedCount() < query.getRetry())
                    .collect(Collectors.toList());
        } else {
            zNodePaths = zooKeeper.getChildren(rootPath, false);
            totalCount = zNodePaths.size();
            voList = findByPage(zNodePaths, rootPath, start, pageSize);
        }
        voCommonPager.setPage(PageHelper.buildPage(query.getPageParameter(), totalCount));
        voCommonPager.setDataList(voList);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return voCommonPager;
}
 
Example 20
Project: jdk8u-jdk   File: TimeZoneNameUtility.java   View Source Code Vote up 3 votes
/**
 * Retrieves a standard or daylight-saving time name for the given time zone ID.
 *
 * @param id       time zone ID
 * @param daylight true for a daylight saving time name, or false for a standard time name
 * @param style    TimeZone.LONG or TimeZone.SHORT
 * @param locale   desired Locale
 * @return the requested time zone name, or null if not found.
 */
public static String retrieveDisplayName(String id, boolean daylight, int style, Locale locale) {
    String[] names = retrieveDisplayNamesImpl(id, locale);
    if (Objects.nonNull(names)) {
        return names[(daylight ? 4 : 2) - style];
    } else {
        return null;
    }
}