Example usage for org.apache.commons.lang3 StringUtils trimToNull

List of usage examples for org.apache.commons.lang3 StringUtils trimToNull

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils trimToNull.

Prototype

public static String trimToNull(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null .

Usage

From source file:hu.bme.mit.sette.run.Run.java

private static String readToolVersion(File versionFile) {
    try {/*w w  w .j  ava 2  s  .  c  o  m*/
        return StringUtils
                .trimToNull(FileUtils.readFileToString(versionFile).replace("\n", "").replace("\r", ""));
    } catch (IOException e) {
        // TODO handle error
        System.err.println("Cannot read tool version from: " + versionFile);
        return null;
    }
}

From source file:com.neocotic.blingaer.link.LinkServiceImpl.java

@Override
public String fetchTitle(String url) throws IllegalArgumentException {
    LOG.trace("Entered method - fetchTitle");

    if (validateUrl(url).hasErrors()) {
        throw new IllegalArgumentException("Invalid URL");
    }//w w  w. java2 s .co m

    String content = null;
    Reader reader = null;

    try {
        reader = new InputStreamReader(new URL(url).openStream());

        content = IOUtils.toString(reader);

        reader.close();
    } catch (Exception e) {
        LOG.debug("Swallowed exception", e);
    } finally {
        IOUtils.closeQuietly(reader);
    }

    // Use URL if content could not be retrieved
    if (content == null) {
        return url;
    }

    // Attempts to extract charset declared in the HTML
    String charSet = null;
    Matcher matcher = Pattern.compile("/<meta[^>]*?charset=([^>]*?)\\/?>/is").matcher(content);

    while (matcher.find()) {
        charSet = StringUtils.trimToNull(matcher.group());
        break;
    }

    // Attempts to extract title declared in the HTML
    String title = null;
    matcher = Pattern.compile("/<title>(.*?)<\\/title>/is").matcher(content);

    while (matcher.find()) {
        title = StringUtils.trimToNull(matcher.group());
        break;
    }

    // If title wasn't found uses an error message (if applicable) or URL
    if (title == null) {
        title = (content.indexOf("Error") == 0) ? content : url;
    }

    // Attempts charset conversion to UTF-8
    try {
        if (charSet == null) {
            title = new String(title.getBytes(), "UTF-8");
        } else {
            title = new String(title.getBytes(charSet), "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        LOG.debug("Swallowed exception", e);
    }

    // Removes HTML entities
    title = StringEscapeUtils.unescapeHtml4(title);

    // Removes all tags
    title = title.replaceAll("<(.|\\n)*?>", StringUtils.EMPTY);

    LOG.trace("Exiting method - fetchTitle");

    return title;
}

From source file:com.adobe.acs.commons.mcp.impl.processes.AssetFolderCreator.java

/**
 * Parse a single cell from an Excel row.
 *
 * @param cell the cell to process from the Excel row.
 * @param previousAssetFolderPath the node path of the previous
 * @return the asset folder path to the asset folder represented by {@param cell}
 * @throws IllegalArgumentException//from  w w w  . ja  va2s. c om
 */
private String parseAssetFolderCell(final Cell cell, final String previousAssetFolderPath)
        throws IllegalArgumentException {
    final String cellValue = StringUtils.trimToNull(cell.getStringCellValue());

    if (StringUtils.isNotBlank(cellValue)) {

        // Generate a asset folder definition that will in turn be used to drive the asset folder definition creation
        AssetFolderDefinition assetFolderDefinition = getAssetFolderDefinition(primary, cellValue,
                previousAssetFolderPath);

        // Try using the fallback converter if the primary convert could not resolve to a valid definition.
        if (assetFolderDefinition == null) {
            assetFolderDefinition = getAssetFolderDefinition(fallback, cellValue, previousAssetFolderPath);
        }

        if (assetFolderDefinition == null) {
            log.warn("Could not find a Asset Folder Converter that accepts value [ {} ]; skipping...",
                    cellValue);
            // Record parse failure
            record(ReportRowStatus.FAILED_TO_PARSE, "", cellValue);
            throw new IllegalArgumentException(String.format(
                    "Unable to parse value [ %s ]. Skipping rest of row to prevent undesired structured from being created.",
                    cellValue));
        } else {
            /* Prepare for next Cell */
            if (assetFolderDefinitions.get(assetFolderDefinition.getId()) == null) {
                assetFolderDefinitions.put(assetFolderDefinition.getId(), assetFolderDefinition);
            }

            return assetFolderDefinition.getPath();
        }
    } else {
        // If cell is blank then treat as it it is empty.
        return previousAssetFolderPath;
    }
}

From source file:com.omertron.slackbot.listeners.GoogleSheetsListener.java

@Override
public void onEvent(SlackMessagePosted event, SlackSession session) {
    // Channel On Which Message Was Posted
    SlackChannel msgChannel = event.getChannel();
    if (!authenticate(session, msgChannel, event.getSender())) {
        return;// w  w w  . j a  v  a  2  s. co  m
    }

    Matcher m = PAT_SHEETS.matcher(event.getMessageContent());
    if (m.matches()) {
        String command = StringUtils.trimToNull(m.group(1)) == null ? "HELP" : m.group(1).toUpperCase().trim();
        String params = StringUtils.trimToNull(m.group(2));
        LOG.info("Command '{}' & params '{}'", command, params);

        // Do an initial read of the sheet information
        if (sheetInfo == null) {
            readSheetInfo();
        }

        switch (command) {
        case "HELP":
            session.sendMessage(msgChannel, "", helpMessage);
            break;
        case "NEXT":
            botUpdateChannel(session, event, E_GAME_DIE);
            readSheetInfo();
            session.sendMessage(msgChannel, "", createGameInfo(sheetInfo));
            break;
        case "ADD":
            addNameToNextGame(session, msgChannel, params, event.getSender());
            break;
        case "REMOVE":
            removeNameFromNextGame(session, msgChannel, params, event.getSender());
            break;
        case "GAME":
            updateGameName(session, msgChannel, params);
            break;
        case "WINNER":
            updateGenericPlayer(session, msgChannel, RANGE_GAME_WINNERS, params, "winner", true);
            break;
        case "OWNER":
            updateGenericPlayer(session, msgChannel, RANGE_GAME_OWNER, params, "owner", false);
            break;
        case "CHOOSER":
            updateGenericPlayer(session, msgChannel, RANGE_GAME_CHOOSER, params, "chooser", false);
            break;
        case "NIGHT":
            createGameNightMessage(session, msgChannel);
            break;
        default:
            session.sendMessage(msgChannel, "Sorry, '" + command + "' is not implemented yet.");
        }
    }
}

From source file:alfio.extension.ExtensionService.java

private void deleteAndInsertSetting(String level, String path, List<ExtensionMetadataValue> toUpdate) {
    extensionRepository.deleteSettingValue(level, path);
    List<ExtensionMetadataValue> toUpdate2 = (toUpdate == null ? Collections.emptyList() : toUpdate);
    List<ExtensionMetadataValue> filtered = toUpdate2.stream()
            .filter(f -> StringUtils.trimToNull(f.getValue()) != null).collect(Collectors.toList());
    for (ExtensionMetadataValue v : filtered) {
        extensionRepository.insertSettingValue(v.getId(), path, v.getValue());
    }//w  w  w .j ava 2  s  .c  o  m
}

From source file:hoot.services.models.osm.Relation.java

/**
 * Returns an XML representation of the element; does not add tags
 *
 * @param parent//from  w w  w.j  a  v  a  2s  . c  o m
 *          XML node this element should be attached under
 * @param modifyingUserId
 *          ID of the user which created this element
 * @param modifyingUserDisplayName
 *          user display name of the user which created this element
 * @param multiLayerUniqueElementIds
 *          if true, ID's are prepended with <map id>_<first letter of the
 *          element type>_; this setting activated is not compatible with
 *          standard OSM clients (specific to Hootenanny iD)
 * @param addChildren
 *          if true, element children are added to the element xml
 * @return an XML element
 * @throws Exception
 */
public org.w3c.dom.Element toXml(final org.w3c.dom.Element parentXml, final long modifyingUserId,
        final String modifyingUserDisplayName, final boolean multiLayerUniqueElementIds,
        final boolean addChildren) throws Exception {
    org.w3c.dom.Element element = super.toXml(parentXml, modifyingUserId, modifyingUserDisplayName,
            multiLayerUniqueElementIds, addChildren);
    Document doc = parentXml.getOwnerDocument();

    if (addChildren) {
        final List<CurrentRelationMembers> members = getMembers();
        // output in sequence order; query returns list in the proper order
        for (CurrentRelationMembers member : members) {
            org.w3c.dom.Element memberElement = doc.createElement("member");
            memberElement.setAttribute("type", member.getMemberType().toString().toLowerCase());
            assert (StringUtils.trimToNull(memberElement.getAttribute("type")) != null);
            String role = member.getMemberRole();
            if (StringUtils.isEmpty(member.getMemberRole())) {
                memberElement.setAttribute("role", member.getMemberRole());
                role = "";
            }
            memberElement.setAttribute("role", role);
            assert (memberElement.getAttribute("role") != null);
            memberElement.setAttribute("ref", String.valueOf(member.getMemberId()));
            assert (StringUtils.trimToNull(memberElement.getAttribute("ref")) != null);
            element.appendChild(memberElement);
        }
    }

    org.w3c.dom.Element elementWithTags = addTagsXml(element);
    if (elementWithTags == null) {
        return element;
    } else {
        return elementWithTags;
    }
}

From source file:com.thruzero.common.core.infonode.builder.TokenStreamInfoNodeBuilder.java

protected InfoNodeElement initLeafNode(final String tokenStream, final String separator,
        final InfoNodeElement targetNode) {
    // TODO-p1(george) Rewrite this using RegEx
    String attributeStream = StringUtils.substringBetween(tokenStream, "[@", "]");
    String elementName;//from   ww  w  . j  a  va 2s . c  o m
    String elementValue;

    // handle the attributes
    if (StringUtils.isEmpty(attributeStream)) {
        elementName = StringUtils.trimToNull(StringUtils.substringBefore(tokenStream, "="));
        elementValue = StringUtils.trimToNull(StringUtils.substringAfter(tokenStream, "="));
    } else {
        StringTokenizer st1 = new StringTokenizer(attributeStream, separator);

        while (st1.hasMoreTokens()) {
            String attributeSpec = st1.nextToken();
            StringTokenizer st2 = new StringTokenizer(attributeSpec, "=");

            if (!st2.hasMoreTokens()) {
                throw new TokenStreamException(
                        "Malformed Token Stream (missing attribute name and value): " + tokenStream);
            }
            String attributeName = StringUtils.removeStart(st2.nextToken().trim(), "@");

            String attributeValue = null;
            if (st2.hasMoreTokens()) {
                attributeValue = trimQuotes(st2.nextToken().trim());
            }

            if (StringUtils.isEmpty(attributeValue)) {
                throw new TokenStreamException(
                        "Malformed Token Stream (missing attribute value): " + tokenStream);
            }

            targetNode.setAttribute(attributeName, attributeValue);
        }

        elementName = StringUtils.trimToNull(StringUtils.substringBefore(tokenStream, "["));
        elementValue = StringUtils.trimToNull(StringUtils.substringAfter(tokenStream, "]"));
    }

    // set the element name
    if (elementName == null) {
        throw new TokenStreamException("Malformed Token Stream (missing element name): " + tokenStream);
    }
    targetNode.setName(elementName);

    // set the element value
    if (elementValue != null) {
        elementValue = StringUtils.removeStart(elementValue, "=");
        targetNode.setText(elementValue);
    }

    return targetNode;
}

From source file:com.norconex.collector.http.url.impl.TikaLinkExtractor.java

@Override
public void loadFromXML(Reader in) {
    XMLConfiguration xml = ConfigurationUtil.newXMLConfiguration(in);
    setIgnoreNofollow(xml.getBoolean("[@ignoreNofollow]", isIgnoreNofollow()));
    setKeepReferrerData(xml.getBoolean("[@keepReferrerData]", isKeepReferrerData()));
    // Content Types
    ContentType[] cts = ContentType/* w w w.  j  a  va  2  s.  c o  m*/
            .valuesOf(StringUtils.split(StringUtils.trimToNull(xml.getString("contentTypes")), ", "));
    if (!ArrayUtils.isEmpty(cts)) {
        setContentTypes(cts);
    }
}

From source file:com.webbfontaine.valuewebb.gtns.TTGTNSSynchronizer.java

protected void updateTTForSentError(TtGen ttGen, List<String> errorMessages) {
    String errMessage = StringUtils.join(errorMessages.toArray(), '\n');
    errMessage = StringUtils.defaultString(StringUtils.trimToNull(errMessage), "N/A");

    ttGen.setFcvrCurrentSentError(errMessage);

    updateTT(ttGen, ERROR_RESPONSE);/*w  w w  .  ja  v a 2  s. com*/
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Updates item item./*from  w w w  .j  av a 2s.c om*/
 * @param owner user name
 * @param folderId folder id (optional)
 * @param itemId item id
 * @param title title
 * @param description description
 * @param text text
 * @param thumbnailUrl thumbnail URL
 * @param itemType item type (must be a URL type)
 * @param extent extent
 * @param typeKeywords type keywords
 * @param tags tags tags
 * @param token token
 * @return add item response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ItemResponse updateItem(String owner, String folderId, String itemId, String title, String description,
        String text, URL thumbnailUrl, ItemType itemType, Double[] extent, String[] typeKeywords, String[] tags,
        String token) throws IOException, URISyntaxException {
    URIBuilder builder = new URIBuilder(updateItemUri(owner, StringUtils.trimToNull(folderId), itemId));

    HttpPost req = new HttpPost(builder.build());
    HashMap<String, String> params = new HashMap<>();
    params.put("f", "json");
    params.put("title", title);
    params.put("description", description);
    params.put("type", itemType.getTypeName());
    params.put("text", text);
    if (thumbnailUrl != null) {
        params.put("thumbnailurl", thumbnailUrl.toExternalForm());
    }
    if (extent != null && extent.length == 4) {
        params.put("extent",
                Arrays.asList(extent).stream().map(Object::toString).collect(Collectors.joining(",")));
    }
    if (typeKeywords != null) {
        params.put("typeKeywords", Arrays.asList(typeKeywords).stream().collect(Collectors.joining(",")));
    }
    if (tags != null) {
        params.put("tags", Arrays.asList(tags).stream().collect(Collectors.joining(",")));
    }
    params.put("token", token);

    req.setEntity(createEntity(params));

    return execute(req, ItemResponse.class);
}