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

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

Introduction

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

Prototype

public static String trim(final String str) 

Source Link

Document

Removes control characters (char <= 32) from both ends of this String, handling null by returning null .

The String is trimmed using String#trim() .

Usage

From source file:com.ottogroup.bi.asap.pipeline.MicroPipeline.java

/**
 * Subscribes the {@link Component} referenced by the <i>subscriberId</i> to the {@link Component} referenced by the <i>publisherId</i>
 * @param subscriberId/*from w w w .j a  v a 2  s  . c  o m*/
 * @param publisherId
 * @throws RequiredInputMissingException
 * @throws UnknownComponentException
 * @throws IllegalComponentSubscriptionException thrown in case a component tries to subscribe itself to an {@link Emitter} or a {@link Source} tries to subscribe itself somewhere else
 */
public void subscribe(final String subscriberId, final String publisherId)
        throws RequiredInputMissingException, UnknownComponentException, IllegalComponentSubscriptionException {

    ///////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(subscriberId))
        throw new RequiredInputMissingException("Missing required input for 'subscriberId'");
    if (StringUtils.isBlank(publisherId))
        throw new RequiredInputMissingException("Missing required input for 'publisherId'");
    if (StringUtils.equalsIgnoreCase(subscriberId, publisherId))
        throw new IllegalComponentSubscriptionException("Self-subscriptions are not permitted [subscriberId='"
                + subscriberId + "', publisherId='" + publisherId + "']");
    //
    ///////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////
    // ensure that the subscriber id does not reference a source component,
    // ensure that the publisher id does not reference an emitter component and
    // ensure that subscriber id and publisher id are different
    String sid = StringUtils.lowerCase(StringUtils.trim(subscriberId));
    String pid = StringUtils.lowerCase(StringUtils.trim(publisherId));

    if (this.sourceExecutors.containsKey(sid))
        throw new IllegalComponentSubscriptionException("Source component '" + subscriberId
                + "' is not allowed to subscribe itself to another component");
    if (this.emitterExecutors.containsKey(pid))
        throw new IllegalComponentSubscriptionException("Emitter component '" + publisherId
                + "' is not allowed to serve as publisher for another component");

    // execute subscription
    Mailbox subscriberMailbox = null;
    if (this.operatorExecutors.containsKey(sid)) {
        OperatorExecutor subscriber = this.operatorExecutors.get(sid);
        if (subscriber == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by subscriberId '" + subscriberId + "'");
        subscriberMailbox = subscriber.getMailbox();
    } else if (this.emitterExecutors.containsKey(sid)) {
        EmitterExecutor subscriber = this.emitterExecutors.get(sid);
        if (subscriber == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by subscriberId '" + subscriberId + "'");
        subscriberMailbox = subscriber.getMailbox();
    } else {
        throw new UnknownComponentException(
                "Unknown component referenced by subscriberId '" + subscriberId + "'");
    }

    if (this.operatorExecutors.containsKey(pid)) {
        OperatorExecutor publisher = this.operatorExecutors.get(pid);
        if (publisher == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by publisherId '" + publisherId + "'");
        publisher.subscribe(sid, subscriberMailbox);
    } else if (this.sourceExecutors.containsKey(pid)) {
        SourceExecutor publisher = this.sourceExecutors.get(pid);
        if (publisher == null)
            throw new UnknownComponentException(
                    "Unknown component referenced by publisherId '" + publisherId + "'");
        publisher.subscribe(sid, subscriberMailbox);
    } else {
        throw new UnknownComponentException(
                "Unknown component referenced by publisherId '" + publisherId + "'");
    }
    //
    ///////////////////////////////////////////////////////////////////

}

From source file:com.netflix.metacat.connector.jdbc.services.JdbcConnectorTableService.java

/**
 * Rebuild a source type definition./*from  w w w. ja  va  2 s  .  c o m*/
 *
 * @param type      The base type e.g. VARCHAR
 * @param size      The size if applicable to the {@code type}
 * @param precision The precision if applicable to the {@code type} e.g. DECIMAL's
 * @return The representation of source type e.g. INTEGER, VARCHAR(50) or DECIMAL(20, 10)
 * @throws SQLDataException When size or precision can't be parsed to integers if non null
 */
protected String buildSourceType(@Nonnull @NonNull final String type, @Nullable final String size,
        @Nullable final String precision) throws SQLDataException {
    if (size != null) {
        final int sizeInt;
        try {
            sizeInt = Integer.parseInt(size);
        } catch (final NumberFormatException nfe) {
            throw new SQLDataException("Size field could not be converted to integer", nfe);
        }
        // Make sure if the type is unsigned it's created correctly
        final String baseType;
        final String afterMagnitude;
        final int unsignedIndex = StringUtils.indexOfIgnoreCase(type, UNSIGNED);
        if (unsignedIndex != -1) {
            baseType = StringUtils.trim(type.substring(0, unsignedIndex));
            afterMagnitude = type.substring(unsignedIndex);
        } else {
            baseType = type;
            afterMagnitude = null;
        }

        if (precision != null) {
            final int precisionInt;
            try {
                precisionInt = Integer.parseInt(precision);
            } catch (final NumberFormatException nfe) {
                throw new SQLDataException("Precision field could not be converted to integer", nfe);
            }
            return baseType + LEFT_PAREN + sizeInt + COMMA_SPACE + precisionInt + RIGHT_PAREN
                    + (afterMagnitude != null ? SPACE + afterMagnitude : EMPTY);
        } else {
            return baseType + LEFT_PAREN + sizeInt + RIGHT_PAREN
                    + (afterMagnitude != null ? SPACE + afterMagnitude : EMPTY);
        }
    } else {
        return type;
    }
}

From source file:com.microsoft.Malmo.Utils.TextureHelper.java

public static int loadShader(String filename, int shaderType) throws IOException {
    int shaderID = -1;
    InputStream stream = MalmoMod.class.getClassLoader().getResourceAsStream(filename);
    if (stream == null) {
        System.out.println("Cannot find shader.");
        return -1;
    }/*from   w  w w  . ja  v  a  2s.  co  m*/
    try {
        byte[] abyte = IOUtils.toByteArray((InputStream) (new BufferedInputStream(stream)));
        ByteBuffer bytebuffer = BufferUtils.createByteBuffer(abyte.length);
        bytebuffer.put(abyte);
        bytebuffer.position(0);
        shaderID = OpenGlHelper.glCreateShader(shaderType);
        OpenGlHelper.glShaderSource(shaderID, bytebuffer);
        OpenGlHelper.glCompileShader(shaderID);

        if (OpenGlHelper.glGetShaderi(shaderID, OpenGlHelper.GL_COMPILE_STATUS) == 0) {
            String s = StringUtils.trim(OpenGlHelper.glGetShaderInfoLog(shaderID, 32768));
            JsonException jsonexception = new JsonException("Couldn\'t compile shader program: " + s);
            throw jsonexception;
        }
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return shaderID;
}

From source file:com.intuit.karate.Script.java

private static void evalJsonEmbeddedExpressions(String path, Object o, ScriptContext context,
        DocumentContext root) {//from  w ww.  j  av  a  2 s  .c  om
    if (o == null) {
        return;
    }
    if (o instanceof Map) {
        Map<String, Object> map = (Map<String, Object>) o;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String childPath = path + "." + entry.getKey();
            evalJsonEmbeddedExpressions(childPath, entry.getValue(), context, root);
        }
    } else if (o instanceof List) {
        List list = (List) o;
        int size = list.size();
        for (int i = 0; i < size; i++) {
            Object child = list.get(i);
            String childPath = path + "[" + i + "]";
            evalJsonEmbeddedExpressions(childPath, child, context, root);
        }
    } else if (o instanceof String) {
        String value = (String) o;
        value = StringUtils.trim(value);
        if (isEmbeddedExpression(value)) {
            try {
                ScriptValue sv = evalInNashorn(value.substring(1), context);
                root.set(path, sv.getValue());
            } catch (Exception e) {
                logger.warn("embedded json script eval failed at path {}: {}", path, e.getMessage());
            }
        }
    } else {
        logger.trace("ignoring type: {} - {}", o.getClass(), o);
    }
}

From source file:net.eledge.android.europeana.search.model.record.enums.RecordDetails.java

private static String cleanCombineResults(String[] array) {
    List<String> result = new ArrayList<>();
    if (array != null) {
        for (String s : array) {
            if (StringUtils.isNotBlank(s) && !StringUtils.startsWithIgnoreCase(s, "http://")
                    && !StringUtils.startsWithIgnoreCase(s, "https://")) {
                result.add(StringUtils.trim(s));
            }/*from   w ww. j a  v a2 s  . co  m*/
        }
        return StringUtils.join(result, "; ");
    }
    return null;
}

From source file:eu.semlibproject.annotationserver.restapis.ServicesAPI.java

private void createAndSendMessage(Transport transport, String subject, String text, String nameFrom,
        String emailFrom, Emails emails, String ip) { // Assuming you are sending email from localhost
    String host = ConfigManager.getInstance().getSmtpMailhost();
    String port = ConfigManager.getInstance().getSmtpMailport();
    String password = ConfigManager.getInstance().getSmtpMailpassword();
    String auth = ConfigManager.getInstance().getSmtpMailauth();
    String sender = ConfigManager.getInstance().getSmtpMailuser();

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.starttls.enable", "true");
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.user", sender);
    properties.setProperty("mail.smtp.password", password);
    properties.setProperty("mail.smtp.auth", auth);
    properties.setProperty("mail.smtp.port", port);

    javax.mail.Session session = javax.mail.Session.getDefaultInstance(properties);

    // Create a default MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Set From: header field of the header.
    if (!StringUtils.isBlank(sender)) {
        try {/*from w  ww .  j av a 2 s. com*/
            message.setFrom(new InternetAddress(sender));

        } catch (AddressException ex) {
            logger.log(Level.SEVERE, "Sender address is not a valid mail address" + sender, ex);
        } catch (MessagingException ex) {
            logger.log(Level.SEVERE, "Can't create message for Sender: " + sender + " due to", ex);
        }

    }

    List<Address> addresses = new ArrayList<Address>();

    String receivers = emails.getReceivers();
    receivers = StringUtils.trim(receivers);

    for (String receiver : receivers.split(";")) {
        if (!StringUtils.isBlank(receiver)) {
            try {
                addresses.add(new InternetAddress(receiver));
            } catch (AddressException ex) {
                logger.log(Level.SEVERE, "Receiver address is not a valid mail address" + receiver, ex);
            } catch (MessagingException ex) {
                logger.log(Level.SEVERE, "Can't create message for Receiver: " + receiver + " due to", ex);
            }
        }
    }
    Address[] add = new Address[addresses.size()];
    addresses.toArray(add);
    try {
        message.addRecipients(Message.RecipientType.TO, add);

        // Set Subject: header field
        message.setSubject("[Pundit Contact Form]: " + subject);

        // Now set the actual message
        message.setText("Subject: " + subject + " \n" + "From: " + nameFrom + " (email: " + emailFrom + ") \n"
                + "Date: " + new Date() + "\n" + "IP: " + ip + "\n" + "Text: \n" + text);

    } catch (MessagingException ex) {
        logger.log(Level.SEVERE, "Can't create message for Recipient: " + add + " due to", ex);
    }
    // Send message

    try {
        logger.log(Level.INFO, "Trying to send message to receivers: {0}",
                Arrays.toString(message.getAllRecipients()));
        transport = session.getTransport("smtp");
        transport.connect(host, sender, password);
        transport.sendMessage(message, message.getAllRecipients());
        logger.log(Level.INFO, "Sent messages to all receivers {0}",
                Arrays.toString(message.getAllRecipients()));
    } catch (NoSuchProviderException nspe) {
        logger.log(Level.SEVERE, "Cannot find smtp provider", nspe);
    } catch (MessagingException me) {
        logger.log(Level.SEVERE, "Cannot set transport layer ", me);
    } finally {
        try {

            transport.close();
        } catch (MessagingException ex) {

        } catch (NullPointerException ne) {
        }

    }

}

From source file:com.thinkbiganalytics.feedmgr.nifi.PropertyExpressionResolver.java

/**
 * Resolves the variables in the value of the specified property.
 *
 * @param property the property/*from   w  ww  .j  a  v  a2 s .  co m*/
 * @param metadata the feed
 * @return the result of the transformation
 */
private ResolveResult resolveVariables(@Nonnull final NifiProperty property,
        @Nonnull final FeedMetadata metadata) {
    // Filter blank values
    final String value = property.getValue();
    if (StringUtils.isBlank(value)) {
        return new ResolveResult(false, false);
    }

    final boolean[] hasConfig = { false };
    final boolean[] isModified = { false };

    StrLookup resolver = new StrLookup() {
        @Override
        public String lookup(String variable) {
            // Resolve configuration variables
            final String configValue = getConfigurationPropertyValue(property, variable);
            if (configValue != null && property.getValue() != null
                    && !property.getValue().equalsIgnoreCase(configValue)) {
                hasConfig[0] = true;
                isModified[0] = true;
                //if this is the first time we found the config var, set the template value correctly
                if (!property.isContainsConfigurationVariables()) {
                    property.setTemplateValue(property.getValue());
                    property.setContainsConfigurationVariables(true);
                }
                return configValue;

            }

            // Resolve metadata variables
            try {
                final String metadataValue = getMetadataPropertyValue(metadata, variable);
                if (metadataValue != null) {
                    isModified[0] = true;
                    return metadataValue;
                }
            } catch (Exception e) {
                log.error("Unable to resolve variable: " + variable, e);
            }

            return null;
        }
    };
    StrSubstitutor ss = new StrSubstitutor(resolver);
    ss.setEnableSubstitutionInVariables(true);
    //escape
    String val = StringUtils.trim(ss.replace(value));
    //fix
    property.setValue(val);

    return new ResolveResult(hasConfig[0], isModified[0]);
}

From source file:de.micromata.genome.gwiki.model.filter.GWikiFilters.java

public void init(GWikiWeb wikiWeb, GWikiGlobalConfig wikiConfig) {
    List<String> regClasses = wikiConfig.getStringList("GWIKI_FILTER_CLASSES");
    final List<GWikiPluginFilterDescriptor> pluginFilters = wikiWeb.getDaoContext().getPluginRepository()
            .getPluginFilters();//  w w w. j  a  v  a 2 s .c  o  m
    List<String> allClasses = getSortedClasses(regClasses, pluginFilters);
    for (String rc : allClasses) {
        rc = StringUtils.trim(rc);
        if (StringUtils.isEmpty(rc) == true) {
            continue;
        }
        try {
            registerFilter(wikiWeb, ClassUtils.classForName(rc));
        } catch (Throwable ex) {
            GWikiLog.warn("Cannot register filter class: " + rc + "; " + ex.getMessage(), ex);
        }
    }
    initTextExtractors(wikiWeb, wikiConfig);
}

From source file:net.lmxm.ute.configuration.ConfigurationReader.java

/**
 * Parses the Maven artifact.//from   ww  w. j av  a  2s.c  o  m
 *
 * @param mavenArtifactType the Maven artifact type
 *
 * @return the file
 */
private MavenArtifact parseMavenArtifact(final MavenArtifactType mavenArtifactType) {
    final String prefix = "parseMavenArtifact() :";

    LOGGER.debug("{} entered", prefix);

    MavenArtifact mavenArtifact = new MavenArtifact();

    mavenArtifact.setCoordinates(StringUtils.trim(mavenArtifactType.getCoordinates()));
    mavenArtifact.setTargetName(StringUtils.trim(mavenArtifactType.getTargetName()));

    if (mavenArtifact.isEmpty()) {
        mavenArtifact = null;
    }

    LOGGER.debug("{} returning {}", prefix, mavenArtifact);

    return mavenArtifact;
}

From source file:com.neophob.sematrix.core.glue.Collector.java

/**
 * load a saved preset./* w  w  w.j  a  v  a2  s .c  om*/
 *
 * @param preset the new current status
 */
public void setCurrentStatus(List<String> preset) {
    LOG.log(Level.FINEST, "--------------");
    long start = System.currentTimeMillis();
    setLoadingPresent(true);
    for (String s : preset) {
        s = StringUtils.trim(s);
        s = StringUtils.removeEnd(s, ";");
        LOG.log(Level.FINEST, "LOAD PRESET: " + s);
        MessageProcessor.processMsg(StringUtils.split(s, ' '), false, null);
    }
    setLoadingPresent(false);
    long needed = System.currentTimeMillis() - start;
    LOG.log(Level.INFO, "Preset loaded in " + needed + "ms");
}