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.spqr.resman.node.SPQRNodeManager.java

/**
 * De-registers the referenced node //from   ww w  . ja va2  s.co m
 * @param nodeId
 * @return
 */
public NodeDeRegistrationResponse deregisterNode(final String nodeId) {

    /////////////////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(nodeId))
        return new NodeDeRegistrationResponse("", NodeDeRegistrationState.MISSING_NODE_ID, "");
    String id = StringUtils.lowerCase(StringUtils.trim(nodeId));
    if (!this.processingNodes.containsKey(id))
        return new NodeDeRegistrationResponse(nodeId, NodeDeRegistrationState.NO_SUCH_NODE_ID,
                "Unknown node id: " + nodeId);
    //
    /////////////////////////////////////////////////////////////////////////////

    final SPQRNodeClient client = this.processingNodes.remove(id);
    if (client != null)
        client.shutdown();

    return new NodeDeRegistrationResponse(nodeId, NodeDeRegistrationState.OK, "");
}

From source file:com.stefanbrenner.droplet.service.impl.XMPMetadataService.java

/**
 * A new raw file was created in the watched folder. A new xmp file with the
 * same filename as the raw file is created and the metadata gets added to
 * it. If an output folder is set, both files are finally moved to that
 * folder./*from  w  w w  .  ja  v  a 2 s.c  o  m*/
 * 
 * @param rawFile
 *            the new raw file
 */
@Override
public void onFileCreate(final File rawFile) {

    dropletContext.addLoggingMessage(Messages.getString("ProcessingPanel.newRAWFileFound", rawFile.getName()));

    try {
        // create xmp file
        File xmpFile = com.stefanbrenner.droplet.utils.FileUtils.newFileBasedOn(rawFile, "xmp");

        // fill with metadata
        XMPMeta xmpMeta = XMPMetaFactory.create();

        /* Keywords */
        for (String tag : StringUtils.split(metadata.getTags(), ',')) {
            xmpMeta.appendArrayItem(SCHEMA_DC, "dc:subject", new PropertyOptions().setArray(true),
                    StringUtils.trim(tag), null);
        }

        /* Title and Description */
        // xmpMeta.setLocalizedText(schemaDc, "dc:title",
        // "x-default", "x-default", "Droplet Title");
        String description = StringUtils.trim(metadata.getDescription());
        description += "\n\n" + TITLE;
        description += "\n" + Configuration.getMessageProtocolProvider().getName();
        description += "\n" + dropletContext.getLastSetMessage();
        xmpMeta.setLocalizedText(SCHEMA_DC, "dc:description", "x-default", "x-default", description);

        // final String NS_DRP = "http://www.droplet.com/schema/1.0/";
        // REGISTRY.registerNamespace(NS_DRP, "drp");
        //
        // for (IActionDevice device :
        // dropletContext.getDroplet().getDevices(IActionDevice.class)) {
        // xmpMeta.appendArrayItem(NS_DRP, "device", new
        // PropertyOptions().setArray(true),
        // "Device " + device.getName(), null);
        // for (IAction action : device.getEnabledActions()) {
        // xmpMeta.appendArrayItem(NS_DRP, "action", new
        // PropertyOptions().setArray(true),
        // "Action " + action.getOffset(), null);
        // }
        // }

        /* UserComments */
        xmpMeta.setProperty(SCHEMA_EXIF, "exif:UserComment",
                "This picture was created with the help of Droplet - Toolkit for Liquid Art Photographer");

        // write to file
        FileOutputStream fos = FileUtils.openOutputStream(xmpFile);
        XMPMetaFactory.serialize(xmpMeta, fos, new SerializeOptions(SerializeOptions.OMIT_PACKET_WRAPPER));
        fos.close();

        dropletContext
                .addLoggingMessage(Messages.getString("ProcessingPanel.newXMPFileCreated", xmpFile.getName()));

        if (outputFolderURI != null) {
            File outputFolder = new File(outputFolderURI);
            FileUtils.moveFileToDirectory(xmpFile, outputFolder, false);
            FileUtils.moveFileToDirectory(rawFile, outputFolder, false);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (XMPException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.micromata.genome.logging.spi.ifiles.IndexHeader.java

private void parse(MappedByteBuffer mem, long fileSize) {
    fileType = new byte[INDEX_FILE_TYPE.length];
    fileVersion = new byte[INDEX_FILE_VERSION.length];
    //    mem.position(0);
    int pos = 0;//  ww w .  j  a v a2 s . com
    NIOUtils.getBytes(mem, pos, fileType);
    pos += fileType.length;
    NIOUtils.getBytes(mem, pos, fileVersion);
    pos += fileVersion.length;
    created = mem.getLong(pos);
    pos += Long.BYTES;
    indexDirectoryIdx = mem.getInt(pos);
    pos += Integer.BYTES;
    startIndex = mem.getInt(pos);
    pos += Integer.BYTES;

    int max = startIndex - (Integer.BYTES + HEADER_NAME_LENGTH);
    int offset = 0;
    while (pos < max) {
        String headerName = NIOUtils.readAsciiString(mem, pos, HEADER_NAME_LENGTH);
        pos += HEADER_NAME_LENGTH;
        int fieldLength = mem.getInt(pos);
        pos += Integer.BYTES;
        headerName = StringUtils.trim(headerName);
        headerOrder.add(Pair.make(headerName, fieldLength));
        searchFieldsLength.put(headerName, fieldLength);
        searchFieldsOffsets.put(headerName, offset);
        offset += fieldLength + 1;
    }
}

From source file:com.hubrick.vertx.s3.signature.AWS4SignatureBuilder.java

public AWS4SignatureBuilder canonicalQueryString(final String canonicalQueryString) {
    final String defaultString = StringUtils.defaultString(canonicalQueryString);

    // this way of parsing the query string is the only way to satisfy the
    // test-suite, therefore we do it with a matcher:
    final Matcher matcher = QUERY_STRING_MATCHING_PATTERN.matcher(defaultString);
    final List<KeyValue<String, String>> parameters = Lists.newLinkedList();

    while (matcher.find()) {
        final String key = StringUtils.trim(matcher.group(1));
        final String value = StringUtils.trim(matcher.group(2));
        parameters.add(new DefaultKeyValue<>(key, value));
    }/*ww w  .  j ava  2  s .  co m*/

    this.canonicalQueryString = parameters.stream().sorted(Comparator.comparing(KeyValue::getKey))
            .map(kv -> queryParameterEscape(kv.getKey()) + "=" + queryParameterEscape(kv.getValue()))
            .collect(Collectors.joining("&"));

    return this;
}

From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineFactory.java

/**
 * Instantiates the {@link MicroPipeline} according to the provided {@link MicroPipelineComponentConfiguration} 
 * @param cfg/*from   ww w.j  av a  2s.  c om*/
 * @param executorService
 * @return
 * @throws RequiredInputMissingException
 * TODO validate micro pipeline for path from source to emitter
 */
public MicroPipeline instantiatePipeline(final MicroPipelineConfiguration cfg,
        final ExecutorService executorService) throws RequiredInputMissingException,
        QueueInitializationFailedException, ComponentInitializationFailedException {

    ///////////////////////////////////////////////////////////////////////////////////
    // validate input
    if (cfg == null)
        throw new RequiredInputMissingException("Missing required configuration");
    if (StringUtils.isBlank(cfg.getId()))
        throw new RequiredInputMissingException("Missing required micro pipeline id");
    if (cfg.getComponents() == null || cfg.getComponents().isEmpty())
        throw new RequiredInputMissingException("Missing required component configurations");
    if (cfg.getQueues() == null || cfg.getQueues().isEmpty())
        throw new RequiredInputMissingException("Missing required queue configurations");
    //
    ///////////////////////////////////////////////////////////////////////////////////

    MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
            StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "queue", "messages");

    final MetricsHandler metricsHandler = new MetricsHandler();
    MetricsReporterFactory.attachReporters(metricsHandler, cfg.getMetricsReporter());

    ///////////////////////////////////////////////////////////////////////////////////
    // (1) initialize queues

    // keep track of all ready created queue instances and create a new one for each configuration
    // entry. if creation fails for any reason, all previously created queues are shut down and
    // a queue initialization exception is thrown
    MicroPipeline microPipeline = new MicroPipeline(StringUtils.lowerCase(StringUtils.trim(cfg.getId())), cfg);
    for (final StreamingMessageQueueConfiguration queueConfig : cfg.getQueues()) {
        String id = StringUtils.lowerCase(StringUtils.trim(queueConfig.getId()));

        // a queue for that identifier already exists: kill the pipeline and tell the caller about it
        if (microPipeline.hasQueue(id)) {
            logger.error("queue initialization failed [id=" + id + "]. Forcing shutdown of all queues.");
            microPipeline.shutdown();
            throw new QueueInitializationFailedException("Non-unique queue identifier found [id=" + id + "]");
        }

        // try to instantiate the queue, if it fails .... shutdown queues initialized so far and throw an exception
        try {
            StreamingMessageQueue queueInstance = initializeQueue(queueConfig);

            /////////////////////////////////////////////////////////////////////
            // add queue message insertion and retrieval counters
            if (queueConfig.isAttachInsertionCounter()) {
                final Counter queueInsertionCounter = metricsHandler.counter(
                        MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
                                StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "queue", id, "messages",
                                "in"),
                        true);
                queueInstance.setMessageInsertionCounter(queueInsertionCounter);

                if (logger.isDebugEnabled())
                    logger.debug("queue[id=" + id + "]: message insertion counter attached");
            }

            if (queueConfig.isAttachRetrievalCounter()) {
                final Counter queueRetrievalCounter = metricsHandler.counter(
                        MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
                                StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "queue", id, "messages",
                                "out"),
                        true);
                queueInstance.setMessageRetrievalCounter(queueRetrievalCounter);

                if (logger.isDebugEnabled())
                    logger.debug("queue[id=" + id + "]: message retrieval counter attached");
            }
            /////////////////////////////////////////////////////////////////////

            microPipeline.addQueue(id, queueInstance);
            logger.info("queue initialized[id=" + id + "]");
        } catch (Exception e) {
            logger.error("queue initialization failed [id=" + id + "]. Forcing shutdown of all queues.");
            microPipeline.shutdown();
            throw new QueueInitializationFailedException(
                    "Failed to initialize queue [id=" + id + "]. Reason: " + e.getMessage(), e);
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////////////////////////
    // (2) initialize components
    final Map<String, MicroPipelineComponent> components = new HashMap<>();
    boolean sourceComponentFound = false;
    boolean emitterComponentFound = false;
    for (final MicroPipelineComponentConfiguration componentCfg : cfg.getComponents()) {
        String id = StringUtils.lowerCase(StringUtils.trim(componentCfg.getId()));

        // a component for that identifier already exists: kill the pipeline and tell the caller about it
        if (microPipeline.hasComponent(id)) {
            logger.error("component initialization failed [id=" + id + ", class=" + componentCfg.getName()
                    + ", version=" + componentCfg.getVersion()
                    + "]. Forcing shutdown of all queues and components.");
            microPipeline.shutdown();
            throw new ComponentInitializationFailedException(
                    "Non-unique component identifier found [id=" + id + "]");
        }

        // try to instantiate component, if it fails .... shutdown queues and components initialized so far and throw an exception
        try {
            MicroPipelineComponent component = initializeComponent(componentCfg, microPipeline.getQueues());
            if (component.getType() == null) {
                logger.error("component initialization failed [id=" + id + ", class=" + componentCfg.getName()
                        + ", version=" + componentCfg.getVersion()
                        + "]. Type missing. Forcing shutdown of all queues and components.");
                microPipeline.shutdown();
                throw new ComponentInitializationFailedException(
                        "Failed to initialize component [id=" + id + ", class=" + componentCfg.getName()
                                + ", version=" + componentCfg.getVersion() + "]. Reason: type missing");
            }

            final StreamingMessageQueue fromQueue = microPipeline
                    .getQueue(StringUtils.lowerCase(StringUtils.trim(componentCfg.getFromQueue())));
            final StreamingMessageQueue toQueue = microPipeline
                    .getQueue(StringUtils.lowerCase(StringUtils.trim(componentCfg.getToQueue())));

            Counter messageCounter = null;
            if (componentCfg.isAttachMessageCounter()) {
                messageCounter = metricsHandler.counter(
                        MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
                                StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "component", id,
                                "messages", "count"),
                        true);
            }

            switch (component.getType()) {
            case SOURCE: {
                SourceRuntimeEnvironment srcEnv = new SourceRuntimeEnvironment(this.processingNodeId,
                        cfg.getId(), (Source) component, toQueue.getProducer());

                ///////////////////////////////////////////////
                // attach monitoring components
                if (messageCounter != null)
                    srcEnv.setMessageCounter(messageCounter);
                ///////////////////////////////////////////////

                microPipeline.addSource(id, srcEnv);
                sourceComponentFound = true;
                break;
            }
            case DIRECT_RESPONSE_OPERATOR: {

                DirectResponseOperatorRuntimeEnvironment directResponseEnv = new DirectResponseOperatorRuntimeEnvironment(
                        this.processingNodeId, cfg.getId(), (DirectResponseOperator) component,
                        fromQueue.getConsumer(), toQueue.getProducer());

                ///////////////////////////////////////////////
                // attach monitoring components
                if (componentCfg.isAttachProcessingTimer()) {
                    final Timer messageProcessingTimer = metricsHandler.timer(
                            MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
                                    StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "component", id,
                                    "messages", "timer"));
                    directResponseEnv.setMessageProcessingTimer(messageProcessingTimer);
                }

                if (messageCounter != null)
                    directResponseEnv.setMessageCounter(messageCounter);
                ///////////////////////////////////////////////

                microPipeline.addOperator(id, directResponseEnv);
                break;
            }
            case DELAYED_RESPONSE_OPERATOR: {
                DelayedResponseOperatorRuntimeEnvironment delayedResponseEnv = new DelayedResponseOperatorRuntimeEnvironment(
                        this.processingNodeId, cfg.getId(), (DelayedResponseOperator) component,
                        getResponseWaitStrategy(componentCfg), fromQueue.getConsumer(), toQueue.getProducer(),
                        executorService);

                ///////////////////////////////////////////////
                // attach monitoring components
                if (messageCounter != null)
                    delayedResponseEnv.setMessageCounter(messageCounter);
                ///////////////////////////////////////////////

                microPipeline.addOperator(id, delayedResponseEnv);
                break;
            }
            case EMITTER: {
                EmitterRuntimeEnvironment emitterEnv = new EmitterRuntimeEnvironment(this.processingNodeId,
                        cfg.getId(), (Emitter) component, fromQueue.getConsumer());

                ///////////////////////////////////////////////
                // attach monitoring components
                if (componentCfg.isAttachProcessingTimer()) {
                    final Timer messageEmitDurationTimer = metricsHandler.timer(
                            MetricRegistry.name(StringUtils.lowerCase(StringUtils.trim(this.processingNodeId)),
                                    StringUtils.lowerCase(StringUtils.trim(cfg.getId())), "component", id,
                                    "messages", "emit", "duration"));
                    emitterEnv.setMessageEmitDurationTimer(messageEmitDurationTimer);
                }

                if (messageCounter != null)
                    emitterEnv.setMessageCounter(messageCounter);
                ///////////////////////////////////////////////

                microPipeline.addEmitter(id, emitterEnv);
                emitterComponentFound = true;
                break;
            }
            }

            components.put(id, component);
        } catch (Exception e) {
            logger.error("component initialization failed [id=" + id + ", class=" + componentCfg.getName()
                    + ", version=" + componentCfg.getVersion()
                    + "]. Forcing shutdown of all queues and components. Reason: " + e.getMessage(), e);
            microPipeline.shutdown();
            throw new ComponentInitializationFailedException(
                    "Failed to initialize component [id=" + id + ", class=" + componentCfg.getName()
                            + ", version=" + componentCfg.getVersion() + "]. Reason: " + e.getMessage(),
                    e);
        }
    }

    if (!sourceComponentFound) {
        microPipeline.shutdown();
        throw new RequiredInputMissingException("Missing required source component");
    }

    if (!emitterComponentFound) {
        microPipeline.shutdown();
        throw new RequiredInputMissingException("Missing required emitter component");
    }

    ///////////////////////////////////////////////////////////////////////////////////

    microPipeline.attachComponentMetricsHandler(metricsHandler);

    ///////////////////////////////////////////////////////////////////////////////////
    // (3) start components --> ramp up their runtime environments 
    for (String sourceId : microPipeline.getSources().keySet()) {
        executorService.submit(microPipeline.getSources().get(sourceId));
        if (logger.isDebugEnabled())
            logger.debug("Started runtime environment for source [id=" + sourceId + "]");
    }
    for (String directResponseOperatorId : microPipeline.getDirectResponseOperators().keySet()) {
        executorService.submit(microPipeline.getDirectResponseOperators().get(directResponseOperatorId));
        if (logger.isDebugEnabled())
            logger.debug("Started runtime environment for direct response operator [id="
                    + directResponseOperatorId + "]");
    }
    for (String delayedResponseOperatorId : microPipeline.getDelayedResponseOperators().keySet()) {
        executorService.submit(microPipeline.getDelayedResponseOperators().get(delayedResponseOperatorId));
        if (logger.isDebugEnabled())
            logger.debug("Started runtime environment for delayed response operator [id="
                    + delayedResponseOperatorId + "]");
    }
    for (String emitterId : microPipeline.getEmitters().keySet()) {
        executorService.submit(microPipeline.getEmitters().get(emitterId));
        if (logger.isDebugEnabled())
            logger.debug("Started runtime environment for emitter [id=" + emitterId + "]");
    }

    if (logger.isDebugEnabled())
        logger.debug("Started stats collector");
    //
    ///////////////////////////////////////////////////////////////////////////////////

    return microPipeline;
}

From source file:cop.raml.processor.RestProcessorTest.java

@Test
public void shouldWorkCorrectlyForNoCommentedSources_v08() throws IOException, URISyntaxException {
    File dir = getResourceAsFile("spring/empty");
    ThreadLocalContext.setConfig(Config.builder().apiMediaType("application/json").ramlDev(true)
            .ramlShowExample(false).ramlVersion(RAML_0_8).build());

    runAnnotationProcessor(dir);//  w w w .  j a  v  a2 s .  c  o m

    //        System.out.println("----------");
    //        System.out.println(DevUtils.getRaml());
    //        System.out.println("----------");

    String actual = DevUtils.getRaml();
    String expected = StringUtils.trim(TestUtils.getResourceAsString("v0.8/empty.raml"));
    TestUtils.assertThatEquals(actual, expected);
}

From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineValidator.java

/**
 * Validates the provided {@link StreamingMessageQueueConfiguration} for being compliant with basic requirements
 * set for queues inside {@link MicroPipelineConfiguration}
 * @param queueCfg//from   w w  w . j  a v  a2  s .  c  o  m
 * @param queueIdentifiers
 * @return
 */
protected MicroPipelineValidationResult validateQueue(final StreamingMessageQueueConfiguration queueCfg,
        final Set<String> queueIdentifiers) {

    // the queue configuration must not be null ... for obvious reasons ;-)
    if (queueCfg == null)
        return MicroPipelineValidationResult.MISSING_QUEUE_CONFIGURATION;

    // queue identifier must neither be null nor empty
    if (StringUtils.isBlank(queueCfg.getId()))
        return MicroPipelineValidationResult.MISSING_QUEUE_ID;

    // convert to trimmed lower-case representation and check if it is unique
    String tempId = StringUtils.lowerCase(StringUtils.trim(queueCfg.getId()));
    if (queueIdentifiers.contains(tempId))
        return MicroPipelineValidationResult.NON_UNIQUE_QUEUE_ID;

    return MicroPipelineValidationResult.OK;
}

From source file:com.ottogroup.bi.asap.resman.node.ProcessingNodeManager.java

/**
 * De-Registers the referenced processing node from the internal handler map. The node is expected to be shut down already
 * and thus no corresponding message is sent towards it
 * @param processingNodeId/*from ww  w  .  j  a  v a 2 s.  c  om*/
 * @throws RequiredInputMissingException
 */
public String deregisterProcessingNode(final String processingNodeId)
        throws RequiredInputMissingException, UnknownProcessingNodeException {

    ///////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(processingNodeId))
        throw new RequiredInputMissingException("Missing processing node identifier");
    String pid = StringUtils.lowerCase(StringUtils.trim(processingNodeId));
    if (!this.processingNodes.containsKey(pid))
        throw new UnknownProcessingNodeException(
                "Referenced processing node '" + processingNodeId + "' unknown to node manager");
    //
    ///////////////////////////////////////////////////////

    final ProcessingNode node = this.processingNodes.remove(pid);

    if (logger.isDebugEnabled())
        logger.debug("processing node deregistered [id=" + node.getId() + ", protocol=" + node.getProtocol()
                + ", host=" + node.getHost() + ", servicePort=" + node.getServicePort() + ", adminPort="
                + node.getAdminPort() + "]");

    return processingNodeId;
}

From source file:com.ottogroup.bi.asap.component.operator.executor.OperatorExecutor.java

/**
 * Unsubscribes the referenced subscriber from operator
 * @param subscriberId/*from   w w  w.  jav  a 2s  .c om*/
 * @throws RequiredInputMissingException
 */
public void unsubscribe(final String subscriberId) throws RequiredInputMissingException {

    ///////////////////////////////////////////////////////////////////////////
    // validate input
    if (StringUtils.isBlank(subscriberId))
        throw new RequiredInputMissingException("Missing required subscriber identifier");
    //
    ///////////////////////////////////////////////////////////////////////////

    this.subscriberMailboxes.remove(StringUtils.trim(StringUtils.lowerCase(subscriberId)));
}

From source file:com.ottogroup.bi.spqr.metrics.MetricsHandler.java

/**
 * Registers a new {@link JmxReporter}. 
 * @param id//  w  w w . j  ava2  s . c o m
 * @param reporterInstance reporter instance (must have been started)
 * @throws RequiredInputMissingException
 */
public void addJmxReporter(final String id, final JmxReporter reporterInstance)
        throws RequiredInputMissingException {

    ////////////////////////////////////////////////////////////////
    // input validation
    if (StringUtils.isBlank(id))
        throw new RequiredInputMissingException("Missing required reporter identifier");
    if (reporterInstance == null)
        throw new RequiredInputMissingException("Missing required reporter instance");
    ////////////////////////////////////////////////////////////////

    this.jmxReporters.put(StringUtils.lowerCase(StringUtils.trim(id)), reporterInstance);
}