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:org.cyclop.common.StringHelper.java

public static Optional<InetAddress> toInetAddress(String ip) {
    ip = StringUtils.trimToNull(ip);
    if (ip == null) {
        return Optional.empty();
    }/*from  w w w .  ja  v  a 2s.  com*/
    InetAddress addr = null;
    try {
        addr = InetAddress.getByName(ip);
    } catch (UnknownHostException | SecurityException e) {
        LOG.warn("Cannot convert: " + ip + " to valid IP: " + e.getMessage());
        LOG.debug(e.getMessage(), e);
    }
    return Optional.ofNullable(addr);
}

From source file:org.cyclop.service.common.FileStorage.java

public @Valid <T> Optional<T> read(@NotNull UserIdentifier userId, @NotNull Class<T> clazz)
        throws ServiceException {
    Path filePath = getPath(userId, clazz);
    LOG.debug("Reading file {} for {}", filePath, userId);
    try (FileChannel channel = openForRead(filePath)) {
        if (channel == null) {
            LOG.debug("File not found: {}", filePath);
            return Optional.empty();
        }//from   w w  w  .  j  a va  2s . c o m
        int fileSize = (int) channel.size();
        if (fileSize > config.fileStore.maxFileSize) {
            LOG.info("File: {} too large: {} - skipping it", filePath, fileSize);
            return Optional.empty();
        }
        ByteBuffer buf = ByteBuffer.allocate(fileSize);
        channel.read(buf);
        buf.flip();
        String decoded = decoder.get().decode(buf).toString();
        decoded = StringUtils.trimToNull(decoded);
        if (decoded == null) {
            return Optional.empty();
        }
        T content = jsonMarshaller.unmarshal(clazz, decoded);

        LOG.debug("File read");
        return Optional.ofNullable(content);
    } catch (IOException | SecurityException | IllegalStateException e) {
        throw new ServiceException("Error reading filr from:" + filePath + " - " + e.getMessage(), e);
    }

}

From source file:org.dspace.app.rest.utils.DiscoverQueryBuilder.java

private void fillFacetIntoQueryArgs(Context context, DSpaceObject scope, String prefix, DiscoverQuery queryArgs,
        DiscoverySearchFilterFacet facet, final int pageSize) {
    if (facet.getType().equals(DiscoveryConfigurationParameters.TYPE_DATE)) {
        try {//from  w ww.  j  a  va  2 s  .  com
            FacetYearRange facetYearRange = searchService.getFacetYearRange(context, scope, facet,
                    queryArgs.getFilterQueries());

            queryArgs.addYearRangeFacet(facet, facetYearRange);

        } catch (Exception e) {
            log.error(LogManager.getHeader(context, "Error in Discovery while setting up date facet range",
                    "date facet: " + facet), e);
        }

    } else {

        //Add one to our facet limit to make sure that if we have more then the shown facets that we show our
        // "show more" url
        int facetLimit = pageSize + 1;
        //This should take care of the sorting for us
        queryArgs.addFacetField(new DiscoverFacetField(facet.getIndexFieldName(), facet.getType(), facetLimit,
                facet.getSortOrderSidebar(), StringUtils.trimToNull(prefix)));
    }
}

From source file:org.dspace.rest.SearchResource.java

@GET
@Path("/item")
@ApiOperation(value = "Retrieve items based on given pairs of metadatafields and values.", response = Item.class)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response searchItems(

        @ApiParam(value = "The metadatafields to use in the search, colon (;) separated, in the form of \"metadatafield:value\"", required = true) @QueryParam("fields") String fields,

        @ApiParam(value = "Show additional data for the item.", required = false, allowMultiple = true, allowableValues = "all,metadata,parentCollection,parentCollectionList,parentCommunityList,bitstreams") @QueryParam("expand") String expand,

        @ApiParam(value = "The maximum amount of items shown.", required = false) @QueryParam("limit") int limit,
        @ApiParam(value = "The amount of items to skip.", required = false) @QueryParam("offset") int offset,
        @ApiParam(value = "The field by which the result should be sorted.", required = false) @QueryParam("sort-by") String sortBy,
        @ApiParam(value = "A field to limit the search to certain collections/communities.", required = false) @QueryParam("scope") String scope,
        @ApiParam(value = "The ordering of the results.", required = false, allowableValues = "asc,desc") @QueryParam("order") String order,

        @QueryParam("userIP") String user_ip, @QueryParam("userAgent") String user_agent,
        @QueryParam("xforwardedfor") String xforwardedfor, @Context HttpHeaders headers,
        @Context HttpServletRequest request) throws WebApplicationException, Exception {

    // get the context user.
    context = createContext();//w  w w . jav  a 2 s  .  co  m

    if (log.isDebugEnabled()) {
        log.debug("user:  " + context.getCurrentUser());
    }

    DiscoverQuery dq = new DiscoverQuery();

    dq.setDSpaceObjectFilter(org.dspace.core.Constants.ITEM);

    String cleanFields = StringUtils.trimToNull(fields);
    String cleanExpand = StringUtils.trimToNull(expand);

    if (null == cleanExpand) {
        cleanExpand = "metadata";
    }

    if (null != cleanFields) {
        String[] splitFields = StringUtils.split(cleanFields, ';');
        String query = StringUtils.join(splitFields, " AND ");
        dq.setQuery(query);
    }

    dq.setMaxResults(getMaxResults(limit));

    dq.setStart(offset);

    Response response;
    try {
        if (StringUtils.isNotBlank(scope)) {
            scopeObject = getScope(scope);
        }

        SearchService searchService = SearchUtils.getSearchService();

        if (sortBy != null) {
            String field = getSortFieldName(sortBy, scopeObject);
            dq.setSortField(field, getSortOrder(order));
        }

        //DSpaceObject dso = Collection.find(context);
        DiscoverResult result = scopeObject == null ? searchService.search(context, dq)
                : searchService.search(context, scopeObject, dq);

        List<DSpaceObject> dspaceObjects = result.getDspaceObjects();

        List<org.dspace.rest.common.Item> toReturn = new ArrayList<org.dspace.rest.common.Item>();
        for (DSpaceObject obj : dspaceObjects) {
            Item it = (Item) obj;
            toReturn.add(new org.dspace.rest.common.Item(it, cleanExpand, context));

            writeStats(it, UsageEvent.Action.VIEW, user_ip, user_agent, xforwardedfor, headers, request,
                    context);
        }

        context.complete();

        GenericEntity<List<org.dspace.rest.common.Item>> entity = new GenericEntity<List<org.dspace.rest.common.Item>>(
                toReturn) {
        };

        response = Response.ok(entity).build();

    } catch (Exception ex) {
        log.error(ex.getMessage());
        response = Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
    }

    return response;
}

From source file:org.dspace.utils.servlet.DSpaceWebappServletFilter.java

public void init(FilterConfig filterConfig) throws ServletException {
    // ensure the kernel is running, if not then we have to die here
    try {/*from ww w .j  a  v a 2s  . c o m*/
        getKernel();
        String param = filterConfig.getInitParameter("paths-to-be-ignored");
        pathsToBeIgnored = new ArrayList<String>();
        if (null != StringUtils.trimToNull(param)) {
            String[] items = StringUtils.split(param, ';');
            for (String item : items) {
                pathsToBeIgnored.add(item);
            }
        }

    } catch (IllegalStateException e) {
        // no kernel so we die
        String message = "Could not start up DSpaceWebappServletFilter because the DSpace Kernel is unavailable or not running: "
                + e.getMessage();
        System.err.println(message);
        throw new ServletException(message, e);
    }
}

From source file:org.eclipse.hudson.model.project.property.StringProjectProperty.java

@Override
protected String prepareValue(String candidateValue) {
    return StringUtils.trimToNull(candidateValue);
}

From source file:org.esigate.impl.UriMapping.java

/**
 * Creates a UriMapping instance based on the mapping definition given as parameter.
 * <p>//  ww w .  ja  va 2  s . co m
 * Mapping is split in 3 parts :
 * <ul>
 * <li>Host, including the scheme and port : http://www.example:8080</li>
 * <li>path, left part before the wildcard caracter *</li>
 * <li>extension, right part after the wildcard caracter *</li>
 * </ul>
 * 
 * @param mapping
 *            the mapping expression as string
 * @return the uri mapping object
 * @throws ConfigurationException
 */
public static UriMapping create(String mapping) {
    Matcher matcher = MAPPING_PATTERN.matcher(mapping);
    if (!matcher.matches()) {
        throw new ConfigurationException("Unrecognized URI pattern: " + mapping);
    }
    String host = StringUtils.trimToNull(matcher.group(1));
    String path = StringUtils.trimToNull(matcher.group(5));

    if (path != null && !path.startsWith("/")) {
        throw new ConfigurationException(
                "Unrecognized URI pattern: " + mapping + " Mapping path should start with / was: " + path);
    }
    String extension = StringUtils.trimToNull(matcher.group(7));
    if (extension != null && !extension.startsWith(".")) {
        throw new ConfigurationException("Unrecognized URI pattern: " + mapping
                + " Mapping extension should start with . was: " + extension);
    }
    return new UriMapping(host, path, extension);
}

From source file:org.flowable.engine.impl.bpmn.deployer.BpmnDeployer.java

protected void createLocalizationValues(String processDefinitionId, Process process) {
    if (process == null)
        return;//  w  w  w . jav a 2s . co m

    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration()
            .getDynamicBpmnService();
    ObjectNode infoNode = dynamicBpmnService.getProcessDefinitionInfo(processDefinitionId);

    boolean localizationValuesChanged = false;
    List<ExtensionElement> localizationElements = process.getExtensionElements().get("localization");
    if (localizationElements != null) {
        for (ExtensionElement localizationElement : localizationElements) {
            if (BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())
                    || BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX
                            .equals(localizationElement.getNamespacePrefix())) {

                String locale = localizationElement.getAttributeValue(null, "locale");
                String name = localizationElement.getAttributeValue(null, "name");
                String documentation = null;
                List<ExtensionElement> documentationElements = localizationElement.getChildElements()
                        .get("documentation");
                if (documentationElements != null) {
                    for (ExtensionElement documentationElement : documentationElements) {
                        documentation = StringUtils.trimToNull(documentationElement.getElementText());
                        break;
                    }
                }

                String processId = process.getId();
                if (isEqualToCurrentLocalizationValue(locale, processId, "name", name, infoNode) == false) {
                    dynamicBpmnService.changeLocalizationName(locale, processId, name, infoNode);
                    localizationValuesChanged = true;
                }

                if (documentation != null && isEqualToCurrentLocalizationValue(locale, processId, "description",
                        documentation, infoNode) == false) {
                    dynamicBpmnService.changeLocalizationDescription(locale, processId, documentation,
                            infoNode);
                    localizationValuesChanged = true;
                }

                break;
            }
        }
    }

    boolean isFlowElementLocalizationChanged = localizeFlowElements(process.getFlowElements(), infoNode);
    boolean isDataObjectLocalizationChanged = localizeDataObjectElements(process.getDataObjects(), infoNode);
    if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
        localizationValuesChanged = true;
    }

    if (localizationValuesChanged) {
        dynamicBpmnService.saveProcessDefinitionInfo(processDefinitionId, infoNode);
    }
}

From source file:org.flowable.engine.impl.bpmn.deployer.BpmnDeployer.java

protected boolean localizeFlowElements(Collection<FlowElement> flowElements, ObjectNode infoNode) {
    boolean localizationValuesChanged = false;

    if (flowElements == null)
        return localizationValuesChanged;

    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration()
            .getDynamicBpmnService();/*from ww  w .  j  a  v a  2 s  .co m*/

    for (FlowElement flowElement : flowElements) {
        if (flowElement instanceof UserTask || flowElement instanceof SubProcess) {
            List<ExtensionElement> localizationElements = flowElement.getExtensionElements()
                    .get("localization");
            if (localizationElements != null) {
                for (ExtensionElement localizationElement : localizationElements) {
                    if (BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX
                            .equals(localizationElement.getNamespacePrefix())
                            || BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX
                                    .equals(localizationElement.getNamespacePrefix())) {

                        String locale = localizationElement.getAttributeValue(null, "locale");
                        String name = localizationElement.getAttributeValue(null, "name");
                        String documentation = null;
                        List<ExtensionElement> documentationElements = localizationElement.getChildElements()
                                .get("documentation");
                        if (documentationElements != null) {
                            for (ExtensionElement documentationElement : documentationElements) {
                                documentation = StringUtils.trimToNull(documentationElement.getElementText());
                                break;
                            }
                        }

                        String flowElementId = flowElement.getId();
                        if (isEqualToCurrentLocalizationValue(locale, flowElementId, "name", name,
                                infoNode) == false) {
                            dynamicBpmnService.changeLocalizationName(locale, flowElementId, name, infoNode);
                            localizationValuesChanged = true;
                        }

                        if (documentation != null && isEqualToCurrentLocalizationValue(locale, flowElementId,
                                "description", documentation, infoNode) == false) {
                            dynamicBpmnService.changeLocalizationDescription(locale, flowElementId,
                                    documentation, infoNode);
                            localizationValuesChanged = true;
                        }

                        break;
                    }
                }
            }

            if (flowElement instanceof SubProcess) {
                SubProcess subprocess = (SubProcess) flowElement;
                boolean isFlowElementLocalizationChanged = localizeFlowElements(subprocess.getFlowElements(),
                        infoNode);
                boolean isDataObjectLocalizationChanged = localizeDataObjectElements(
                        subprocess.getDataObjects(), infoNode);
                if (isFlowElementLocalizationChanged || isDataObjectLocalizationChanged) {
                    localizationValuesChanged = true;
                }
            }
        }
    }

    return localizationValuesChanged;
}

From source file:org.flowable.engine.impl.bpmn.deployer.BpmnDeployer.java

protected boolean localizeDataObjectElements(List<ValuedDataObject> dataObjects, ObjectNode infoNode) {
    boolean localizationValuesChanged = false;
    CommandContext commandContext = Context.getCommandContext();
    DynamicBpmnService dynamicBpmnService = commandContext.getProcessEngineConfiguration()
            .getDynamicBpmnService();//from  w  w  w .j a  va 2 s  .c  o m

    for (ValuedDataObject dataObject : dataObjects) {
        List<ExtensionElement> localizationElements = dataObject.getExtensionElements().get("localization");
        if (localizationElements != null) {
            for (ExtensionElement localizationElement : localizationElements) {
                if (BpmnXMLConstants.FLOWABLE_EXTENSIONS_PREFIX.equals(localizationElement.getNamespacePrefix())
                        || BpmnXMLConstants.ACTIVITI_EXTENSIONS_PREFIX
                                .equals(localizationElement.getNamespacePrefix())) {

                    String locale = localizationElement.getAttributeValue(null, "locale");
                    String name = localizationElement.getAttributeValue(null, "name");
                    String documentation = null;

                    List<ExtensionElement> documentationElements = localizationElement.getChildElements()
                            .get("documentation");
                    if (documentationElements != null) {
                        for (ExtensionElement documentationElement : documentationElements) {
                            documentation = StringUtils.trimToNull(documentationElement.getElementText());
                            break;
                        }
                    }

                    if (name != null && isEqualToCurrentLocalizationValue(locale, dataObject.getId(),
                            DynamicBpmnConstants.LOCALIZATION_NAME, name, infoNode) == false) {
                        dynamicBpmnService.changeLocalizationName(locale, dataObject.getId(), name, infoNode);
                        localizationValuesChanged = true;
                    }

                    if (documentation != null && isEqualToCurrentLocalizationValue(locale, dataObject.getId(),
                            DynamicBpmnConstants.LOCALIZATION_DESCRIPTION, documentation, infoNode) == false) {

                        dynamicBpmnService.changeLocalizationDescription(locale, dataObject.getId(),
                                documentation, infoNode);
                        localizationValuesChanged = true;
                    }
                }
            }
        }
    }

    return localizationValuesChanged;
}