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

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

Introduction

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

Prototype

public static String lowerCase(final String str) 

Source Link

Document

Converts a String to lower case as per String#toLowerCase() .

A null input String returns null .

 StringUtils.lowerCase(null)  = null StringUtils.lowerCase("")    = "" StringUtils.lowerCase("aBc") = "abc" 

Note: As described in the documentation for String#toLowerCase() , the result of this method is affected by the current locale.

Usage

From source file:com.mirth.connect.client.ui.util.SQLParserUtil.java

public String[] Parse() {
    try {//from ww  w.j  a v a 2s .  c o  m
        List<String> varList = new ArrayList<String>();

        Pattern pattern = Pattern.compile(SQL_PATTERN, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(_sqlStatement);
        while (matcher.find()) {
            String key = matcher.group();
            int fromClause = key.toUpperCase().indexOf(" FROM ");

            if (fromClause > 0) {
                String columnText = key.substring(6, fromClause).replaceAll("`", "");
                columnText = removeNestedFunctions(columnText, 0);

                String[] vars = columnText.split(",");

                for (int i = 0; i < vars.length; i++) {
                    if (vars[i].length() > 0) {
                        for (int j = 0; j < keywords.length; j++) {
                            int index = vars[i].toUpperCase().indexOf(keywords[j]);
                            int size = (keywords[j]).length();
                            if (index != -1) {
                                if (index > 0) {
                                    if (vars[i].substring(index - 1, index).equals(" ")
                                            && (vars[i].length() == index + size || vars[i]
                                                    .substring(index + size, index + size + 1).equals(" "))) {
                                        vars[i] = vars[i].replaceAll(vars[i].substring(index, index + size),
                                                "");
                                    }
                                } else if (vars[i].length() == index + size
                                        || vars[i].substring(index + size, index + size + 1).equals(" ")) {
                                    vars[i] = vars[i].replaceAll(vars[i].substring(index, index + size), "");
                                }
                            }
                        }
                        if (vars[i].length() > 0) {
                            String var;

                            if (vars[i].toUpperCase().indexOf(" AS ") != -1) {
                                var = (vars[i].substring(vars[i].toUpperCase().indexOf(" AS ") + 4))
                                        .replaceAll(" ", "").replaceAll("\\(", "").replaceAll("\\)", "");
                            } else if (vars[i].indexOf('(') != -1 || vars[i].indexOf(')') != -1
                                    || vars[i].indexOf('}') != -1 || vars[i].indexOf('{') != -1
                                    || vars[i].indexOf('*') != -1) {
                                continue;
                            } else {
                                vars[i] = vars[i].trim();
                                var = vars[i].replaceAll(" ", "").replaceAll("\\(", "").replaceAll("\\)", "");

                                if (var.lastIndexOf('.') != -1) {
                                    var = var.substring(var.lastIndexOf('.') + 1);
                                }
                            }

                            if ((StringUtils.substring(var, 0, 1).equals("\"")
                                    && StringUtils.substring(var, -1).equals("\""))
                                    || (StringUtils.substring(var, 0, 1).equals("'")
                                            && StringUtils.substring(var, -1).equals("'"))) {
                                var = StringUtils.substring(var, 1, -1);
                            }

                            if ((StringUtils.substring(var, 0, 2).equals("\\\"")
                                    && StringUtils.substring(var, -2).equals("\\\""))
                                    || (StringUtils.substring(var, 0, 2).equals("\\'")
                                            && StringUtils.substring(var, -2).equals("\\'"))) {
                                var = StringUtils.substring(var, 2, -2);
                            }

                            var = StringUtils.lowerCase(var);

                            varList.add(var);
                        }
                    }
                }
            }
        }
        return varList.toArray(new String[varList.size()]);
    } catch (Exception e) {
        logger.error(e);
    }
    return new String[0];
}

From source file:com.ottogroup.bi.spqr.resman.node.SPQRNodeManager.java

/**
 * De-registers the referenced node //  w  w  w.  j  av a  2  s.c o 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:gov.nih.nci.caintegrator.web.action.analysis.biodbnet.BioDbNetSearchAction.java

/**
 * Generates the search inputs in the following manner if case insensitivity has been selected.
 *  - the original inputs//from  ww  w . ja v a2 s . c o m
 *  - inputs are transformed to all upper case
 *  - inputs are transformed to all lower case
 *  - inputs are transformed to 1st letter upper case, all others lower case
 * @return the transformed input strings as comma separated values
 */
private Set<String> handleCaseSensitivity(SearchParameters searchParams) {
    Set<String> inputs = Sets.newTreeSet();
    if (searchParams.isCaseSensitiveSearch() || searchParams.getSearchType() == SearchType.GENE_ID) {
        CollectionUtils.addAll(inputs, StringUtils.split(searchParams.getInputValues(), ','));
        return inputs;
    }
    String[] splitInputs = StringUtils.split(searchParams.getInputValues(), ',');
    for (String input : splitInputs) {
        inputs.add(input);
        inputs.add(StringUtils.upperCase(input));
        inputs.add(StringUtils.lowerCase(input));
        inputs.add(StringUtils.capitalize(input));
    }
    return inputs;
}

From source file:fr.scc.elo.controller.EloController.java

@GET
@Path("/match/winners/{w}/loosers/{l}/score/{s}/type/{t}/create/{c}")
@ApiOperation(value = "gerer le score d'un match", notes = "calcule l'evolution du elo de chaque joueur suite a un match", response = MatchResponse.class)
public Response manageMatch(@BeanParam MatchRequest request, @Context HttpServletRequest http)
        throws EloException {
    try {/*from   w w  w .  ja  v  a 2 s  .  c om*/
        if (!connectionService.acceptIPUpdate(http.getRemoteAddr())) {
            throw new EloException("Unauthorized IP: " + http.getRemoteAddr());
        }
        MatchResponse response = eloManager.manageMatch(StringUtils.lowerCase(request.getWinnerList()),
                StringUtils.lowerCase(request.getLooserList()), request.getScore(), request.getTypeMatch(),
                request.getCreatePlayers());
        return Response.ok().entity(response.toString()).build();
    } catch (Exception e) {
        return Response.ok().entity(e.getMessage()).build();
    }
}

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

public static Country safeValueOf(String string) {
    if (StringUtils.isNotBlank(string)) {
        string = StringUtils.replaceChars(string, " _", "");
        string = StringUtils.lowerCase(string);
        for (Country c : values()) {
            if (c.hardcoded.equals(string)) {
                return c;
            }/*from  w  w w  .j a  v a 2s  . c om*/
        }
    }
    return null;
}

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  ava2s.  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:io.seqware.pipeline.plugins.FileProvenanceQueryTool.java

@Override
public ReturnValue do_run() {
    Path randomTempDirectory = null;
    Path originalReport = null;/*from   www  . j a  v a2s. c  o m*/
    Path bulkImportFile = null;
    try {
        if (options.has(this.inFileSpec)) {
            originalReport = FileSystems.getDefault().getPath(options.valueOf(inFileSpec));
        } else {
            originalReport = populateOriginalReportFromWS();
        }

        List<String> headers;
        List<Boolean> numericDataType;
        // construct column name and datatypes
        // convert file provenance report into derby bulk load format
        try (BufferedReader originalReader = Files.newBufferedReader(originalReport,
                Charset.defaultCharset())) {
            // construct column name and datatypes
            String headerLine = originalReader.readLine();
            headers = Lists.newArrayList();
            numericDataType = Lists.newArrayList();
            for (String column : headerLine.split("\t")) {
                String editedColumnName = StringUtils.lowerCase(column).replaceAll(" ", "_").replaceAll("-",
                        "_");
                headers.add(editedColumnName);
                // note that Parent Sample SWID is a silly column that has colons in it
                numericDataType.add(
                        !editedColumnName.contains("parent_sample") && (editedColumnName.contains("swid")));
            }
            bulkImportFile = Files.createTempFile("import", "txt");
            try (BufferedWriter derbyImportWriter = Files.newBufferedWriter(bulkImportFile,
                    Charset.defaultCharset())) {
                Log.debug("Bulk import file written to " + bulkImportFile.toString());
                while (originalReader.ready()) {
                    String line = originalReader.readLine();
                    StringBuilder builder = new StringBuilder();
                    int i = 0;
                    for (String colValue : line.split("\t")) {
                        if (i != 0) {
                            builder.append("\t");
                        }
                        if (numericDataType.get(i)) {
                            if (!colValue.trim().isEmpty()) {
                                builder.append(colValue);
                            }
                        } else {
                            // assume that this is a string
                            // need to double quotes to preserve them, see
                            // https://db.apache.org/derby/docs/10.4/tools/ctoolsimportdefaultformat.html
                            builder.append("\"").append(colValue.replaceAll("\"", "\"\"")).append("\"");
                        }
                        i++;
                    }
                    derbyImportWriter.write(builder.toString());
                    derbyImportWriter.newLine();
                }
            }
        }
        randomTempDirectory = Files.createTempDirectory("randomFileProvenanceQueryDir");

        // try using in-memory for better performance
        String protocol = "jdbc:h2:";
        if (options.has(useH2InMemorySpec)) {
            protocol = protocol + "mem:";
        }
        Connection connection = spinUpEmbeddedDB(randomTempDirectory, "org.h2.Driver", protocol);

        // drop table if it exists already (running in IDE?)
        Statement dropTableStatement = null;
        try {
            dropTableStatement = connection.createStatement();
            dropTableStatement.executeUpdate("DROP TABLE " + TABLE_NAME);
        } catch (SQLException e) {
            Log.debug("Report table didn't exist (normal)");
        } finally {
            DbUtils.closeQuietly(dropTableStatement);
        }

        // create table creation query
        StringBuilder tableCreateBuilder = new StringBuilder();
        // tableCreateBuilder
        tableCreateBuilder.append("CREATE TABLE " + TABLE_NAME + " (");
        for (int i = 0; i < headers.size(); i++) {
            if (i != 0) {
                tableCreateBuilder.append(",");
            }
            if (numericDataType.get(i)) {
                tableCreateBuilder.append(headers.get(i)).append(" INT ");
            } else {
                tableCreateBuilder.append(headers.get(i)).append(" VARCHAR ");
            }
        }
        tableCreateBuilder.append(")");

        bulkImportH2(tableCreateBuilder, connection, bulkImportFile);

        // query the database and dump the results to
        try (BufferedWriter outputWriter = Files.newBufferedWriter(Paths.get(options.valueOf(outFileSpec)),
                Charset.defaultCharset(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
            // query the database and dump the results to
            QueryRunner runner = new QueryRunner();
            List<Map<String, Object>> mapList = runner.query(connection, options.valueOf(querySpec),
                    new MapListHandler());
            // output header
            if (mapList.isEmpty()) {
                Log.fatal("Query had no results");
                System.exit(-1);
            }
            StringBuilder builder = new StringBuilder();
            for (String columnName : mapList.get(0).keySet()) {
                if (builder.length() != 0) {
                    builder.append("\t");
                }
                builder.append(StringUtils.lowerCase(columnName));
            }
            outputWriter.append(builder);
            outputWriter.newLine();
            for (Map<String, Object> rowMap : mapList) {
                StringBuilder rowBuilder = new StringBuilder();
                for (Entry<String, Object> e : rowMap.entrySet()) {
                    if (rowBuilder.length() != 0) {
                        rowBuilder.append("\t");
                    }
                    rowBuilder.append(e.getValue());
                }
                outputWriter.append(rowBuilder);
                outputWriter.newLine();
            }
        }
        DbUtils.closeQuietly(connection);
        Log.stdoutWithTime("Wrote output to " + options.valueOf(outFileSpec));
        return new ReturnValue();
    } catch (IOException | SQLException | ClassNotFoundException | InstantiationException
            | IllegalAccessException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (originalReport != null) {
            FileUtils.deleteQuietly(originalReport.toFile());
        }
        if (bulkImportFile != null) {
            FileUtils.deleteQuietly(bulkImportFile.toFile());
        }
        if (randomTempDirectory != null && randomTempDirectory.toFile().exists()) {
            FileUtils.deleteQuietly(randomTempDirectory.toFile());
        }

    }
}

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  .ja  va2 s .com
 * @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 w  w  w . ja 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.spqr.metrics.MetricsHandler.java

/**
 * Registers a new {@link JmxReporter}. 
 * @param id/*from   w w  w. ja  v  a 2  s  .com*/
 * @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);
}