List of usage examples for java.lang NumberFormatException NumberFormatException
public NumberFormatException(String s)
NumberFormatException
with the specified detail message. From source file:org.jasig.ssp.service.impl.EvaluatedSuccessIndicatorServiceImpl.java
private BigDecimal normalizeForScaleEvaluation(@Nullable Object metric, @Nonnull SuccessIndicator successIndicator) throws NumberFormatException, IllegalArgumentException { if (metric == null) { return null; }/* www. j av a 2 s . c o m*/ if (metric instanceof Boolean) { return ((Boolean) metric).booleanValue() ? BigDecimal.ONE : BigDecimal.ZERO; } if (metric instanceof BigDecimal) { return ((BigDecimal) metric); } if (metric instanceof Number) { return BigDecimal.valueOf(((Number) metric).doubleValue()).setScale(DECIMAL_SCALE); } if (metric instanceof String) { return new BigDecimal((String) metric).setScale(DECIMAL_SCALE); } if (metric instanceof Ratio) { return ((Ratio) metric).ratio(); } throw new NumberFormatException("Cannot interpret evaluation input value [" + metric + "] of type [" + metric.getClass().getName() + "] as a BigDecimal"); }
From source file:com.cloud.network.bigswitch.BigSwitchBcfUtils.java
public Integer getSubnetMaskLength(String maskString) { if (!IPAddress.isValidIPv4(maskString)) { return null; }//ww w . ja v a2s. c o m String[] octets = maskString.split("\\."); Integer bits = 0; for (String o : octets) { switch (o) { case "255": bits += 8; continue; case "254": bits += 7; return bits; case "252": bits += 6; return bits; case "248": bits += 5; return bits; case "240": bits += 4; return bits; case "224": bits += 3; return bits; case "192": bits += 2; return bits; case "128": bits += 1; return bits; case "0": return bits; default: throw new NumberFormatException("non-contiguous subnet mask not supported"); } } return bits; }
From source file:com.funambol.foundation.items.dao.PIMCalendarDAO.java
/** * Adds a calendar. If necessary, a new ID is generated and set in the * CalendarWrapper.//from ww w .j a va 2s . co m * * @param c as a CalendarWrapper object, usually without an ID set. * @throws DAOException * * @see CalendarWrapper */ public void addItem(CalendarWrapper cw) throws DAOException { if (log.isTraceEnabled()) { log.trace("PIMCalendarDAO addItem begin"); } Connection con = null; PreparedStatement ps = null; long id = 0; String allDay = null; String body = null; Short busyStatus = null; String categories = null; String companies = null; int duration = 0; Date dend = null; short importance = 0; String location = null; Short meetingStatus = null; String mileage = null; Date replyTime = null; short sensitivity = 0; Date dstart = null; String subject = null; int interval = 0; short monthOfYear = 0; short dayOfMonth = 0; String dayOfWeekMask = null; short instance = 0; String startDatePattern = null; String endDatePattern = null; Reminder reminder = null; RecurrencePattern rp = null; short recurrenceType = -1; String sId = null; int occurrences = -1; String folder = null; String dstartTimeZone = null; String dendTimeZone = null; String reminderTimeZone = null; Date completed = null; short percentComplete = -1; Timestamp lastUpdate = cw.getLastUpdate(); if (lastUpdate == null) { lastUpdate = new Timestamp(System.currentTimeMillis()); } try { sId = cw.getId(); if (sId == null || sId.length() == 0) { // ...as it should be sId = getNextID(); cw.setId(sId); } id = Long.parseLong(sId); CalendarContent c = cw.getCalendar().getCalendarContent(); rp = c.getRecurrencePattern(); boolean allDayB; if (c.getAllDay() != null && c.getAllDay().booleanValue()) { allDayB = true; allDay = "1"; } else { allDayB = false; allDay = "0"; } String sd = null; if (c.getDtStart() != null) { sd = c.getDtStart().getPropertyValueAsString(); dstart = getDateFromString(allDayB, sd, "000000"); } String ed = null; if ((sd != null && sd.length() > 0) || c.getDtEnd() != null) { ed = c.getDtEnd().getPropertyValueAsString(); // // Fix for Siemens S56 end date issue only for event // @todo: verify if is really need to do this // if (c instanceof Event) { if (ed == null || ed.length() == 0) { ed = sd; } } dend = getDateFromString(allDayB, ed, "235900"); } body = Property.stringFrom(c.getDescription()); if (c.getBusyStatus() != null) { busyStatus = new Short(c.getBusyStatus().shortValue()); } categories = Property.stringFrom(c.getCategories()); companies = Property.stringFrom(c.getOrganizer()); location = Property.stringFrom(c.getLocation()); folder = Property.stringFrom(c.getFolder()); dstartTimeZone = timeZoneFrom(c.getDtStart()); dendTimeZone = timeZoneFrom(c.getDtEnd()); reminderTimeZone = timeZoneFrom(c.getReminder()); meetingStatus = c.getMeetingStatus(); Integer mileageInteger = c.getMileage(); // NB: not an int... if (mileageInteger != null) { // ...therefore it may be null mileage = String.valueOf(mileageInteger); } if (c instanceof Event) { replyTime = getDateFromString(allDayB, // @todo or false? Property.stringFrom(((Event) c).getReplyTime()), "000000"); } try { sensitivity = Short.parseShort(Property.stringFrom(c.getAccessClass())); } catch (NumberFormatException nfe) { sensitivity = 0; // The short must go on } if ((subject = Property.stringFrom(c.getSummary())) == null && body != null) { int endOfSentence = body.indexOf('.'); if (endOfSentence == -1) { endOfSentence = body.length(); } if (endOfSentence > SQL_SUBJECT_DIM) { endOfSentence = SQL_SUBJECT_DIM; } subject = body.substring(0, endOfSentence); } String isInfinite = "0"; if (rp != null) { interval = rp.getInterval(); recurrenceType = rp.getTypeId(); monthOfYear = rp.getMonthOfYear(); dayOfMonth = rp.getDayOfMonth(); dayOfWeekMask = String.valueOf(rp.getDayOfWeekMask()); instance = rp.getInstance(); startDatePattern = rp.getStartDatePattern(); endDatePattern = rp.getEndDatePattern(); if (rp.isNoEndDate()) { isInfinite = "1"; } occurrences = rp.getOccurrences(); } if (c instanceof Task) { Task t = (Task) c; if (t.getDateCompleted() != null) { completed = getDateFromString(allDayB, ((Task) c).getDateCompleted().getPropertyValueAsString(), "000000"); } try { String complete = Property.stringFrom(t.getComplete()); if (complete != null && complete.equals("1")) { percentComplete = 100; } else { percentComplete = Short.parseShort(Property.stringFrom(t.getPercentComplete())); } if (percentComplete < 0 || percentComplete > 100) { throw new NumberFormatException("A percentage can't be " + percentComplete); } } catch (NumberFormatException nfe) { percentComplete = -1; // the short must go on } meetingStatus = getTaskStatus(t); } con = getUserDataSource().getRoutedConnection(userId); ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR); ps.setLong(1, id); ps.setString(2, userId); ps.setLong(3, lastUpdate.getTime()); ps.setString(4, String.valueOf(Def.PIM_STATE_NEW)); ps.setString(5, allDay); ps.setString(6, StringUtils.left(body, SQL_BODY_DIM)); if (busyStatus != null) { ps.setShort(7, busyStatus.shortValue()); } else { ps.setNull(7, Types.SMALLINT); } ps.setString(8, StringUtils.left(categories, SQL_CATEGORIES_DIM)); ps.setString(9, StringUtils.left(companies, SQL_COMPANIES_DIM)); ps.setInt(10, duration); if (dend != null) { ps.setTimestamp(11, new Timestamp(dend.getTime())); } else { ps.setNull(11, Types.TIMESTAMP); } if (c.getPriority() != null) { String priority = c.getPriority().getPropertyValueAsString(); if (priority != null && priority.length() > 0) { importance = Short.parseShort(priority); ps.setShort(12, importance); } else { ps.setNull(12, Types.SMALLINT); } } else { ps.setNull(12, Types.SMALLINT); } ps.setString(13, StringUtils.left(location, SQL_LOCATION_DIM)); if (meetingStatus != null) { ps.setShort(14, meetingStatus.shortValue()); } else { ps.setNull(14, Types.SMALLINT); } ps.setString(15, mileage); reminder = c.getReminder(); if (reminder != null && reminder.isActive()) { Timestamp reminderTime = getReminderTime(dstart, reminder); if (reminderTime == null) { ps.setNull(16, Types.TIMESTAMP); } else { ps.setTimestamp(16, reminderTime); } ps.setInt(17, reminder.getRepeatCount()); ps.setString(18, (reminder.isActive()) ? "1" : "0"); String soundFileValue = reminder.getSoundFile(); ps.setString(19, StringUtils.left(soundFileValue, SQL_SOUNDFILE_DIM)); ps.setInt(20, reminder.getOptions()); } else { ps.setNull(16, Types.TIMESTAMP); ps.setInt(17, 0); ps.setString(18, "0"); ps.setString(19, null); ps.setInt(20, 0); } if (replyTime != null) { ps.setTimestamp(21, new Timestamp(replyTime.getTime())); } else { ps.setNull(21, Types.TIMESTAMP); } ps.setShort(22, sensitivity); if (dstart != null) { ps.setTimestamp(23, new Timestamp(dstart.getTime())); } else { ps.setNull(23, Types.TIMESTAMP); } ps.setString(24, StringUtils.left(subject, SQL_SUBJECT_DIM)); ps.setShort(25, recurrenceType); ps.setInt(26, interval); ps.setShort(27, monthOfYear); ps.setShort(28, dayOfMonth); ps.setString(29, StringUtils.left(dayOfWeekMask, SQL_DAYOFWEEKMASK_DIM)); ps.setShort(30, instance); ps.setString(31, StringUtils.left(startDatePattern, SQL_STARTDATEPATTERN_DIM)); ps.setString(32, isInfinite); ps.setString(33, StringUtils.left(endDatePattern, SQL_ENDDATEPATTERN_DIM)); ps.setInt(34, occurrences); if (c instanceof Event) { ps.setInt(35, CALENDAR_EVENT_TYPE); ps.setNull(36, Types.TIMESTAMP); // completed ps.setNull(37, Types.SMALLINT); // percent_complete } else { ps.setInt(35, CALENDAR_TASK_TYPE); if (completed != null) { ps.setTimestamp(36, new Timestamp(completed.getTime())); } else { ps.setNull(36, Types.TIMESTAMP); } if (percentComplete != -1) { ps.setShort(37, percentComplete); } else { ps.setNull(37, Types.SMALLINT); } } ps.setString(38, StringUtils.left(folder, SQL_FOLDER_DIM)); ps.setString(39, StringUtils.left(dstartTimeZone, SQL_TIME_ZONE_DIM)); ps.setString(40, StringUtils.left(dendTimeZone, SQL_TIME_ZONE_DIM)); ps.setString(41, StringUtils.left(reminderTimeZone, SQL_TIME_ZONE_DIM)); ps.executeUpdate(); DBTools.close(null, ps, null); if (recurrenceType != -1) { List<ExceptionToRecurrenceRule> exceptions = rp.getExceptions(); for (ExceptionToRecurrenceRule etrr : exceptions) { ps = con.prepareStatement(SQL_INSERT_INTO_FNBL_PIM_CALENDAR_EXCEPTION); ps.setLong(1, id); ps.setString(2, (etrr.isAddition() ? "1" : "0")); ps.setTimestamp(3, new Timestamp(getDateFromString(allDayB, etrr.getDate(), "000000").getTime())); ps.executeUpdate(); DBTools.close(null, ps, null); } } } catch (Exception e) { throw new DAOException("Error adding a calendar item: " + e.getMessage(), e); } finally { DBTools.close(con, ps, null); } }
From source file:com.ellychou.todo.rest.service.SpringContextJerseyTest.java
/** * Get the port to be used for test application deployments. * * @return The HTTP port of the URI/*from www . java 2s . c om*/ */ protected final int getPort() { final String value = AccessController .doPrivileged(PropertiesHelper.getSystemProperty(TestProperties.CONTAINER_PORT)); if (value != null) { try { final int i = Integer.parseInt(value); if (i <= 0) { throw new NumberFormatException("Value not positive."); } return i; } catch (NumberFormatException e) { LOGGER.log(Level.CONFIG, "Value of " + TestProperties.CONTAINER_PORT + " property is not a valid positive integer [" + value + "]." + " Reverting to default [" + TestProperties.DEFAULT_CONTAINER_PORT + "].", e); } } return TestProperties.DEFAULT_CONTAINER_PORT; }
From source file:erigo.ctstream.CTstream.java
/** * /*from w ww . ja va2 s.c om*/ * CTstream constructor * * @param argsI Command line arguments */ public CTstream(String[] argsI) { // Create a String version of FPS_VALUES String FPS_VALUES_STR = new String(FPS_VALUES[0].toString()); for (int i = 1; i < FPS_VALUES.length; ++i) { FPS_VALUES_STR = FPS_VALUES_STR + "," + FPS_VALUES[i].toString(); } // Create a String version of CTsettings.flushIntervalLongs String FLUSH_VALUES_STR = String.format("%.1f", CTsettings.flushIntervalLongs[0] / 1000.0); for (int i = 1; i < CTsettings.flushIntervalLongs.length; ++i) { // Except for the first flush value (handled above, first item in the string) the rest of these // are whole numbers, so we will print them out with no decimal places FLUSH_VALUES_STR = FLUSH_VALUES_STR + "," + String.format("%.0f", CTsettings.flushIntervalLongs[i] / 1000.0); } // // Parse command line arguments // // 1. Setup command line options // Options options = new Options(); // Boolean options (only the flag, no argument) options.addOption("h", "help", false, "Print this message."); options.addOption("nm", "no_mouse_cursor", false, "Don't include mouse cursor in output screen capture images."); options.addOption("nz", "no_zip", false, "Turn off ZIP output."); options.addOption("x", "debug", false, "Turn on debug output."); options.addOption("cd", "change_detect", false, "Save only changed images."); options.addOption("fs", "full_screen", false, "Capture the full screen."); options.addOption("p", "preview", false, "Display live preview image"); options.addOption("T", "UI_on_top", false, "Keep CTstream on top of all other windows."); options.addOption("sc", "screencap", false, "Capture screen images"); options.addOption("w", "webcam", false, "Capture webcam images"); options.addOption("a", "audio", false, "Record audio."); options.addOption("t", "text", false, "Capture text."); // Command line options that include a flag // For example, the following will be for "-outputfolder <folder> (Location of output files...)" Option option = Option.builder("o").longOpt("outputfolder").argName("folder").hasArg() .desc("Location of output files (source is created under this folder); default = \"" + outputFolder + "\".") .build(); options.addOption(option); option = Option.builder("fps").argName("framespersec").hasArg().desc( "Image rate (images/sec); default = " + DEFAULT_FPS + "; accepted values = " + FPS_VALUES_STR + ".") .build(); options.addOption(option); option = Option.builder("f").argName("autoFlush").hasArg() .desc("Flush interval (sec); amount of data per block; default = " + Double.toString(AUTO_FLUSH_DEFAULT) + "; accepted values = " + FLUSH_VALUES_STR + ".") .build(); options.addOption(option); option = Option.builder("s").argName("source name").hasArg() .desc("Name of output source; default = \"" + sourceName + "\".").build(); options.addOption(option); option = Option.builder("sc_chan").argName("screencap_chan_name").hasArg() .desc("Screen capture image channel name (must end in \".jpg\" or \".jpeg\"); default = \"" + screencapStreamName + "\".") .build(); options.addOption(option); option = Option.builder("webcam_chan").argName("webcam_chan_name").hasArg() .desc("Web camera image channel name (must end in \".jpg\" or \".jpeg\"); default = \"" + webcamStreamName + "\".") .build(); options.addOption(option); option = Option.builder("audio_chan").argName("audio_chan_name").hasArg() .desc("Audio channel name (must end in \".wav\"); default = \"" + audioStreamName + "\".").build(); options.addOption(option); option = Option.builder("text_chan").argName("text_chan_name").hasArg() .desc("Text channel name (must end in \".txt\"); default = \"" + textStreamName + "\".").build(); options.addOption(option); option = Option.builder("q").argName("imagequality").hasArg() .desc("Image quality, 0.00 - 1.00 (higher numbers are better quality); default = " + Float.toString(imageQuality) + ".") .build(); options.addOption(option); // // 2. Parse command line options // CommandLineParser parser = new DefaultParser(); CommandLine line = null; try { line = parser.parse(options, argsI); } catch (ParseException exp) { // oops, something went wrong System.err.println("Command line argument parsing failed: " + exp.getMessage()); return; } // // 3. Retrieve the command line values // if (line.hasOption("help")) { // Display help message and quit HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(160); formatter.printHelp("CTstream", options); System.exit(0); } bPreview = line.hasOption("preview"); bScreencap = line.hasOption("screencap"); bWebcam = line.hasOption("webcam"); bAudio = line.hasOption("audio"); bText = line.hasOption("text"); // Source name sourceName = line.getOptionValue("s", sourceName); // Where to write the files to outputFolder = line.getOptionValue("outputfolder", outputFolder); // Channel names; check filename extensions screencapStreamName = line.getOptionValue("sc_chan", screencapStreamName); webcamStreamName = line.getOptionValue("webcam_chan", webcamStreamName); audioStreamName = line.getOptionValue("audio_chan", audioStreamName); textStreamName = line.getOptionValue("text_chan", textStreamName); try { checkFilenames(); } catch (Exception e) { System.err.println(e.getMessage()); return; } // Auto-flush time try { double autoFlush = Double.parseDouble(line.getOptionValue("f", "" + AUTO_FLUSH_DEFAULT)); flushMillis = (long) (autoFlush * 1000.); boolean bGotMatch = false; for (int i = 0; i < CTsettings.flushIntervalLongs.length; ++i) { if (flushMillis == CTsettings.flushIntervalLongs[i]) { bGotMatch = true; break; } } if (!bGotMatch) { throw new NumberFormatException("bad input value"); } } catch (NumberFormatException nfe) { System.err.println("\nAuto flush time must be one of the following values: " + FLUSH_VALUES_STR); return; } // ZIP output files? (the only way to turn off ZIP is using this command line flag) bZipMode = !line.hasOption("no_zip"); // Include cursor in output screen capture images? bIncludeMouseCursor = !line.hasOption("no_mouse_cursor"); // How many frames (screen or webcam images) to capture per second try { framesPerSec = Double.parseDouble(line.getOptionValue("fps", "" + DEFAULT_FPS)); if (framesPerSec <= 0.0) { throw new NumberFormatException("value must be greater than 0.0"); } // Make sure framesPerSec is one of the accepted values Double userVal = framesPerSec; if (!Arrays.asList(FPS_VALUES).contains(userVal)) { throw new NumberFormatException(new String("framespersec value must be one of: " + FPS_VALUES_STR)); } } catch (NumberFormatException nfe) { System.err.println( "\nError parsing \"fps\"; it must be one of the accepted floating point values:\n" + nfe); return; } // Run CT in debug mode? bDebugMode = line.hasOption("debug"); // changeDetect mode? MJM bChangeDetect = line.hasOption("change_detect"); // Capture the full screen? bFullScreen = line.hasOption("full_screen"); // Keep CTstream UI on top of all other windows? bStayOnTop = line.hasOption("UI_on_top"); // Image quality String imageQualityStr = line.getOptionValue("q", "" + imageQuality); try { imageQuality = Float.parseFloat(imageQualityStr); if ((imageQuality < 0.0f) || (imageQuality > 1.0f)) { throw new NumberFormatException(""); } } catch (NumberFormatException nfe) { System.err.println("\nimage quality must be a number in the range 0.0 <= x <= 1.0"); return; } // // Specify a shutdown hook to catch Ctrl+c // final CTstream temporaryCTS = this; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (bCallExitFromShutdownHook) { temporaryCTS.exit(true); } } }); // For now, we are going to assume that shaped windows (PERPIXEL_TRANSPARENT) are supported. // For a discussion of translucent and shaped windows see https://docs.oracle.com/javase/tutorial/uiswing/misc/trans_shaped_windows.html // This includes examples on how to check if TRANSLUCENT and PERPIXEL_TRANSPARENT are supported by the graphics. // For thread safety: Schedule a job for the event-dispatching thread to create and show the GUI SwingUtilities.invokeLater(new Runnable() { public void run() { temporaryCTS.createAndShowGUI(true); } }); }
From source file:com.ottogroup.bi.streaming.operator.json.JsonProcessingUtils.java
/** * Extracts from a {@link JSONObject} the value of the field referenced by the provided path. The received content is treated as * {@link Integer} value. If the value is a plain {@link Integer} value it is returned right away. Integer values contained inside {@link String} * instances are parsed out by {@link Integer#parseInt(String)}. If parsing fails or the type is not of the referenced ones the method * throws a {@link NumberFormatException} * @param jsonObject// w ww.ja v a 2 s . co m * The {@link JSONObject} to read the value from (null is not permitted as input) * @param fieldPath * Path inside the {@link JSONObject} pointing towards the value of interest (null is not permitted as input) * @param required * Field is required to exist at the end of the given path * @return * Value found at the end of the provided path. An empty path simply returns the input * @throws JSONException * Thrown in case extracting values from the {@link JSONObject} fails for any reason * @throws IllegalArgumentException * Thrown in case a provided parameter does not comply with the restrictions * @throws NoSuchElementException * Thrown in case an element referenced inside the path does not exist at the expected location inside the {@link JSONObject} * @throws NumberFormatException * Thrown in case parsing out an {@link Integer} from the retrieved field value fails for any format related reason */ public Integer getIntegerFieldValue(final JSONObject jsonObject, final String[] fieldPath, final boolean required) throws JSONException, IllegalArgumentException, NoSuchElementException, NumberFormatException { Object value = getFieldValue(jsonObject, fieldPath, required); if (value == null && !required) return null; if (value instanceof Integer) return (Integer) value; else if (value instanceof String) return Integer.parseInt((String) value); throw new NumberFormatException("Types of " + (value != null ? value.getClass().getName() : "null") + " cannot be parsed into a valid integer representation"); }
From source file:com.partnet.automation.HtmlView.java
/** * Waits for a page to load; a set amount of time is allotted. * /*ww w .j a va 2 s . c o m*/ * @param ignoreWebDriverException * - whether or not a {@link WebDriverException} should be ignored. * In certain cases, it can be useful to not ignore exceptions thrown * when waiting for the page to load, however typically this value * should be true. */ protected void waitForPageToLoad(boolean ignoreWebDriverException) { LOG.debug("Wait for page to load.."); String stringWaitProp = System.getProperty(WAIT_FOR_PAGE_PROP, "90"); int waitProp; try { waitProp = Integer.parseInt(stringWaitProp); } catch (NumberFormatException e) { throw new NumberFormatException( String.format("%s, could not determine %s", e.getMessage(), WAIT_FOR_PAGE_PROP)); } WebDriverWait wait = new WebDriverWait(webDriver, waitProp); if (ignoreWebDriverException) { wait.ignoring(WebDriverException.class); } wait.until(conditionPageLoaded); // wait for the page to load }
From source file:classification.SentimentClassification.java
/** * @param doc//from w w w. j a v a2s . co m * @param sentenceLevelAnnotation * @param docContent * @param currentSentenceLevel */ private void extractOrientationTermPhrases(Document doc, Annotation sentenceLevelAnnotation, DocumentContent docContent, SentimentSentence currentSentenceLevel) { if (sentenceLevelAnnotation.getFeatures().containsKey("OrientationTermPhrase")) { String orienttionTermFeatureString = sentenceLevelAnnotation.getFeatures().get("OrientationTermPhrase") .toString(); String[] orientationTermIDs = splitFeatureString(orienttionTermFeatureString); for (String currentID : orientationTermIDs) { try { log.info("Extract OrientationTermPhrase with currentID: " + currentID); currentID = currentID.trim(); Integer otID = null; try { otID = Integer.valueOf(currentID); } catch (NumberFormatException nfex) { log.error("Cannot extract Orientationterm Gate ID from String: " + otID); throw new NumberFormatException("Cannot extract Orientationterm Gate ID from String: " + otID + "\n" + nfex.getMessage()); } Phrase orientationPhrase = extractPhrase(doc.getAnnotations().get(otID), docContent, "Orientation", databaseConn.getConstantEntites().getOrientationPhraseType()); currentSentenceLevel.getOrientationTermPhraseList().add(orientationPhrase); } catch (NumberFormatException nfex) { log.error(nfex.getMessage()); log.error("Continue with next orientationTerm"); continue; } } } }
From source file:com.glaf.core.util.GetterUtils.java
public static short getShortStrict(String value) { int i = getIntegerStrict(value); if ((i < Short.MIN_VALUE) || (i > Short.MAX_VALUE)) { throw new NumberFormatException("Out of range value " + value); }/*ww w .ja v a 2s . c o m*/ return (short) i; }
From source file:edu.nyu.tandon.tool.RawHits.java
/** * Interpret the given command, changing the static variables. * See the help printing code for possible commands. * * @param line the command line./*from w w w . j ava2s. co m*/ * @return false iff we should exit after this command. */ public boolean interpretCommand(final String line) { String[] part = line.substring(1).split("[ \t\n\r]+"); final Command command; int i; if (part[0].length() == 0) { System.err.println("$ prints this help."); System.err.println("$mode [time|short|long|snippet|trec <topicNo> <runTag>] chooses display mode."); System.err.println( "$limit <max> output at most <max> results per query."); System.err.println( "$divert [<filename>] diverts output to <filename> or to stdout."); System.err.println( "$weight {index:weight} set index weights (unspecified weights are set to 1)."); System.err.println("$mplex [<on>|<off>] set/unset multiplex mode."); System.err.println( "$equalize <sample> equalize scores using the given sample size."); System.err.println( "$score {<scorerClass>(<arg>,...)[:<weight>]} order documents according to <scorerClass>."); System.err.println( "$expand {<expanderClass>(<arg>,...)} expand terms and prefixes according to <expanderClass>."); System.err.println("$quit quits."); return true; } try { command = Command.valueOf(part[0].toUpperCase()); } catch (IllegalArgumentException e) { System.err.println("Invalid command \"" + part[0] + "\"; type $ for help."); return true; } switch (command) { case MODE: if (part.length >= 2) { try { final OutputType tempMode = OutputType.valueOf(part[1].toUpperCase()); if (tempMode != OutputType.TREC && part.length > 2) System.err.println("Extra arguments."); else if (tempMode == OutputType.TREC && part.length != 4) System.err.println("Missing or extra arguments."); else { displayMode = tempMode; if (displayMode == OutputType.TREC) { trecTopicNumber = Integer.parseInt(part[2]); trecRunTag = part[3]; } } } catch (IllegalArgumentException e) { System.err.println("Unknown mode: " + part[1]); } } else System.err.println("Missing mode."); break; case LIMIT: int out = -1; if (part.length == 2) { try { out = Integer.parseInt(part[1]); } catch (NumberFormatException e) { } if (out >= 0) maxOutput = out; } if (out < 0) System.err.println("Missing or incorrect limit."); break; case SCORE: final Scorer[] scorer = new Scorer[part.length - 1]; final double[] weight = new double[part.length - 1]; for (i = 1; i < part.length; i++) try { weight[i - 1] = loadClassFromSpec(part[i], scorer, i - 1); if (weight[i - 1] < 0) throw new IllegalArgumentException("Weights should be non-negative"); } catch (Exception e) { System.err.print("Error while parsing specification: "); e.printStackTrace(System.err); break; } if (i == part.length) queryEngine.score(scorer, weight); break; case EXPAND: if (part.length > 2) System.err.println("Wrong argument(s) to command"); else if (part.length == 1) { queryEngine.transformer(null); } else { QueryTransformer[] t = new QueryTransformer[1]; try { loadClassFromSpec(part[1], t, 0); queryEngine.transformer(t[0]); } catch (Exception e) { System.err.print("Error while parsing specification: "); e.printStackTrace(System.err); break; } } break; case MPLEX: if (part.length != 2 || (part.length == 2 && !"on".equals(part[1]) && !"off".equals(part[1]))) System.err.println("Wrong argument(s) to command"); else { if (part.length > 1) queryEngine.multiplex = "on".equals(part[1]); System.err.println("Multiplex: " + part[1]); } break; case DIVERT: if (part.length > 2) System.err.println("Wrong argument(s) to command"); else { outputPH.close(); try { outputPH = part.length == 1 ? System.out : new PrintStream(new FastBufferedOutputStream( new FileOutputStream(part[1] + "-" + phBatch++ + ".ph.txt"))); outputName = part[1]; } catch (FileNotFoundException e) { System.err.println("Cannot create file " + part[1]); outputPH = System.out; } } break; case EQUALIZE: try { if (part.length != 2) throw new NumberFormatException("Illegal number of arguments"); queryEngine.equalize(Integer.parseInt(part[1])); System.err.println("Equalization sample set to " + Integer.parseInt(part[1])); } catch (NumberFormatException e) { System.err.println(e.getMessage()); } break; case QUIT: return false; } return true; }