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

The following are Jave code examples for showing how to use defaultString() of the org.apache.commons.lang3.StringUtils 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: xDoc   File: ParamTagConverter.java   View Source Code Vote up 6 votes
@Override
public DocTag converter(ParamTag o) {

    //解析 "@param user :username 用户名|必填" 这种注释
    boolean require = false;
    String paramDesc = o.parameterComment();
    if (paramDesc.contains("|")) {
        int endIndex = paramDesc.lastIndexOf("|必填");
        require = endIndex > 0;
        if (require) {
            paramDesc = paramDesc.substring(0, endIndex);
        }
    }

    String paramName = StringUtils.defaultString(o.parameterName());
    if (paramDesc.startsWith(":")) {
        int index = paramDesc.indexOf(" ");
        if (index > 0) {
            paramName = paramDesc.substring(1, index);
            paramDesc = paramDesc.substring(index + 1);
        }
    }
    return new ParamTagImpl(o.name(), paramName, paramDesc, require);
}
 
Example 2
Project: OperatieBRP   File: AfnemerindicatieConversie.java   View Source Code Vote up 6 votes
private void converteerAfnemerindicatiebestand(final long maxAfnemerindicatieId,
                                               final OutputStream os, final LineIterator it) throws IOException {
    long voortgang = 0;
    final Map<Short, Short> partijConversieMap = partijConversie.getPartijConversieMap();
    final Map<Integer, Integer> leveringsautorisatieConversieMap = leveringsautorisatieConversie.getLeveringsautorisatieConversieMap();
    while (it.hasNext()) {
        final String line = it.nextLine();
        final String[] splitLine = StringUtils.split(line, ",");
        final long origId = Long.parseLong(splitLine[0]);
        final long id = maxAfnemerindicatieId + origId;
        final String pers = splitLine[1];
        final String afnemer = String.valueOf(partijConversieMap.get(Short.parseShort(splitLine[2])));
        final String levsautorisatie = String.valueOf(leveringsautorisatieConversieMap.get(Integer.parseInt(splitLine[3])));
        final String dataanvmaterieleperiode = StringUtils.defaultString(StringUtils.trimToNull(splitLine[4]), NULL_VALUE);
        final String dateindevolgen = StringUtils.defaultString(StringUtils.trimToNull(splitLine[5]), NULL_VALUE);
        final String indag = splitLine[6];
        final String newLine = String.format("%s,%s,%s,%s,%s,%s,%s%n", id, pers, afnemer, levsautorisatie,
                dataanvmaterieleperiode, dateindevolgen, indag);
        IOUtils.write(newLine, os, StandardCharsets.UTF_8);

        voortgang++;
        if (voortgang % LOG_TRESHOLD == 0) {
            LOGGER.info("Voortgang persafnemerindicatie {}", voortgang);
        }
    }
}
 
Example 3
Project: NGB-master   File: ReferenceManager.java   View Source Code Vote up 6 votes
/**
 * Validates and parses the given to make sure that all mandatory properties,
 * describing genome data, are provided.
 * <p>
 * The default values will be assigned in cases when it is possible to do. E.g., to treat omitted
 * custom name for a genome it's possible to use an original name of corresponded file without
 * extension.
 *
 * @param path {@code File}     Path to fasta file
 * @param name {@code String}   Alternative name
 */
private String parse(final String path, final String name) {
    Assert.notNull(path, getMessage(MessageCode.RESOURCE_NOT_FOUND));
    // checks that an original file name is provided, because it is used as a name
    // for a genome if custom name isn't specified
    String fileName = StringUtils.trimToNull(FilenameUtils.getName(path));
    Assert.notNull(fileName, getMessage(MessageCode.MANDATORY_FILE_NAME));
    // checks that file is in one of supported formats
    boolean supported = false;
    final Collection<String> formats = FastaUtils.getFastaExtensions();
    for (final String ext : formats) {
        if (fileName.endsWith(ext)) {
            supported = true;
            fileName = Utils.removeFileExtension(fileName, ext);
            break;
        }
    }
    if (!supported) {
        throw new IllegalArgumentException(getMessage("error.reference.illegal.file.type",
                StringUtils.join(formats, ", ")));
    }
    // if no custom name is provided for a genome, then a file name without extension should be
    // used by default
    return StringUtils.defaultString(StringUtils.trimToNull(name), fileName);
}
 
Example 4
Project: util   File: ExceptionUtil.java   View Source Code Vote up 6 votes
/**
 * 拼装 短异常类名: 异常信息 <-- RootCause的短异常类名: 异常信息
 */
public static String toStringWithRootCause(@Nullable Throwable t) {
	if (t == null) {
		return StringUtils.EMPTY;
	}

	final String clsName = ClassUtils.getShortClassName(t, null);
	final String message = StringUtils.defaultString(t.getMessage());
	Throwable cause = getRootCause(t);

	StringBuilder sb = new StringBuilder(128).append(clsName).append(": ").append(message);
	if (cause != t) {
		sb.append("; <---").append(toStringWithShortName(cause));
	}

	return sb.toString();
}
 
Example 5
Project: ProjectAltaria   File: XKCDComic.java   View Source Code Vote up 5 votes
public void setImageLink(String imageLink) {
    imageLink = StringUtils.defaultString(imageLink, "");
    if (imageLink.endsWith(".png")) {
        try {
            String biggerImage = imageLink.replace(".png", "_2x.png");
            Request request = new Request.Builder()
                    .url(biggerImage)
                    .head()
                    .build();

            Response response = HttpManager.getInstance().getDefaultClient()
                                           .newBuilder()
                                           .followRedirects(false)
                                           .followSslRedirects(false)
                                           .build()
                                           .newCall(request)
                                           .execute();

            if (response.code() < 300) {
                this.imageLink = biggerImage;
            } else {
                this.imageLink = imageLink;
            }
        } catch (Exception e) {
            //Ok to throw exception
            LogManager.getLogger(App.class).trace(e);
            this.imageLink = imageLink;
        }
    } else {
        this.imageLink = imageLink;
    }
}
 
Example 6
Project: mensa-api   File: MenuWeekScraper.java   View Source Code Vote up 5 votes
private Stream<Dish> getDishesFromRow(Element row, int rowIndex, LocalDate baseDate, String mensaId) {
	Elements categoryCell = row.select("th");
	Elements dishCells = row.select("td");
	if (!categoryCell.isEmpty() && dishCells.size() == 5) {
		String category = StringUtils.defaultString(categoryCell.get(0).text());
		AtomicInteger dayIndex = new AtomicInteger(0);
		return dishCells.stream().flatMap(cell -> getDishesFromCell(cell, category, rowIndex, baseDate.plusDays(dayIndex.getAndIncrement()), mensaId));
	}
	return Stream.empty();
}
 
Example 7
Project: mensa-api   File: SingleDayScraper.java   View Source Code Vote up 5 votes
@Override
Stream<LocalDate> getBaseDate(Element element) {
    Stream<LocalDate> result = Stream.empty();
    String text = StringUtils.defaultString(element.text());
    try {
        result = Stream.of(LocalDate.parse(text, formatter));
    } catch (DateTimeParseException e) {
        log.warn("Failed to parse base date from string: {}", text);
    }
    return result;

}
 
Example 8
Project: plugin-km-confluence   File: ConfluencePluginResource.java   View Source Code Vote up 5 votes
/**
 * Find the spaces matching to the given criteria. Look into space key, and
 * space name.
 * 
 * @param parameters
 *            the node parameters.
 * @param criteria
 *            the search criteria.
 * @param start
 *            the cursor position.
 * @return <code>true</code> when there are more spaces to fetch.
 */
private boolean addAllByName(final Map<String, String> parameters, final String criteria, final List<Space> result, final int start)
		throws IOException {
	// The result should be JSON, otherwise, an empty result is mocked
	final String spacesAsJson = StringUtils.defaultString(
			getConfluenceResource(parameters, "/rest/api/space?type=global&limit=100&start=" + start),
			"{\"results\":[],\"_links\":{}}");

	// Build the result from JSON
	final TypeReference<Map<String, Object>> typeReference = new TypeReference<Map<String, Object>>() {
		// Nothing to override
	};
	final Map<String, Object> readValue = objectMapper.readValue(spacesAsJson, typeReference);
	@SuppressWarnings("unchecked")
	final Collection<Map<String, Object>> spaces = (Collection<Map<String, Object>>) readValue.get("results");

	// Prepare the context, an ordered set of projects
	final Format format = new NormalizeFormat();
	final String formatCriteria = format.format(criteria);

	// Get the projects and parse them
	for (final Map<String, Object> spaceRaw : spaces) {
		final Space space = toSpaceLight(spaceRaw);

		// Check the values of this project
		if (format.format(space.getName()).contains(formatCriteria) || format.format(space.getId()).contains(formatCriteria)) {
			result.add(space);
		}
	}
	return ((Map<?, ?>) readValue.get("_links")).containsKey("next");
}
 
Example 9
Project: microservice   File: ModelController.java   View Source Code Vote up 5 votes
/**
 * 创建模型
 */
@RequestMapping(value = "create", method = RequestMethod.POST)
public void create(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description,
                   HttpServletRequest request, HttpServletResponse response) {
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        ObjectNode editorNode = objectMapper.createObjectNode();
        editorNode.put("id", "canvas");
        editorNode.put("resourceId", "canvas");
        ObjectNode stencilSetNode = objectMapper.createObjectNode();
        stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
        editorNode.put("stencilset", stencilSetNode);
        Model modelData = repositoryService.newModel();

        ObjectNode modelObjectNode = objectMapper.createObjectNode();
        modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        description = StringUtils.defaultString(description);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
        modelData.setMetaInfo(modelObjectNode.toString());
        modelData.setName(name);
        modelData.setKey(StringUtils.defaultString(key));

        repositoryService.saveModel(modelData);
        repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));

        response.sendRedirect(request.getContextPath() + "/modeler.html?modelId=" + modelData.getId());
    } catch (Exception e) {
        logger.error("创建模型失败:", e);
    }
}
 
Example 10
Project: smarti   File: PropertyInjectionTransformer.java   View Source Code Vote up 5 votes
protected Resource transformText(String fileName, Resource resource) throws IOException {
    if (injectableTextFiles.stream()
            .noneMatch(p -> pathMatcher.match(p, fileName))) {
        log.trace("{} not in injectable-files, skipping", fileName);
        return resource;
    } else {
        log.trace("transforming {}", fileName);
    }

    final byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
    final String content = new String(bytes, DEFAULT_CHARSET);
    final StringBuffer transformed = new StringBuffer();

    final Matcher m = TEXT_REPLACE_PATTERN.matcher(content);
    while (m.find()) {
        final String match = m.group(),
                key = m.group(1),
                fallback = StringUtils.defaultString(m.group(2), match);
        if (log.isTraceEnabled()) {
            final String replace = environment.getProperty(key);
            if (replace == null) {
                if (m.group(2) == null) {
                    log.trace("{} -> '{}' (property not found, no fallback)", match, fallback);
                } else {
                    log.trace("{} -> '{}' (fallback)", match, fallback);
                }
            } else {
                log.trace("{} -> '{}' (env '{}')", match, replace, key);
            }
        }
        m.appendReplacement(transformed, Matcher.quoteReplacement(environment.getProperty(key, fallback)));
    }
    m.appendTail(transformed);

    return new TransformedResource(resource, transformed.toString().getBytes(DEFAULT_CHARSET));
}
 
Example 11
Project: smarti   File: AuthTokenService.java   View Source Code Vote up 5 votes
public AuthToken createAuthToken(ObjectId clientId, String label) {
    label = StringUtils.defaultString(label, "new-token");

    final AuthToken authToken = authTokenRepository.save(new AuthToken(clientId).setLabel(label));
    authToken.setSecret(RandomUtils.nextString(8));
    return authTokenRepository.save(authToken);
}
 
Example 12
Project: NGB-master   File: WigManager.java   View Source Code Vote up 5 votes
protected String parseName(final String fileName, final String alternativeName) {
    boolean supported = false;
    for (final String ext : WIG_EXTENSIONS) {
        if (fileName.endsWith(ext)) {
            supported = true;
            break;
        }
    }
    if (!supported) {
        throw new IllegalArgumentException(getMessage("error.illegal.file.type",
                                                      StringUtils.join(WIG_EXTENSIONS, ", ")));
    }
    return StringUtils.defaultString(StringUtils.trimToNull(alternativeName), fileName);
}
 
Example 13
Project: plugin-prov-aws   File: ProvAwsPriceImportResource.java   View Source Code Vote up 5 votes
/**
 * Install AWS prices from the JSON file.
 * 
 * @param node
 *            The related AWS {@link Node}
 * @param regions
 *            The available regions.
 * @param api
 *            The API name, only for log.
 * @param endpoint
 *            The prices end-point JSON URL.
 * @param apiClass
 *            The mapping model from JSON at region level.
 * @param mapper
 *            The mapping function from JSON at region level to JPA entity.
 */
private <R extends AwsRegionPrices, T extends AwsPrices<R>> void installPrices(final Node node, final Map<String, ProvLocation> regions,
		final String api, final String endpoint, final Class<T> apiClass, final BiFunction<R, ProvLocation, Integer> mapper)
		throws IOException {
	log.info("AWS {} prices...", api);

	// Track the created instance to cache instance and price type
	int priceCounter = 0;
	importCatalogResource.nextStep(node.getId(), t -> t.setPhase(api));

	try {
		// Get the remote prices stream
		String rawJson = StringUtils.defaultString(new CurlProcessor().get(endpoint), "callback({\"config\":{\"regions\":[]}});");

		// All regions are considered
		final int configIndex = rawJson.indexOf('{');
		final int configCloseIndex = rawJson.lastIndexOf('}');
		final T prices = objectMapper.readValue(rawJson.substring(configIndex, configCloseIndex + 1), apiClass);

		// Install the region as needed
		prices.getConfig().getRegions().forEach(r -> r
				.setRegion(installRegion(regions, mapSpotToNewRegion.getOrDefault(r.getRegion(), r.getRegion()), node).getName()));
		nextStep(node, null, 0);

		// Install the (EC2 + Spot) prices for each region
		priceCounter = prices.getConfig().getRegions().stream().mapToInt(r -> mapper.apply(r, regions.get(r.getRegion()))).sum();
	} finally {
		// Report
		log.info("AWS {} import finished : {} prices", api, priceCounter);
		nextStep(node, null, 1);
	}
}
 
Example 14
Project: careconnect-reference-implementation   File: BaseProvider.java   View Source Code Vote up 5 votes
public void startRequest(HttpServletRequest theRequest) {
    if (theRequest == null) {
        return;
    }

    Set<String> headerNames = new TreeSet<String>();
    for (Enumeration<String> enums = theRequest.getHeaderNames(); enums.hasMoreElements();) {
        headerNames.add(enums.nextElement());
    }
    ourLog.debug("Request headers: {}", headerNames);

    Enumeration<String> forwardedFors = theRequest.getHeaders("x-forwarded-for");
    StringBuilder b = new StringBuilder();
    for (Enumeration<String> enums = forwardedFors; enums != null && enums.hasMoreElements();) {
        if (b.length() > 0) {
            b.append(" / ");
        }
        b.append(enums.nextElement());
    }

    String forwardedFor = b.toString();
    String ip = theRequest.getRemoteAddr();
    if (StringUtils.isBlank(forwardedFor)) {
        org.slf4j.MDC.put(REMOTE_ADDR, ip);
        ourLog.debug("Request is from address: {}", ip);
    } else {
        org.slf4j.MDC.put(REMOTE_ADDR, forwardedFor);
        ourLog.debug("Request is from forwarded address: {}", forwardedFor);
    }

    String userAgent = StringUtils.defaultString(theRequest.getHeader("user-agent"));
    org.slf4j.MDC.put(REMOTE_UA, userAgent);

}
 
Example 15
Project: cas-5.1.0   File: TokenAuthenticationHandler.java   View Source Code Vote up 4 votes
@Override
protected Authenticator<TokenCredentials> getAuthenticator(final Credential credential) {
    final TokenCredential tokenCredential = (TokenCredential) credential;
    LOGGER.debug("Locating token secret for service [{}]", tokenCredential.getService());

    final RegisteredService service = this.servicesManager.findServiceBy(tokenCredential.getService());
    final String signingSecret = getRegisteredServiceJwtSigningSecret(service);
    final String encryptionSecret = getRegisteredServiceJwtEncryptionSecret(service);

    final String signingSecretAlg =
            StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_SIGNING_ALG),
                    JWSAlgorithm.HS256.getName());

    final String encryptionSecretAlg =
            StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_ENCRYPTION_ALG),
                    JWEAlgorithm.DIR.getName());

    final String encryptionSecretMethod =
            StringUtils.defaultString(getRegisteredServiceJwtSecret(service, TokenConstants.PROPERTY_NAME_TOKEN_SECRET_ENCRYPTION_METHOD),
                    EncryptionMethod.A192CBC_HS384.getName());

    if (StringUtils.isNotBlank(signingSecret)) {
        Set<Algorithm> sets = new HashSet<>();
        sets.addAll(JWSAlgorithm.Family.EC);
        sets.addAll(JWSAlgorithm.Family.HMAC_SHA);
        sets.addAll(JWSAlgorithm.Family.RSA);
        sets.addAll(JWSAlgorithm.Family.SIGNATURE);

        final JWSAlgorithm signingAlg = findAlgorithmFamily(sets, signingSecretAlg);

        final JwtAuthenticator a = new JwtAuthenticator();
        a.setSignatureConfiguration(new SecretSignatureConfiguration(signingSecret, signingAlg));

        if (StringUtils.isNotBlank(encryptionSecret)) {
            sets = new HashSet<>();
            sets.addAll(JWEAlgorithm.Family.AES_GCM_KW);
            sets.addAll(JWEAlgorithm.Family.AES_KW);
            sets.addAll(JWEAlgorithm.Family.ASYMMETRIC);
            sets.addAll(JWEAlgorithm.Family.ECDH_ES);
            sets.addAll(JWEAlgorithm.Family.PBES2);
            sets.addAll(JWEAlgorithm.Family.RSA);
            sets.addAll(JWEAlgorithm.Family.SYMMETRIC);

            final JWEAlgorithm encAlg = findAlgorithmFamily(sets, encryptionSecretAlg);

            sets = new HashSet<>();
            sets.addAll(EncryptionMethod.Family.AES_CBC_HMAC_SHA);
            sets.addAll(EncryptionMethod.Family.AES_GCM);

            final EncryptionMethod encMethod = findAlgorithmFamily(sets, encryptionSecretMethod);
            a.setEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret, encAlg, encMethod));
        } else {
            LOGGER.warn("JWT authentication is configured to share a single key for both signing/encryption");
        }
        return a;
    }
    LOGGER.warn("No token signing secret is defined for service [{}]. Ensure [{}] property is defined for service",
            service.getServiceId(), TokenConstants.PROPERTY_NAME_TOKEN_SECRET_SIGNING);
    return null;
}
 
Example 16
Project: HL7Receiver   File: HomertonPractitionerTransform.java   View Source Code Vote up 4 votes
private Organization calculcatePractitionerRoleOrganisationFromDuplicates(Practitioner practitioner, List<Xcn> sources) throws TransformException {

        // role - collect identifiers to help determine role
        String gmcCode = PractitionerCommon.getIdentifierValue(practitioner.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_GMC_NUMBER);
        String primaryPersonnelId = PractitionerCommon.getIdentifierValue(practitioner.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_HOMERTON_PRIMARY_PRACTITIONER_ID);
        String postcode = sources  // practitioner's organisation postcode is stored as a identifier
                .stream()
                .filter(t -> StringUtils.isNotEmpty(t.getId()))
                .filter(t -> StringUtils.deleteWhitespace(StringUtils.defaultString(t.getIdentifierTypeCode())).equalsIgnoreCase("postcode"))
                .map(t -> StringUtils.trim(StringUtils.defaultString(t.getId())).toUpperCase())
                .collect(StreamExtension.firstOrNullCollector());

        if (StringUtils.isNotEmpty(gmcCode)) {
            // looks like a gp practitioner

            Organization primaryCareProviderOrganisation = targetResources.getResourceSingleOrNull(ResourceTag.MainPrimaryCareProviderOrganisation, Organization.class);
            Practitioner primaryCareProviderPractitioner = targetResources.getResourceSingleOrNull(ResourceTag.MainPrimaryCareProviderPractitioner, Practitioner.class);

            // attempt match on primary care provider practitioner GMC code
            if (primaryCareProviderPractitioner != null) {
                String primaryCarePractitionerGmcCode = PractitionerCommon.getIdentifierValue(primaryCareProviderPractitioner.getIdentifier(), FhirUri.IDENTIFIER_SYSTEM_GMC_NUMBER);

                if (StringUtils.isNotEmpty(primaryCarePractitionerGmcCode))
                    if (gmcCode.equalsIgnoreCase(primaryCarePractitionerGmcCode))
                        return primaryCareProviderOrganisation;
            }

            // attempt match on primary care provider organisation postcode
            if (primaryCareProviderOrganisation != null) {
                String existingPrimaryCareOrganisationPostcode = StringUtils.defaultString(AddressConverter.getPostcode(primaryCareProviderOrganisation.getAddress()));

                if (StringUtils.isNotEmpty(postcode)) {

                    if ((StringUtils.deleteWhitespace(postcode)
                            .equalsIgnoreCase(StringUtils.deleteWhitespace(existingPrimaryCareOrganisationPostcode)))) {

                        return primaryCareProviderOrganisation;

                    }
                }
            }

        } else if (StringUtils.isNotEmpty(primaryPersonnelId)) {

            return this.targetResources.getResourceSingle(ResourceTag.MainHospitalOrganisation, Organization.class);
        }

        // else could not match

        return null;
    }
 
Example 17
Project: history-api-navigation   File: HistoryApiNavigationStateManager.java   View Source Code Vote up 4 votes
public HistoryApiNavigationStateManager(final Page page, final String contextPath)
{
    this.page = page;
    this.contextPath = StringUtils.defaultString(contextPath, "");
}
 
Example 18
Project: patternlab-for-sling   File: PatternLabUtils.java   View Source Code Vote up 4 votes
public static String getResourceTitleOrName(final Resource resource) {
    final String title = resource.getValueMap().get(JCR_TITLE, String.class);
    return StringUtils.defaultString(title, resource.getName());
}
 
Example 19
Project: smarti   File: MongoUserDetailsService.java   View Source Code Vote up 3 votes
@PostConstruct
protected void initialize() {
    // Check for at least one admin-user
    final long adminUsers = mongoTemplate.count(Query.query(Criteria.where(SmartiUser.FIELD_ROLES).is("ADMIN")), SmartiUser.class);
    if (adminUsers < 1) {
        log.debug("No admin-users found, creating");
        String adminUser = "admin";
        int i = 0;
        final String password = StringUtils.defaultString(securityConfigurationProperties.getMongo().getAdminPassword(), UUID.randomUUID().toString());
        final String encodedPassword = passwordEncoder.encodePassword(password);
        while (!createAdminUser(adminUser, encodedPassword)) {
            adminUser = String.format("admin%d", ++i);
        }
        if (StringUtils.isNotBlank(securityConfigurationProperties.getMongo().getAdminPassword())) {
            log.error("Created new Admin-User '{}' with password passed as 'security.config.mongo.admin-password'", adminUser);
        } else {
            log.error("Created new Admin-User '{}' with password '{}'", adminUser, password);
        }
    } else {
        log.debug("Found {} Admin-Users", adminUsers);
    }
}