Java Code Examples for org.apache.commons.lang3.StringUtils#defaultIfBlank()

The following examples show how to use org.apache.commons.lang3.StringUtils#defaultIfBlank() . 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: PasswordResetService.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
private void handleSendAndUpdateDatabase(EmailProperties emailProperties, Map<String, Object> templateFields, String emailAddress, String username, String tempPassword) throws AlertException {
    try {
        String alertLogo = alertProperties.getAlertLogo();

        Map<String, String> contentIdsToFilePaths = new HashMap<>();
        EmailMessagingService emailService = new EmailMessagingService(emailProperties, freemarkerTemplatingService);
        emailService.addTemplateImage(templateFields, contentIdsToFilePaths, EmailPropertyKeys.EMAIL_LOGO_IMAGE.getPropertyKey(), alertLogo);

        EmailTarget passwordResetEmail = new EmailTarget(emailAddress, TEMPLATE_NAME, templateFields, contentIdsToFilePaths);
        emailService.sendEmailMessage(passwordResetEmail);
        // Only change the password if there isn't an issue with sending the email
        userAccessor.changeUserPassword(username, tempPassword);
    } catch (Exception genericException) {
        throw new AlertException("Problem sending password reset email. " + StringUtils.defaultIfBlank(genericException.getMessage(), ""), genericException);
    }
}
 
Example 2
Source File: GameSetupController.java    From Rails with GNU General Public License v2.0 6 votes vote down vote up
private GameSetupController() {
    GameInfoParser gip = new GameInfoParser();
    try {
        gameList.addAll(gip.processGameList());
        credits = gip.getCredits();
    } catch (ConfigurationException e) {
        log.error("Unable to initialize Game setup controller", e);
    }

    window = new GameSetupWindow(this);

    savedFileExtension = "." + StringUtils.defaultIfBlank(Config.get("save.filename.extension"), GameUIManager.DEFAULT_SAVE_EXTENSION);

    // Notify the sound manager about having started the setup menu
    SoundManager.notifyOfGameSetup();
}
 
Example 3
Source File: OracleExtractor.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
@Override
public List<Command> getDataMetadata(String schema, String entity, WorkUnit workUnit, List<Predicate> predicateList)
    throws DataRecordException {
  log.debug("Build query to extract data");
  List<Command> commands = new ArrayList<>();
  int fetchSize = this.workUnitState.getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_JDBC_RESULTSET_FETCH_SIZE,
      ConfigurationKeys.DEFAULT_SOURCE_QUERYBASED_JDBC_RESULTSET_FETCH_SIZE);
  log.info("Setting jdbc resultset fetch size as " + fetchSize);

  String watermarkFilter = StringUtils.defaultIfBlank(this.concatPredicates(predicateList), EMPTY_CONDITION);
  String query = this.getExtractSql();

  query = query.replace(ConfigurationKeys.DEFAULT_SOURCE_QUERYBASED_WATERMARK_PREDICATE_SYMBOL, watermarkFilter);
  query = addSampleQueryPart(query);

  commands.add(getCommand(query, JdbcCommand.JdbcCommandType.QUERY));
  commands.add(getCommand(fetchSize, JdbcCommand.JdbcCommandType.FETCHSIZE));
  return commands;
}
 
Example 4
Source File: CheckInApiController.java    From alf.io with GNU General Public License v3.0 6 votes vote down vote up
@PostMapping("/check-in/event/{eventName}/bulk")
public Map<String, TicketAndCheckInResult> bulkCheckIn(@PathVariable("eventName") String eventName,
                                                       @RequestBody List<TicketIdentifierCode> ticketIdentifierCodes,
                                                       @RequestParam(value = "offlineUser", required = false) String offlineUser,
                                                       @RequestParam(value = "forceCheckInPaymentOnSite", required = false, defaultValue = "false") boolean forceCheckInPaymentOnSite,
                                                       Principal principal) {
    String username = principal.getName();
    String auditUser = StringUtils.defaultIfBlank(offlineUser, username);
    return ticketIdentifierCodes.stream()
        .distinct()
        .map(t -> {
            TicketAndCheckInResult res = checkInManager.checkIn(eventName, t.getIdentifier(),
                Optional.ofNullable(t.getCode()),
                username, auditUser, forceCheckInPaymentOnSite);
            return Pair.of(t.identifier, res);
        })
        .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
}
 
Example 5
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
/**
 * Creates instance of the client.
 *
 * @param httpClient HTTP client
 * @param url URL of the GPT REST end point
 * @param cred credentials
 * @param index index name
 */
public Client(CloseableHttpClient httpClient, URL url, SimpleCredentials cred, String index) {
  this.httpClient = httpClient;
  this.url = url;
  this.cred = cred;
  this.index = StringUtils.defaultIfBlank(index, DEFAULT_INDEX);

  mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
 
Example 6
Source File: UserRestController.java    From jakduk-api with MIT License 5 votes vote down vote up
@PostMapping("/social")
public EmptyJsonResponse createSocialUser(
        @Valid @RequestBody SocialUserForm form,
        HttpSession session) {

    AttemptSocialUser attemptSocialUser = (AttemptSocialUser) session.getAttribute(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE);

    if (Objects.isNull(attemptSocialUser))
        throw new ServiceException(ServiceError.CANNOT_GET_ATTEMPT_SNS_PROFILE);

    String largePictureUrl = StringUtils.defaultIfBlank(form.getExternalLargePictureUrl(), null);

    User user = userService.createSocialUser(form.getEmail().trim(), form.getUsername().trim(), attemptSocialUser.getProviderId(),
            attemptSocialUser.getProviderUserId().trim(), form.getFootballClub(), form.getAbout(),
            form.getUserPictureId(), largePictureUrl);

    // Perform the security
    Authentication authentication = authenticationManager.authenticate(
            new SnsAuthenticationToken(
                    user.getEmail()
            )
    );

    AuthUtils.setAuthentication(authentication);

    session.removeAttribute(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE);

    rabbitMQPublisher.sendWelcome(JakdukUtils.getLocale(), user.getEmail(), user.getUsername());

    return EmptyJsonResponse.newInstance();
}
 
Example 7
Source File: UpdateEmailService.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private void handleSendAndUpdateDatabase(EmailProperties emailProperties, Map<String, Object> templateFields, String emailAddress) throws AlertException {
    try {
        String alertLogo = alertProperties.getAlertLogo();

        Map<String, String> contentIdsToFilePaths = new HashMap<>();
        EmailMessagingService emailService = new EmailMessagingService(emailProperties, freemarkerTemplatingService);
        emailService.addTemplateImage(templateFields, contentIdsToFilePaths, EmailPropertyKeys.EMAIL_LOGO_IMAGE.getPropertyKey(), alertLogo);

        EmailTarget passwordResetEmail = new EmailTarget(emailAddress, TEMPLATE_NAME, templateFields, contentIdsToFilePaths);
        emailService.sendEmailMessage(passwordResetEmail);
    } catch (Exception genericException) {
        throw new AlertException("Problem sending version update email. " + StringUtils.defaultIfBlank(genericException.getMessage(), StringUtils.EMPTY), genericException);
    }
}
 
Example 8
Source File: Discord.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
public void setConfig() {
    webhook = StringUtils.trimToNull(Config.get("notify.discord.webhook"));
    String message = StringUtils.defaultIfBlank(Config.get("notify.message"), MESSAGE_TEMPLATE);
    body = StringUtils.replace(BODY_TEMPLATE, "@@", message);

    parseUserMappings(Config.get("notify.discord.user_mapping"));
}
 
Example 9
Source File: Slack.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
public void setConfig() {
    webhook = StringUtils.trimToNull(Config.get("notify.slack.webhook"));
    String message = StringUtils.defaultIfBlank(Config.get("notify.message"), MESSAGE_TEMPLATE);
    body = StringUtils.replace(BODY_TEMPLATE, "@@", message);

    parseUserMappings(Config.get("notify.slack.user_mapping"));
}
 
Example 10
Source File: ArticleService.java    From jakduk-api with MIT License 5 votes vote down vote up
/**
    * 자유게시판 글쓰기
 *
    * @param subject 글 제목
    * @param content 글 내용
    * @param categoryCode 글 말머리 Code
    * @param linkedGallery 사진 연동 여부
    */
public Article insertArticle(CommonWriter writer, Constants.BOARD_TYPE board, String subject, String content, String categoryCode,
							 Boolean linkedGallery) {

	if (BoardCategoryGenerator.notExistCategory(board, categoryCode))
		throw new ServiceException(ServiceError.NOT_FOUND_CATEGORY);

	// shortContent 만듦
	String stripHtmlContent = StringUtils.defaultIfBlank(JakdukUtils.stripHtmlTag(content), StringUtils.EMPTY);
	String shortContent = StringUtils.truncate(stripHtmlContent, Constants.ARTICLE_SHORT_CONTENT_LENGTH);

	ObjectId objectId = new ObjectId();

	Article article = new Article();
	article.setWriter(writer);
	article.setBoard(board.name());
	article.setCategory(Constants.BOARD_TYPE.FREE.equals(board) ? null : categoryCode);
	article.setSubject(subject);
	article.setContent(content);
	article.setShortContent(shortContent);
	article.setViews(0);
	article.setSeq(commonService.getNextSequence(Constants.SEQ_BOARD));
	article.setLogs(this.initBoardLogs(objectId, Constants.ARTICLE_LOG_TYPE.CREATE.name(), writer));
	article.setLastUpdated(LocalDateTime.ofInstant(objectId.getDate().toInstant(), ZoneId.systemDefault()));
	article.setLinkedGallery(linkedGallery);

	articleRepository.save(article);

	log.info("new post created. post seq={}, subject={}", article.getSeq(), article.getSubject());

	return article;
}
 
Example 11
Source File: CheckInApiController.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping("/check-in/event/{eventName}/ticket/{ticketIdentifier}/confirm-on-site-payment")
public TicketAndCheckInResult confirmOnSitePayment(@PathVariable("eventName") String eventName,
                                                   @PathVariable("ticketIdentifier") String ticketIdentifier,
                                                   @RequestBody TicketCode ticketCode,
                                                   @RequestParam(value = "offlineUser", required = false) String offlineUser,
                                                   Principal principal) {
    String username = principal.getName();
    String auditUser = StringUtils.defaultIfBlank(offlineUser, username);
    return checkInManager.confirmOnSitePayment(eventName, ticketIdentifier, Optional.ofNullable(ticketCode).map(TicketCode::getCode), username, auditUser);
}
 
Example 12
Source File: ImageBuildController.java    From uyuni with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @return the version
 */
public String getVersion() {
    return StringUtils.defaultIfBlank(version, "latest");
}
 
Example 13
Source File: DubboReaderExtension.java    From swagger-dubbo with Apache License 2.0 4 votes vote down vote up
private static String getResponseContainer(ApiOperation apiOperation) {
	return apiOperation == null ? null
			: StringUtils.defaultIfBlank(apiOperation.responseContainer(), null);
}
 
Example 14
Source File: FeatureFileUtilsImpl.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
@Override
public List<FileDetails> getFeatureScripts(
	@NotNull final String path,
	final String featureGroup,
	final String baseUrl) {
	checkArgument(StringUtils.isNotBlank(path));

	/*
		Assume a null base url is just an empty string
	 */
	final String fixedBaseUrl = StringUtils.defaultIfBlank(baseUrl, "");
	final String fixedPath = fixedBaseUrl + path;

	/*
		We need to be wary of different OSs throwing exceptions working with
		urls in these file methods.
	 */
	return Try.of(() -> {
		if (Files.isDirectory(Paths.get(fixedPath))) {
			/*
				We know this is a local directory, so process the files.
				We only return files that match the feature group header
			 */
			return processLocalFiles(fixedPath).stream()
				.filter(e -> FEATURE_READER.selectFile(e, featureGroup))
				.map(e -> new FileDetails(e, true))
				.collect(Collectors.toList());

		}

		if (Files.isRegularFile(Paths.get(fixedPath)) || Files.isRegularFile(Paths.get("./" + fixedPath))) {
			/*
				We know this is a single file, so just return it. Note that we
				ignore the supplied feature group when we are looking at
				a single file
			 */
			return Arrays.asList(new FileDetails(new File(path), true));
		}

		throw new Exception();
	})
	/*
		Either there was an exception because the url was not accepted in the
		file operations, or we correctly determine that the url is not a
		file or directory
	 */
	.orElse(Try.of(() -> processRemoteUrl(fixedPath).stream()
		.map(e -> new FileDetails(e, false))
		.collect(Collectors.toList()))
	)
	/*
		This wasn't a url or a file, so we just have to throw an exception
	 */
	.getOrElseThrow(
		ex -> new FileProfileAccessException("Error attempting to open \"" + path
			+ "\". Make sure the supplied path or URL was correct.", ex)
	);
}
 
Example 15
Source File: ProfileMessagingLogicImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public boolean sendNewMessage(final String uuidTo, final String uuidFrom, final String threadId, final String subject, final String messageStr) {

	String messageSubject = StringUtils.defaultIfBlank(subject, ProfileConstants.DEFAULT_PRIVATE_MESSAGE_SUBJECT);

	//setup thread
	MessageThread thread = new MessageThread();
	thread.setId(threadId);
	thread.setSubject(messageSubject);

	//setup message
	Message message = new Message();
	message.setId(ProfileUtils.generateUuid());
	message.setFrom(uuidFrom);
	message.setMessage(messageStr);
	message.setDatePosted(new Date());
	message.setThread(thread.getId());
	//saveNewMessage(message);
	
	
	//setup participants
	//at present we have one for the receipient and one for sender.
	//in future we may have multiple recipients and will need to check the existing list of thread participants 
	List<String> threadParticipants = new ArrayList<String>();
	threadParticipants.add(uuidTo);
	threadParticipants.add(uuidFrom);

	List<MessageParticipant> participants = new ArrayList<MessageParticipant>();
	for(String threadParticipant : threadParticipants){
		MessageParticipant p = new MessageParticipant();
		p.setMessageId(message.getId());
		p.setUuid(threadParticipant);
		if(StringUtils.equals(threadParticipant, message.getFrom())) {
			p.setRead(true); //sender 
		} else {
			p.setRead(false);
		}
		p.setDeleted(false);
		
		participants.add(p);
	}
	
	if(saveAllNewMessageParts(thread, message, participants)) {
		sendMessageEmailNotification(threadParticipants, uuidFrom, threadId, messageSubject, messageStr, EmailType.EMAIL_NOTIFICATION_MESSAGE_NEW);
           //post event
           sakaiProxy.postEvent(ProfileConstants.EVENT_MESSAGE_SENT, "/profile/" + uuidTo, true);
		return true;
	}
	return false;
}
 
Example 16
Source File: DcatRecordAdaptor.java    From geoportal-server-harvester with Apache License 2.0 4 votes vote down vote up
@Override
public String getDescription() {
  return StringUtils.defaultIfBlank(getString("description"),getAbstract());
}
 
Example 17
Source File: ArticleService.java    From jakduk-api with MIT License 4 votes vote down vote up
/**
 * 자유게시판 글 고치기
 *
 * @param board 게시판
 * @param seq 글 seq
 * @param subject 글 제목
 * @param content 글 내용
 * @param categoryCode 글 말머리 Code
 * @param linkedGallery 사진 연동 여부
 */
public Article updateArticle(CommonWriter writer, Constants.BOARD_TYPE board, Integer seq, String subject, String content, String categoryCode,
							 Boolean linkedGallery) {

	Article article = articleRepository.findOneByBoardAndSeq(board.name(), seq)
			.orElseThrow(() -> new ServiceException(ServiceError.NOT_FOUND_ARTICLE));

	if (! article.getWriter().getUserId().equals(writer.getUserId()))
		throw new ServiceException(ServiceError.FORBIDDEN);

	if (BoardCategoryGenerator.notExistCategory(board, categoryCode))
		throw new ServiceException(ServiceError.NOT_FOUND_CATEGORY);

	// shortContent 만듦
	String stripHtmlContent = StringUtils.defaultIfBlank(JakdukUtils.stripHtmlTag(content), StringUtils.EMPTY);
	String shortContent = StringUtils.truncate(stripHtmlContent, Constants.ARTICLE_SHORT_CONTENT_LENGTH);

	article.setSubject(subject);
	article.setContent(content);
	article.setCategory(Constants.BOARD_TYPE.FREE.equals(board) ? null : categoryCode);
	article.setShortContent(shortContent);
	article.setLinkedGallery(linkedGallery);

	// boardHistory
	List<BoardLog> logs = article.getLogs();

	if (CollectionUtils.isEmpty(logs))
		logs = new ArrayList<>();

	ObjectId logId = new ObjectId();
	logs.add(new BoardLog(logId.toString(), Constants.ARTICLE_LOG_TYPE.EDIT.name(), new SimpleWriter(writer.getUserId(), writer.getUsername())));
	article.setLogs(logs);

	// lastUpdated
	article.setLastUpdated(LocalDateTime.ofInstant(logId.getDate().toInstant(), ZoneId.systemDefault()));

	articleRepository.save(article);

	log.info("post was edited. post seq={}, subject={}", article.getSeq(), article.getSubject());

	return article;
}
 
Example 18
Source File: CsvLibraryBuilder.java    From sailfish-core with Apache License 2.0 3 votes vote down vote up
private ScriptList parseScriptList(Map<String, String> row, long currentRecordNumber) throws InvalidRowException {

		String name = row.get(CsvHeader.Name.getFieldKey());

		if(name == null) {
			throw new InvalidRowException(CsvHeader.Name.getFieldKey()
					+ " is required for Script List");
		}

        Set<String> serviceNames = parseServiceListReferences(row.get(CsvHeader.Services.getFieldKey()));

		String priorityString = row.get(CsvHeader.Priority.getFieldKey());

		long priority = 0;
        boolean priorityParsed = true;

		if(StringUtils.isNotEmpty(priorityString)) {

			try {

				priority = Long.parseLong(priorityString);

			} catch(NumberFormatException e) {
                priorityParsed = false;
			}

		}

		String executor = StringUtils.defaultIfBlank(row.get(CsvHeader.Executor.getFieldKey()), null);
        String variableSet = StringUtils.stripToNull(row.get(CsvHeader.VariableSet.getFieldKey()));

        ScriptList result = new ScriptList(name, executor, serviceNames, parseApiOptions(row), priority, currentRecordNumber, variableSet);

        if (!priorityParsed) {
            result.addRejectCause(new ImportError(currentRecordNumber, "'Priority' value is not parsable to number (long)"));
        }

		return result;

	}
 
Example 19
Source File: ModuleDetector.java    From analysis-model with MIT License 2 votes vote down vote up
/**
 * Returns the project name stored in the POM.
 *
 * @param pom
 *         Maven POM file name
 *
 * @return the project name or an empty string if the name could not be resolved
 */
private String parsePom(final String pom) {
    String name = parsePomAttribute(pom, "name");

    return StringUtils.defaultIfBlank(name, parsePomAttribute(pom, "artifactId"));
}
 
Example 20
Source File: AgpOutputConnector.java    From geoportal-server-harvester with Apache License 2.0 2 votes vote down vote up
/**
 * Creates instance of the connector.
 * @param metaAnalyzer meta analyzer
 * @param geometryServiceUrl geometry service URL
 */
public AgpOutputConnector(MetaAnalyzer metaAnalyzer, String geometryServiceUrl) {
  this.metaAnalyzer = metaAnalyzer;
  this.geometryServiceUrl = StringUtils.defaultIfBlank(geometryServiceUrl, DEFAULT_GEOMETRY_SERVICE);
}