List of usage examples for java.lang Float Float
@Deprecated(since = "9") public Float(String s) throws NumberFormatException
From source file:com.splicemachine.tutorials.model.RULPredictiveModel.java
/** * Build and Test Model/*from w w w.j a v a 2 s . co m*/ */ public static void buildRULModel(String trainTableName, String testTableName, String saveModelPath) { try { if (trainTableName == null || trainTableName.length() == 0) trainTableName = "IOT.TRAIN_AGG_1_VIEW"; if (testTableName == null || testTableName.length() == 0) testTableName = "IOT.TEST_AGG_1_VIEW"; if (saveModelPath == null || saveModelPath.length() == 0) saveModelPath = "/tmp"; if (!saveModelPath.endsWith("/")) saveModelPath = saveModelPath + "/"; String jdbcUrl = "jdbc:splice://localhost:1527/splicedb;user=splice;password=admin;useSpark=true"; SparkSession sparkSession = SpliceSpark.getSession(); // LOAD TRAIN AND TEST DATA Map<String, String> options = new HashMap<String, String>(); options.put("driver", "com.splicemachine.db.jdbc.ClientDriver"); options.put("url", jdbcUrl); // Train Data options.put("dbtable", trainTableName); Dataset<Row> trainds = sparkSession.read().format("jdbc").options(options).load(); // Test Data options.put("dbtable", testTableName); Dataset<Row> testds = sparkSession.read().format("jdbc").options(options).load(); /******** Connection con = DriverManager.getConnection("jdbc:default:connection"); PreparedStatement ps = con.prepareStatement(statement); ResultSet rs = ps.executeQuery(); // Convert result set to Java RDD JavaRDD<LocatedRow> resultSetRDD = SparkMLibUtils.resultSetToRDD(rs) ; ******/ // Prepare data // Fill in nulls trainds = trainds.na().fill(0); testds = trainds.na().fill(0); // Relabel Label Column trainds = trainds.withColumnRenamed("PREDICTION", "label"); testds = testds.withColumnRenamed("PREDICTION", "label"); // Create Features Vector VectorAssembler assembler = new VectorAssembler().setInputCols(new String[] { "OP_SETTING_1", "OP_SETTING_2", "OP_SETTING_3", "SENSOR_MEASURE_1", "SENSOR_MEASURE_2", "SENSOR_MEASURE_3", "SENSOR_MEASURE_4", "SENSOR_MEASURE_5", "SENSOR_MEASURE_6", "SENSOR_MEASURE_7", "SENSOR_MEASURE_8", "SENSOR_MEASURE_9", "SENSOR_MEASURE_10", "SENSOR_MEASURE_11", "SENSOR_MEASURE_12", "SENSOR_MEASURE_13", "SENSOR_MEASURE_14", "SENSOR_MEASURE_15", "SENSOR_MEASURE_16", "SENSOR_MEASURE_17", "SENSOR_MEASURE_18", "SENSOR_MEASURE_19", "SENSOR_MEASURE_20", "SENSOR_MEASURE_21", "AVG_SENSOR_1", "AVG_SENSOR_2", "AVG_SENSOR_3", "AVG_SENSOR_4", "AVG_SENSOR_5", "AVG_SENSOR_6", "AVG_SENSOR_7", "AVG_SENSOR_8", "AVG_SENSOR_9", "AVG_SENSOR_10", "AVG_SENSOR_11", "AVG_SENSOR_12", "AVG_SENSOR_13", "AVG_SENSOR_14", "AVG_SENSOR_15", "AVG_SENSOR_16", "AVG_SENSOR_17", "AVG_SENSOR_18", "AVG_SENSOR_19", "AVG_SENSOR_20", "AVG_SENSOR_21" }).setOutputCol("features"); //Algorithm DecisionTreeClassifier dt = new DecisionTreeClassifier(); //Create Pipeline Pipeline pipeline = new Pipeline().setStages(new PipelineStage[] { assembler, dt }); // removed normalizer //Create parameters for iteration for validator ParamMap[] paramGrid = new ParamGridBuilder().addGrid(dt.maxDepth(), new int[] { 2, 4, 6 }) .addGrid(dt.maxBins(), new int[] { 20, 60 }).build(); //Create Validator CrossValidator cv = new CrossValidator().setEstimator(pipeline) .setEvaluator(new BinaryClassificationEvaluator()).setEstimatorParamMaps(paramGrid) .setNumFolds(2); //Create Model - This process generates Multiple models, iterating thru the // range of parameter values, and finds the best model CrossValidatorModel cvModel = cv.fit(trainds); //Test the generated Model Dataset<Row> predictionsDF = cvModel.transform(testds).select("rawPrediction", "probability", "label", "prediction"); //Calculate accuracy of the model Long correctPredCnt = predictionsDF .filter(predictionsDF.col("label").equalTo(predictionsDF.col("prediction"))).count(); Float totalCnt = new Float(predictionsDF.count()); float acc = correctPredCnt / totalCnt; System.out.println("ACCURACY = " + acc); //Save the pipeline and Model. Model will be used for predictions and pipeline can be // generate model on different set of data. pipeline.write().overwrite().save(saveModelPath + "pipeline/"); cvModel.write().overwrite().save(saveModelPath + "model/"); } catch (IOException sqle) { LOG.error("Exception in getColumnStatistics", sqle); sqle.printStackTrace(); } }
From source file:org.apache.synapse.mediators.builtin.PropertyMediatorTest.java
public void testTypeAwarePropertyHandling() throws Exception { PropertyMediator propMediatorOne = new PropertyMediator(); propMediatorOne.setName("nameOne"); propMediatorOne.setValue("valueOne", XMLConfigConstants.DATA_TYPES.STRING.name()); PropertyMediator propMediatorTwo = new PropertyMediator(); propMediatorTwo.setName("nameTwo"); propMediatorTwo.setValue("25000", XMLConfigConstants.DATA_TYPES.INTEGER.name()); propMediatorTwo.setScope(XMLConfigConstants.SCOPE_AXIS2); PropertyMediator propMediatorThree = new PropertyMediator(); propMediatorThree.setName("nameThree"); propMediatorThree.setValue("123.456", XMLConfigConstants.DATA_TYPES.DOUBLE.name()); propMediatorThree.setScope(XMLConfigConstants.SCOPE_TRANSPORT); PropertyMediator propMediatorFour = new PropertyMediator(); propMediatorFour.setName("nameFour"); propMediatorFour.setValue("true", XMLConfigConstants.DATA_TYPES.BOOLEAN.name()); PropertyMediator propMediatorFive = new PropertyMediator(); propMediatorFive.setName("nameFive"); propMediatorFive.setValue("123456", XMLConfigConstants.DATA_TYPES.LONG.name()); propMediatorFive.setScope(XMLConfigConstants.SCOPE_AXIS2); PropertyMediator propMediatorSix = new PropertyMediator(); propMediatorSix.setName("nameSix"); propMediatorSix.setValue("12345", XMLConfigConstants.DATA_TYPES.SHORT.name()); propMediatorSix.setScope(XMLConfigConstants.SCOPE_TRANSPORT); PropertyMediator propMediatorSeven = new PropertyMediator(); propMediatorSeven.setName("nameSeven"); propMediatorSeven.setValue("123.456", XMLConfigConstants.DATA_TYPES.FLOAT.name()); MessageContext synCtx = TestUtils.createLightweightSynapseMessageContext("<empty/>"); propMediatorOne.mediate(synCtx);/*from w w w .java 2 s.c o m*/ propMediatorTwo.mediate(synCtx); propMediatorThree.mediate(synCtx); propMediatorFour.mediate(synCtx); propMediatorFive.mediate(synCtx); propMediatorSix.mediate(synCtx); propMediatorSeven.mediate(synCtx); org.apache.axis2.context.MessageContext axisCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext(); Map transportHeaders = (Map) axisCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); Object valueOne = synCtx.getProperty("nameOne"); Object valueTwo = axisCtx.getProperty("nameTwo"); Object valueThree = transportHeaders.get("nameThree"); Object valueFour = synCtx.getProperty("nameFour"); Object valueFive = axisCtx.getProperty("nameFive"); Object valueSix = transportHeaders.get("nameSix"); Object valueSeven = synCtx.getProperty("nameSeven"); assertEquals("valueOne", valueOne); assertEquals(new Integer(25000), valueTwo); assertEquals(new Double(123.456), valueThree); assertEquals(Boolean.TRUE, valueFour); assertEquals(new Long(123456), valueFive); assertEquals(new Short("12345"), valueSix); assertEquals(new Float(123.456), valueSeven); }
From source file:iddb.core.util.Functions.java
public static String minutes2Str(Long minutes) { Float num;// ww w . java 2 s . c o m String suffix = ""; if (minutes < 60) { num = new Float(minutes); } else if (minutes < 1440) { num = Float.valueOf(minutes) / 60; suffix = "h"; } else if (minutes < 10080) { num = Float.valueOf(minutes) / 1440; suffix = "d"; } else if (minutes < 525600) { num = Float.valueOf(minutes) / 10080; suffix = "w"; } else { num = Float.valueOf(minutes) / 525600; suffix = "y"; } if ("0".equals(num.toString().substring(num.toString().indexOf(".") + 1))) { return String.format("%d%s", num.intValue(), suffix); } return String.format("%.2g%s", num, suffix); // 2=1 decimal }
From source file:Main.java
/** * <p>Converts an array of primitive floats to objects.</p> * * <p>This method returns <code>null</code> for a <code>null</code> input array.</p> * * @param array a <code>float</code> array * @return a <code>Float</code> array, <code>null</code> if null array input */// ww w . j av a 2 s . c o m public static Float[] toObject(float[] array) { if (array == null) { return null; } else if (array.length == 0) { return EMPTY_FLOAT_OBJECT_ARRAY; } final Float[] result = new Float[array.length]; for (int i = 0; i < array.length; i++) { result[i] = new Float(array[i]); } return result; }
From source file:dsd.dao.WorstCaseDAO.java
private static Object[][] PrepareMultipleValuesForInsert(List<WorstPylonCase> listOfData) { Object[][] valueArray = new Object[listOfData.size()][10]; for (int i = 0; i < listOfData.size(); i++) { valueArray[i][0] = new Integer(listOfData.get(i).getPylonNumber()); valueArray[i][1] = new Float(listOfData.get(i).getN()); valueArray[i][2] = new Float(listOfData.get(i).getTx()); valueArray[i][3] = new Float(listOfData.get(i).getTy()); valueArray[i][4] = new Float(listOfData.get(i).getMx()); valueArray[i][5] = new Float(listOfData.get(i).getMy()); valueArray[i][6] = new Float(listOfData.get(i).getM()); valueArray[i][7] = new Float(listOfData.get(i).getSafetyFactor()); valueArray[i][8] = new Integer(listOfData.get(i).getComboNumber()); valueArray[i][9] = new Timestamp(listOfData.get(i).getTimestamp()); }//ww w.ja v a 2s . c o m return valueArray; }
From source file:org.openmrs.module.vcttrac.web.view.chart.VCTCreatePieChartView.java
private JFreeChart createCounselingTypePieChartView() { DefaultPieDataset pieDataset = new DefaultPieDataset(); VCTModuleService service = Context.getService(VCTModuleService.class); try {//w w w.j av a 2s. c o m Date reportingDate = new Date(); int numberOfIndividual = service.getVCTClientsBasedOnCounselingType(1, reportingDate).size(); int numberOfCouples = service.getVCTClientsBasedOnCounselingType(2, reportingDate).size(); int numberOfNotCounseled = service.getVCTClientsBasedOnCounselingType(3, reportingDate).size(); int all = numberOfIndividual + numberOfCouples + numberOfNotCounseled; Float percentageIndividual = new Float(100 * numberOfIndividual / all); pieDataset.setValue("Individual (" + numberOfIndividual + " , " + percentageIndividual + "%)", percentageIndividual); Float percentageCouple = new Float(100 * numberOfCouples / all); pieDataset.setValue("Couples (" + numberOfCouples + " , " + percentageCouple + "%)", percentageCouple); Float percentageNotCounseled = new Float(100 * numberOfNotCounseled / all); pieDataset.setValue("Not Counseled (" + numberOfNotCounseled + " , " + percentageNotCounseled + "%)", percentageNotCounseled); JFreeChart chart = ChartFactory.createPieChart( VCTTracUtil.getMessage("vcttrac.statistic.graph.typeofcounseling", null), pieDataset, true, true, false); return chart; } catch (Exception e) { log.error(">>COUNSELING>>TYPE>>PIE>>CHART>> " + e.getMessage()); e.printStackTrace(); return ChartFactory.createPieChart( VCTTracUtil.getMessage("vcttrac.statistic.graph.typeofcounseling", null), null, true, true, false); } }
From source file:org.openmrs.module.pmtct.web.view.chart.InfantPieChartView.java
/** * @see org.openmrs.module.pmtct.web.view.chart.AbstractChartView#createChart(java.util.Map, * javax.servlet.http.HttpServletRequest) */// w w w .j av a 2 s . co m @Override protected JFreeChart createChart(Map<String, Object> model, HttpServletRequest request) { UserContext userContext = Context.getUserContext(); ApplicationContext appContext = ContextProvider.getApplicationContext(); PMTCTModuleTag tag = new PMTCTModuleTag(); List<Object> res = new ArrayList<Object>(); DefaultPieDataset pieDataset = new DefaultPieDataset(); String title = "", descriptionTitle = "", dateInterval = ""; Concept concept = null; SimpleDateFormat df = Context.getDateFormat(); Encounter matEnc = null; Date today = new Date(); Date oneYearFromNow = new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS); String endDate = df.format(today); String startDate = df.format(oneYearFromNow); dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - " + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")"; if (request.getParameter("type").compareTo("1") == 0) { try { // Date myDate = new Date("1/1/" + ((new Date()).getYear() + 1900)); // String startDate = df.format(myDate); // Date today=new Date(); // Date oneYearFromNow=new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS); PmtctService pmtct; pmtct = Context.getService(PmtctService.class); try { res = pmtct.getGeneralStatForInfantTests_Charting_IFM(startDate, endDate); } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } List<String> infantFeedingMethodOptions = new ArrayList<String>(); List<Integer> infantFeedingMethodValues = new ArrayList<Integer>(); Collection<ConceptAnswer> answers = Context.getConceptService() .getConcept(PMTCTConstants.INFANT_FEEDING_METHOD).getAnswers(); for (ConceptAnswer str : answers) { infantFeedingMethodOptions.add(str.getAnswerConcept().getName().getName()); infantFeedingMethodValues.add(0); } infantFeedingMethodOptions.add("Others"); infantFeedingMethodValues.add(0); for (Object ob : res) { int patientId = (Integer) ((Object[]) ob)[0]; matEnc = tag.getMaternityEncounterInfo(patientId); String infantFeedingMethod = tag.observationValueByConcept(matEnc, PMTCTConstants.INFANT_FEEDING_METHOD); int i = 0; boolean found = false; for (String s : infantFeedingMethodOptions) { if ((s.compareToIgnoreCase(infantFeedingMethod)) == 0) { infantFeedingMethodValues.set(i, infantFeedingMethodValues.get(i) + 1); found = true; } i++; } if (!found) { infantFeedingMethodValues.set(infantFeedingMethodValues.size() - 1, infantFeedingMethodValues.get(infantFeedingMethodValues.size() - 1) + 1); } } int i = 0; for (String s : infantFeedingMethodOptions) { if (infantFeedingMethodValues.get(i) > 0) { Float percentage = new Float(100 * infantFeedingMethodValues.get(i) / res.size()); pieDataset.setValue(s + " (" + infantFeedingMethodValues.get(i) + " , " + percentage + "%)", percentage); } i++; } title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale()); concept = Context.getConceptService().getConcept(PMTCTConstants.INFANT_FEEDING_METHOD); } catch (Exception ex) { ex.printStackTrace(); } } else if (request.getParameter("type").compareTo("2") == 0) { try { // Date myDate2 = new Date("1/1/" + ((new Date()).getYear() + 1900)); // String startDate2 = df.format(myDate2); // Date today=new Date(); // Date oneYearFromNow=new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS); // String endDate2 = df.format(today); // String startDate2 = df.format(oneYearFromNow); // dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - " + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")"; PmtctService pmtct; pmtct = Context.getService(PmtctService.class); try { res = pmtct.getGeneralStatForInfantTests_Charting_SerAt9Months(startDate, endDate); } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } List<String> hivTestResultOptions = new ArrayList<String>(); List<Integer> ser9m_hivTestResultValues = new ArrayList<Integer>(); Collection<ConceptAnswer> answers = Context.getConceptService() .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers(); for (ConceptAnswer str : answers) { hivTestResultOptions.add(str.getAnswerConcept().getName().getName()); ser9m_hivTestResultValues.add(0); } hivTestResultOptions.add("Others"); ser9m_hivTestResultValues.add(0); for (Object ob : res) { int val = 0; String temp = "", ser9m_hivTestResult = ""; temp = "" + ((Object[]) ob)[2]; val = (temp.compareTo("") == 0) ? 0 : Integer.parseInt(temp); if (val > 0) ser9m_hivTestResult = tag.getConceptNameById(temp); int i = 0; boolean ser9m_found = false; for (String s : hivTestResultOptions) { if ((s.compareToIgnoreCase(ser9m_hivTestResult)) == 0) { ser9m_hivTestResultValues.set(i, ser9m_hivTestResultValues.get(i) + 1); ser9m_found = true; } i++; } if (!ser9m_found) { ser9m_hivTestResultValues.set(ser9m_hivTestResultValues.size() - 1, ser9m_hivTestResultValues.get(ser9m_hivTestResultValues.size() - 1) + 1); } } int i = 0; for (String s : hivTestResultOptions) { if (ser9m_hivTestResultValues.get(i) > 0) { Float percentage = new Float(100 * ser9m_hivTestResultValues.get(i) / res.size()); pieDataset.setValue(s + " (" + ser9m_hivTestResultValues.get(i) + " , " + percentage + "%)", percentage); } i++; } title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale()); concept = null; descriptionTitle = Context.getEncounterService() .getEncounterType(PMTCTConfigurationUtils.getSerology9MonthEncounterTypeId()).getName(); descriptionTitle += dateInterval; } catch (Exception ex) { ex.printStackTrace(); } } else if (request.getParameter("type").compareTo("3") == 0) { try { // Date myDate3 = new Date("1/1/" + ((new Date()).getYear() + 1900)); // String startDate3 = df.format(myDate3); // String endDate3 = df.format(today); // String startDate3 = df.format(oneYearFromNow); // dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - " + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")"; PmtctService pmtct; pmtct = Context.getService(PmtctService.class); try { res = pmtct.getGeneralStatForInfantTests_Charting_SerAt18Months(startDate, endDate); } catch (SQLException ex) { ex.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } List<String> hivTestResultOptions = new ArrayList<String>(); List<Integer> ser18m_hivTestResultValues = new ArrayList<Integer>(); Collection<ConceptAnswer> answers = Context.getConceptService() .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers(); for (ConceptAnswer str : answers) { hivTestResultOptions.add(str.getAnswerConcept().getName().getName()); ser18m_hivTestResultValues.add(0); } hivTestResultOptions.add("Others"); ser18m_hivTestResultValues.add(0); for (Object ob : res) { int val = 0; String temp = "", ser18m_hivTestResult = ""; temp = "" + ((Object[]) ob)[2]; val = (temp.compareTo("") == 0) ? 0 : Integer.parseInt(temp); if (val > 0) ser18m_hivTestResult = tag.getConceptNameById(temp); int i = 0; boolean ser18m_found = false; for (String s : hivTestResultOptions) { if ((s.compareToIgnoreCase(ser18m_hivTestResult)) == 0) { ser18m_hivTestResultValues.set(i, ser18m_hivTestResultValues.get(i) + 1); ser18m_found = true; } i++; } if (!ser18m_found) { ser18m_hivTestResultValues.set(ser18m_hivTestResultValues.size() - 1, ser18m_hivTestResultValues.get(ser18m_hivTestResultValues.size() - 1) + 1); } } int i = 0; for (String s : hivTestResultOptions) { if (ser18m_hivTestResultValues.get(i) > 0) { Float percentage = new Float(100 * ser18m_hivTestResultValues.get(i) / res.size()); pieDataset.setValue( s + " (" + ser18m_hivTestResultValues.get(i) + " , " + percentage + "%)", percentage); } i++; } title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale()); concept = null; descriptionTitle = Context.getEncounterService() .getEncounterType(PMTCTConfigurationUtils.getSerology18MonthEncounterTypeId()).getName(); descriptionTitle += dateInterval; } catch (Exception ex) { ex.printStackTrace(); } } else if (request.getParameter("type").compareTo("4") == 0) { try { PmtctService pmtct; pmtct = Context.getService(PmtctService.class); try { res = pmtct.getGeneralStatForInfantTests_Charting_PCR(startDate, endDate); } catch (SQLException ex) { ex.printStackTrace(); } List<String> hivTestResultOptions = new ArrayList<String>(); List<Integer> pcr_hivTestResultValues = new ArrayList<Integer>(); Collection<ConceptAnswer> answers = Context.getConceptService() .getConcept(PMTCTConstants.RESULT_OF_HIV_TEST).getAnswers(); for (ConceptAnswer str : answers) { hivTestResultOptions.add(str.getAnswerConcept().getName().getName()); pcr_hivTestResultValues.add(0); } hivTestResultOptions.add("Others"); pcr_hivTestResultValues.add(0); for (Object ob : res) { int val = 0; String temp = "", pcr_hivTestResult = ""; temp = "" + ((Object[]) ob)[2]; val = (temp.compareTo("") == 0) ? 0 : Integer.parseInt(temp); if (val > 0) pcr_hivTestResult = tag.getConceptNameById(temp); int i = 0; boolean pcr_found = false; for (String s : hivTestResultOptions) { if ((s.compareToIgnoreCase(pcr_hivTestResult)) == 0) { pcr_hivTestResultValues.set(i, pcr_hivTestResultValues.get(i) + 1); pcr_found = true; } i++; } if (!pcr_found) { pcr_hivTestResultValues.set(pcr_hivTestResultValues.size() - 1, pcr_hivTestResultValues.get(pcr_hivTestResultValues.size() - 1) + 1); } } int i = 0; for (String s : hivTestResultOptions) { if (pcr_hivTestResultValues.get(i) > 0) { Float percentage = new Float(100 * pcr_hivTestResultValues.get(i) / res.size()); pieDataset.setValue(s + " (" + pcr_hivTestResultValues.get(i) + " , " + percentage + "%)", percentage); } i++; } title = appContext.getMessage("pmtct.menu.infantTest", null, userContext.getLocale()); concept = null; descriptionTitle = Context.getEncounterService() .getEncounterType(PMTCTConfigurationUtils.getPCRTestEncounterTypeId()).getName(); descriptionTitle += dateInterval; } catch (Exception ex) { ex.printStackTrace(); } } JFreeChart chart = ChartFactory.createPieChart(title + " : " + ((null != concept) ? concept.getPreferredName(userContext.getLocale()) + dateInterval : descriptionTitle), pieDataset, true, true, false); return chart; }
From source file:com.mb.framework.util.property.PropertyUtilExt.java
/** * Copy property values from the origin bean to the destination bean for all * cases where the property names are the same. For each property, a * conversion is attempted as necessary. All combinations of standard * JavaBeans and DynaBeans as origin and destination are supported. * Properties that exist in the origin bean, but do not exist in the * destination bean (or are read-only in the destination bean) are silently * ignored.//w ww.java 2 s. c om * <p> * In addition to the method with the same name in the * <code>org.apache.commons.beanutils.PropertyUtils</code> class this method * can also copy properties of the following types: * <ul> * <li>java.lang.Integer</li> * <li>java.lang.Double</li> * <li>java.lang.Long</li> * <li>java.lang.Short</li> * <li>java.lang.Float</li> * <li>java.lang.String</li> * <li>java.lang.Boolean</li> * <li>java.sql.Date</li> * <li>java.sql.Time</li> * <li>java.sql.Timestamp</li> * <li>java.math.BigDecimal</li> * <li>a container-managed relations field.</li> * </ul> * * @param dest * Destination bean whose properties are modified * @param orig * Origin bean whose properties are retrieved * @throws IllegalAccessException * if the caller does not have access to the property accessor * method * @throws InvocationTargetException * if the property accessor method throws an exception * @throws NoSuchMethodException * if an accessor method for this propety cannot be found * @throws ClassNotFoundException * if an incorrect relations class mapping exists. * @throws InstantiationException * if an object of the mapped relations class can not be * constructed. */ public static void copyProperties(Object dest, Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, Exception { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (PropertyUtils.getPropertyDescriptor(dest, name) != null) { Object origValue = PropertyUtils.getSimpleProperty(orig, name); String origParamType = origDescriptors[i].getPropertyType().getName(); try { // edited // if (origValue == null)throw new NullPointerException(); PropertyUtils.setSimpleProperty(dest, name, origValue); } catch (Exception e) { try { String destParamType = PropertyUtils.getPropertyType(dest, name).getName(); if (origValue instanceof String) { if (destParamType.equals("java.lang.Integer")) { Integer intValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { intValue = new Integer(sValue); } PropertyUtils.setSimpleProperty(dest, name, intValue); } else if (destParamType.equals("java.lang.Byte")) { Byte byteValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { byteValue = new Byte(sValue); } PropertyUtils.setSimpleProperty(dest, name, byteValue); } else if (destParamType.equals("java.lang.Double")) { Double doubleValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { doubleValue = new Double(sValue); } PropertyUtils.setSimpleProperty(dest, name, doubleValue); } else if (destParamType.equals("java.lang.Long")) { Long longValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { longValue = new Long(sValue); } PropertyUtils.setSimpleProperty(dest, name, longValue); } else if (destParamType.equals("java.lang.Short")) { Short shortValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { shortValue = new Short(sValue); } PropertyUtils.setSimpleProperty(dest, name, shortValue); } else if (destParamType.equals("java.lang.Float")) { Float floatValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { floatValue = new Float(sValue); } PropertyUtils.setSimpleProperty(dest, name, floatValue); } else if (destParamType.equals("java.sql.Date")) { java.sql.Date dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Date(DATE_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.sql.Time")) { java.sql.Time dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Time(TIME_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.sql.Timestamp")) { java.sql.Timestamp dateValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { dateValue = new java.sql.Timestamp(TIMESTAMP_FORMATTER.parse(sValue).getTime()); } PropertyUtils.setSimpleProperty(dest, name, dateValue); } else if (destParamType.equals("java.lang.Boolean")) { Boolean bValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { bValue = Boolean.valueOf(sValue); } PropertyUtils.setSimpleProperty(dest, name, bValue); } else if (destParamType.equals("java.math.BigDecimal")) { BigDecimal bdValue = null; String sValue = ((String) origValue).trim(); if (sValue.length() > 0) { bdValue = new BigDecimal(sValue); } PropertyUtils.setSimpleProperty(dest, name, bdValue); } } else if ((origValue != null) && (destParamType.equals("java.lang.String"))) { // we're transferring a business-layer value object // into a String-based Struts form bean.. if ("java.sql.Date".equals(origParamType)) { PropertyUtils.setSimpleProperty(dest, name, DATE_FORMATTER.format(origValue)); } else if ("java.sql.Timestamp".equals(origParamType)) { PropertyUtils.setSimpleProperty(dest, name, TIMESTAMP_FORMATTER.format(origValue)); } else if ("java.sql.Blob".equals(origParamType)) { // convert a Blob to a String.. Blob blob = (Blob) origValue; BufferedInputStream bin = null; try { int bytesRead; StringBuffer result = new StringBuffer(); byte[] buffer = new byte[READ_BUFFER_LENGTH]; bin = new BufferedInputStream(blob.getBinaryStream()); do { bytesRead = bin.read(buffer); if (bytesRead != -1) { result.append(new String(buffer, 0, bytesRead)); } } while (bytesRead == READ_BUFFER_LENGTH); PropertyUtils.setSimpleProperty(dest, name, result.toString()); } finally { if (bin != null) try { bin.close(); } catch (IOException ignored) { } } } else { PropertyUtils.setSimpleProperty(dest, name, origValue.toString()); } } } catch (Exception e2) { throw e2; } } } } }
From source file:MathUtils.java
/** * Convert a String in Double, Float, Integer, Long, Short or Byte, depending on the T exemple * For exemple convert("2", 0f) will return 2.0 as a float * @param <T> type returned//from ww w . jav a2 s.c o m * @param str String to convert * @param exemple exemple of the type * @return a number representation of the String * @throws IllegalArgumentException if the T type is not Double, Float, Integer, Long, Short or Byte * @throws NumberFormatException if the conversion fails */ public static <T extends Number> T convert(String str, T exemple) throws NumberFormatException, IllegalArgumentException { T result = null; if (exemple instanceof Double) { result = (T) new Double(str); } else if (exemple instanceof Float) { result = (T) new Float(str); } else if (exemple instanceof Integer) { result = (T) new Integer(str); } else if (exemple instanceof Long) { result = (T) new Long(str); } else if (exemple instanceof Short) { result = (T) new Short(str); } else if (exemple instanceof Byte) { result = (T) new Byte(str); } else { throw new IllegalArgumentException("Conversion is not possible with class " + exemple.getClass() + "; only allowing Double, Float, integer, Long, Short & Byte"); } return result; }
From source file:org.aksw.gerbil.bat.annotator.NERDAnnotator.java
/** * Send request to NERD and parse the response as a set of scored annotations. * //from ww w. j a va 2s . c om * @param text * the text to send */ public HashSet<ScoredAnnotation> getNERDAnnotations(String text) { HashSet<ScoredAnnotation> annotations = Sets.newHashSet(); try { // lastTime = Calendar.getInstance().getTimeInMillis(); LOGGER.debug("shipping to NERD the text to annotate"); NERD nerd = new NERD(NERD_API, key); List<Entity> entities = nerd.annotate(ExtractorType.NERDML, DocumentType.PLAINTEXT, text, GranularityType.OEN, 60L, true, true); LOGGER.debug("NERD has found {} entities", entities.size()); for (Entity e : entities) { int id = DBpediaToWikiId.getId(wikiApi, e.getUri()); annotations.add(new ScoredAnnotation(e.getStartChar(), e.getEndChar() - e.getStartChar(), id, new Float(e.getConfidence()))); } } catch (Exception e) { e.printStackTrace(); // TODO // fix the error handling in order to closely check what is the source of the error throw new AnnotationException( "An error occurred while querying " + this.getName() + " API. Message: " + e.getMessage()); } return annotations; }