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

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

Introduction

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

Prototype

public static String trimToNull(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:mitm.application.djigzo.james.mailets.PDFEncrypt.java

private void initOpenPermissions() {
    String param = StringUtils.trimToNull(getInitParameter(Parameter.OPEN_PERMISSION.name));

    if (param != null) {
        String[] permissions = StringUtils.split(param, ',');

        for (String permissionName : permissions) {
            permissionName = StringUtils.trim(permissionName);

            OpenPermission openPermission = OpenPermission.fromName(permissionName);

            if (openPermission == null) {
                throw new IllegalArgumentException(permissionName + " is not a valid OpenPermission.");
            }/*from www  .  j av a2s. co  m*/

            openPermissions.add(openPermission);
        }
    }

    /*
     * Set default permissions to all if nothing was set.
     */
    if (openPermissions.size() == 0) {
        openPermissions.add(OpenPermission.ALL);
    }
}

From source file:com.prowidesoftware.swift.io.parser.MxParser.java

/**
 * Takes an xml with an MX message and detects the specific message type
 * parsing just the namespace from the Document element. If the Document
 * element is not present, or without the namespace or if the namespace url
 * contains invalid content it will return null.
 * <br><br>//from  w w  w .  ja  v a  2  s .c  o  m
 * Example of a recognizable Document element:<br>
 * <Doc:Document xmlns:Doc="urn:swift:xsd:camt.003.001.04" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 * <br>
 * The implementation is intended to be lightweight and efficient, based on {@link javax.xml.stream.XMLStreamReader} 
 *
 * @return id with the detected MX message type or null if it cannot be determined.
 * @since 7.7
 */
public MxId detectMessage() {
    if (StringUtils.isBlank(this.buffer)) {
        log.log(Level.SEVERE, "cannot detect message from null or empty content");
        return null;
    }
    final javax.xml.stream.XMLInputFactory xif = javax.xml.stream.XMLInputFactory.newInstance();
    try {
        final javax.xml.stream.XMLStreamReader reader = xif
                .createXMLStreamReader(new StringReader(this.buffer));
        while (reader.hasNext()) {
            int event = reader.next();
            if (javax.xml.stream.XMLStreamConstants.START_ELEMENT == event
                    && reader.getLocalName().equals(DOCUMENT_LOCALNAME)) {
                if (reader.getNamespaceCount() > 0) {
                    //log.finest("ELEMENT START: " + reader.getLocalName() + " , namespace count is: " + reader.getNamespaceCount());
                    for (int nsIndex = 0; nsIndex < reader.getNamespaceCount(); nsIndex++) {
                        final String nsPrefix = StringUtils.trimToNull(reader.getNamespacePrefix(nsIndex));
                        final String elementPrefix = StringUtils.trimToNull(reader.getPrefix());
                        if (StringUtils.equals(nsPrefix, elementPrefix)) {
                            String nsId = reader.getNamespaceURI(nsIndex);
                            //log.finest("\tNamepsace prefix: " + nsPrefix + " associated with URI " + nsId);
                            return new MxId(nsId);
                        }
                    }
                }
            }
        }
    } catch (final Exception e) {
        log.log(Level.SEVERE, "error while detecting message", e);
    }
    return null;
}

From source file:com.abstratt.mdd.core.util.TypeUtils.java

/**
 * Returns whether two types are compatible. Optionally, takes template
 * parameter substitutions into account.
 * /*from w w  w. j a va 2 s.c o m*/
 * @param repository
 * @param source
 * @param destination
 * @param substitutions
 *            a list of template parameter substitutions, or
 *            <code>null</code>
 * @return
 */
public static boolean isCompatible(IBasicRepository repository, Type source, Type destination,
        ParameterSubstitutionMap substitutions) {
    if (destination == null
            || destination == repository.findNamedElement(ANY_TYPE, IRepository.PACKAGE.getClass_(), null)
            || source == repository.findNamedElement(NULL_TYPE, IRepository.PACKAGE.getClass_(), null))
        return true;
    if (source == null)
        return false;
    if (source == destination)
        return true;
    // do not check if wildcard
    if (MDDExtensionUtils.isWildcardType(destination))
        return true;
    Boolean templateCompatible = null;
    // if destination is actually a template parameter, test compatibility with the resolved parameter
    if (substitutions != null && destination.isTemplateParameter()) {
        Type actualDestination = (Type) substitutions.resolveTemplateParameter(destination);
        return actualDestination == null ? false
                : isCompatible(repository, source, actualDestination, substitutions);
    }
    if ((source instanceof TemplateableElement) && !(destination instanceof TemplateableElement)) {
        if (((TemplateableElement) source).isTemplate())
            return false;
    } else if (!(source instanceof TemplateableElement) && (destination instanceof TemplateableElement)) {
        if (((TemplateableElement) destination).isTemplate())
            return false;
    } else if (source instanceof TemplateableElement && destination instanceof TemplateableElement) {
        final TemplateableElement templateableSource = (TemplateableElement) source;
        final TemplateableElement templateableDestination = (TemplateableElement) destination;
        if (templateableSource.isTemplate() != templateableDestination.isTemplate())
            // one of them is a template, the other is not, cannot be compatible
            return false;
        if (templateableSource.isTemplate())
            // if both are templates, general conformance checking should be
            // enough
            return source.conformsTo(destination);
        // if both are bound elements, use template-aware conformance checking
        if (!templateableSource.getTemplateBindings().isEmpty()
                || !templateableDestination.getTemplateBindings().isEmpty())
            templateCompatible = TemplateUtils.isCompatible(templateableSource, templateableDestination);
    }
    // behavior comparison takes parameters into account
    if (source instanceof Behavior || MDDExtensionUtils.isSignature(source)) {
        if (!MDDExtensionUtils.isSignature(destination))
            return false;
        final List<Parameter> destinationParams;
        final List<Parameter> sourceParams;
        if (source instanceof Behavior)
            sourceParams = ((Behavior) source).getOwnedParameters();
        else
            // source is not an inlined closure
            // (note this is currently not supported, see issue #50)
            sourceParams = MDDExtensionUtils.getSignatureParameters(source);
        destinationParams = MDDExtensionUtils.getSignatureParameters(destination);
        return isCompatible(repository, sourceParams.toArray(new Parameter[sourceParams.size()]),
                destinationParams.toArray(new Parameter[destinationParams.size()]), substitutions);
    }
    // for data types, we perform shape-based compatibility check
    if (destination instanceof DataType && source instanceof Classifier) {
        List<Property> destinationAttributes = ((Classifier) destination).getAllAttributes();
        List<Property> sourceAttributes = ((Classifier) source).getAllAttributes();
        if (destinationAttributes.size() != sourceAttributes.size())
            return false;
        for (int i = 0; i < sourceAttributes.size(); i++) {
            // if any defines a property name, names must match
            String destinationName = StringUtils.trimToNull(destinationAttributes.get(i).getName());
            String sourceName = StringUtils.trimToNull(sourceAttributes.get(i).getName());
            if (destinationName != null && sourceName != null && !destinationName.equals(sourceName))
                return false;
            if (!isCompatible(repository, sourceAttributes.get(i), destinationAttributes.get(i), substitutions))
                return false;
        }
        return true;
    }
    if (Boolean.TRUE.equals(templateCompatible))
        // if they are deemed template compatible, go with that - conformance doesn't understand templates
        return true;
    // general type conformance
    return source.conformsTo(destination);
}

From source file:mitm.application.djigzo.james.mailets.Notify.java

private Collection<MailAddress> parseAddress(String input, Mail mail) throws MessagingException {
    input = StringUtils.trimToNull(input);

    Collection<MailAddress> result = new LinkedHashSet<MailAddress>();

    if (input != null) {
        SpecialAddress specialAddress = SpecialAddress.fromName(input);

        if (specialAddress != null) {
            handleSpecialAddress(mail, result, specialAddress);
        } else {//from w  w  w. ja  v a2s  . c  o m
            /*
             * Check if the address is a mail attribute
             */
            Matcher matcher = MAIL_ATTR_PATTERN.matcher(input);

            if (matcher.matches()) {
                handleMailAttribute(mail, matcher.group(1), result);
            } else {
                /*
                 * Check if the address is a user property address
                 */
                matcher = USER_VAR_PATTERN.matcher(input);

                if (matcher.matches()) {
                    handleUserProperty(mail, matcher.group(1), result);
                } else {
                    /*
                     * Assume the input is a normal email address. However, we never want 
                     * the invalid@invalid.tld address
                     */
                    if (!EmailAddressUtils.isInvalidDummyAddress(input)) {
                        result.add(new MailAddress(input));
                    }
                }
            }
        }
    }

    return result;
}

From source file:com.bluexml.xforms.actions.AbstractWorkflowAction.java

/**
 * Finds the workflow definition id for a form.
 * //from w w w  . j  a va 2s .c  om
 * @param candidateProcessId
 *            the url param the form was called with (if relevant). null if
 *            no URL param was
 *            given.
 * @param formName
 *            the name of the workflow form, e.g.
 *            "DigitizationProcess_Debut"
 * @return candidateProcessId if given. Otherwise, the id for the latest
 *         deployed version of the
 *         process definition
 */
protected String findProcessId(String candidateProcessId, String formName) {
    if (StringUtils.trimToNull(candidateProcessId) != null) {
        return candidateProcessId;
    }
    logger.debug("Entering findProcessId");
    String processName = controller.workflowExtractProcessNameFromFormName(formName);
    logger.debug(" got processName: " + processName);

    String definitionName = controller.getWorkflowBlueXMLDefinitionName(processName);
    logger.debug(" got definitionName: " + definitionName);
    return controller.workflowGetIdForProcessDefinition(transaction, definitionName); // $$
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Erzeugt den Pfad fuer den zu speichernden Kontoauszug.
 * @param k das Konto./*from  w ww. ja  v a 2  s  .  c o  m*/
 * @param ka der Kontoauszug. Optional. Wenn er fehlt, werden Default-Werte verwendet.
 * @param path Ordner, in dem die Kontoauszuege gespeichert werden.
 * @param folder Template fuer den Unterordner.
 * @param name Template fuer den Dateinamen.
 * @return der Pfad.
 * @throws RemoteException
 * @throws ApplicationException
 */
public static String createPath(Konto k, Kontoauszug ka, String path, String folder, String name)
        throws RemoteException, ApplicationException {
    if (k == null)
        throw new ApplicationException(i18n.tr("Kein Konto angegeben"));

    Map<String, Object> ctx = new HashMap<String, Object>();

    {
        String iban = StringUtils.trimToNull(k.getIban());
        if (iban == null)
            iban = StringUtils.trimToEmpty(k.getKontonummer());

        ctx.put("iban", iban.replaceAll(" ", ""));
    }

    {
        String bic = StringUtils.trimToNull(k.getBic());
        if (bic == null)
            bic = StringUtils.trimToEmpty(k.getBLZ());

        ctx.put("bic", bic.replaceAll(" ", ""));
    }

    {
        Calendar cal = Calendar.getInstance();
        if (ka != null) {
            if (ka.getErstellungsdatum() != null)
                cal.setTime(ka.getErstellungsdatum());
            else if (ka.getAusfuehrungsdatum() != null)
                cal.setTime(ka.getAusfuehrungsdatum());
        }

        Integer i = ka != null && ka.getJahr() != null ? ka.getJahr() : null;
        ctx.put("jahr", i != null ? i.toString() : Integer.toString(cal.get(Calendar.YEAR)));
        ctx.put("monat", String.format("%02d", cal.get(Calendar.MONTH) + 1));
        ctx.put("tag", String.format("%02d", cal.get(Calendar.DATE)));
        ctx.put("stunde", String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)));
        ctx.put("minute", String.format("%02d", cal.get(Calendar.MINUTE)));
    }

    {
        Integer i = ka != null && ka.getNummer() != null ? ka.getNummer() : null;
        ctx.put("nummer", String.format("%03d", i != null ? i.intValue() : 1));
    }

    VelocityService velocity = Application.getBootLoader().getBootable(VelocityService.class);
    StringBuilder sb = new StringBuilder();

    /////////////////////////////
    // Pfad
    {
        if (path == null || path.length() == 0)
            path = Application.getPluginLoader().getPlugin(HBCI.class).getResources().getWorkPath();
        sb.append(path);

        if (!path.endsWith(File.separator))
            sb.append(File.separator);
    }
    //
    /////////////////////////////

    /////////////////////////////
    // Unter-Ordner
    {
        if (folder != null && folder.length() > 0) {
            try {
                // Velocity-Escaping machen wir. Das sollte der User nicht selbst machen muessen
                // Eigentlich wird hier nur "\$" gegen "\\$" ersetzt. Die zusaetzlichen
                // Die extra Escapings sind fuer Java selbst in String-Literalen.
                folder = folder.replace("\\$", "\\\\$");
                folder = velocity.merge(folder, ctx);
            } catch (Exception e) {
                Logger.error("folder template invalid: \"" + folder + "\"", e);
            }
            sb.append(folder);
            if (!folder.endsWith(File.separator))
                sb.append(File.separator);
        }
    }
    //
    /////////////////////////////

    /////////////////////////////
    // Dateiname
    {
        if (name == null || name.length() == 0 && ka != null)
            name = ka.getDateiname();

        if (name == null || name.length() == 0)
            name = MetaKey.KONTOAUSZUG_TEMPLATE_NAME.getDefault();

        try {
            name = velocity.merge(name, ctx);
        } catch (Exception e) {
            Logger.error("name template invalid: \"" + name + "\"", e);
        }
        sb.append(name);

        // Dateiendung noch anhaengen.
        Format f = Format.find(ka != null ? ka.getFormat() : null);
        if (f == null)
            f = Format.PDF;

        sb.append(".");
        sb.append(f.getExtention());
    }

    return sb.toString();
}

From source file:mitm.application.djigzo.james.mailets.PDFEncrypt.java

private void initViewerPreferences() {
    String param = StringUtils.trimToNull(getInitParameter(Parameter.VIEWER_PREFERENCE.name));

    if (param != null) {
        String[] preferences = StringUtils.split(param, ',');

        for (String preferenceName : preferences) {
            preferenceName = StringUtils.trim(preferenceName);

            ViewerPreference viewerPreference = ViewerPreference.fromName(preferenceName);

            if (viewerPreference == null) {
                throw new IllegalArgumentException(preferenceName + " is not a valid ViewerPreference.");
            }//from   w w w.  j  a  va  2  s  .c  o m

            if (viewerPreferences == null) {
                viewerPreferences = new HashSet<ViewerPreference>();
            }

            viewerPreferences.add(viewerPreference);
        }
    }
}

From source file:ch.entwine.weblounge.dispatcher.impl.handler.FeedRequestHandlerImpl.java

/**
 * Compiles the feed based on feed type, version and request parameters.
 * /*from  ww w  .  j  av  a2  s  .co  m*/
 * @param feedType
 *          feed type
 * @param feedVersion
 *          feed version
 * @param site
 *          the site
 * @param request
 *          the request
 * @param response
 *          the response
 * @return the feed object
 * @throws ContentRepositoryException
 *           if the content repository can't be accessed
 */
private SyndFeed createFeed(String feedType, String feedVersion, Site site, WebloungeRequest request,
        WebloungeResponse response) throws ContentRepositoryException {

    // Extract the subjects. The parameter may be specified multiple times
    // and add more than one subject by separating them using a comma.
    String[] subjectParameter = request.getParameterValues(PARAM_SUBJECT);
    List<String> subjects = new ArrayList<String>();
    if (subjectParameter != null) {
        for (String parameter : subjectParameter) {
            for (String subject : parameter.split(",")) {
                if (StringUtils.isNotBlank(subject))
                    subjects.add(StringUtils.trim(subject));
            }
        }
    }

    // How many entries do we need?
    int limit = DEFAULT_LIMIT;
    String limitParameter = StringUtils.trimToNull(request.getParameter(PARAM_LIMIT));
    if (limitParameter != null) {
        try {
            limit = Integer.parseInt(limitParameter);
        } catch (Throwable t) {
            logger.debug("Non parseable number {} specified as limit", limitParameter);
            limit = DEFAULT_LIMIT;
        }
    }

    // Get hold of the content repository
    ContentRepository contentRepository = site.getContentRepository();
    if (contentRepository == null) {
        logger.warn("No content repository found for site '{}'", site);
        return null;
    } else if (contentRepository.isIndexing()) {
        logger.debug("Content repository of site '{}' is currently being indexed", site);
        DispatchUtils.sendServiceUnavailable(request, response);
        return null;
    }

    // User and language
    Language language = request.getLanguage();
    // User user = request.getUser();

    // Determine the feed type
    feedType = feedType.toLowerCase() + "_" + feedVersion;
    SyndFeed feed = new SyndFeedImpl();
    feed.setFeedType(feedType);
    feed.setLink(request.getRequestURL().toString());
    feed.setTitle(site.getName());
    feed.setDescription(site.getName());
    feed.setLanguage(language.getIdentifier());
    feed.setPublishedDate(new Date());

    // TODO: Add more feed metadata, ask site

    SearchQuery query = new SearchQueryImpl(site);
    query.withVersion(Resource.LIVE);
    query.withTypes(Page.TYPE);
    query.withLimit(limit);
    query.sortByPublishingDate(Order.Descending);
    for (String subject : subjects) {
        query.withSubject(subject);
    }

    // Load the result and add feed entries
    SearchResult result = contentRepository.find(query);
    List<SyndEntry> entries = new ArrayList<SyndEntry>();
    int items = Math.min(limit, result.getItems().length);

    for (int i = 0; i < items; i++) {
        SearchResultItem item = result.getItems()[i];

        // Get the page
        PageSearchResultItem pageItem = (PageSearchResultItem) item;
        Page page = pageItem.getPage();

        // TODO: Can the page be accessed?

        // Set the page's language to the feed language
        page.switchTo(language);

        // Tag the cache entry
        response.addTag(CacheTag.Resource, page.getIdentifier());

        // If this is to become the most recent entry, let's set the feed's
        // modification date to be that of this entry
        if (entries.size() == 0) {
            feed.setPublishedDate(page.getPublishFrom());
        }

        // Create the entry
        SyndEntry entry = new SyndEntryImpl();
        entry.setPublishedDate(page.getPublishFrom());
        entry.setUpdatedDate(page.getModificationDate());
        entry.setLink(site.getHostname(request.getEnvironment()).toExternalForm() + item.getUrl().getLink());
        entry.setAuthor(page.getCreator().getName());
        entry.setTitle(page.getTitle());
        entry.setUri(page.getIdentifier());

        // Categories
        if (page.getSubjects().length > 0) {
            List<SyndCategory> categories = new ArrayList<SyndCategory>();
            for (String subject : page.getSubjects()) {
                SyndCategory category = new SyndCategoryImpl();
                category.setName(subject);
                categories.add(category);
            }
            entry.setCategories(categories);
        }

        // Try to render the preview pagelets and write them to the feed
        List<SyndContent> entryContent = new ArrayList<SyndContent>();
        Composer composer = new ComposerImpl("preview", page.getPreview());
        StringBuffer renderedContent = new StringBuffer();

        for (Pagelet pagelet : composer.getPagelets()) {
            Module module = site.getModule(pagelet.getModule());
            PageletRenderer renderer = null;
            if (module == null) {
                logger.warn("Skipping pagelet {} in feed due to missing module '{}'", pagelet,
                        pagelet.getModule());
                continue;
            }

            renderer = module.getRenderer(pagelet.getIdentifier());
            if (renderer == null) {
                logger.warn("Skipping pagelet {} in feed due to missing renderer '{}/{}'",
                        new Object[] { pagelet, pagelet.getModule(), pagelet.getIdentifier() });
                continue;
            }

            URL rendererURL = renderer.getRenderer(RendererType.Feed.toString());
            Environment environment = request.getEnvironment();
            if (rendererURL == null)
                rendererURL = renderer.getRenderer();
            if (rendererURL != null) {
                String pageletContent = null;
                try {
                    pagelet.switchTo(language);
                    pageletContent = loadContents(rendererURL, site, page, composer, pagelet, environment);
                    renderedContent.append(pageletContent);
                } catch (ServletException e) {
                    logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
                    DispatchUtils.sendInternalError(request, response);
                } catch (IOException e) {
                    logger.warn("Error processing the pagelet renderer at {}: {}", rendererURL, e.getMessage());
                    DispatchUtils.sendInternalError(request, response);
                }
            }
        }

        if (renderedContent.length() > 0) {
            SyndContent content = new SyndContentImpl();
            content.setType("text/html");
            content.setMode("escaped");
            content.setValue(renderedContent.toString());
            entryContent.add(content);
            entry.setContents(entryContent);
        }

        entries.add(entry);
    }

    feed.setEntries(entries);

    return feed;
}

From source file:de.willuhn.jameica.hbci.passports.pintan.server.PinTanConfigImpl.java

/**
 * @see de.willuhn.jameica.hbci.passports.pintan.rmi.PinTanConfig#isChipTANUSB()
 *///  ww  w .  j  av a 2s. co m
@Override
public Boolean isChipTANUSB() throws RemoteException {
    String s = StringUtils.trimToNull(settings.getString(getID() + ".chiptan.usb.enabled", null));
    return s != null ? Boolean.valueOf(s) : null;
}

From source file:com.bluexml.xforms.controller.mapping.MappingToolSearch.java

/**
 * Tells whether the search field has a single UI input control.
 * /*www.jav  a2  s.  c  o  m*/
 * @param fieldType
 * @return
 */
private boolean hasSingleInput(SearchFieldType fieldType) {
    String inputs = fieldType.getInputs();
    boolean singleInput = ((StringUtils.trimToNull(inputs) == null) || (StringUtils.equals(inputs, "1")));
    return singleInput;
}