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:hudson.model.AbstractModelObject.java

/**
 * Checks jndi,environment, hudson environment and system properties for specified key.
 * Property is checked in direct order://from   w w w.  ja  v  a2 s .  c o m
 * <ol>
 * <li>JNDI ({@link InitialContext#lookup(String)})</li>
 * <li>Hudson environment ({@link EnvVars#masterEnvVars})</li>
 * <li>System properties ({@link System#getProperty(String)})</li>
 * </ol>
 * @param key - the name of the configured property.
 * @return the string value of the configured property, or null if there is no property with that key.
 */
protected String getConfiguredHudsonProperty(String key) {
    if (StringUtils.isNotBlank(key)) {
        String resultValue;
        try {
            InitialContext iniCtxt = new InitialContext();
            Context env = (Context) iniCtxt.lookup("java:comp/env");
            resultValue = StringUtils.trimToNull((String) env.lookup(key));
            if (null != resultValue) {
                return resultValue;
            }
            // look at one more place. See http://issues.hudson-ci.org/browse/HUDSON-1314
            resultValue = StringUtils.trimToNull((String) iniCtxt.lookup(key));
            if (null != resultValue) {
                return resultValue;
            }
        } catch (NamingException e) {
            // ignore
        }

        // look at the env var next
        resultValue = StringUtils.trimToNull(EnvVars.masterEnvVars.get(key));
        if (null != resultValue) {
            return resultValue;
        }

        // finally check the system property
        resultValue = StringUtils.trimToNull(System.getProperty(key));
        if (null != resultValue) {
            return resultValue;
        }
    }
    return null;
}

From source file:com.monarchapis.driver.servlet.ApiRequest.java

/**
 * Returns the true client IP address. If the request went through a reverse
 * proxy, then the X-Forwarded-For header is used to determine the client IP
 * address. Otherwise, the remote address of the request is used.
 * /*from w w  w .  j av  a  2  s  .c om*/
 * @return The IP address as a string.
 */
public String getIpAddress() {
    String ipAddress = StringUtils.trimToNull(getHeader("X-Forwarded-For"));

    // If there is an X-Forwarded-For header, pull the first IP in the comma
    // separated list.
    return (ipAddress != null) ? StringUtils.split(ipAddress, ',')[0].trim() : getRemoteAddr();
}

From source file:hoot.services.writers.review.ReviewPrepareDbWriter2.java

@Override
protected boolean parseElementUniqueIdTags(final long mapId) throws Exception {
    final String logMsgStart = "Parsing element unique ID tags for map with ID: " + mapId + ".  Step 2 of 4.";
    log.info(logMsgStart);//from  ww w  .  j ava 2 s.  co  m

    uniqueIdsParsed = 0;
    idMappingRecordWritten = false;
    List<ElementIdMappings> elementIdMappingRecordsToInsert = new ArrayList<ElementIdMappings>();
    //create this outside of the batch read loop, since we need to maintain a list of unique
    //ID's parsed over the entire map's set of reviewable records
    Set<String> elementIds = new HashSet<String>();

    for (ElementType elementType : ElementType.values()) {
        if (!elementType.equals(ElementType.Changeset)) {
            //final Element prototype = ElementFactory.getInstance().create(elementType, conn);

            int numElementsReturned = Integer.MAX_VALUE;
            int elementIndex = 0;
            while (numElementsReturned > 0) {
                //get all reviewable elements
                final Map<Long, Object> reviewableElementRecords = getParseableElementRecords(mapId,
                        elementType, maxRecordSelectSize, elementIndex);
                numElementsReturned = reviewableElementRecords.size();
                elementIndex += numElementsReturned;
                for (Map.Entry<Long, Object> reviewableElementRecordEntry : reviewableElementRecords
                        .entrySet()) {
                    final long osmElementId = reviewableElementRecordEntry.getKey();
                    final Object reviewableElementRecord = reviewableElementRecordEntry.getValue();
                    final Map<String, String> tags = PostgresUtils.postgresObjToHStore((PGobject) MethodUtils
                            .invokeMethod(reviewableElementRecord, "getTags", new Object[] {}));
                    final String uniqueElementIdStr = StringUtils.trimToNull(tags.get("uuid"));
                    if (uniqueElementIdStr == null) {
                        log.warn("Invalid UUID: " + uniqueElementIdStr + " for map with ID: " + mapId
                                + ".  Skipping adding unique ID record...");
                    } else {
                        //In the case of the fuzzy match conflict example, this ID may be made up of multiple
                        //parts.  Treat each ID part separately.  TODO: add test for this case
                        String[] uniqueElementIds = null;
                        if (uniqueElementIdStr.contains(";")) {
                            log.debug("Multiple part UUID...");
                            uniqueElementIds = uniqueElementIdStr.split(";");
                        } else {
                            uniqueElementIds = new String[1];
                            uniqueElementIds[0] = uniqueElementIdStr;
                        }

                        for (String uniqueElementId : uniqueElementIds) {
                            //TODO: make this a batch query somehow
                            if (new SQLQuery(conn, DbUtils.getConfiguration(mapId)).from(elementIdMappings)
                                    .where(elementIdMappings.mapId.eq(mapId)
                                            .and(elementIdMappings.elementId.eq(uniqueElementId)))
                                    .count() > 0) {
                                log.warn("UUID: " + uniqueElementId + " for map with ID: " + mapId
                                        + " already exists.  " + "Skipping adding unique ID record...");
                            } else {
                                if (elementIds.add(uniqueElementId)) //don't add duplicates
                                {
                                    log.debug("Adding UUID: " + uniqueElementId);
                                    elementIdMappingRecordsToInsert.add(createElementIdMappingRecord(
                                            uniqueElementId, osmElementId, elementType, mapId));
                                    flushIdMappingRecords(elementIdMappingRecordsToInsert, maxRecordBatchSize,
                                            logMsgStart);
                                } else {
                                    log.warn("Duplicate element ID: " + uniqueElementId.toString()
                                            + " for map with ID: " + mapId
                                            + ".  Skipping adding unique ID record...");
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    //final flush
    flushIdMappingRecords(elementIdMappingRecordsToInsert, 0, logMsgStart);

    log.debug("Wrote " + elementIds.size() + " ID mappings.");

    return idMappingRecordWritten;
}

From source file:gtu.youtube.JavaYoutubeDownloader.java

public static void mainRun(String videoId, String realUrl, String outputDir) {
    try {//w  w w.j ava 2 s  . co m
        JavaYoutubeDownloader t = new JavaYoutubeDownloader();
        String[] args = t.makeFakeArgs(videoId, outputDir);
        t.customDownloadUrl_by_gtu001 = StringUtils.trimToNull(realUrl);
        t.run(args);
        System.out.println("done...");
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:com.webbfontaine.valuewebb.utils.TTMailUtils.java

public List<String> getMailRecepientsForResponseOk() {

    List<String> emails = new ArrayList<>();

    if (ApplicationProperties.isImporterMailingEnabled()) {
        Company company = loadCompany();
        if (company != null) {
            String email = company.getEmail();
            if (!StringUtils.isEmpty(email)) {
                emails.add(email);//ww w.  j av  a2  s.  co  m
            }
        }
    }

    if (ApplicationProperties.isApplicantMailingEnabled()) {
        if (!StringUtils.isEmpty(ttGen.getAppEmail())) {
            emails.add(ttGen.getAppEmail());
        }
    }

    if (StringUtils.trimToNull(ApplicationProperties.getAdditionalMailingList()) != null) {
        String[] additionalEmails = RECIPIENT_PATTERN.split(ApplicationProperties.getAdditionalMailingList());
        emails.addAll(Arrays.asList(additionalEmails));
    }

    return emails;
}

From source file:com.epam.catgenome.controller.ExceptionHandlerAdvice.java

@ResponseBody
@Order(Ordered.HIGHEST_PRECEDENCE)/* w w w  .  jav  a 2  s  . com*/
@ExceptionHandler(Throwable.class)
public final ResponseEntity<Result<String>> handleUncaughtException(final Throwable exception,
        final WebRequest request) {
    // adds information about encountered error to application log
    LOG.error(MessageHelper.getMessage("logger.error", request.getDescription(true)), exception);
    HttpStatus code = HttpStatus.OK;

    String message;
    if (exception instanceof FileNotFoundException) {
        // any details about real path of a resource should be normally prevented to send to the client
        message = MessageHelper.getMessage("error.io.not.found");
    } else if (exception instanceof DataAccessException) {
        // any details about data access error should be normally prevented to send to the client,
        // as its message can contain information about failed SQL query or/and database schema
        if (exception instanceof BadSqlGrammarException) {
            // for convenience we need to provide detailed information about occurred BadSqlGrammarException,
            // but it can be retrieved
            SQLException root = ((BadSqlGrammarException) exception).getSQLException();
            if (root.getNextException() != null) {
                LOG.error(MessageHelper.getMessage("logger.error.root.cause", request.getDescription(true)),
                        root.getNextException());
            }
            message = MessageHelper.getMessage("error.sql.bad.grammar");
        } else {
            message = MessageHelper.getMessage("error.sql");
        }
    } else if (exception instanceof UnauthorizedClientException) {
        message = exception.getMessage();
        code = HttpStatus.UNAUTHORIZED;
    } else {
        message = exception.getMessage();
    }

    return new ResponseEntity<>(Result.error(StringUtils.defaultString(StringUtils.trimToNull(message),
            MessageHelper.getMessage("error" + ".default"))), code);
}

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

/**
 * Adds item./*  w  w  w.  j  a  v a  2 s.co  m*/
 * @param owner owner
 * @param folderId folder id (optional)
 * @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 addItem(String owner, String folderId, 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(addItemUri(owner, StringUtils.trimToNull(folderId)));

    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);
}

From source file:com.blackducksoftware.integration.hub.bamboo.tasks.HubScanTaskConfigurator.java

private void checkBomWaitTime(final String bomWaitTime, final ErrorCollection errorCollection) {
    if (StringUtils.isBlank(bomWaitTime)) {
        return;//from w  w w .ja  v  a2s.  co  m
    }
    int bomWaitTimeInt = 0;
    try {
        final String integerString = StringUtils.trimToNull(bomWaitTime);
        if (integerString != null) {
            try {
                bomWaitTimeInt = Integer.valueOf(integerString);
            } catch (final NumberFormatException e) {
                errorCollection.addError(HubScanConfigFieldEnum.MAX_WAIT_TIME_FOR_BOM_UPDATE.getKey(),
                        "The String : " + bomWaitTime + " , is not an Integer.");
                return;
            }
        } else {
            errorCollection.addError(HubScanConfigFieldEnum.MAX_WAIT_TIME_FOR_BOM_UPDATE.getKey(),
                    "The String : " + bomWaitTime + " , is not an Integer.");
        }
    } catch (final IllegalArgumentException e) {
        errorCollection.addError(HubScanConfigFieldEnum.MAX_WAIT_TIME_FOR_BOM_UPDATE.getKey(), e.getMessage());
        return;
    }
    if (bomWaitTimeInt <= 0) {
        errorCollection.addError(HubScanConfigFieldEnum.MAX_WAIT_TIME_FOR_BOM_UPDATE.getKey(),
                "The maximum wait time for the BOM Update must be greater than 0.");
    }
}

From source file:de.micromata.tpsb.doc.parser.JavaDocUtil.java

/**
 * Extrahiert alle Tags aus dem JavaDoc/*from  w  w w .  j  a  va 2 s .c o m*/
 * 
 * @param cleanedContent bereinigter Inhalt
 * @return Tupel Tagname auf Liste von Key-Value Paaren
 */
private static Map<String, List<Pair<String, String>>> extractTags(String cleanedContent) {
    Map<String, List<Pair<String, String>>> tagMap = new HashMap<String, List<Pair<String, String>>>();
    String[] lines = StringUtils.split(cleanedContent, LINE_FEED);
    if (lines == null) {
        return tagMap;
    }
    // Tag-Bereich aus Javadoc extrahieren
    List<String> tagContent = new ArrayList<String>();
    boolean found = false;
    for (String line : lines) {
        String trimmedLine = line.trim();
        if (trimmedLine.startsWith("@") == false && found == false) {
            continue;
        }
        tagContent.add(trimmedLine);
        found = true;
    }

    for (int i = 0; i < tagContent.size();) {
        String tag = tagContent.get(i++);
        if (StringUtils.trimToNull(tag) == null) {
            continue;
        }
        // Prfen ob nchste Zeile noch zum aktuellen Tag gehrt
        for (int j = i; j < tagContent.size(); j++) {
            i = j;
            String t = tagContent.get(j);
            if (t.startsWith("@") == false && StringUtils.isNotBlank(t) == true) {
                tag += " " + t;
            } else {
                break;
            }
        }
        parseTag(tag, tagMap);
    }
    return tagMap;
}

From source file:hu.bme.mit.sette.common.model.snippet.SnippetProjectSettings.java

/**
 * Creates an instance of the object./*w w  w .java  2 s. c  om*/
 *
 * @param pBaseDirectory
 *            The base directory.
 * @throws ValidatorException
 *             if validation has failed
 */
public SnippetProjectSettings(final File pBaseDirectory) throws ValidatorException {
    Validate.notNull(pBaseDirectory, "The base directory must not be null");
    baseDirectory = pBaseDirectory;

    // validate base directory and stop if already error
    new FileValidator(baseDirectory).type(FileType.DIRECTORY).readable(true).executable(true).validate();

    // parse and validate configuration file
    File configurationFile = new File(baseDirectory, CONFIGURATION_FILE_NAME);
    FileValidator vc = new FileValidator(configurationFile);
    vc.type(FileType.REGULAR_FILE).readable(true);
    vc.validate(); // stop if already error

    Properties configuration = new Properties();

    FileInputStream is = null;
    try {
        is = new FileInputStream(configurationFile);
        configuration.load(is);
    } catch (IOException | SecurityException | IllegalArgumentException e) {
        IOUtils.closeQuietly(is);
        vc.addException("Cannot read file contents as Java properties", e);
        vc.validate();// stop if already error
    }

    // read properties
    snippetSourceDirectoryPath = StringUtils.trimToNull(configuration.getProperty("snippet-src"));
    snippetBinaryDirectoryPath = StringUtils.trimToNull(configuration.getProperty("snippet-bin"));
    inputSourceDirectoryPath = StringUtils.trimToNull(configuration.getProperty("input-src"));
    inputBinaryDirectoryPath = StringUtils.trimToNull(configuration.getProperty("input-bin"));
    libraryDirectoryPath = StringUtils.trimToNull(configuration.getProperty("snippet-libs"));

    // validate properties and save File objects
    if (snippetSourceDirectoryPath == null) {
        vc.addException("The \"snippet-src\" property must exist and must not be blank");
        // set only to enable further validation regardless this error
        snippetSourceDirectory = null;
    } else {
        snippetSourceDirectory = new File(baseDirectory, snippetSourceDirectoryPath);
    }

    if (snippetBinaryDirectoryPath == null) {
        vc.addException("The \"snippet-bin\" property must exist and must not be blank");
        // set only to enable further validation regardless this error
        snippetBinaryDirectory = null;
    } else {
        snippetBinaryDirectory = new File(baseDirectory, snippetBinaryDirectoryPath);
    }

    if (inputSourceDirectoryPath == null && inputBinaryDirectoryPath == null) {
        // no inputs
        inputSourceDirectory = null;
        inputBinaryDirectory = null;
    } else if (inputSourceDirectoryPath != null && inputBinaryDirectoryPath != null) {
        // has inputs
        inputSourceDirectory = new File(baseDirectory, inputSourceDirectoryPath);
        inputBinaryDirectory = new File(baseDirectory, inputBinaryDirectoryPath);
    } else {
        // inconsistent
        vc.addException(
                "Both the \"input-bin\" and \"input-src\" properties must exist and must not be blank or both must be skipped");
        // set only to enable further validation regardless this error
        inputSourceDirectory = null;
        inputBinaryDirectory = null;
    }

    if (libraryDirectoryPath == null) {
        libraryDirectory = null;
    } else {
        libraryDirectory = new File(baseDirectory, libraryDirectoryPath);
    }

    // validate that dirs exists and that they are readable
    File[] directories = new File[] { snippetSourceDirectory, snippetBinaryDirectory, inputSourceDirectory,
            inputBinaryDirectory, libraryDirectory };

    for (File dir : directories) {
        if (dir != null) {
            vc.addChildIfInvalid(
                    new FileValidator(dir).type(FileType.DIRECTORY).readable(true).executable(true));
        }
    }

    // final validation check
    vc.validate();
}