List of usage examples for org.apache.commons.lang3.math NumberUtils toInt
public static int toInt(final String str)
Convert a String
to an int
, returning zero
if the conversion fails.
If the string is null
, zero
is returned.
NumberUtils.toInt(null) = 0 NumberUtils.toInt("") = 0 NumberUtils.toInt("1") = 1
From source file:com.bekwam.examples.javafx.oldscores2.ScoresDialogController.java
@FXML public void updateMath1995() { if (logger.isDebugEnabled()) { logger.debug("[UPD 1995]"); }/*from w w w.j a v a2 s.c o m*/ if (dao == null) { throw new IllegalArgumentException( "dao has not been set; call setRecenteredDAO() before calling this method"); } String recenteredScore_s = txtMathScoreRecentered.getText(); if (StringUtils.isNumeric(recenteredScore_s)) { Integer scoreRecentered = NumberUtils.toInt(recenteredScore_s); if (withinRange(scoreRecentered)) { if (needsRound(scoreRecentered)) { scoreRecentered = round(scoreRecentered); txtMathScoreRecentered.setText(String.valueOf(scoreRecentered)); } resetErrMsgs(); Integer score1995 = dao.lookup1995MathScore(scoreRecentered); txtMathScore1995.setText(String.valueOf(score1995)); } else { errMsgMathRecentered.setVisible(true); } } else { errMsgMathRecentered.setVisible(true); } }
From source file:com.mirth.connect.connectors.ws.WebServiceDispatcher.java
@Override public void onDeploy() throws ConnectorTaskException { this.connectorProperties = (WebServiceDispatcherProperties) getConnectorProperties(); // load the default configuration String configurationClass = configurationController.getProperty(connectorProperties.getProtocol(), "wsConfigurationClass"); try {// w w w .ja v a 2 s . c o m configuration = (WebServiceConfiguration) Class.forName(configurationClass).newInstance(); } catch (Exception e) { logger.trace("could not find custom configuration class, using default"); configuration = new DefaultWebServiceConfiguration(); } try { socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()); configuration.configureConnectorDeploy(this); } catch (Exception e) { throw new ConnectorTaskException(e); } timeout = NumberUtils.toInt(connectorProperties.getSocketTimeout()); }
From source file:com.autonomy.nonaci.indexing.impl.IndexingServiceImpl.java
/** * Executes an index command/*from w w w. j ava 2s . co m*/ * * @param serverDetails The connection details of the indexing server. * @param command The index command to execute * @return the index queue id for the command * @throws com.autonomy.nonaci.indexing.IndexingException if an error response was detected, or if something went * wrong while executing the command */ @Override public int executeCommand(final ServerDetails serverDetails, final IndexCommand command) throws IndexingException { LOGGER.trace("executeCommand() called..."); // Sanity check... Validate.notNull(serverDetails, "Indexing server connection details must be set before calling this method."); Validate.notNull(command.getCommand(), "You must set a valid index command to execute"); Validate.notNull(httpClient, "You must set httpClient before executing commands"); HttpResponse httpResponse = null; try { // Create the HTTP method to use... final HttpUriRequest httpRequest = (command.getPostData() == null) ? createGetMethod(serverDetails, command) : createPostMethod(serverDetails, command); LOGGER.debug("Executing a {} index command...", command.getCommand()); // Execute the command... httpResponse = httpClient.execute(httpRequest); LOGGER.debug("Successfully executed the index command, HTTP status - {}...", httpResponse.getStatusLine().getStatusCode()); // Get the response... final ByteArrayOutputStream baos = new ByteArrayOutputStream(); httpResponse.getEntity().writeTo(baos); final String response = baos.toString("UTF-8"); if (!response.contains("INDEXID")) { throw new IndexingException(response.trim()); } // Get the index queue id... final Matcher matcher = pattern.matcher(response); if (matcher.matches()) { return NumberUtils.toInt(matcher.group(1)); } throw new IndexingException("Unable to get index queue id from response: [" + response + ']'); } catch (final IOException ioe) { throw new IndexingException("Unable to execute the Index command", ioe); } catch (final URISyntaxException urise) { throw new IndexingException("Unable to construct the Index command URI.", urise); } finally { try { if (httpResponse != null) { // Release the HTTP connection... EntityUtils.consume(httpResponse.getEntity()); } } catch (final IOException ioe) { LOGGER.error("Unable to consume any remaining content from the IndexCommand response.", ioe); } } }
From source file:com.norconex.importer.handler.splitter.impl.CsvSplitter.java
private boolean isColumnMatching(String colName, int colPosition, String... namesOrPossToMatch) { if (ArrayUtils.isEmpty(namesOrPossToMatch)) { return false; }/*from w w w . j av a 2s .c o m*/ for (String nameOrPosToMatch : namesOrPossToMatch) { if (StringUtils.isBlank(nameOrPosToMatch)) { continue; } if (Objects.equals(nameOrPosToMatch, colName) || NumberUtils.toInt(nameOrPosToMatch) == colPosition) { return true; } } return false; }
From source file:de.adorsys.multibanking.hbci.model.HbciMapping.java
public static BankAccount toBankAccount(Konto konto) { BankAccount bankAccount = new BankAccount(); bankAccount.accountNumber(konto.number); bankAccount.bic(konto.bic);/*from w w w . jav a 2 s .c om*/ bankAccount.blz(konto.blz); bankAccount.country(konto.country); bankAccount.currency(konto.curr); bankAccount.iban(konto.iban); bankAccount.owner((konto.name + (konto.name2 != null ? konto.name2 : "")).trim()); bankAccount.name(konto.type); bankAccount.type(BankAccountType.fromHbciType(NumberUtils.toInt(konto.acctype))); return bankAccount; }
From source file:com.omertron.omdbapi.model.OmdbVideoFull.java
public void setMetascore(String metascore) { if (NumberUtils.isParsable(metascore)) { this.metascore = NumberUtils.toInt(metascore); } }
From source file:com.enation.app.b2b2c.core.action.api.store.StoreApiAction.java
/** * /*from ww w . j a v a 2 s. com*/ * @param store ?,Store * @return json * result 1?0 */ public String edit() { try { HttpServletRequest request = ThreadContextHolder.getHttpRequest(); Map<String, Object> map = new HashMap<String, Object>(); map.put("store_id", request.getParameter("store_id")); map.put("attr", request.getParameter("attr")); map.put("zip", request.getParameter("zip")); map.put("tel", request.getParameter("tel")); map.put("qq", request.getParameter("qq")); map.put("description", description); //??src? whj 2015-06-18 map.put("store_logo", request.getParameter("store_logo")); map.put("store_banner", request.getParameter("store_banner")); map.put("store_provinceid", NumberUtils.toInt(request.getParameter("province_id").toString())); map.put("store_cityid", NumberUtils.toInt(request.getParameter("city_id").toString())); map.put("store_regionid", NumberUtils.toInt(request.getParameter("region_id").toString())); map.put("store_province", request.getParameter("province")); map.put("store_city", request.getParameter("city")); map.put("store_region", request.getParameter("region")); this.storeManager.editStore(map); this.showSuccessJson("??"); } catch (Exception e) { e.printStackTrace(); this.showErrorJson("?"); this.logger.error("?:" + e); } return this.JSON_MESSAGE; }
From source file:fr.paris.lutece.plugins.grusupply.service.CustomerProvider.java
/** * Converts a IdentityDto to a customer/* w w w . j a v a2 s.c om*/ * * @param identityDto * the identity * @return the customer */ private static Customer convert(IdentityDto identityDto) { Customer customer = new Customer(); customer.setId(identityDto.getCustomerId()); customer.setConnectionId(identityDto.getConnectionId()); customer.setLastname(getAttribute(identityDto, ATTRIBUTE_IDENTITY_NAME_FAMILLY)); customer.setFirstname(getAttribute(identityDto, ATTRIBUTE_IDENTITY_NAME_GIVEN)); customer.setEmail(getAttribute(identityDto, ATTRIBUTE_IDENTITY_HOMEINFO_ONLINE_EMAIL)); customer.setMobilePhone(getAttribute(identityDto, ATTRIBUTE_IDENTITY_HOMEINFO_TELECOM_MOBILE_NUMBER)); customer.setFixedPhoneNumber( getAttribute(identityDto, ATTRIBUTE_IDENTITY_HOMEINFO_TELECOM_TELEPHONE_NUMBER)); customer.setIdTitle(NumberUtils.toInt(getAttribute(identityDto, ATTRIBUTE_IDENTITY_GENDER))); customer.setBirthDate(getAttribute(identityDto, ATTRIBUTE_IDENTITY_BIRTHDATE)); return customer; }
From source file:com.blackducksoftware.integration.hub.teamcity.agent.scan.HubBuildProcess.java
@Override public BuildFinishedStatus call() throws IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, EncryptionException { final BuildProgressLogger buildLogger = build.getBuildLogger(); final HubAgentBuildLogger hubLogger = new HubAgentBuildLogger(buildLogger); final Map<String, String> variables = getVariables(); final CIEnvironmentVariables commonVariables = new CIEnvironmentVariables(); commonVariables.putAll(variables);/*from www . ja v a2 s . c om*/ hubLogger.setLogLevel(commonVariables); setHubLogger(hubLogger); if (StringUtils.isBlank(System.getProperty("http.maxRedirects"))) { // If this property is not set the default is 20 // When not set the Authenticator redirects in a loop and results in // an error for too many redirects System.setProperty("http.maxRedirects", "3"); } result = BuildFinishedStatus.FINISHED_SUCCESS; logger.targetStarted("Hub Build Step"); final String localHostName = HostnameHelper.getMyHostname(); logger.info("Running on machine : " + localHostName); final String thirdPartyVersion = ServerVersionHolder.getVersion().getDisplayVersion(); final String pluginVersion = getPluginVersion(commonVariables); logger.info("TeamCity version : " + thirdPartyVersion); logger.info("Hub TeamCity Plugin version : " + pluginVersion); try { final HubServerConfig hubConfig = getHubServerConfig(logger, commonVariables); if (hubConfig == null) { logger.error("Please verify the correct dependent Hub configuration plugin is installed"); logger.error("Please verify the configuration is correct if the plugin is installed."); result = BuildFinishedStatus.FINISHED_FAILED; return result; } hubConfig.print(logger); final boolean isRiskReportGenerated = Boolean .parseBoolean(commonVariables.getValue(HubConstantValues.HUB_GENERATE_RISK_REPORT)); boolean isFailOnPolicySelected = false; final Collection<AgentBuildFeature> features = build .getBuildFeaturesOfType(HubBundle.POLICY_FAILURE_CONDITION); // The feature is only allowed to have a single instance in the // configuration therefore we just want to make // sure the feature collection has something meaning that it was // configured. if (features != null && features.iterator() != null && !features.isEmpty() && features.iterator().next() != null) { isFailOnPolicySelected = true; } long waitTimeForReport; final String maxWaitTimeForRiskReport = commonVariables .getValue(HubConstantValues.HUB_MAX_WAIT_TIME_FOR_RISK_REPORT); if (StringUtils.isNotBlank(maxWaitTimeForRiskReport)) { waitTimeForReport = NumberUtils.toInt(maxWaitTimeForRiskReport); if (waitTimeForReport <= 0) { // 5 minutes is the default waitTimeForReport = DEFAULT_MAX_WAIT_TIME_MILLISEC; } else { waitTimeForReport = waitTimeForReport * 60 * 1000; } } else { waitTimeForReport = DEFAULT_MAX_WAIT_TIME_MILLISEC; } logger.info("--> Generate Risk Report : " + isRiskReportGenerated); logger.info("--> Bom wait time : " + maxWaitTimeForRiskReport); logger.info("--> Check Policies : " + isFailOnPolicySelected); final File workingDirectory = context.getWorkingDirectory(); final File toolsDir = new File(build.getAgentConfiguration().getAgentToolsDirectory(), "HubCLI"); final HubScanConfig hubScanConfig = getScanConfig(workingDirectory, toolsDir, hubLogger, commonVariables); final RestConnection restConnection = getRestConnection(logger, hubConfig); restConnection.connect(); HubServicesFactory services = new HubServicesFactory(restConnection); services.addEnvironmentVariables(variables); PhoneHomeService phoneHomeService = services.createPhoneHomeService(); PhoneHomeRequestBody.Builder builder = phoneHomeService.createInitialPhoneHomeRequestBodyBuilder(); builder.setArtifactId("hub-teamcity"); builder.setArtifactVersion(pluginVersion); builder.addToMetaData("teamcity.version", thirdPartyVersion); phoneHomeService.phoneHome(builder); final SignatureScannerService signatureScannerService = services .createSignatureScannerService(hubConfig.getTimeout() * 60 * 1000); final ProjectRequest projectRequest = getProjectRequest(hubLogger, commonVariables); if (hubScanConfig == null) { logger.error("Please verify the Black Duck Hub Runner configuration is correct."); result = BuildFinishedStatus.FINISHED_FAILED; return result; } else if (projectRequest == null) { logger.debug("No project and version specified."); } final boolean shouldWaitForScansFinished = isRiskReportGenerated || isFailOnPolicySelected; ProjectVersionWrapper projectVersionWrapper = null; try { projectVersionWrapper = signatureScannerService.installAndRunControlledScan(hubConfig, hubScanConfig, projectRequest, shouldWaitForScansFinished); } catch (final HubIntegrationException e) { logger.error(e.getMessage(), e); result = BuildFinishedStatus.FINISHED_FAILED; return result; } catch (final InterruptedException e) { logger.error("BD scan was interrupted."); result = BuildFinishedStatus.INTERRUPTED; return result; } if (!hubScanConfig.isDryRun()) { final MetaHandler metaHandler = new MetaHandler(logger); ProjectView project = null; if (isRiskReportGenerated) { logger.info("Generating Risk Report"); publishRiskReportFiles(logger, workingDirectory, services.createReportService(waitTimeForReport), projectVersionWrapper.getProjectView(), projectVersionWrapper.getProjectVersionView()); } if (isFailOnPolicySelected) { logger.info("Checking for Policy violations."); checkPolicyFailures(build, logger, services.createHubService(), metaHandler, projectVersionWrapper.getProjectVersionView(), hubScanConfig.isDryRun()); } } else { if (isRiskReportGenerated) { logger.warn("Will not generate the risk report because this was a dry run scan."); } if (isFailOnPolicySelected) { logger.warn("Will not run the Failure conditions because this was a dry run scan."); } } } catch (final Exception e) { logger.error(e); result = BuildFinishedStatus.FINISHED_FAILED; } logger.targetFinished("Hub Build Step"); return result; }
From source file:gov.va.chir.tagline.dao.FileDao.java
public static Collection<Document> loadScoringLines(final File file, boolean hasHeader) throws IOException { final Map<String, Map<Integer, Line>> docMap = new HashMap<String, Map<Integer, Line>>(); // Assumes tab-delimited columns. May not be sorted. // Column labels may be on first line // Col 0 = NoteID // Col 1 = LineID // Col 2 = Text final int POS_DOC_ID = 0; final int POS_LINE_ID = 1; final int POS_TEXT = 2; final List<String> contents = FileUtils.readLines(file); for (int i = (hasHeader ? 1 : 0); i < contents.size(); i++) { final String l = contents.get(i); final String[] array = l.split("\t"); if (!docMap.containsKey(array[POS_DOC_ID])) { docMap.put(array[POS_DOC_ID], new TreeMap<Integer, Line>()); }// www. java 2 s .c om int lineId = NumberUtils.toInt(array[POS_LINE_ID]); final Line line = new Line(lineId, array[POS_TEXT]); docMap.get(array[POS_DOC_ID]).put(lineId, line); } final Collection<Document> docs = new ArrayList<Document>(); for (String docId : docMap.keySet()) { docs.add(new Document(docId, new ArrayList<Line>(docMap.get(docId).values()))); } return docs; }