List of usage examples for java.lang Float parseFloat
public static float parseFloat(String s) throws NumberFormatException
From source file:alba.solr.docvalues.FloatFunction.java
@Override public float floatVal(int doc) { // TODO Auto-generated method stub Map<String, Object> params = new HashMap<String, Object>(); for (String s : args.keySet()) { if (args.get(s).startsWith("\"")) { params.put(s, args.get(s));//from w w w . j av a 2 s. co m } else if (NumberUtils.isNumber(args.get(s))) { Object objVal; try { objVal = Long.parseLong(args.get(s)); } catch (NumberFormatException nfe1) { try { objVal = Float.parseFloat(args.get(s)); } catch (NumberFormatException nfe2) { objVal = s; } } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } else if ("false".equals(args.get(s).toLowerCase())) { params.put(s, false); } else if ("true".equals(args.get(s).toLowerCase())) { params.put(s, true); } else { SchemaField f = fp.getReq().getSchema().getField(args.get(s)); ValueSource vs = f.getType().getValueSource(f, fp); Object objVal = null; try { objVal = vs.getValues(this.context, this.readerContext).longVal(doc); params.put(s, objVal); } catch (IOException e) { // TODO Auto-generated catch block // TODO Log properly try { objVal = vs.getValues(this.context, this.readerContext).floatVal(doc); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); try { objVal = vs.getValues(this.context, this.readerContext).strVal(doc); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } e.printStackTrace(); } if (objVal != null) { params.put(s, objVal); } else { params.put(s, "N/A"); } } } CallableFunction cf = functions.get(this.functionName); if (cf == null) { logger.error("unable to get function " + this.functionName); } if (cf != null) { List<Object> fnParams = new ArrayList<Object>(); Parameter[] methodParameters = cf.getMethod().getParameters(); //TODO spostare quanto pi codice possibile in fase di inizializzazione for (Parameter p : methodParameters) { if (p.isAnnotationPresent(Param.class)) { Param paramAnnotation = p.getAnnotation(Param.class); fnParams.add(params.get(paramAnnotation.name())); } } try { return (float) cf.getMethod().invoke(cf.getInstance(), fnParams.toArray()); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { // TODO Auto-generated catch block logger.error("errore mentre chiamavo " + cf.getMethod().getName(), e); for (Object o : fnParams) { logger.error("p " + o.toString()); } } } return -1f; }
From source file:hu.bme.mit.sette.common.model.runner.xml.ParameterElement.java
@Override protected void validate2(final GeneralValidator validator) { switch (getType()) { case BYTE:// ww w. ja v a 2s .co m // TODO validator exception Byte.parseByte(value); break; case SHORT: // TODO validator exception Short.parseShort(value); break; case INT: // TODO validator exception Integer.parseInt(value); break; case LONG: // TODO validator exception Long.parseLong(value); break; case FLOAT: // TODO validator exception Float.parseFloat(value); break; case DOUBLE: // TODO validator exception Double.parseDouble(value); break; case BOOLEAN: if (!value.equals("true") && !value.equals("false")) { // TODO error handling throw new RuntimeException("Bad boolean: " + value); } break; case CHAR: if (value.length() != 1) { // TODO error handling throw new RuntimeException("Bad char: " + value); } break; case EXPRESSION: if (StringUtils.isBlank(value)) { // TODO error handling throw new RuntimeException("Blank expression"); } break; default: // TODO error handling throw new RuntimeException("Unhandled parameter type: " + getType()); } }
From source file:hivemall.classifier.AROWClassifierUDTF.java
@Override protected CommandLine processOptions(ObjectInspector[] argOIs) throws UDFArgumentException { final CommandLine cl = super.processOptions(argOIs); float r = 0.1f; if (cl != null) { String r_str = cl.getOptionValue("r"); if (r_str != null) { r = Float.parseFloat(r_str); if (!(r > 0)) { throw new UDFArgumentException("Regularization parameter must be greater than 0: " + r_str); }/* w w w .ja va 2 s. co m*/ } } this.r = r; return cl; }
From source file:com.deltachi.videotex.grabers.IMDBGraber.java
@Override public Video getVideo(String imdbCode) throws JSONException, IOException { Video video = null;//from www .j a v a2s . c om JSONReader jsonReader = new JSONReader(); JSONObject jSONObject = null; jSONObject = jsonReader.readJsonFromUrl("http://www.omdbapi.com/?i=" + imdbCode); video = new Video(); video.setTitle(jSONObject.get("Title").toString()); video.setYear(Integer.parseInt(jSONObject.get("Year").toString())); video.setRated(jSONObject.get("Rated").toString()); String releasedString = jSONObject.get("Released").toString(); SimpleDateFormat releasedFormat = new SimpleDateFormat("dd MMM yyyy", Locale.US); Date released = null; try { released = releasedFormat.parse(releasedString); } catch (ParseException ex) { Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex); } video.setReleased(released); video.setRuntime(jSONObject.get("Runtime").toString()); String[] genres = jSONObject.get("Genre").toString().split(", "); Collection<Genre> genreCollection = new ArrayList<>(); for (String genres1 : genres) { Genre genre = new Genre(); genre.setName(genres1); genreCollection.add(genre); } video.setGenreCollection(genreCollection); video.setDirector(jSONObject.get("Director").toString()); video.setWriter("Writer"); video.setActors(jSONObject.get("Actors").toString()); video.setPlot(jSONObject.get("Plot").toString()); video.setLanguage(jSONObject.get("Language").toString()); video.setCountry(jSONObject.get("Country").toString()); video.setAwards(jSONObject.get("Awards").toString()); URL posterUrl = null; try { posterUrl = new URL(jSONObject.get("Poster").toString()); } catch (MalformedURLException ex) { Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex); } byte[] posterFile = null; try { posterFile = Downloader.getAsByteArray(posterUrl); } catch (IOException ex) { Logger.getLogger(IMDBGraber.class.getName()).log(Level.SEVERE, null, ex); } video.setPoster(posterFile); video.setRating(Float.parseFloat(jSONObject.get("imdbRating").toString())); video.setImdbCode(imdbCode); return video; }
From source file:org.thingsplode.synapse.core.MediaType.java
public MediaType(String segment) { if (Util.isEmpty(segment)) { segment = "text/plain"; }// w w w. java 2 s.c o m this.name = segment; String[] pieces = segment.split("\\s*;\\s*"); Matcher matcher = MEDIA_TYPE_PATTERN.matcher(pieces[0]); if (matcher.matches()) { this.type = matcher.group(1); this.subtype = matcher.group(2); } for (int i = 1; i < pieces.length; ++i) { Matcher p = PARAMETER_PATTERN.matcher(pieces[i]); if (p.matches()) { String token = p.group(1); String value = p.group(2); if ("q".equalsIgnoreCase(token)) { this.qvalue = Float.parseFloat(value); } else if (value != null) { this.parameters.put(token, value); } else { this.parameters.put(token, null); } } } }
From source file:controllers.ChargesControllerServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from ww w. j a v a2 s. co m*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String product_id = request.getParameter("product_id"); String token = request.getParameter("conektaTokenId"); String path = request.getPathInfo(); String url = path; Charge conektaCharge; if (url == null || url.equals("/")) { Conekta.apiKey = "key_eYvWV7gSDkNYXsmr"; JSONObject card_payment_params; JSONObject valid_visa_card; try { Product product = Product.find(product_id); valid_visa_card = new JSONObject("{'card':'" + token + "'}"); card_payment_params = new JSONObject("{'description':'" + product.description + "'," + "'reference_id':'" + product.id + "'," + "'amount':" + ((int) Float.parseFloat(product.price) * 100) + "," + "'currency':'MXN'" + "}"); conektaCharge = Charge.create(card_payment_params.put("card", valid_visa_card.get("card"))); url = request.getContextPath() + "/charges"; models.Charge charge = new models.Charge(); charge.build(conektaCharge.id, conektaCharge.livemode.toString(), conektaCharge.created_at.toString(), conektaCharge.status, conektaCharge.currency, conektaCharge.description, conektaCharge.reference_id, conektaCharge.failure_code, conektaCharge.failure_message, conektaCharge.amount.toString(), ((CardPayment) conektaCharge.payment_method).name, ((CardPayment) conektaCharge.payment_method).exp_month, ((CardPayment) conektaCharge.payment_method).exp_year, ((CardPayment) conektaCharge.payment_method).auth_code, ((CardPayment) conektaCharge.payment_method).last4, ((CardPayment) conektaCharge.payment_method).brand); charge.save(); } catch (Exception ex) { Logger.getLogger(ChargesControllerServlet.class.getName()).log(Level.SEVERE, null, ex); } } response.sendRedirect(url); }
From source file:cn.ttyhuo.activity.InfoOwnerActivity.java
@Override protected void initView() { super.initView(); mEditDate = (TextView) findViewById(R.id.edit_date); mEditChexing = (TextView) findViewById(R.id.edit_chexing); mEditZaizhong = (EditText) findViewById(R.id.edit_zaizhong); mEditChechang = (EditText) findViewById(R.id.edit_chechang); mEditZuowei = (EditText) findViewById(R.id.edit_zuowei); mEditChepai = (EditText) findViewById(R.id.edit_chepaihao); mEditXinghao = (EditText) findViewById(R.id.edit_xinghao); mEditKuan = (EditText) findViewById(R.id.edit_kuan); mEditGao = (EditText) findViewById(R.id.edit_gao); tv_edit_tips = (TextView) findViewById(R.id.tv_edit_tips); // /*from w ww. j a v a 2 s . c o m*/ mEditZaizhong.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { String numStr = v.getText().toString(); if (!StringNumberUtils.isPositiveDecimal(numStr) && !StringNumberUtils.isPositiveInteger(numStr)) { Toast.makeText(mContext, "1.0-100.0", Toast.LENGTH_SHORT).show(); } else { float num = Float.parseFloat(numStr); if (num > 10.0 || num < 1.0) { Toast.makeText(mContext, "1.0-100.0", Toast.LENGTH_SHORT).show(); } } return false; } }); progressBar = (ProgressBar) findViewById(R.id.progressBar1); if (progressBar != null) progressBar.setVisibility(View.VISIBLE); isDoingUpdate = true; if (!NetworkUtils.isNetworkAvailable(mContext)) { Toast.makeText(mContext, "??", Toast.LENGTH_LONG).show(); } new UrlThread(handler, UrlList.MAIN + "mvc/editTruckInfoJson".toString(), 1).start(); }
From source file:Ctrl.CtrlProducts.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w. j a v a2 s . c o m * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String action = request.getParameter("action"); if (action.equals("Tm Kim")) { String name = request.getParameter("txtTenSP"); Products sp = new Products(); List<Product> list = new ArrayList<Product>(); list = sp.HienthiSPadmin(name); request.setAttribute("listSP", list); RequestDispatcher rd = request.getRequestDispatcher("Product.jsp"); rd.forward(request, response); } else if (action.equals("Delete")) { String code = request.getParameter("txtcode"); Products sp = new Products(); sp.delete(code); String url = "Product.jsp"; RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } else if (action.equals("Edit")) { String code = request.getParameter("txtcode").trim(); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); Product sp = new Product(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh); request.setAttribute("SP", sp); RequestDispatcher rd = request.getRequestDispatcher("chinhsuasp.jsp"); rd.forward(request, response); } else if (action.equals("Update")) { String code = request.getParameter("txtcode"); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); String ten = request.getParameter("txtTenSP"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); String url = "Product.jsp"; Products sp = new Products(); sp.insert(name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh, code); RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, response); } else if (action.equals("Thm")) { String code = request.getParameter("txtcode"); String name = request.getParameter("txtname"); String pri = request.getParameter("txtprice"); String manhinh = request.getParameter("txtmanhinh"); String ram = request.getParameter("txtram"); String hdd = request.getParameter("txthdd"); String cpu = request.getParameter("txtcpu"); String khuyenmai = request.getParameter("txtkhuyenmai"); String baohanh = request.getParameter("txtbaohanh"); String hinh = request.getParameter("txthinh"); int nkhuyenmai = Integer.parseInt(khuyenmai); float fpri = Float.parseFloat(pri); Products sp = new Products(); sp.newsp(code, name, fpri, manhinh, ram, hdd, cpu, nkhuyenmai, baohanh, hinh); RequestDispatcher rd = request.getRequestDispatcher("CtrlProducts?action=Tm+Kim&txtTenSP"); rd.forward(request, response); } else if (action.equals("Thm Sn Phm")) { RequestDispatcher rd = request.getRequestDispatcher("newsp.jsp"); rd.forward(request, response); } else if (action.equals("Qun l ti khon")) { RequestDispatcher rd = request.getRequestDispatcher("Quanliuser.jsp"); rd.forward(request, response); } if (action.equals("Logout")) { HttpSession session = request.getSession(true); session.invalidate(); RequestDispatcher rd = request.getRequestDispatcher("Trangchu.jsp"); rd.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } }
From source file:account.management.controller.ReportBsController.java
@FXML private void onShowBalanceSheetClick(ActionEvent event) { String start_date, end_date;//from ww w . j a va 2s . co m try { start_date = new SimpleDateFormat("yyyy-MM-dd") .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.start.getValue().toString())); end_date = new SimpleDateFormat("yyyy-MM-dd") .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.end.getValue().toString())); HttpResponse<JsonNode> res = Unirest.get(MetaData.baseUrl + "report/balancesheet") .queryString("date", "\"" + start_date + "\"").asJson(); HttpResponse<JsonNode> res2 = Unirest.get(MetaData.baseUrl + "report/balancesheet") .queryString("date", "\"" + end_date + "\"").asJson(); JSONArray bs = res.getBody().getArray(); JSONArray bs2 = res2.getBody().getArray(); System.out.println(bs); System.out.println(bs2); HashMap params = new HashMap(); Vector v = new Vector(); float total_non_current_asset = 0, total_current_asset = 0, total_revenue = 0, total_expense = 0, equity = 0, long_term_liability = 0, current_liability = 0; for (int i = 0; i < bs.length(); i++) { JSONObject obj = bs.getJSONObject(i); JSONObject obj2 = bs2.getJSONObject(i); String id = obj.get("id").toString(); String balance = String.valueOf(Float.parseFloat(obj2.get("totalBalance").toString()) - Float.parseFloat(obj.get("totalBalance").toString())); v.add(new BS(id, balance)); params.put(id, balance); // total non current asset if (Integer.parseInt(id) >= 9 && Integer.parseInt(id) <= 12) { total_non_current_asset += Float.parseFloat(balance); } // total current asset if (Integer.parseInt(id) >= 13 && Integer.parseInt(id) <= 27) { total_current_asset += Float.parseFloat(balance); } // total revenue if (Integer.parseInt(id) >= 38 && Integer.parseInt(id) <= 40) { total_revenue += Float.parseFloat(balance); } // total expense if ((Integer.parseInt(id) >= 42 && Integer.parseInt(id) <= 44) || (Integer.parseInt(id) >= 46 && Integer.parseInt(id) <= 48) || (Integer.parseInt(id) >= 50 && Integer.parseInt(id) <= 57)) { total_expense += Float.parseFloat(balance); } if (Integer.parseInt(id) == 28) { equity = Float.parseFloat(balance); } if (Integer.parseInt(id) == 29) { equity = equity - Float.parseFloat(balance); } if (Integer.parseInt(id) == 30) { long_term_liability = Float.parseFloat(balance); } if (Integer.parseInt(id) == 33) { current_liability = Float.parseFloat(balance); } } if (total_expense < 0) { total_expense *= -1; } params.put("date", new SimpleDateFormat("dd-MM-yyyy") .format(new SimpleDateFormat("yyyy-MM-dd").parse(this.start.getValue().toString())) + "To " + new SimpleDateFormat("dd-MM-yyyy").format( new SimpleDateFormat("yyyy-MM-dd").parse(this.end.getValue().toString()))); params.put("total_non_current_asset", String.valueOf(total_non_current_asset)); params.put("total_current_asset", String.valueOf(total_current_asset)); params.put("total_asset", String.valueOf(total_current_asset + total_non_current_asset)); params.put("total_revenue", String.valueOf(total_revenue)); params.put("total_expense", String.valueOf(total_expense)); params.put("net_profit", String.valueOf(total_revenue - total_expense)); params.put("total_equity", String.valueOf(equity + total_revenue - total_expense)); System.out.println(long_term_liability); System.out.println(current_liability); params.put("total_liability", String.valueOf(long_term_liability + current_liability)); Report r = new Report(); r.getReport("src\\report\\bs.jrxml", new JRBeanCollectionDataSource(v), params, "Balance Sheet"); r.getReport("src\\report\\pl.jrxml", new JRBeanCollectionDataSource(v), params, "Profit-Loss Statement"); } catch (ParseException ex) { Logger.getLogger(LCReportController.class.getName()).log(Level.SEVERE, null, ex); } catch (UnirestException ex) { Logger.getLogger(LCReportController.class.getName()).log(Level.SEVERE, null, ex); } finally { this.cancel.getScene().getWindow().hide(); } }
From source file:com.wipro.ats.bdre.dq.rule.CommonDQFunctions.java
public String checkFloat(String num, String rangeMin, String rangeMax) { try {//from ww w.j av a 2 s.co m Float n = Float.parseFloat(num); Float min = Float.parseFloat(rangeMin); Float max = Float.parseFloat(rangeMax); if (n > min && n < max) return num; else return "Float number not in range"; } catch (NumberFormatException ex) { LOGGER.info("Not a valid float number!"); return "null"; } }