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

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

Introduction

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

Prototype

public static String[] splitPreserveAllTokens(String str, String separatorChars) 

Source Link

Document

Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators.

Usage

From source file:com.npower.dm.export.XMLWriter4Software.java

private void writeFile4Package(SoftwarePackage softwarePackage) throws IOException, SQLException, DMException {
    if (softwarePackage.getBinary() != null) {
        String oldfileName = softwarePackage.getBlobFilename();
        String[] str = StringUtils.splitPreserveAllTokens(oldfileName, '.');
        String newfileName = str[0] + "." + softwarePackage.getId() + "." + str[1];
        File file = new File(System.getProperty("otas.dm.home"), "./output/softwares/packages");
        if (!file.exists()) {
            file.mkdirs();//from  w  w w .ja v  a 2s .c  om
        }
        file = new File(file, newfileName);
        FileOutputStream fos = new FileOutputStream(file);
        Blob binaryBlob = softwarePackage.getBinary().getBinaryBlob();
        fos.write(binaryBlob.getBytes(1, (int) binaryBlob.length()));
        fos.close();
    } else {
        throw new DMException("file of softwarePackage is null");
    }
}

From source file:com.npower.dm.model.TestGenerateModelXMLByCSV.java

/**
 * @param filename//from  w  w w . j  a v  a 2 s  .c  o  m
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 */
private Map<String, TreeSet<String>> loadData(String filename) throws FileNotFoundException, IOException {
    // Load Manufacturers
    Map<String, TreeSet<String>> maps = new HashMap<String, TreeSet<String>>();
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line = reader.readLine();
    String[] manufacturers = StringUtils.splitPreserveAllTokens(line, ',');
    for (int i = 0; i < manufacturers.length; i++) {
        maps.put(manufacturers[i].trim(), new TreeSet<String>());
    }

    // Load models
    line = reader.readLine();
    while (line != null) {
        String[] models = StringUtils.splitPreserveAllTokens(line, ',');
        for (int i = 0; i < models.length; i++) {
            if (StringUtils.isNotEmpty(models[i])) {
                maps.get(manufacturers[i].trim()).add(models[i]);
            }
        }
        line = reader.readLine();
    }

    reader.close();
    return maps;
}

From source file:com.haulmont.cuba.core.global.MetadataTools.java

/**
 * Return a collection of properties included into entity's name pattern (see {@link NamePattern}).
 *
 * @param metaClass   entity metaclass//from   w  w w. ja  v a 2  s.  c  o  m
 * @param useOriginal if true, and if the given metaclass doesn't define a {@link NamePattern} and if it is an
 *                    extended entity, this method tries to find a name pattern in an original entity
 * @return collection of the name pattern properties
 */
@Nonnull
public Collection<MetaProperty> getNamePatternProperties(MetaClass metaClass, boolean useOriginal) {
    Collection<MetaProperty> properties = new ArrayList<>();
    String pattern = (String) getMetaAnnotationAttributes(metaClass.getAnnotations(), NamePattern.class)
            .get("value");
    if (pattern == null && useOriginal) {
        MetaClass original = metadata.getExtendedEntities().getOriginalMetaClass(metaClass);
        if (original != null) {
            pattern = (String) getMetaAnnotationAttributes(original.getAnnotations(), NamePattern.class)
                    .get("value");
        }
    }
    if (!StringUtils.isBlank(pattern)) {
        String value = StringUtils.substringAfter(pattern, "|");
        String[] fields = StringUtils.splitPreserveAllTokens(value, ",");
        for (String field : fields) {
            String fieldName = StringUtils.trim(field);

            MetaProperty property = metaClass.getProperty(fieldName);
            if (property != null) {
                properties.add(metaClass.getProperty(fieldName));
            } else {
                throw new DevelopmentException(
                        String.format("Property '%s' is not found in %s", field, metaClass.toString()),
                        "NamePattern", pattern);
            }
        }
    }
    return properties;
}

From source file:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
 * Paste data from clipboard into spreadsheet.
 * Currently only implemented for string data.
 *//*from  w ww .j a  v a 2s . co  m*/
public void paste() {
    //System.out.println("Trying to Paste");
    int[] rows = getSelectedRows();
    int[] cols = getSelectedColumns();
    pastedRows[0] = -1;
    pastedRows[1] = -1;
    if (rows != null && cols != null && rows.length > 0 && cols.length > 0) {
        int startRow = rows[0];
        pastedRows[0] = startRow;
        int startCol = cols[0];
        try {
            Clipboard sysClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
            if (sysClipboard.isDataFlavorAvailable(DataFlavor.stringFlavor)) {
                String trstring = (String) sysClipboard.getData(DataFlavor.stringFlavor);
                StringTokenizer st1 = new StringTokenizer(trstring, "\n\r");
                for (int i = 0; st1.hasMoreTokens(); i++) {
                    String rowstring = st1.nextToken();
                    //System.out.println("Row [" + rowstring+"]");
                    String[] tokens = StringUtils.splitPreserveAllTokens(rowstring, '\t');
                    for (int j = 0; j < tokens.length; j++) {
                        if (startRow + i < getRowCount() && startCol + j < getColumnCount()) {
                            int colInx = startCol + j;
                            if (tokens[j].length() <= model.getColDataLen(colInx)) {
                                String token = tokens[j];
                                if ("\b".equals(token)) //is placeholder for empty cell
                                {
                                    token = "";
                                }
                                setValueAt(token, startRow + i, colInx);
                            } else {
                                String msg = String.format(getResourceString("UI_NEWDATA_TOO_LONG"),
                                        new Object[] { model.getColumnName(startCol + j),
                                                model.getColDataLen(colInx) });
                                UIRegistry.getStatusBar().setErrorMessage(msg);
                                Toolkit.getDefaultToolkit().beep();
                            }
                        }
                        //System.out.println("Putting [" + tokens[j] + "] at row=" + startRow + i + "column=" + startCol + j);
                    }
                    pastedRows[1] = pastedRows[1] + 1;
                }
            }
        } catch (IllegalStateException ex) {
            UIRegistry.displayStatusBarErrMsg(getResourceString("Spreadsheet.ClipboardUnavailable"));
        } catch (Exception ex) {
            edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
            edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(SpreadSheet.class, ex);
            ex.printStackTrace();
        }
    }
}

From source file:edu.ku.brc.specify.web.SpecifyExplorer.java

/**
 * @param out/*from w  ww  .jav  a2  s .c  om*/
 * @param pointsStr
 * @param sortByCE
 */
protected void createMap(final PrintWriter out, final String pointsStr, final boolean sortByCE) {
    DataProviderSessionIFace session = null;
    try {
        session = DataProviderFactory.getInstance().createSession();

        String mapTemplate = "";
        try {
            File templateFile = new File(
                    UIRegistry.getDefaultWorkingPath() + File.separator + "site/map_template.html");
            mapTemplate = FileUtils.readFileToString(templateFile);

        } catch (IOException ex) {
            ex.printStackTrace();
            out.println(ex.toString());
        }

        if (StringUtils.isEmpty(template)) {
            out.println("The template file is empty!");
        }

        int inx = mapTemplate.indexOf(contentTag);
        String subContent = mapTemplate.substring(0, inx);
        out.println(StringUtils.replace(subContent, "<!-- Title -->", "Mapping Collection Objects"));

        String[] points = StringUtils.splitPreserveAllTokens(pointsStr, ';');
        /*System.out.println("["+pointsStr+"]");
        for (int i=0;i<points.length;i++)
        {
        System.out.println("i["+i+"]Loc["+points[i]+"] CO["+points[i+1]+"]");
        i++;
        }*/

        double maxLat = Double.MIN_VALUE;
        double minLat = Double.MAX_VALUE;

        double maxLon = Double.MIN_VALUE;
        double minLon = Double.MAX_VALUE;

        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Hashtable<Locality, CollectingEvent> locToCE = new Hashtable<Locality, CollectingEvent>();

        boolean drawLines = false;

        Hashtable<CollectingEvent, CEForPoly> hash = new Hashtable<CollectingEvent, CEForPoly>();
        StringBuilder locStr = new StringBuilder();

        int locCnt = 0;
        for (int i = 0; i < points.length; i++) {
            //System.out.println("i["+i+"]Loc["+points[i]+"]");
            if (StringUtils.isEmpty(points[i])) {
                break;
            }

            //String title = "";
            Locality locality = (Locality) session.createQuery("from Locality WHERE id = " + points[i], false)
                    .list().get(0);
            if (locality != null) {
                StringBuilder sb = new StringBuilder();
                String[] colObjsIds = StringUtils.splitPreserveAllTokens(points[i + 1], ',');
                for (String id : colObjsIds) {
                    //System.out.println("co["+id+"]");
                    if (StringUtils.isNotEmpty(id)) {
                        CollectionObject co = (CollectionObject) session
                                .createQuery("from CollectionObject WHERE id = " + id, false).list().get(0);
                        if (co != null) {
                            CollectingEvent ce = co.getCollectingEvent();
                            if (ce != null) {
                                CollectingEvent colEv = locToCE.get(locality);
                                if (colEv == null) {
                                    locToCE.put(locality, ce);

                                } else if (!ce.getCollectingEventId().equals(colEv.getCollectingEventId())) {
                                    drawLines = false;
                                }
                                //sb.append("<h3>"+sdf.format(ce.getStartDate().getTime())+"</h3>");
                                Locality loc = ce.getLocality();
                                if (loc != null && loc.getLatitude1() != null && loc.getLongitude1() != null) {
                                    CEForPoly cep = hash.get(ce);
                                    if (cep == null) {
                                        cep = new CEForPoly(ce.getStartDate(), loc.getLatitude1().doubleValue(),
                                                loc.getLongitude1().doubleValue(), "");
                                        hash.put(ce, cep);
                                    }
                                    cep.getColObjs().add(co);
                                }
                            }
                            for (Determination det : co.getDeterminations()) {
                                if (det.isCurrentDet()) {
                                    Taxon txn = det.getPreferredTaxon();
                                    if (txn != null) {
                                        sb.append("<a href='SpecifyExplorer?cls=CollectionObject&id="
                                                + co.getCollectionObjectId() + "'>" + txn.getFullName()
                                                + "</a>");
                                        sb.append("<br/>");
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }

                if (locality.getLatitude1() != null && locality.getLongitude1() != null) {
                    if (locCnt == 0) {
                        maxLat = locality.getLatitude1().doubleValue();
                        minLat = maxLat;

                        maxLon = locality.getLongitude1().doubleValue();
                        minLon = maxLon;

                    } else {
                        maxLat = Math.max(maxLat, locality.getLatitude1().doubleValue());
                        minLat = Math.min(minLat, locality.getLatitude1().doubleValue());

                        maxLon = Math.max(maxLon, locality.getLongitude1().doubleValue());
                        minLon = Math.min(minLon, locality.getLongitude1().doubleValue());
                    }

                    locStr.append("var point = new GLatLng(" + locality.getLatitude1() + ","
                            + locality.getLongitude1() + ");\n");
                    locStr.append("var marker = createMarker(point,\"" + locality.getLocalityName() + "\",\""
                            + sb.toString() + "\");\n");
                    locStr.append("map.addOverlay(marker);\n");
                    locCnt++;
                }

            }
            i++;
        }

        System.out.println("maxLat: " + maxLat);
        System.out.println("minLat: " + minLat);
        System.out.println("maxLon: " + maxLon);
        System.out.println("minLon: " + minLon);

        double halfLat = (maxLat - minLat) / 2;
        double halfLon = (maxLon - minLon) / 2;
        System.out.println("halfLat: " + halfLat);
        System.out.println("halfLon: " + halfLon);

        int zoom = 2;
        if (halfLat == 0.0 && halfLon == 0.0) {
            zoom = 12;

        } else if (halfLat < 0.5 && halfLon < 0.5) {
            zoom = 10;

        } else if (halfLat < 2.0 && halfLon < 2.0) {
            zoom = 8;

        } else if (halfLat < 7.0 && halfLon < 7.0) {
            zoom = 6;
        }

        out.println("        map.setCenter(new GLatLng( " + (minLat + halfLat) + "," + (minLon + halfLon)
                + "), " + zoom + ");\n");

        out.println(locStr.toString());

        if (drawLines) {
            if (hash.size() > 0) {
                out.println("var polyline = new GPolyline([");
                for (CEForPoly cep : hash.values()) {
                    out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
                }
            }
            out.println("], \"#FF0000\", 5);\n");
            out.println("map.addOverlay(polyline);\n");

        }

        if (false) {
            out.println("var polygon = new GPolygon([");
            for (CEForPoly cep : hash.values()) {
                out.println("new GLatLng(" + cep.getLat() + ", " + cep.getLon() + "),\n");
            }
            out.println("], \"#ff0000\", 5, 0.7, \"#0000ff\", 0.4);\n");
            out.println("map.addOverlay(polygon);\n");
        }

        out.println(mapTemplate.substring(inx + contentTag.length() + 1, mapTemplate.length()));

    } catch (Exception ex) {
        ex.printStackTrace();

    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:edu.ku.brc.specify.dbsupport.SpecifySchemaUpdateService.java

/**
 * //from  w  w w.j  a va  2s.c om
 */
public static void addNewAttachmentTables(final Connection conn) {
    File sqlFile = XMLHelper.getConfigDir("new_attch_tables.sql");
    try {
        String str = FileUtils.readFileToString(sqlFile);
        String[] stmts = StringUtils.splitPreserveAllTokens(str, ';');
        for (String sql : stmts) {
            String[] toks = StringUtils.splitPreserveAllTokens(sql, '`');
            if (toks.length == 73) {
                if (!BasicSQLUtils.doesTableExist(conn, toks[1])) {
                    int rv = BasicSQLUtils.update(conn, sql);
                    System.out.println("rv = " + rv);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.ku.brc.specify.utilapps.BuildSampleDatabase.java

/**
 * @param treeDef//from   www.  j a  va2 s. com
 * @return
 */
public LithoStrat convertLithoStratFromCSV(final LithoStratTreeDef treeDef) {
    Hashtable<String, LithoStrat> lithoStratHash = new Hashtable<String, LithoStrat>();

    lithoStratHash.clear();

    File file = new File("demo_files/Stratigraphy.csv");
    if (!file.exists()) {
        log.error("Couldn't file[" + file.getAbsolutePath() + "] checking the config dir");
        file = XMLHelper.getConfigDir("Stratigraphy.csv");
        if (!file.exists()) {
            file = new File("Specify/demo_files/Stratigraphy.csv");
        }
    }

    if (file == null || !file.exists()) {
        log.error("Couldn't file[" + file.getAbsolutePath() + "]");
        return null;
    }

    List<String> lines = null;
    try {
        lines = FileUtils.readLines(file);

    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }

    startTx();

    // setup the root Geography record (planet Earth)
    LithoStrat earth = new LithoStrat();
    earth.initialize();
    earth.setName(getResourceString("Earth"));
    earth.setFullName(earth.getName());
    earth.setNodeNumber(1);
    earth.setHighestChildNodeNumber(1);
    earth.setRankId(0);
    earth.setDefinition(treeDef);
    LithoStratTreeDefItem defItem = treeDef.getDefItemByRank(0);
    earth.setDefinitionItem(defItem);

    persist(earth);

    frame.setDesc("Adding Stratigraphy Objects");
    frame.setProcess(0, lines.size());

    int counter = 0;
    // for each old record, convert the record
    for (String line : lines) {
        if (counter == 0) {
            counter = 1;
            continue; // skip header line
        }

        if (counter % 100 == 0) {
            frame.setProcess(counter);
            log.info("Converted " + counter + " Stratigraphy records");
        }

        String[] columns = StringUtils.splitPreserveAllTokens(line, ',');
        if (columns.length < 7) {
            log.error("Skipping[" + line + "]");
            continue;
        }

        // grab the important data fields from the old record
        String superGroup = columns[2];
        String lithoGroup = columns[3];
        String formation = columns[4];
        String member = columns[5];
        String bed = columns[6];

        // create a new Litho Stratigraphy object from the old data
        @SuppressWarnings("unused")
        LithoStrat newStrat = convertOldStratRecord(superGroup, lithoGroup, formation, member, bed, earth);

        counter++;
    }

    frame.setProcess(counter);

    log.info("Converted " + counter + " Stratigraphy records");

    TreeHelper.fixFullnameForNodeAndDescendants(earth);
    earth.setNodeNumber(1);
    fixNodeNumbersFromRoot(earth);

    commitTx();

    /*startTx();
    TreeHelper.fixFullnameForNodeAndDescendants(earth);
    earth.setNodeNumber(1);
    fixNodeNumbersFromRoot(earth);
            
    printTree(earth, 0);
    saveTree(earth);
            
    commitTx();*/

    log.info("Converted " + counter + " Stratigraphy records");

    // set up Geography foreign key mapping for locality
    lithoStratHash.clear();

    return earth;
}

From source file:org.apache.archiva.repository.content.maven2.RepositoryRequest.java

/**
 * <p>/*from  ww  w .  j a  v a 2  s . co m*/
 * Tests the path to see if it conforms to the expectations of a default layout request.
 * </p>
 * <p>
 * NOTE: This does a cursory check on the count of path elements only.  A result of
 * true from this method is not a guarantee that the path sections are valid and
 * can be resolved to an artifact reference.  use {@link #toArtifactReference(String)}
 * if you want a more complete analysis of the validity of the path.
 * </p>
 *
 * @param requestedPath the path to test.
 * @return true if the requestedPath is likely that of a default layout request.
 */
public boolean isDefault(String requestedPath) {
    if (StringUtils.isBlank(requestedPath)) {
        return false;
    }

    String pathParts[] = StringUtils.splitPreserveAllTokens(requestedPath, '/');
    if (pathParts.length > 3) {
        return true;
    } else if (pathParts.length == 3) {
        // check if artifact-level metadata (ex. eclipse/jdtcore/maven-metadata.xml)
        if (isMetadata(requestedPath)) {
            return true;
        } else {
            // check if checksum of artifact-level metadata (ex. eclipse/jdtcore/maven-metadata.xml.sha1)
            int idx = requestedPath.lastIndexOf('.');
            if (idx > 0) {
                String base = requestedPath.substring(0, idx);
                if (isMetadata(base) && isSupportFile(requestedPath)) {
                    return true;
                }
            }

            return false;
        }
    } else {
        return false;
    }
}

From source file:org.apache.archiva.repository.content.maven2.RepositoryRequest.java

/**
 * <p>// w  w  w . j  a  v a2  s.com
 * Tests the path to see if it conforms to the expectations of a legacy layout request.
 * </p>
 * <p>
 * NOTE: This does a cursory check on the count of path elements only.  A result of
 * true from this method is not a guarantee that the path sections are valid and
 * can be resolved to an artifact reference.  use {@link #toArtifactReference(String)}
 * if you want a more complete analysis of the validity of the path.
 * </p>
 *
 * @param requestedPath the path to test.
 * @return true if the requestedPath is likely that of a legacy layout request.
 */
public boolean isLegacy(String requestedPath) {
    if (StringUtils.isBlank(requestedPath)) {
        return false;
    }

    String pathParts[] = StringUtils.splitPreserveAllTokens(requestedPath, '/');
    return pathParts.length == 3;
}

From source file:org.apache.click.extras.control.DateField.java

/**
 * Return the names of months and weekdays as a script.
 *//*from  w w  w .j a  v a  2s . c om*/
protected void addCalenderTranslations(List<Element> headElements) {
    JsScript script = new JsScript();
    script.setId("datefield-js-setup-global");
    if (!headElements.contains(script)) {
        DateFormatSymbols dfs = new DateFormatSymbols(getLocale());

        HtmlStringBuffer buffer = new HtmlStringBuffer(150);
        buffer.append("Date.months=new Array(");
        generateJavaScriptArray(buffer, dfs.getMonths(), 0, 12);
        buffer.append(");\n");

        buffer.append("Date.monthAbbreviations=new Array(");
        generateJavaScriptArray(buffer, dfs.getShortMonths(), 0, 12);
        buffer.append(");\n");

        buffer.append("Date.dayNames=new Array(");
        generateJavaScriptArray(buffer, dfs.getWeekdays(), Calendar.SUNDAY, Calendar.SATURDAY + 1);
        buffer.append(");\n");

        buffer.append("Date.dayAbbreviations=new Array(");
        generateJavaScriptArray(buffer, dfs.getShortWeekdays(), Calendar.SUNDAY, Calendar.SATURDAY + 1);
        buffer.append(");\n");

        String[] weekdays = null;
        if (getMessages().containsKey("calendar-weekdays-heading")) {
            String headings = getMessage("calendar-weekdays-heading");
            weekdays = StringUtils.splitPreserveAllTokens("," + headings, ',');
        } else {
            weekdays = dfs.getShortWeekdays();
        }
        String[] days = new String[7];
        int firstDayOfWeek = getFirstDayOfWeek() - 1;
        for (int i = 0; i < 7; i++) {
            days[i] = weekdays[(i + firstDayOfWeek) % 7 + 1];
        }
        buffer.append("Date.weekdays=new Array(");
        generateJavaScriptArray(buffer, days, 0, 7);
        buffer.append(");\n");

        buffer.append("Date.first_day_of_week=").append(firstDayOfWeek).append(";\n");
        if (getMessages().containsKey("calendar-ok")) {
            buffer.append("_translations[\"OK\"] = \"");
            buffer.append(getMessage("calendar-ok"));
            buffer.append("\";\n");
        }
        if (getMessages().containsKey("calendar-now")) {
            buffer.append("_translations[\"Now\"] = \"");
            buffer.append(getMessage("calendar-now"));
            buffer.append("\";\n");
        }
        if (getMessages().containsKey("calendar-today")) {
            buffer.append("_translations[\"Today\"] = \"");
            buffer.append(getMessage("calendar-today"));
            buffer.append("\";\n");
        }
        if (getMessages().containsKey("calendar-clear")) {
            buffer.append("_translations[\"Clear\"] = \"");
            buffer.append(getMessage("calendar-clear"));
            buffer.append("\";\n");
        }

        script.setContent(buffer.toString());
        headElements.add(script);
    }
}