List of usage examples for org.apache.commons.lang StringUtils countMatches
public static int countMatches(String str, String sub)
Counts how many times the substring appears in the larger String.
From source file:de.tudarmstadt.ukp.clarin.webanno.tsv.WebannoTsv1Reader.java
/** * Iterate through all lines and get available annotations<br> * First column is sentence number and a blank new line marks end of a sentence<br> * The Second column is the token <br> * The third column is the lemma annotation <br> * The fourth column is the POS annotation <br> * The fifth column is used for Named Entity annotations (Multiple annotations separeted by | * character) <br>//from w ww . j ava 2s. co m * The sixth column is the origin token number of dependency parsing <br> * The seventh column is the function/type of the dependency parsing <br> * eighth and ninth columns are undefined currently */ private void setAnnotations(InputStream aIs, String aEncoding, StringBuilder text, Map<Integer, String> tokens, Map<Integer, String> pos, Map<Integer, String> lemma, Map<Integer, String> namedEntity, Map<Integer, String> dependencyFunction, Map<Integer, Integer> dependencyDependent, List<Integer> firstTokenInSentence) throws IOException { int tokenNumber = 0; boolean first = true; int base = 0; LineIterator lineIterator = IOUtils.lineIterator(aIs, aEncoding); boolean textFound = false; StringBuffer tmpText = new StringBuffer(); while (lineIterator.hasNext()) { String line = lineIterator.next().trim(); if (line.startsWith("#text=")) { text.append(line.substring(6) + "\n"); textFound = true; continue; } if (line.startsWith("#")) { continue;// it is a comment line } int count = StringUtils.countMatches(line, "\t"); if (line.isEmpty()) { continue; } if (count != 9) {// not a proper TSV file getUimaContext().getLogger().log(Level.INFO, "This is not a valid TSV File"); throw new IOException(fileName + " This is not a valid TSV File"); } StringTokenizer lineTk = new StringTokenizer(line, "\t"); if (first) { tokenNumber = Integer.parseInt(line.substring(0, line.indexOf("\t"))); firstTokenInSentence.add(tokenNumber); first = false; } else { int lineNumber = Integer.parseInt(line.substring(0, line.indexOf("\t"))); if (lineNumber == 1) { base = tokenNumber; firstTokenInSentence.add(base); } tokenNumber = base + Integer.parseInt(line.substring(0, line.indexOf("\t"))); } while (lineTk.hasMoreElements()) { lineTk.nextToken(); String token = lineTk.nextToken(); // for backward compatibility tmpText.append(token + " "); tokens.put(tokenNumber, token); lemma.put(tokenNumber, lineTk.nextToken()); pos.put(tokenNumber, lineTk.nextToken()); String ne = lineTk.nextToken(); lineTk.nextToken();// make it compatible with prev WebAnno TSV reader namedEntity.put(tokenNumber, (ne.equals("_") || ne.equals("-")) ? "O" : ne); String dependentValue = lineTk.nextToken(); if (NumberUtils.isDigits(dependentValue)) { int dependent = Integer.parseInt(dependentValue); dependencyDependent.put(tokenNumber, dependent == 0 ? 0 : base + dependent); dependencyFunction.put(tokenNumber, lineTk.nextToken()); } else { lineTk.nextToken(); } lineTk.nextToken(); lineTk.nextToken(); } } if (!textFound) { text.append(tmpText); } }
From source file:com.emc.storageos.driver.dellsc.helpers.DellSCProvisioning.java
/** * Export volumes to initiators through a given set of ports. If ports are * not provided, use port requirements from ExportPathsServiceOption * storage capability.// w w w .j a va 2s .c o m * * @param initiators The initiators to export to. * @param volumes The volumes to export. * @param volumeToHLUMap Map of volume nativeID to requested HLU. HLU * value of -1 means that HLU is not defined and will * be assigned by array. * @param recommendedPorts List of storage ports recommended for the export. * Optional. * @param availablePorts List of ports available for the export. * @param capabilities The storage capabilities. * @param usedRecommendedPorts True if driver used recommended and only * recommended ports for the export, false * otherwise. * @param selectedPorts Ports selected for the export (if recommended ports * have not been used). * @return The export task. * @throws DellSCDriverException */ public DriverTask exportVolumesToInitiators(List<Initiator> initiators, List<StorageVolume> volumes, Map<String, String> volumeToHLUMap, List<StoragePort> recommendedPorts, List<StoragePort> availablePorts, StorageCapabilities capabilities, MutableBoolean usedRecommendedPorts, List<StoragePort> selectedPorts) { LOG.info("Exporting volumes to inititators"); DellSCDriverTask task = new DellSCDriverTask("exportVolumes"); ScServer server = null; List<ScServerHba> preferredHbas = new ArrayList<>(); StringBuilder errBuffer = new StringBuilder(); int volumesMapped = 0; Set<StoragePort> usedPorts = new HashSet<>(); String preferredController = null; // Cache of controller port instance IDs to StoragePort objects Map<String, StoragePort> discoveredPorts = new HashMap<>(); // See if a max port count has been specified int maxPaths = -1; List<ExportPathsServiceOption> pathOptions = capabilities.getCommonCapabilitis().getExportPathParams(); for (ExportPathsServiceOption pathOption : pathOptions) { // List but appears to only ever have one option? maxPaths = pathOption.getMaxPath(); } // Get the recommended server ports to use List<String> recommendedServerPorts = new ArrayList<>(); for (StoragePort port : recommendedPorts) { recommendedServerPorts.add(port.getNativeId()); } for (StorageVolume volume : volumes) { String ssn = volume.getStorageSystemId(); try { StorageCenterAPI api = connectionManager.getConnection(ssn); // Find our actual volume ScVolume scVol = null; int dotCount = StringUtils.countMatches(volume.getNativeId(), "."); if (dotCount == 2) { // Not actually a volume scVol = api.createReplayView(volume.getNativeId(), String.format("View of %s", volume.getNativeId())); } else { // Normal volume instance ID scVol = api.getVolume(volume.getNativeId()); } if (scVol == null) { throw new DellSCDriverException( String.format("Unable to find volume %s", volume.getNativeId())); } // Look up the server if needed if (server == null) { server = createOrFindScServer(api, ssn, initiators, preferredHbas); } if (server == null) { // Unable to find or create the server, can't continue throw new DellSCDriverException(SERVER_CREATE_FAIL_MSG); } // See if we have a preferred controller if (preferredController == null && scVol.active) { // At least first volume is active somewhere, so we need to try to // use that controller for all mappings ScVolumeConfiguration volConfig = api.getVolumeConfig(scVol.instanceId); if (volConfig != null) { preferredController = volConfig.controller.instanceId; } } // Next try to get a preferred controller based on what's requested if (preferredController == null && !recommendedPorts.isEmpty()) { try { ScControllerPort scPort = api.getControllerPort(recommendedPorts.get(0).getNativeId()); preferredController = scPort.controller.instanceId; } catch (Exception e) { LOG.warn("Failed to get recommended port controller.", e); } } int preferredLun = -1; if (volumeToHLUMap.containsKey(volume.getNativeId())) { String hlu = volumeToHLUMap.get(volume.getNativeId()); try { preferredLun = Integer.parseInt(hlu); } catch (NumberFormatException e) { LOG.warn("Unable to parse preferred LUN {}", hlu); } } ScMappingProfile profile; // See if the volume is already mapped ScMappingProfile[] mappingProfiles = api.getServerVolumeMapping(scVol.instanceId, server.instanceId); if (mappingProfiles.length > 0) { // This one is already mapped profile = mappingProfiles[0]; } else { profile = api.createVolumeMappingProfile(scVol.instanceId, server.instanceId, preferredLun, new String[0], maxPaths, preferredController); } ScMapping[] maps = api.getMappingProfileMaps(profile.instanceId); for (ScMapping map : maps) { volumeToHLUMap.put(volume.getNativeId(), String.valueOf(map.lun)); StoragePort port; if (discoveredPorts.containsKey(map.controllerPort.instanceId)) { port = discoveredPorts.get(map.controllerPort.instanceId); } else { ScControllerPort scPort = api.getControllerPort(map.controllerPort.instanceId); port = util.getStoragePortForControllerPort(api, scPort); discoveredPorts.put(map.controllerPort.instanceId, port); } usedPorts.add(port); } volumesMapped++; LOG.info("Volume '{}' exported to server '{}'", scVol.name, server.name); } catch (StorageCenterAPIException | DellSCDriverException dex) { String error = String.format("Error mapping volume %s: %s", volume.getDisplayName(), dex); LOG.error(error); errBuffer.append(String.format("%s%n", error)); if (SERVER_CREATE_FAIL_MSG.equals(dex.getMessage())) { // Game over break; } } } // See if we were able to use all of the recommended ports // TODO: Expand this to do more accurate checking usedRecommendedPorts.setValue(recommendedPorts.size() == usedPorts.size()); if (!usedRecommendedPorts.isTrue()) { selectedPorts.addAll(usedPorts); } task.setMessage(errBuffer.toString()); if (volumesMapped == volumes.size()) { task.setStatus(TaskStatus.READY); } else if (volumesMapped == 0) { task.setStatus(TaskStatus.FAILED); } else { task.setStatus(TaskStatus.PARTIALLY_FAILED); } return task; }
From source file:com.flexive.cmis.spi.FlexiveDocument.java
public ContentStream getContentStream() throws IOException { final FxPropertyAssignment assignment = SPIUtils.getContentStreamAssignment(getFxType()); if (assignment == null || !getContent().containsValue(assignment.getXPath())) { return null; }/*from ww w .j a va2 s .com*/ if (assignment.getProperty().getDataType() == FxDataType.Binary) { return new FlexiveContentStream((FxBinary) getContent().getValue(assignment.getXPath())); } else { final String streamOption = assignment.getOption(SPIUtils.OPTION_CONTENTSTREAM).getValue(); return new SimpleContentStream( getContent().getValue(assignment.getXPath()).getBestTranslation().toString().getBytes("UTF-8"), // use MIME type set in stream value if available, otherwise default to text/plain StringUtils.countMatches(streamOption, "/") == 1 ? streamOption : "text/plain", "content"); } }
From source file:com.jsmartdb.framework.manager.EntityWhere.java
public static void getCustomWhere(Class<?> entityClazz, Field[] fields, QueryParam param) { String customWhere = EntityContext.getWhereBuilder().toString(); Map<Integer, Object> paramValues = new TreeMap<Integer, Object>(); for (String key : param.getFilterParamKeys()) { int index = 0; for (int i = 0; i < StringUtils.countMatches(customWhere, key); i++) { index = customWhere.indexOf(key, index); paramValues.put(index, param.get(key)); }/*w ww . j a v a 2 s .co m*/ } EntityContext.addAllBuilderValue(paramValues.values()); for (String key : param.getFilterParamKeys()) { customWhere = customWhere.replaceAll(key, " ? "); } String[] matches = customWhere.split(" "); Map<String, String> queryMap = new HashMap<String, String>(); for (String match : matches) { if (match.trim().isEmpty()) { continue; } Matcher matcher = EntitySelect.SQL_FUNCTION_PATTERN.matcher(match); if (matcher.find()) { match = matcher.group(); match = match.replace("(", "").replace(")", ""); } String value = EntityAlias.getMatchColumn(entityClazz, fields, match, EntityAlias.getAlias(entityClazz), EntityContext.getJoinBuilder()); if (value != null) { queryMap.put(match, value); } } for (String key : queryMap.keySet()) { customWhere = customWhere.replace(key, queryMap.get(key)); } EntityContext.getWhereBuilder().replace(0, EntityContext.getWhereBuilder().length(), customWhere); if (EntityContext.getWhereBuilder().length() <= WHERE_STATEMENT.length()) { EntityContext.getWhereBuilder().replace( EntityContext.getWhereBuilder().length() - WHERE_STATEMENT.length(), EntityContext.getWhereBuilder().length(), ""); } }
From source file:edu.ku.brc.specify.config.FixDBAfterLogin.java
/** * @param pStmt/* w w w .j a va2 s .co m*/ * @param locId * @param origUnit * @param srcUnit * @param lat1Text * @param long1Text * @param isNew * @return * @throws SQLException */ private boolean fixLatLong(final PreparedStatement pStmt, final int locId, final int origUnit, final int srcUnit, final String lat1Text, final String long1Text, final boolean isNew) throws SQLException { pStmt.setInt(3, locId); boolean doUpdate = false; if (isNew) { // These could be entered from Sp5 or Sp6 int numColonsLat = lat1Text != null ? StringUtils.countMatches(lat1Text, ":") : 0; int numColonsLon = long1Text != null ? StringUtils.countMatches(long1Text, ":") : 0; if (numColonsLat == 2 || numColonsLon == 2) // definitely Deg, Min Dec Secs { if (srcUnit != 1) { //log.debug(String.format("1 - Lat[%s] Lon[%s] origUnit %d srcUnit %d", lat1Text, long1Text, origUnit, srcUnit)); pStmt.setInt(1, origUnit); // How Viewed pStmt.setInt(2, 1); // How Stored return true; } return false; } String[] latTokens = StringUtils.split(lat1Text, SEPS); String[] lonTokens = StringUtils.split(long1Text, SEPS); int latLen = latTokens.length; int lonLen = lonTokens.length; if (latLen == 4 || lonLen == 4) { if (srcUnit != 1) // Deg, Min Dec Secs { //log.debug(String.format("Fix1 Lat[%s] Lon[%s] origUnit %d srcUnit %d", lat1Text, long1Text, origUnit, srcUnit)); pStmt.setInt(1, origUnit); // How Viewed pStmt.setInt(2, 1); // How Stored return true; } } else if (latLen == 3 || lonLen == 3) { if (srcUnit != 2) // Degrees Decimal Minutes { //log.debug(String.format("Fix2 Lat[%s] Lon[%s] origUnit %d srcUnit %d", lat1Text, long1Text, origUnit, srcUnit)); pStmt.setInt(1, origUnit); // How Viewed pStmt.setInt(2, 2); // How Stored return true; } } else if (latLen == 2 || lonLen == 2) { if (srcUnit != 0) // Decimal Degrees { //log.debug(String.format("Fix0 Lat[%s] Lon[%s] origUnit %d srcUnit %d", lat1Text, long1Text, origUnit, srcUnit)); pStmt.setInt(1, origUnit); // How Viewed pStmt.setInt(2, 1); // How Stored return true; } } else { log.debug(String.format("*** Couldn't parse Lat[%s] Lon[%s] origUnit %d srcUnit %d", lat1Text, long1Text, origUnit, srcUnit)); } } else { if (srcUnit == 0 && origUnit != 0) { pStmt.setInt(1, origUnit); // How Viewed pStmt.setInt(2, origUnit); // How Stored doUpdate = true; } } return doUpdate; }
From source file:edu.ku.brc.af.prefs.AppPrefsCache.java
/** * Creates or gets the pref node, creates an entry and then hooks it up as a listener. * The current value of the SimpleDateFormat because the default. * @param simpleFormat the SimpleDateFormat object * @param section the section or category of the pref * @param pref the pref's name/*from ww w.j a va 2 s.c o m*/ * @param attrName the actual attribute */ public void registerInternal(final SimpleDateFormat simpleFormat, final String section, final String pref, final String attrName) { checkName(section, pref, attrName); String fullName = makeKey(section, pref, attrName); if (hash.get(fullName) == null) { String defValue = simpleFormat.toPattern(); String prefVal = checkForPref(fullName, defValue); //------------------------------------------------------------------------------- // This corrects the formatter when it has a two digit year (Bug 7555) // still have not found out what is causing the problem. //------------------------------------------------------------------------------- if (prefVal.length() == 8 && StringUtils.countMatches(prefVal, "yyyy") == 0) { prefVal = StringUtils.replace(prefVal, "yy", "yyyy"); } simpleFormat.applyPattern(prefVal); DateFormatCacheEntry dateEntry = new DateFormatCacheEntry(simpleFormat, fullName, prefVal, defValue); getPref().addChangeListener(fullName, dateEntry); hash.put(fullName, dateEntry); } }
From source file:ch.ethz.bsse.indelfixer.stored.Read.java
public String toString(Read paired) { StringBuilder sb = new StringBuilder(); // sb.append("R"); if (this.getHeader() != null) { sb.append(this.getHeader().split(" ")[0].substring(1)); } else {/*ww w . j a va 2 s . c o m*/ sb.append("READ_").append(Globals.READCOUNTER++); } // if (Globals.CONSENSUS) { // sb.append("\t0\t").append("CONSENSUS"); // } else { int flag = 0x0; if (paired != null) { flag |= 0x1; flag |= 0x2; if (this.reverse) { flag |= 0x10; } if (paired.reverse) { flag |= 0x20; } if (this.begin == paired.begin) { if (!this.reverse) { flag |= 0x40; } else { flag |= 0x80; } } else if (this.begin < paired.begin) { flag |= 0x40; } else { flag |= 0x80; } } else { if (this.reverse) { flag |= 0x10; } } sb.append("\t").append(flag); sb.append("\t").append(Globals.GENOMES[this.getBestFittingGenome()].getHeader()); // } sb.append("\t").append(this.getBegin()); sb.append("\t").append(60); sb.append("\t").append(this.getCigars()); if (paired == null) { sb.append("\t").append("*"); sb.append("\t").append("0"); sb.append("\t").append("0"); } else { sb.append("\t").append(Globals.GENOMES[this.getBestFittingGenome()].getHeader() .equals(Globals.GENOMES[paired.getBestFittingGenome()].getHeader()) ? "=" : "*"); sb.append("\t").append(paired.begin); sb.append("\t"); if (this.reverse) { sb.append("-"); } if (paired.begin < this.begin) { sb.append((this.end - paired.begin)); } else { sb.append((paired.end - this.begin)); } } sb.append("\t").append(this.getAlignedRead()); sb.append("\t"); if (this.getQuality() != null && !this.getQuality().isEmpty()) { for (int i = 0; i < this.getQuality().length(); i++) { sb.append((char) this.getQuality().charAt(i)); } } else { sb.append("*"); } sb.append("\t").append("AS:i:").append(this.alignmentScore); sb.append("\t").append("NM:i:").append(StringUtils.countMatches(cigars, "X")); sb.append("\t").append(this.gapCosts); sb.append("\n"); return sb.toString(); }
From source file:com.haulmont.cuba.gui.export.ExcelExporter.java
public void exportDataGrid(DataGrid<Entity> dataGrid, List<DataGrid.Column> columns, ExportDisplay display, List<String> filterDescription, String fileName, ExportMode exportMode) { if (display == null) { throw new IllegalArgumentException("ExportDisplay is null"); }/*from ww w .j a v a 2 s .co m*/ createWorkbookWithSheet(); createFonts(); createFormats(); int r = 0; if (filterDescription != null) { for (r = 0; r < filterDescription.size(); r++) { String line = filterDescription.get(r); HSSFRow row = sheet.createRow(r); if (r == 0) { HSSFRichTextString richTextFilterName = new HSSFRichTextString(line); richTextFilterName.applyFont(boldFont); row.createCell(0).setCellValue(richTextFilterName); } else { row.createCell(0).setCellValue(line); } } r++; } HSSFRow row = sheet.createRow(r); createAutoColumnSizers(columns.size()); float maxHeight = sheet.getDefaultRowHeightInPoints(); CellStyle headerCellStyle = wb.createCellStyle(); headerCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); for (DataGrid.Column column : columns) { String caption = column.getCaption(); int countOfReturnSymbols = StringUtils.countMatches(caption, "\n"); if (countOfReturnSymbols > 0) { maxHeight = Math.max(maxHeight, (countOfReturnSymbols + 1) * sheet.getDefaultRowHeightInPoints()); headerCellStyle.setWrapText(true); } } row.setHeightInPoints(maxHeight); for (int c = 0; c < columns.size(); c++) { DataGrid.Column column = columns.get(c); String caption = column.getCaption(); HSSFCell cell = row.createCell(c); HSSFRichTextString richTextString = new HSSFRichTextString(caption); richTextString.applyFont(boldFont); cell.setCellValue(richTextString); ExcelAutoColumnSizer sizer = new ExcelAutoColumnSizer(); sizer.notifyCellValue(caption, boldFont); sizers[c] = sizer; cell.setCellStyle(headerCellStyle); } CollectionDatasource datasource = dataGrid.getDatasource(); if (exportMode == ExportMode.SELECTED_ROWS && dataGrid.getSelected().size() > 0) { Set<Entity> selected = dataGrid.getSelected(); List<Entity> ordered = ((Collection<Entity>) datasource.getItems()).stream().filter(selected::contains) .collect(Collectors.toList()); for (Entity item : ordered) { createDataGridRow(dataGrid, columns, 0, ++r, item.getId()); } } else { for (Object itemId : datasource.getItemIds()) { createDataGridRow(dataGrid, columns, 0, ++r, itemId); } } for (int c = 0; c < columns.size(); c++) { sheet.setColumnWidth(c, sizers[c].getWidth() * COL_WIDTH_MAGIC); } ByteArrayOutputStream out = new ByteArrayOutputStream(); try { wb.write(out); } catch (IOException e) { throw new RuntimeException("Unable to write document", e); } if (fileName == null) { fileName = messages.getTools().getEntityCaption(datasource.getMetaClass()); } display.show(new ByteArrayDataProvider(out.toByteArray()), fileName + ".xls", ExportFormat.XLS); }
From source file:com.castis.xylophone.adsmadapter.filePolling.InventoryDataListPolling.java
public ParsedDatFileNameInfo parseFileName(File file, Platform platformType) throws WrongFileNameException { ParsedDatFileNameInfo result = new ParsedDatFileNameInfo(); String fileName = null;/*ww w.ja v a2 s . c om*/ try { fileName = file.getName(); int count = StringUtils.countMatches(fileName, "."); if (count == INDEX_COUNT) { String[] values = fileName.split("\\."); result.dataType = InputDataType.valueof(values[INDEX_INPUT_DATA_TYPE]); result.site = values[INDEX_PUBLISHER]; result.treeName = values[INDEX_TREE_NAME]; result.startDate = values[INDEX_START_DATE]; result.platform = Platform.valueof(values[INDEX_PLATFORM_TYPE]); switch (result.dataType) { case CATEGORY_DATA: result.jobNameType = ADSMJobNameType.INVENTORY_CATEGORY_DATA.name(); break; case REGION_DATA: result.jobNameType = ADSMJobNameType.INVENTORY_REGION_DATA.name(); break; default: throw new WrongFileNameException("Check File name rule."); } // ? checkValidStartTime(result.startDate); } else if (txtExtension) { Date date = new Date(); SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd"); String[] values = fileName.split("\\_"); result.dataType = InputDataType.valueof(values[0]); result.site = ADDSAdapterSetting.defaultSiteName; result.startDate = fmt.format(date); result.treeName = Constants.tree.REGION_TREE_NAME; result.platform = platformType; switch (result.dataType) { case CATEGORY_DATA: result.jobNameType = ADSMJobNameType.INVENTORY_CATEGORY_DATA.name(); result.treeName = Constants.tree.CATEGORY_TREE_NAME; break; case REGION_DATA: result.jobNameType = ADSMJobNameType.INVENTORY_REGION_DATA.name(); result.treeName = Constants.tree.REGION_TREE_NAME; break; default: throw new WrongFileNameException("Check File name rule."); } // ? checkValidStartTime(result.startDate); } else throw new WrongFileNameException("Check File name rule."); } catch (WrongFileNameException e) { throw e; } catch (Exception e) { log.error("Fail to pasing FileName.(FileName:" + fileName + ")", e); return null; } return result; }
From source file:edu.ku.brc.af.prefs.AppPrefsCache.java
/** * Returns a SimpleDateFormat for date with two month and day digits and 4 year digits. * @return a SimpleDateFormat for date with two month and day digits and 4 year digits. *//*from www. ja va 2 s. co m*/ public static SimpleDateFormat getDefaultDatePattern() { boolean debug = AppPreferences.getLocalPrefs().getBoolean("DEBUG.DATES", false); SimpleDateFormat sdf = new SimpleDateFormat(); String[] pieces = sdf.toPattern().split(" "); //$NON-NLS-1$ if (pieces != null) { String pattern = pieces[0]; if (debug) { System.out.println("[" + pattern + "][" + sdf.toPattern() + "]"); System.out.println("Months: " + StringUtils.countMatches(pattern, "M")); System.out.println("Days: " + StringUtils.countMatches(pattern, "d")); System.out.println("Years: " + StringUtils.countMatches(pattern, "y")); } int months = StringUtils.countMatches(pattern, "M"); //$NON-NLS-1$ int days = StringUtils.countMatches(pattern, "d"); //$NON-NLS-1$ int years = StringUtils.countMatches(pattern, "y"); //$NON-NLS-1$ if (months == 1) { pattern = pattern.replace("M", "MM"); //$NON-NLS-1$ //$NON-NLS-2$ } if (days == 1) { pattern = pattern.replace("d", "dd"); //$NON-NLS-1$ //$NON-NLS-2$ } if (years == 2) { pattern = pattern.replace("yy", "yyyy"); //$NON-NLS-1$ //$NON-NLS-2$ } if (debug) { System.out.println(pattern); System.out.println("Months: " + StringUtils.countMatches(pattern, "M")); System.out.println("Days: " + StringUtils.countMatches(pattern, "d")); System.out.println("Years: " + StringUtils.countMatches(pattern, "y")); } return new SimpleDateFormat(pattern); } return new SimpleDateFormat("MM/dd/yyyy"); //$NON-NLS-1$ }