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:com.eatthepath.gtfs.TransitSystem.java

private void processVehiclePosition(final VehiclePosition vehiclePosition) {
    this.realtimeDataLock.writeLock().lock();

    try {// w w  w . j  a  va2s. c o  m
        final Vehicle vehicle;

        if (vehiclePosition.getVehicle().hasId()) {
            Vehicle previouslyKnownVehicle = this.getVehicleById(vehiclePosition.getVehicle().getId());

            if (previouslyKnownVehicle != null) {
                vehicle = previouslyKnownVehicle;
            } else {
                vehicle = new Vehicle(StringUtils.trimToNull(vehiclePosition.getVehicle().getId()));
            }
        } else {
            vehicle = new Vehicle(null);
        }

        vehicle.setLabel(vehiclePosition.getVehicle().getLabel());
        vehicle.setLicensePlate(vehiclePosition.getVehicle().getLicensePlate());

        if (vehiclePosition.hasPosition()) {
            vehicle.setPosition(new SimpleGeospatialPoint(vehiclePosition.getPosition().getLatitude(),
                    vehiclePosition.getPosition().getLongitude()));

            vehicle.setBearing(
                    vehiclePosition.getPosition().hasBearing() ? vehiclePosition.getPosition().getBearing()
                            : null);
            vehicle.setOdometer(
                    vehiclePosition.getPosition().hasOdometer() ? vehiclePosition.getPosition().getOdometer()
                            : null);
            vehicle.setSpeed(
                    vehiclePosition.getPosition().hasSpeed() ? vehiclePosition.getPosition().getSpeed() : null);
        }

        if (vehiclePosition.hasTrip()) {
            // TODO Deal with frequency-expanded trips
            if (vehiclePosition.getTrip().hasTripId()) {
                vehicle.setTrip(this.getTripById(vehiclePosition.getTrip().getTripId()));
            } else if (vehiclePosition.getTrip().hasRouteId()) {
                vehicle.setRoute(this.getRouteById(vehiclePosition.getTrip().getRouteId()));
            } else {
                vehicle.setTrip(null);
                vehicle.setRoute(null);
            }

            if (vehicle.getTrip() != null) {
                final Trip trip = vehicle.getTrip();

                if (!this.vehiclesByTrip.containsKey(trip)) {
                    this.vehiclesByTrip.put(trip, new ArrayList<Vehicle>());
                }

                this.vehiclesByTrip.get(trip).add(vehicle);
            }

            if (vehicle.getRoute() != null) {
                final Route route = vehicle.getRoute();

                if (!this.vehiclesByRoute.containsKey(route)) {
                    this.vehiclesByRoute.put(route, new ArrayList<Vehicle>());
                }

                this.vehiclesByRoute.get(route).add(vehicle);
            }
        }

        if (vehiclePosition.hasStopId()) {
            vehicle.setCurrentStop(this.getStopById(vehiclePosition.getStopId()));
        } else if (vehiclePosition.hasCurrentStopSequence()) {
            if (vehicle.getTrip() != null) {
                final Stop stop = vehicle.getTrip()
                        .getStopByOriginalSequenceNumber(vehiclePosition.getCurrentStopSequence());
                vehicle.setCurrentStop(stop);

                if (stop == null) {
                    log.warn(String.format(
                            "Vehicle \"%d\" is on trip \"%s\", but trip has no stop with original sequence number %d.",
                            vehicle.getId(), vehicle.getTrip().getId(),
                            vehiclePosition.getCurrentStopSequence()));
                }
            } else {
                log.warn(String.format(
                        "Vehicle \"%s\" makes reference to a stop sequence number, but is not associated with a trip.",
                        vehicle.getId()));
            }
        }

        vehicle.setStopStatus(vehiclePosition.getCurrentStatus());
        vehicle.setCongestionLevel(vehiclePosition.getCongestionLevel());
    } finally {
        this.realtimeDataLock.writeLock().unlock();
    }
}

From source file:com.webbfontaine.valuewebb.model.util.Utils.java

public static String[] splitToParts(String str, Integer lenghtOfEachPart, Integer reqParts) {

    String[] strParts = new String[reqParts];

    if ((str = StringUtils.trimToNull(str)) == null) {
        return strParts;
    }/*from   ww  w. ja v  a  2  s.  c  o m*/

    String[] splitRes = str.split("(?<=\\G.{" + lenghtOfEachPart + "})");

    for (int i = 0; i < strParts.length && i < splitRes.length; i++) {
        strParts[i] = splitRes[i];
    }

    return strParts;
}

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

/**
 * Adds item.//w w  w  .j av  a 2  s . c  om
 * @param owner user name
 * @param folderId folder id (optional)
 * @param itemId item id
 * @param title title
 * @param description description
 * @param url URL
 * @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,
        URL url, 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("url", url.toExternalForm());
    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:alfio.controller.api.admin.ExtensionApiController.java

@RequestMapping(value = "/log")
public PageAndContent<List<ExtensionLog>> getLog(@RequestParam(required = false, name = "path") String path,
        @RequestParam(required = false, name = "name") String name,
        @RequestParam(required = false, name = "type") ExtensionLog.Type type,
        @RequestParam(required = false, name = "page", defaultValue = "0") Integer page, Principal principal) {
    ensureAdmin(principal);//  w ww.j ava2 s .  c o  m
    final int pageSize = 50;
    Pair<List<ExtensionLog>, Integer> res = extensionService.getLog(StringUtils.trimToNull(path),
            StringUtils.trimToNull(name), type, pageSize, (page == null ? 0 : page) * pageSize);
    return new PageAndContent<>(res.getLeft(), res.getRight());
}

From source file:com.moviejukebox.tools.PropertiesUtil.java

/**
 * Collect keywords list and appropriate keyword values. <br>
 * Example: my.languages = EN,FR my.languages.EN = English my.languages.FR =
 * French/* w w w . j av a2s. c om*/
 *
 * @param prefix Key for keywords list and prefix for value searching.
 * @param defaultValue
 * @return Ordered keyword list and map.
 */
public static KeywordMap getKeywordMap(String prefix, String defaultValue) {
    KeywordMap keywordMap = new KeywordMap();

    String languages = getProperty(prefix, defaultValue);
    if (!isBlank(languages)) {
        for (String lang : languages.split("[ ,]+")) {
            lang = StringUtils.trimToNull(lang);
            if (lang == null) {
                continue;
            }
            keywordMap.keywords.add(lang);
            String values = getProperty(prefix + "." + lang);
            if (values != null) {
                keywordMap.put(lang, values);
            }
        }
    }

    return keywordMap;
}

From source file:com.hubrick.vertx.s3.client.S3Client.java

public void putObject(String bucket, String key, PutObjectRequest putObjectRequest,
        Handler<Response<PutObjectResponseHeaders, Void>> handler, Handler<Throwable> exceptionHandler) {
    checkNotNull(StringUtils.trimToNull(bucket), "bucket must not be null");
    checkNotNull(StringUtils.trimToNull(key), "key must not be null");
    checkNotNull(putObjectRequest, "putObjectRequest must not be null");
    checkNotNull(handler, "handler must not be null");
    checkNotNull(exceptionHandler, "exceptionHandler must not be null");

    final S3ClientRequest request = createPutRequest(bucket, key, putObjectRequest, new HeadersResponseHandler(
            "putObject", jaxbUnmarshaller, new PutResponseHeadersMapper(), handler, exceptionHandler, false));
    request.exceptionHandler(exceptionHandler);
    request.end(putObjectRequest.getData());
}

From source file:alfio.manager.system.ConfigurationManager.java

private Optional<String> evaluateValue(String key, String value) {
    if (ConfigurationKeys.fromString(key).isBooleanComponentType()) {
        return Optional.ofNullable(StringUtils.trimToNull(value));
    }/*from www. j ava 2 s. com*/
    return Optional.of(Objects.requireNonNull(value));
}

From source file:alfio.manager.system.ConfigurationManager.java

private Optional<Boolean> getThreeStateValue(String value) {
    return Optional.ofNullable(StringUtils.trimToNull(value)).map(Boolean::parseBoolean);
}

From source file:com.moviejukebox.tools.PropertiesUtil.java

/**
 * Output a warning message about the property being no longer used
 *
 * @param prop Property to warn about/*from  ww  w.  j  a  va2s . co  m*/
 */
public static void warnDeprecatedProperty(final String prop) {
    String value = StringUtils.trimToNull(PROPS.getProperty(prop));
    if (StringTools.isValidString(value)) {
        LOG.warn(
                "Property '{}' is no longer used, but was found in your configuration files, please remove it.",
                prop);
    }
}

From source file:kenh.xscript.database.elements.Execute.java

/**
 * Execute sql./*from   w w  w  .  j av  a 2  s . c  o  m*/
 * @param sql  
 * @param parameter
 * @param var   variable name of result
 * @param conn
 */
private int executeSQL(SQLBean sqlBean, String var, java.sql.Connection conn)
        throws UnsupportedScriptException {
    if (sqlBean == null || StringUtils.isBlank(sqlBean.getSql())) {
        UnsupportedScriptException ex = new UnsupportedScriptException(this, "Can't find the sql to execute.");
        throw ex;
    }

    if (conn == null) {
        throw new UnsupportedScriptException(this, "Connection is empty.");
    }

    var = StringUtils.trimToNull(var);

    PreparedStatement pstmt = null;
    ResultSet rs = null;

    try {
        if (conn.isClosed()) {
            throw new UnsupportedScriptException(this, "Connection is closed.");
        }

        StringBuffer traceInfo = new StringBuffer();
        traceInfo.append("Execute SQL: \n" + StringUtils.trim(sqlBean.getSql()));

        pstmt = conn.prepareStatement(sqlBean.getSql());
        Map<String, String> parameters = getParameters(sqlBean);

        Iterator<String> elements = parameters.values().iterator();

        // set the Paramter for PreparedStatement
        int i = 1;
        while (elements.hasNext()) {
            String str = elements.next();
            Object obj = this.getEnvironment().parse(str);
            traceInfo.append("\nParam " + i + ": " + obj.toString());
            pstmt.setObject(i, obj);
            i++;
        }

        logger.trace(traceInfo.toString());

        boolean result = false;

        result = pstmt.execute();

        if (result) {
            rs = pstmt.getResultSet();

            if (StringUtils.isNotBlank(var)) {
                ResultSetBean bean = new ResultSetBean(rs);
                this.saveVariable(var, bean, null);
            }

        } else {
            int count = pstmt.getUpdateCount();
            if (StringUtils.isNotBlank(var))
                this.saveVariable(var, count, null);
        }

    } catch (java.sql.SQLException | IllegalAccessException | InstantiationException e) {
        this.getEnvironment().setVariable(Constant.VARIABLE_EXCEPTION, e);
        return EXCEPTION;

    } catch (UnsupportedExpressionException e) {
        throw new UnsupportedScriptException(this, e);
    } finally {

        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
            }
            rs = null;
        }

        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (Exception e) {
            }
            pstmt = null;
        }
    }

    return NONE;

}