List of usage examples for org.apache.commons.lang3 StringUtils isNumeric
public static boolean isNumeric(final CharSequence cs)
Checks if the CharSequence contains only Unicode digits.
From source file:com.bellman.bible.service.format.osistohtml.taghandler.ReferenceHandler.java
/** create a link tag from an OSISref and the content of the tag */// www .java 2 s.c o m private String getReferenceTag(String reference, String content) { log.debug("Ref:" + reference + " Content:" + content); StringBuilder result = new StringBuilder(); try { //JSword does not know the basis (default book) so prepend it if it looks like JSword failed to work it out //We only need to worry about the first ref because JSword uses the first ref as the basis for the subsequent refs // if content starts with a number and is not followed directly by an alpha char e.g. 1Sa if (reference == null && content != null && content.length() > 0 && StringUtils.isNumeric(content.subSequence(0, 1)) && (content.length() < 2 || !StringUtils.isAlphaSpace(content.subSequence(1, 2)))) { // maybe should use VerseRangeFactory.fromstring(orig, basis) // this check for a colon to see if the first ref is verse:chap is not perfect but it will do until JSword adds a fix int firstColonPos = content.indexOf(":"); boolean isVerseAndChapter = firstColonPos > 0 && firstColonPos < 4; if (isVerseAndChapter) { reference = parameters.getBasisRef().getBook().getOSIS() + " " + content; } else { reference = parameters.getBasisRef().getBook().getOSIS() + " " + parameters.getBasisRef().getChapter() + ":" + content; } log.debug("Patched reference:" + reference); } else if (reference == null) { reference = content; } // convert urns of type book:key to sword://book/key to simplify urn parsing (1 fewer case to check for). // Avoid urls of type 'matt 3:14' by excludng urns with a space if (reference.contains(":") && !reference.contains(" ") && !reference.startsWith("sword://")) { reference = "sword://" + reference.replace(":", "/"); } boolean isFullSwordUrn = reference.contains("/") && reference.contains(":"); if (isFullSwordUrn) { // e.g. sword://StrongsRealGreek/01909 // don't play with the reference - just assume it is correct result.append("<a href='").append(reference).append("'>"); result.append(content); result.append("</a>"); } else { Passage ref = (Passage) PassageKeyFactory.instance().getKey(parameters.getDocumentVersification(), reference); boolean isSingleVerse = ref.countVerses() == 1; boolean isSimpleContent = content.length() < 3 && content.length() > 0; Iterator<VerseRange> it = ref.rangeIterator(RestrictionType.CHAPTER); if (isSingleVerse && isSimpleContent) { // simple verse no e.g. 1 or 2 preceding the actual verse in TSK result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":") .append(it.next().getOsisRef()).append("'>"); result.append(content); result.append("</a>"); } else { // multiple complex references boolean isFirst = true; while (it.hasNext()) { Key key = it.next(); if (!isFirst) { result.append(" "); } // we just references the first verse in each range because that is the verse you would jump to. It might be more correct to reference the while range i.e. key.getOsisRef() result.append("<a href='").append(Constants.BIBLE_PROTOCOL).append(":") .append(key.iterator().next().getOsisRef()).append("'>"); result.append(key); result.append("</a>"); isFirst = false; } } } } catch (Exception e) { log.error("Error parsing OSIS reference:" + reference); // just return the content with no html markup result.append(content); } return result.toString(); }
From source file:com.omertron.yamjtrakttv.model.Video.java
public void setYear(String year) { if (StringUtils.isNumeric(year)) { this.year = Integer.parseInt(year); } else {/*ww w.ja va 2 s . co m*/ this.year = 0; } }
From source file:com.hack23.cia.service.impl.action.application.LoginService.java
private static boolean verifyOtp(final LoginRequest serviceRequest, final UserAccount userExist) { boolean authorizedOtp = true; if (userExist.getGoogleAuthKey() != null) { final GoogleAuthenticator gAuth = new GoogleAuthenticator(); if (!StringUtils.isBlank(serviceRequest.getOtpCode()) && StringUtils.isNumeric(serviceRequest.getOtpCode())) { authorizedOtp = gAuth.authorize(userExist.getGoogleAuthKey(), Integer.parseInt(serviceRequest.getOtpCode())); } else {/*from w w w .j a v a 2 s . c o m*/ authorizedOtp = false; } } return authorizedOtp; }
From source file:com.bekwam.examples.javafx.oldscores.ScoresDialogController.java
@FXML public void updateVerbal1995() { if (logger.isDebugEnabled()) { logger.debug("[UPD V 1995]"); }//from www . jav a2 s . co m if (dao == null) { throw new IllegalArgumentException( "dao has not been set; call setRecenteredDAO() before calling this method"); } String recenteredScore_s = txtVerbalScoreRecentered.getText(); if (StringUtils.isNumeric(recenteredScore_s)) { Integer scoreRecentered = NumberUtils.toInt(recenteredScore_s); if (withinRange(scoreRecentered)) { if (needsRound(scoreRecentered)) { scoreRecentered = round(scoreRecentered); txtVerbalScoreRecentered.setText(String.valueOf(scoreRecentered)); } resetErrMsgs(); Integer score1995 = dao.lookup1995VerbalScore(scoreRecentered); txtVerbalScore1995.setText(String.valueOf(score1995)); } else { errMsgVerbalRecentered.setVisible(true); } } else { errMsgVerbalRecentered.setVisible(true); } }
From source file:com.massabot.codesender.GrblController.java
/*********************** * API Implementation. */*w w w . j a v a2 s .c o m*/ ***********************/ @Override protected void rawResponseHandler(String response) { if (GcodeCommand.isOkErrorResponse(response)) { String processed = response; if (response.startsWith("error:")) { String parts[] = response.split(":"); if (parts.length == 2) { String code = parts[1].trim(); if (StringUtils.isNumeric(code)) { String[] errorParts = ERRORS.lookup(code); if (errorParts != null && errorParts.length >= 3) { processed = "error: " + errorParts[1] + ": " + errorParts[2]; } } } } try { this.commandComplete(processed); this.messageForConsole(processed + "\n"); } catch (Exception e) { String message = ""; if (e.getMessage() != null) { message = ": " + e.getMessage(); } this.errorMessageForConsole( Localization.getString("controller.error.response") + " <" + processed + ">" + message); } } else if (GrblUtils.isGrblVersionString(response)) { this.stopPollingPosition(); positionPollTimer = createPositionPollTimer(); this.beginPollingPosition(); this.isReady = true; resetBuffers(); // In case a reset occurred while streaming. if (this.isStreaming()) { checkStreamFinished(); } // Version string goes to console this.messageForConsole(response + "\n"); this.grblVersion = GrblUtils.getVersionDouble(response); this.grblVersionLetter = GrblUtils.getVersionLetter(response); this.capabilities = GrblUtils.getGrblStatusCapabilities(this.grblVersion, this.grblVersionLetter); try { this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_SETTINGS_COMMAND)); this.sendCommandImmediately(createCommand(GrblUtils.GRBL_VIEW_PARSER_STATE_COMMAND)); } catch (Exception e) { throw new RuntimeException(e); } this.beginPollingPosition(); Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, "{0} = {1}{2}", new Object[] { Localization.getString("controller.log.version"), this.grblVersion, this.grblVersionLetter }); Logger.getLogger(GrblController.class.getName()).log(Level.CONFIG, "{0} = {1}", new Object[] { Localization.getString("controller.log.realtime"), this.capabilities.REAL_TIME }); } else if (GrblUtils.isGrblStatusString(response)) { // Only 1 poll is sent at a time so don't decrement, reset to zero. this.outstandingPolls = 0; // Status string goes to verbose console verboseMessageForConsole(response + "\n"); this.handleStatusString(response); } else if (GrblUtils.isGrblFeedbackMessage(response, capabilities)) { GrblFeedbackMessage grblFeedbackMessage = new GrblFeedbackMessage(response); this.verboseMessageForConsole(grblFeedbackMessage.toString() + "\n"); this.messageForConsole(response + "\n"); setDistanceModeCode(grblFeedbackMessage.getDistanceMode()); setUnitsCode(grblFeedbackMessage.getUnits()); } else if (GrblUtils.isGrblSettingMessage(response)) { GrblSettingMessage message = new GrblSettingMessage(response); this.messageForConsole(message + "\n"); if (message.isReportingUnits()) { setReportingUnits(message.getReportingUnits()); } } else { // Display any unhandled messages this.messageForConsole(response + "\n"); } }
From source file:jongo.JongoUtils.java
/** * Infers the java.sql.Types of the given String and returns the JDBC mappable Object corresponding to it. * The conversions are like this:/*from w w w .ja va2 s.c o m*/ * String -> String * Numeric -> Integer * Date or Time -> Date * Decimal -> BigDecimal * ??? -> TimeStamp * @param val a String with the value to be mapped * @return a JDBC mappable object instance with the value */ public static Object parseValue(String val) { Object ret = null; if (!StringUtils.isWhitespace(val) && StringUtils.isNumeric(val)) { try { ret = Integer.valueOf(val); } catch (Exception e) { l.debug(e.getMessage()); } } else { DateTime date = JongoUtils.isDateTime(val); if (date != null) { l.debug("Got a DateTime " + date.toString(ISODateTimeFormat.dateTime())); ret = new java.sql.Timestamp(date.getMillis()); } else { date = JongoUtils.isDate(val); if (date != null) { l.debug("Got a Date " + date.toString(ISODateTimeFormat.date())); ret = new java.sql.Date(date.getMillis()); } else { date = JongoUtils.isTime(val); if (date != null) { l.debug("Got a Time " + date.toString(ISODateTimeFormat.time())); ret = new java.sql.Time(date.getMillis()); } } } if (ret == null && val != null) { l.debug("Not a datetime. Try someting else. "); try { ret = new BigDecimal(val); } catch (NumberFormatException e) { l.debug(e.getMessage()); ret = val; } } } return ret; }
From source file:com.willwinder.universalgcodesender.GrblController.java
/*********************** * API Implementation. */*ww w .j ava 2 s. c o m*/ ***********************/ private static String lookupCode(String input, boolean shortString) { if (input.contains(":")) { String inputParts[] = input.split(":"); if (inputParts.length == 2) { String code = inputParts[1].trim(); if (StringUtils.isNumeric(code)) { String[] lookupParts = null; switch (inputParts[0].toLowerCase()) { case "error": lookupParts = ERRORS.lookup(code); break; case "alarm": lookupParts = ALARMS.lookup(code); break; default: return input; } if (lookupParts == null) { return "(" + input + ") An unknown error has occurred"; } else if (shortString) { return input + " (" + lookupParts[1] + ")"; } else { return "(" + input + ") " + lookupParts[2]; } } } } return input; }
From source file:com.glaf.jbpm.model.Extension.java
public long getLongFieldValue(String name) { if (fields != null) { ExtensionField extensionField = fields.get(name); if (extensionField != null && extensionField.getValue() != null) { String value = extensionField.getValue(); if (StringUtils.isNumeric(value)) { return Long.parseLong(value); }/* w ww . j a va 2 s .com*/ } } return 0; }
From source file:com.thinkbiganalytics.metadata.sla.DefaultServiceLevelAgreementScheduler.java
private String getUniqueName(String name) { String uniqueName = name;//from w w w . ja v a 2s . co m final String checkName = name; String matchingName = Iterables.tryFind(scheduledJobNames.values(), new Predicate<String>() { @Override public boolean apply(String s) { return s.equalsIgnoreCase(checkName); } }).orNull(); if (matchingName != null) { //get numeric string after '-'; if (StringUtils.contains(matchingName, "-")) { String number = StringUtils.substringAfterLast(matchingName, "-"); if (StringUtils.isNotBlank(number)) { number = StringUtils.trim(number); if (StringUtils.isNumeric(number)) { Integer num = Integer.parseInt(number); num++; uniqueName += "-" + num; } else { uniqueName += "-1"; } } } else { uniqueName += "-1"; } } return uniqueName; }
From source file:com.moviejukebox.plugin.FilmaffinityPlugin.java
/** * Scan FilmAffinity html page for the specified movie *//*w w w . j a v a 2 s.c o m*/ private boolean updateFilmAffinityMediaInfo(Movie movie) { Boolean returnStatus = true; Pattern countryPattern = Pattern .compile("<img src=\"/imgs/countries/[A-Z]{2}\\.jpg\" title=\"([\\w ]+)\""); String filmAffinityId = movie.getId(FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); if (StringTools.isNotValidString(filmAffinityId)) { LOG.debug("No valid FilmAffinity ID for movie {}", movie.getBaseName()); return false; } try { String xml = httpClient.request("http://www.filmaffinity.com/es/" + filmAffinityId); if (xml.contains("Serie de TV")) { if (!movie.getMovieType().equals(Movie.TYPE_TVSHOW)) { LOG.debug("{} is a TV Show, skipping.", movie.getTitle()); movie.setMovieType(Movie.TYPE_TVSHOW); return false; } } if (OverrideTools.checkOverwriteTitle(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { String spanishTitle = HTMLTools.getTextAfterElem(xml, "<h1 id=\"main-title\">") .replaceAll("\\s{2,}", " "); movie.setTitle(spanishTitle, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteOriginalTitle(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { movie.setOriginalTitle(HTMLTools.getTextAfterElem(xml, FA_ORIGINAL_TITLE), FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteYear(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { String year = HTMLTools.getTextAfterElem(xml, FA_YEAR); // check to see if the year is numeric, if not, try a different approach if (!StringUtils.isNumeric(year)) { year = HTMLTools.getTextAfterElem(xml, FA_YEAR, 1); } movie.setYear(year, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteRuntime(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { String runTime = HTMLTools.getTextAfterElem(xml, FA_RUNTIME).replace("min.", "m"); if (!"min.".equals(runTime)) { movie.setRuntime(runTime, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } } if (OverrideTools.checkOverwriteCountry(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { Matcher countryMatcher = countryPattern.matcher(xml); if (countryMatcher.find()) { movie.setCountries(countryMatcher.group(1), FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } } if (OverrideTools.checkOverwriteDirectors(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { List<String> newDirectors = Arrays.asList( HTMLTools.removeHtmlTags(HTMLTools.extractTag(xml, FA_DIRECTOR, "</a></dd>")).split(",")); movie.setDirectors(newDirectors, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } /* * Sometimes FilmAffinity includes the writer of novel in the form: * screenwriter (Novela: writer) OR screenwriter1, screenwriter2, * ... (Novela: writer) OR even!! screenwriter1, screenwriter2, ... * (Story: writer1, writer2) * * The info between parenthesis doesn't add. */ if (OverrideTools.checkOverwriteWriters(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { List<String> newWriters = Arrays .asList(HTMLTools.getTextAfterElem(xml, FA_WRITER).split("\\(")[0].split(",")); movie.setWriters(newWriters, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteActors(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { List<String> newActors = Arrays.asList( HTMLTools.removeHtmlTags(HTMLTools.extractTag(xml, FA_CAST, "</a></dd>")).split(",")); movie.setCast(newActors, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteCompany(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { // TODO: Save more than one company. movie.setCompany(HTMLTools.getTextAfterElem(xml, FA_COMPANY).split("/")[0].trim(), FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } if (OverrideTools.checkOverwriteGenres(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { List<String> newGenres = new ArrayList<>(); for (String genre : HTMLTools.removeHtmlTags(HTMLTools.extractTag(xml, FA_GENRE, "</dd>")) .split("\\.|\\|")) { newGenres.add(Library.getIndexingGenre(cleanStringEnding(genre.trim()))); } movie.setGenres(newGenres, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } try { movie.addRating(FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID, (int) (Float.parseFloat( HTMLTools.extractTag(xml, "<div id=\"movie-rat-avg\">", "</div>").replace(",", ".")) * 10)); } catch (Exception e) { // Don't set a rating } if (OverrideTools.checkOverwritePlot(movie, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID)) { String plot = HTMLTools.getTextAfterElem(xml, FA_PLOT); if (plot.endsWith("(FILMAFFINITY)")) { plot = plot.substring(0, plot.length() - 14); } movie.setPlot(plot, FilmAffinityInfo.FILMAFFINITY_PLUGIN_ID); } /* * Fill the rest of the fields from IMDB, taking care not to allow * the title to get overwritten. * * I change temporally: title = Original title to improve the chance * to find the right movie in IMDb. */ String title = movie.getTitle(); String titleSource = movie.getOverrideSource(OverrideFlag.TITLE); movie.setTitle(movie.getOriginalTitle(), movie.getOverrideSource(OverrideFlag.ORIGINALTITLE)); super.scan(movie); // Change the title back to the way it was if (OverrideTools.checkOverwriteTitle(movie, titleSource)) { movie.setTitle(title, titleSource); } } catch (Exception error) { LOG.error("Failed retreiving movie info: {}", filmAffinityId); LOG.error(SystemTools.getStackTrace(error)); returnStatus = false; } return returnStatus; }