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

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

Introduction

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

Prototype

public static String[] splitByWholeSeparator(final String str, final String separator) 

Source Link

Document

Splits the provided text into an array, separator string specified.

The separator(s) will not be included in the returned String array.

Usage

From source file:org.esigate.vars.DriverEsiWhenTest.java

@SuppressWarnings("static-method")
@Test/*from   w ww .jav  a2 s.  co  m*/
public void testEsiWhenCase1() throws IOException, HttpErrorPage {
    // Configuration
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/");

    // Test case
    IncomingRequest request = TestUtils
            .createRequest("http://test.mydomain.fr/foobar/?test=esigate&test2=esigate2")
            .addHeader("Referer", "http://www.esigate.org")
            .addHeader("User-Agent",
                    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) "
                            + "AppleWebKit/536.30.1 (KHTML, like Gecko) " + "Version/6.0.5 Safari/536.30.1")
            .addHeader("Accept-Language", "da, en-gb;q=0.8, en;q=0.7")
            .addCookie(new BasicClientCookie("test-cookie", "test-cookie-value"))
            .addCookie(new BasicClientCookie("test-cookie2", "test-cookie-value2")).build();

    final StringBuilder expected = new StringBuilder();
    addExpression(expected, "!(1==1)", false);
    addExpression(expected, "!(a==a)", false);
    addExpression(expected, "!(a==b)", true);
    addExpression(expected, "1==1", true);
    addExpression(expected, "1==01", true);
    addExpression(expected, "10==01", false);
    addExpression(expected, "a==a", true);
    addExpression(expected, "a==b", false);
    addExpression(expected, "2>=1", true);
    addExpression(expected, "1>=1", true);
    addExpression(expected, "b>=a", true);
    addExpression(expected, "a>=b", false);
    addExpression(expected, "2>1", true);
    addExpression(expected, "b>a", true);
    addExpression(expected, "1>2", false);
    addExpression(expected, "a>b", false);
    addExpression(expected, "2<1", false);
    addExpression(expected, "b<a", false);
    addExpression(expected, "1<2", true);
    addExpression(expected, "2<=1", false);
    addExpression(expected, "1<=2", true);
    addExpression(expected, "$(HTTP_COOKIE{test-cookie})==test-cookie-value", true);
    addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})==test-cookie-value", true);
    addExpression(expected, "$(HTTP_USER_AGENT{os})==MAC", true);
    addExpression(expected, "$(HTTP_USER_AGENT{os})=='MAC'", true);
    addExpression(expected, "$(HTTP_COOKIE{test-cookie})=='test-cookie-value'", true);
    addExpression(expected, "$(HTTP_COOKIE{test-cookie})!='test-cookie-not-this-value'", true);
    addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})=='test-cookie-value'", true);
    addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})!='test-cookie-not-this-value'", true);
    addExpression(expected, "$exists($(HTTP_COOKIE{test-cookie}))", true);
    addExpression(expected, "$exists($(HTTP_COOKIE{'test-cookie'}))", true);
    addExpression(expected, "$exists($(HTTP_COOKIE{fake-cookie}))", false);
    addExpression(expected, "$exists($(HTTP_COOKIE{'fake-cookie'}))", false);

    addExpression(expected, "$(HTTP_REFERER)==http://www.esigate.org", true);
    addExpression(expected, "$(HTTP_HOST)=='test.mydomain.fr'", true);
    addExpression(expected, "$(HTTP_HOST)==test.mydomain.fr", true);

    // Setup remote server (provider) response.
    IResponseHandler mockExecutor = new IResponseHandler() {
        @Override
        public HttpResponse execute(HttpRequest request) {

            StringBuilder content = new StringBuilder();

            String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>");

            for (String expr : expectedArray) {
                addExpression(content, expr.substring(0, expr.indexOf(": ")));
            }

            LOG.info("Backend response:\n" + content.toString());

            return TestUtils.createHttpResponse()
                    .entity(new StringEntity(content.toString(), ContentType.TEXT_HTML)).build();
        }

    };

    // Build driver and request.
    Driver driver = TestUtils.createMockDriver(properties, mockExecutor);

    CloseableHttpResponse response = TestUtils.driverProxy(driver, request, new EsiRenderer());

    String entityContent = EntityUtils.toString(response.getEntity());
    LOG.info("Esigate response: \n" + entityContent);

    String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>");
    String[] resultArray = StringUtils.splitByWholeSeparator(entityContent, "<p>");

    for (int i = 0; i < expectedArray.length; i++) {
        String varName = expectedArray[i].substring(0, expectedArray[i].indexOf(":"));
        Assert.assertEquals(varName, expectedArray[i], resultArray[i]);
        LOG.info("Success with variable {}", varName);
    }

}

From source file:org.finra.datagenerator.engine.scxml.tags.SetAssignExtension.java

/**
 * Performs variable assignments from a set of values
 *
 * @param action            a SetAssignTag Action
 * @param possibleStateList a current list of possible states produced so far from expanding a model state
 * @return the cartesian product of every current possible state and the set of values specified by action
 *//*w  w  w. j ava  2s .co  m*/
public List<Map<String, String>> pipelinePossibleStates(SetAssignTag action,
        List<Map<String, String>> possibleStateList) {
    if (action == null) {
        throw new NullActionException(
                "Called with a null action, and possibleStateList = " + possibleStateList.toString());
    }

    String variable = action.getName();
    String set = action.getSet();

    String[] domain;

    if (set == null) {
        throw new NullSetException("Called with a null set, action name=" + action.getName()
                + " and possibleStateList = " + possibleStateList.toString());
    }

    if (StringUtils.splitByWholeSeparator(set, action.getSeparator()).length == 0) {
        domain = new String[] { "" };
    } else {
        domain = StringUtils.splitByWholeSeparator(set, action.getSeparator());
    }

    //take the product
    List<Map<String, String>> productTemp = new LinkedList<>();
    for (Map<String, String> p : possibleStateList) {
        for (String value : domain) {
            HashMap<String, String> n = new HashMap<>(p);
            n.put(variable, value);
            productTemp.add(n);
        }
    }

    return productTemp;
}

From source file:org.guess.core.orm.PropertyFilter.java

/**
 * @param filterName ,???. //  www .java2  s . c o m
 *                   eg. LIKES_NAME_OR_LOGIN_NAME
 * @param value .
 */
public PropertyFilter(final String filterName, final String value) {

    String firstPart = StringUtils.substringBefore(filterName, "_");
    String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
    String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());

    try {
        matchType = Enum.valueOf(MatchType.class, matchTypeCode);
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    try {
        propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
    } catch (RuntimeException e) {
        throw new IllegalArgumentException(
                "filter??" + filterName + ",.", e);
    }

    String propertyNameStr = StringUtils.substringAfter(filterName, "_");
    AssertUtils.isTrue(StringUtils.isNotBlank(propertyNameStr),
            "filter??" + filterName + ",??.");
    propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);

    this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
}

From source file:org.ihtsdo.otf.refset.service.upload.ImportRF2Service.java

@Override
public Map<String, String> importFile(InputStream is, String refsetId, String user)
        throws RefsetServiceException, EntityNotFoundException {

    if (is == null || StringUtils.isBlank(refsetId)) {

        throw new IllegalArgumentException("Mandatory data ie file or refsetId is missing in request");
    }/*from   w  w  w .  ja va2s  .  co  m*/

    BufferedReader reader = null;
    try {

        reader = new BufferedReader(new InputStreamReader(is));

        String line;

        int row = 0;

        List<Rf2Record> rf2RLst = new ArrayList<Rf2Record>();

        while ((line = reader.readLine()) != null) {

            row++;

            if (StringUtils.isEmpty(line) || row == 1) {

                LOGGER.debug("Line {} is empty skipping", line);
                continue;

            }

            String[] columns = StringUtils.splitByWholeSeparator(line, "\t");

            if (columns != null & columns.length == 6) {

                Rf2Record rf2r = new Rf2Record();

                rf2r.setId(columns[0]);//Per Robert preserve uuid. No need to generate refset tool uuid instead of using RF2 file.
                rf2r.setEffectiveTime(fmt.parseDateTime(columns[1]));
                rf2r.setActive(columns[2]);
                rf2r.setModuleId(columns[3]);
                rf2r.setRefsetId(columns[4]);
                rf2r.setReferencedComponentId(columns[5]);
                rf2r.setCreatedBy(user);
                rf2r.setModifiedBy(user);
                rf2RLst.add(rf2r);

            } else {

                throw new RefsetServiceException("Insufficient data, no further processing is possible");

            }

        }

        return srp.process(rf2RLst, refsetId, user);

    } catch (IOException e) {

        throw new RefsetServiceException(e);

    } finally {

        try {

            reader.close();

        } catch (IOException e) {

            LOGGER.info("Could not close IO resources");
        }
    }
}

From source file:org.ihtsdo.otf.snomed.loader.Rf2SnapshotAuditor.java

public void audit(String file) {

    LOGGER.debug("Starting to audit file {}", file);
    long start = System.currentTimeMillis();
    long totalRow = 0;

    //need to change implementation from super csv to java io as RF2 description has buggy quotes
    BufferedReader reader = null;

    try {//from   www .  j  a  va2s  . c o  m

        if (StringUtils.isBlank(file)) {

            throw new IllegalArgumentException("Please check file supplied.");

        } else if (file.endsWith(".gz")) {

            reader = new BufferedReader(
                    new InputStreamReader(new GZIPInputStream(new FileInputStream(file)), "utf-8"));

        } else {

            reader = new BufferedReader(new FileReader(file));
        }

        LOGGER.debug("Starting to load file {}", file);

        String line;

        beginTx();
        int row = -1;
        DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyyMMdd");

        while ((line = reader.readLine()) != null) {

            row++;

            LOGGER.debug("Processing rowNo={} ", row);
            if (StringUtils.isEmpty(line)) {

                LOGGER.debug("rowNo={} , {} is empty skipping", row, line);

                continue;
            }

            String[] columns = StringUtils.splitByWholeSeparator(line, "\t");

            if (columns != null && columns.length == 9 && row != 0) {

                if (isReload) {

                    Vertex v = getVertex(g, columns[0]);

                    if (v != null) {

                        LOGGER.debug("Not Processing line={}, rowNo={} as record already loaded", line, row);
                        continue;
                    }
                }

                LOGGER.debug("Processing rowNo={} , {}", row, line);

                Rf2Description desc = new Rf2Description();
                //id   effectiveTime   active   moduleId   conceptId   languageCode   typeId   term   caseSignificanceId

                desc.setId(columns[0]);
                desc.setEffectiveTime(fmt.parseDateTime(columns[1]));
                desc.setActive(columns[2]);
                desc.setModuleId(columns[3]);
                desc.setConceptId(columns[4]);
                desc.setLanguageCode(columns[5]);
                desc.setTypeId(columns[6]);
                desc.setTerm(columns[7]);
                desc.setCaseSignificanceId(columns[8]);

                if (!isConceptTitleExist(desc)) {

                    auditDescription(desc);

                } else if (!StringUtils.isEmpty(subType)
                        && subType.equalsIgnoreCase(descMap.get(desc.getTypeId()).toString())
                        && !isSubTypeRelationExist(desc)) {

                    LOGGER.debug("Processing row {} of subType {}", row, subType);

                    processDescription(desc);

                } else {

                    LOGGER.debug("Not processing row {} of description id {}", row, desc.getId());

                }
            } else {

                LOGGER.debug("rowNo={}, {}  does not have required columns, skipping", row, line);
                continue;

            }

            commit(row);

        }
        LOGGER.info("Commiting remaining data");
        g.commit();//remaining operation commit
        totalRow = row;
    } catch (IOException e) {
        g.rollback();
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new RuntimeException("Can not process file", e);
    } catch (Exception e) {
        LOGGER.error("Transaction rolledback");
        g.rollback();
        e.printStackTrace();
        throw new RuntimeException(e);
    } finally {

        if (reader != null) {

            try {
                LOGGER.info("Closing IO resources");
                reader.close();
            } catch (IOException e) {

                LOGGER.error("Error closing bean reader");
                e.printStackTrace();

            }
        }
    }

    LOGGER.info("Total row {} processed in {} minute ", totalRow,
            ((System.currentTimeMillis() - start) / 60000));

}

From source file:org.openbizview.util.RunReport.java

/**
  * Este mtodo utiliza el BIRT engine para generar reportes
 * desde el API utilizando POJO./*w  w  w . ja va  2 s  . c o m*/
  * @param reporte: Nombre del reporte que es leyendo, debe ser .rptdesing
 * @parama format: Formato de salida: html, pdf, doc
 * @param ubicacionrep: Ubicacin del reporte
 * @param rutasalida: Salida del reporte ubicacin en disco
 * @param nbrreporte: nombre del reporte al momento de la salida
 * @param nbrreporte: nombre del reporte al momento de la salida
 * @param feccon
  **/
public void outReporteRecibo(String reporte, String format, String ubicacionrep, String rutasalida,
        String nbrreporte, Date feccon, String job, String paramnames, String paramvalues) {

    //Variables used to control BIRT Engine instance
    //Now, setup the BIRT engine configuration. The Engine Home is hardcoded
    EngineConfig config = new EngineConfig();
    //Create new Report engine based off of the configuration
    ReportEngine engine = new ReportEngine(config);
    IReportRunnable report = null;
    IRunAndRenderTask task;
    IRenderOption options = new RenderOption();
    //PDFRenderOption pdfOptions = new PDFRenderOption();
    final HashMap<String, Date> PARAMAMFECCON = new HashMap<String, Date>();

    PARAMAMFECCON.put("FECCON", feccon);

    //Lectura de parmeros dinmicos desde la tabla t_programacin
    //Funcin agregada para versin 5 de bizview 11/10/2014
    //Por los momentos solo se trabajar con Strings
    final HashMap<String, String> PARAMAMARRAY = new HashMap<String, String>();

    //Arreglo para longitud, se recibe como parmetro de longitud paramvalues
    //Con la libreria String utils se define el separador y con ello se conoce la longitud de los parametros
    //Por ejemplo recibe como parmetro P1|P2|P3, con separador '|', al recorrerlo devuelve longitud tres
    //Se va pasando al reporte cada parametro
    //DVConsultores Andrs Dominguez 18/08/2015
    String[] arraySplitSrtings = StringUtils.splitByWholeSeparator(paramvalues, "|");

    //Si la longitud de los valores de parmetros es diferente de cero
    //Procede a leer y pasar parmetros
    if (arraySplitSrtings.length > 0) {
        String[] arr1 = paramnames.split("\\|", -1);//Toma la lista de parametros de la tabla y hace un split, trabaja el arreglo y lo recorre
        String[] arr2 = paramvalues.split("\\|", -1);//Toma la lista de parametros de la tabla y hace un split, trabaja el arreglo y lo recorre
        for (int i = 0; i < arraySplitSrtings.length; i++) {
            PARAMAMARRAY.put(arr1[i], arr2[i]);
        }

    } //Valida longitud 

    //

    //With our new engine, lets try to open the report design
    try {
        report = engine.openReportDesign(ubicacionrep + File.separator + reporte + ".rptdesign");
    } catch (Exception e) {
        //msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
        //          FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
        // System.exit(-1);
    }

    //With the file open, create the Run and Render task to run the report
    task = engine.createRunAndRenderTask(report);

    //This will set the output file location, the format to render to, and
    //apply to the task
    //System.out.println(format);
    options.setOutputFormat(format);
    options.setOutputFileName(rutasalida + File.separator + nbrreporte + "." + format);
    task.setRenderOption(options);

    try {

        task.setParameterValues(PARAMAMFECCON);
        task.setParameterValues(PARAMAMARRAY);
        task.validateParameters();
        task.run();
    } catch (Exception e) {
        //msj = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
        //FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
        //System.exit(-1);
    }

    //Yeah, we finished. Now destroy the engine and let the garbage collector
    //do its thing
    //System.out.println("Reporte ejecutado : " + nbrreporte);
    engine.destroy();
    task.close();
}

From source file:org.pepstock.jem.ant.tasks.utilities.sort.DefaultComparator.java

/**
 * Loads commands from COMMAND data description
 * /* w w w .  j  av  a  2s  . c  o m*/
 * @param records lines of data set
 * @throws ParseException if there is a mistake on command
 */
private void loadCommands(String records) throws ParseException {
    // splits all words and rejoins removing useless spaces
    String[] s = StringUtils.split(records, " ");
    String commandLine = StringUtils.join(s);
    LogAppl.getInstance().emit(AntMessage.JEMA045I, commandLine);

    // splits command with bracket and comma
    String[] s1 = StringUtils.splitByWholeSeparator(commandLine, "),");
    for (int i = 0; i < s1.length; i++) {
        Object[] result = null;
        // if ends with bracket, uses asis
        // otherwise adds a bracket
        String command = s1[i].endsWith(")") ? s1[i] : s1[i] + ")";
        // parses in cascade mode all message formats
        // first that matches creates result
        // otherwise there is a parse exception
        try {
            result = MESSAGE_FORMAT_1.parse(command);
        } catch (ParseException e) {
            try {
                result = MESSAGE_FORMAT_2.parse(command);
            } catch (ParseException e1) {
                try {
                    result = MESSAGE_FORMAT_2_STRING.parse(command);
                } catch (ParseException e2) {
                    try {
                        result = MESSAGE_FORMAT_1_STRING.parse(command);
                    } catch (ParseException e3) {
                        LogAppl.getInstance().emit(AntMessage.JEMA046W, e3, command, e3.getMessage());
                        throw e3;
                    }
                }
            }
        }
        // if has result, creates a comparator
        // and adds it to a collection
        if (result != null) {
            SingleComparator c;
            try {
                c = createSingleComparator(result);
                comparators.add(c);
            } catch (ParseException e) {
                LogAppl.getInstance().emit(AntMessage.JEMA046W, e, command, e.getMessage());
                throw e;
            }

        }
    }

}

From source file:org.structr.common.PathHelper.java

/**
 * Return array of path parts.//  ww w .  j  a  v  a2s .  c om
 * 
 * @param path
 * @return path parts
 */
public static String[] getParts(final String path) {

    String cleanedPath = clean(path);

    return StringUtils.splitByWholeSeparator(cleanedPath, PATH_SEP);
}

From source file:org.wikipedia.nirvana.nirvanabot.NewPages.java

public void analyzeOldText(NirvanaWiki wiki, String text, Data d, NewPagesBuffer buffer) throws IOException {
    log.debug("analyzing old text");
    String oldText = text;/*  ww w  . j  av a 2s  . c o m*/
    String[] oldItems;

    // remove {{bots|allow=}} record
    String botsAllowString = NirvanaWiki.getAllowBotsString(text);

    log.debug("analyzing old text -> trancate header/footer/middle");
    oldText = extractBotsAllowString(oldText, botsAllowString);
    oldText = trimRight(oldText, footerLastUsed);
    oldText = trimLeft(oldText, headerLastUsed);
    oldText = trimMiddle(oldText, middleLastUsed);

    //FileTools.dump(footer, "dump", this.pageName +".footer.txt");

    oldItems = StringUtils.splitByWholeSeparator(oldText, delimeter); // removes empty items
    if (delimeter.equals("\n"))
        log.debug("delimeter is \\n");
    else if (delimeter.equals("\r"))
        log.debug("delimeter is \\r");
    else
        log.debug("delimeter is \"" + delimeter + "\"");

    log.debug("analyzing old text -> parse items, len = " + oldItems.length);

    d.oldCount = oldItems.length;
    int pos = 0;
    while (pos < oldItems.length && UPDATE_FROM_OLD && buffer.size() < maxItems) {
        ArrayList<PageInfo> bunch = new ArrayList<PageInfo>(WIKI_API_BUNCH_SIZE);
        for (; bunch.size() < WIKI_API_BUNCH_SIZE && pos < oldItems.length; pos++) {
            String item = oldItems[pos];
            if (item.isEmpty())
                continue;
            log.trace("check old line: \t" + item + "");
            if (buffer.checkIsDuplicated(item)) {
                log.debug("SKIP old line: \t" + item);
                continue;
            }
            bunch.add(new PageInfo(item));
        }
        if (this.deletedFlag == PortalParam.Deleted.REMOVE || this.deletedFlag == PortalParam.Deleted.MARK) {
            checkDeleted(wiki, bunch);
        }
        int j = 0;
        for (; j < bunch.size() && buffer.size() < maxItems; j++) {
            String item = bunch.get(j).item;
            if (this.deletedFlag == PortalParam.Deleted.REMOVE && !bunch.get(j).exists) {
                log.debug("REMOVE old line: \t" + item);
                d.deletedCount++;
            } else {
                if (this.deletedFlag == PortalParam.Deleted.MARK) {
                    item = bunch.get(j).exists ? unmarkDeleted(item) : markDeleted(item);
                }
                log.debug("ADD old line: \t" + item);
                buffer.addOldItem(item);
            }
        }
        pos = pos - bunch.size() + j;
    }
    for (; pos < oldItems.length; pos++) {
        String item = oldItems[pos];
        if (item.isEmpty())
            continue;
        log.trace("check old line: \t" + item + "");
        if (buffer.checkIsDuplicated(item)) {
            log.debug("SKIP old line: \t" + item);
            continue;
        }
        log.debug("ARCHIVE old line:" + item);
        if (UPDATE_ARCHIVE && archive != null) {
            d.archiveItems.add(item);
        }
        d.archiveCount++;
    }
    log.debug("bots allow string: " + botsAllowString);
    if (!botsAllowString.isEmpty()) {
        botsAllowString = botsAllowString + "\n";
    }
    d.newText = buffer.getNewText(botsAllowString);
}

From source file:stepReport.model.ConnectionDB.java

public void loadValues() throws IOException {
    try {// w  w w .jav  a2 s  .co m
        BufferedReader br = new BufferedReader(new FileReader("config.cfg"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();
            while (line != null) {
                sb.append(line);
                sb.append(lineSeparator());
                line = br.readLine();
            }

            String[] separated = StringUtils.splitByWholeSeparator(sb.toString(), " ");
            ConnectionDB.serverName = separated[0];
            ConnectionDB.user = separated[1];
            ConnectionDB.password = separated[2];

            ConnectionDB.url = "jdbc:mysql://" + ConnectionDB.serverName + "/" + ConnectionDB.dbName;

        } finally {
            br.close();
        }
    } catch (java.io.FileNotFoundException ex) {
        JOptionPane.showMessageDialog(new JFrame(),
                "Erro: Configurar os dados do Servidor antes de realizar a busca");
    }

}