Example usage for java.lang Float Float

List of usage examples for java.lang Float Float

Introduction

In this page you can find the example usage for java.lang Float Float.

Prototype

@Deprecated(since = "9")
public Float(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Usage

From source file:de.hybris.platform.test.HJMPTest.java

@Test
public void testWriteReadValues() {
    LOG.debug(">>> testWriteReadValues()");

    final Float floatValue = new Float(1234.5678f);
    /* conv-LOG */LOG.debug(">>> Float (" + floatValue + ") <<<");
    remote.setFloat(floatValue);//from  w ww  . java2 s .c  om
    assertEquals(floatValue, remote.getFloat());

    final Double doubleValue = new Double(2234.5678d);
    /* conv-LOG */LOG.debug(">>> Double (" + doubleValue + ") <<<");
    remote.setDouble(doubleValue);
    assertEquals(doubleValue, remote.getDouble());

    final Character characterValue = Character.valueOf('g');
    /* conv-LOG */LOG.debug(">>> Character (" + characterValue + ") <<<");
    remote.setCharacter(characterValue);
    assertEquals(characterValue, remote.getCharacter());

    final Integer integerValue = Integer.valueOf(3357);
    /* conv-LOG */LOG.debug(">>> Integer (" + integerValue + ") <<<");
    remote.setInteger(integerValue);
    assertEquals(integerValue, remote.getInteger());

    final Long longValue = Long.valueOf(4357L);
    /* conv-LOG */LOG.debug(">>> Long (" + longValue + ") <<<");
    remote.setLong(longValue);
    assertEquals(longValue, remote.getLong());

    final Calendar now = Utilities.getDefaultCalendar();
    now.set(Calendar.MILLISECOND, 0);

    /* conv-LOG */LOG.debug(">>> Date (" + now + ", ms=" + now.getTime() + ")<<<");
    remote.setDate(now.getTime());
    final java.util.Date got = remote.getDate();
    /* conv-LOG */LOG.debug(">>> found (" + got.getTime() + ")<<<");
    assertEquals(now.getTime(), got);

    // try to get 123,4567 as big decimal
    final BigDecimal bigDecimalValue = BigDecimal.valueOf(1234567, 4);
    /* conv-LOG */LOG.debug(">>> BigDecimal (" + bigDecimalValue + ")<<<");
    remote.setBigDecimal(bigDecimalValue);
    assertTrue(remote.getBigDecimal().compareTo(bigDecimalValue) == 0);

    final java.sql.Timestamp timestamp = new java.sql.Timestamp(now.getTime().getTime());
    /* conv-LOG */LOG.debug(">>> Timestamp (" + timestamp + ", ms=" + timestamp.getTime() + ")<<<");
    remote.setDate(timestamp);
    final java.util.Date got2 = remote.getDate();
    /* conv-LOG */LOG.debug(">>> found (" + got2.getTime() + ")<<<");
    assertEquals(now.getTime(), got2);

    final String str = "Alles wird gut!";
    /* conv-LOG */LOG.debug(">>> String (" + str + ")<<<");
    remote.setString(str);
    assertEquals(str, remote.getString());

    final String longstr = "Alles wird lange gut!";
    /* conv-LOG */LOG.debug(">>> Long String (" + longstr + ")<<<");
    remote.setLongString(longstr);
    assertEquals(longstr, remote.getLongString());

    //put 50000 chars into it
    String longstr2 = "";
    for (int i2 = 0; i2 < 5000; i2++) {
        longstr2 += "01234567890";
    }
    remote.setLongString(longstr2);
    assertEquals(longstr2, remote.getLongString());

    /*
     * remote.setString( "" ); assertEquals( "" , remote.getString() ); remote.setString( null ); assertNull(
     * remote.getString() ); remote.setLongString( "" ); assertEquals( "" , remote.getLongString() );
     * remote.setLongString( null ); assertNull( remote.getLongString() );
     */

    final Boolean booleanValue = Boolean.TRUE;
    /* conv-LOG */LOG.debug(">>> Boolean (" + booleanValue + ")<<<");
    remote.setBoolean(booleanValue);
    assertEquals(booleanValue, remote.getBoolean());

    final float floatValue2 = 5234.5678f;
    /* conv-LOG */LOG.debug(">>> float (" + floatValue2 + ") <<<");
    remote.setPrimitiveFloat(floatValue2);
    assertTrue(">>> float (" + floatValue2 + ") <<<", floatValue2 == remote.getPrimitiveFloat());

    final double doubleValue2 = 6234.5678d;
    /* conv-LOG */LOG.debug(">>> double (" + doubleValue2 + ") <<<");
    remote.setPrimitiveDouble(doubleValue2);
    assertTrue(">>> double (" + doubleValue2 + ") <<<", doubleValue2 == remote.getPrimitiveDouble());

    final int integerValue2 = 7357;
    /* conv-LOG */LOG.debug(">>> int (" + integerValue2 + ") <<<");
    remote.setPrimitiveInteger(integerValue2);
    assertTrue(integerValue2 == remote.getPrimitiveInteger());

    final long longValue2 = 8357L;
    /* conv-LOG */LOG.debug(">>> long (" + longValue2 + ") <<<");
    remote.setPrimitiveLong(longValue2);
    assertTrue(">>> long (" + longValue2 + ") <<<", longValue2 == remote.getPrimitiveLong());

    final byte byteValue = 123;
    /* conv-LOG */LOG.debug(">>> byte (" + byteValue + ") <<<");
    remote.setPrimitiveByte(byteValue);
    assertTrue(">>> byte (" + byteValue + ") <<<", byteValue == remote.getPrimitiveByte());

    final boolean booleanValue2 = true;
    /* conv-LOG */LOG.debug(">>> boolean (" + booleanValue2 + ") <<<");
    remote.setPrimitiveBoolean(booleanValue2);
    assertTrue(">>> boolean (" + booleanValue2 + ") <<<", booleanValue2 == remote.getPrimitiveBoolean());

    final char characterValue2 = 'g';
    /* conv-LOG */LOG.debug(">>> char (" + characterValue2 + ") <<<");
    remote.setPrimitiveChar(characterValue2);
    assertTrue(">>> char (" + characterValue2 + ") <<<", characterValue2 == remote.getPrimitiveChar());

    final ArrayList list = new ArrayList();
    LOG.debug(">>> Serializable with standard classes (" + list + ") <<<");
    remote.setSerializable(list);
    assertEquals(list, remote.getSerializable());

    if (!Config.isOracleUsed()) {
        try {
            final HashMap bigtest = new HashMap();
            LOG.debug(">>> Serializable with standard classes (big thing) <<<");
            final byte[] byteArray = new byte[100000];
            bigtest.put("test", byteArray);
            remote.setSerializable(bigtest);
            final Map longtestret = (Map) remote.getSerializable();
            assertTrue(longtestret.size() == 1);
            final byte[] byteArray2 = (byte[]) longtestret.get("test");
            assertTrue(byteArray2.length == 100000);
        } catch (final Exception e) {
            throw new JaloSystemException(e,
                    "Unable to write big serializable object, db: " + Config.getDatabase() + ".", 0);
        }
    }

    /* conv-LOG */LOG.debug(">>> Serializable (null) <<<");
    remote.setSerializable(null);
    assertNull(remote.getSerializable());

    //         try
    //         {
    //            final Dummy dummy = new Dummy();
    //            /*conv-LOG*/ LOG.debug(">>> Serializable with custom classes ("+dummy+") <<<");
    //            remote.setSerializable( dummy );
    //            final Serializable x = remote.getSerializable();
    //            assertTrue( dummy.equals( x ) || x == null );
    //            if( x == null )
    //               /*conv-LOG*/ LOG.debug(">>> ok, we're still unable of writing non-serverside classes to database : read NULL ");
    //         }
    //         catch( Exception e )
    //         {
    //            /*conv-LOG*/ LOG.debug(">>> ok, we're still unable of writing non-serverside classes to database : " + e );
    //         }

    //
    // search
    //

    try {
        /* conv-LOG */LOG.debug(">>> Search ( " + str + ", " + integerValue2 + " ) <<<");
        home.finderTest(str, integerValue2);
    } catch (final Exception e) {
        e.printStackTrace();
        fail("TestItem not found!");
    }

    //
    // 'null' tests
    //

    /* conv-LOG */LOG.debug(">>> String (null) <<<");
    remote.setString(null);
    assertNull(remote.getString());

    /* conv-LOG */LOG.debug(">>> Character (null) <<<");
    remote.setCharacter(null);
    assertNull(remote.getCharacter());

    /* conv-LOG */LOG.debug(">>> Integer (null) <<<");
    remote.setInteger(null);
    assertNull(remote.getInteger());

    /* conv-LOG */LOG.debug(">>> Date (null) <<<");
    remote.setDate(null);
    assertNull(remote.getDate());

    /* conv-LOG */LOG.debug(">>> Double (null) <<<");
    remote.setDouble(null);
    assertNull(remote.getDouble());

    /* conv-LOG */LOG.debug(">>> Float (null) <<<");
    remote.setFloat(null);
    assertNull(remote.getFloat());
}

From source file:com.emc.plants.service.impl.ReportGeneratorBean.java

/** 
 * Run the report to get the top selling items for a range of dates.
 *
 * @param startdate Start of date range.
 * @param enddate End of date range.//w  ww  .  j a  v  a2s .  c  o  m
 * @param quantity Number of items to return in report.
 * @param reportFormat - Report format information.
 * @return Report containing results.
 */
@SuppressWarnings("unchecked")
public Report getTopSellersForDates(java.util.Date startdate, java.util.Date enddate, int quantity,
        ReportFormat reportFormat) {
    Report report = null;
    Connection conn = null;
    ResultSet results = null;
    PreparedStatement sqlStatement = null;
    try {
        // Establish connection to datasource.
        String orderItemsTableName = "ORDERITEM";
        DataSource ds = (DataSource) Util.getInitialContext().lookup("jdbc/PlantsByWebSphereDataSource");
        conn = ds.getConnection();

        // Set sort order of ascending or descending.
        String sortOrder;
        if (reportFormat.isAscending())
            sortOrder = "ASC";
        else
            sortOrder = "DESC";

        // Set up where by clause.
        String startDateString = Long.toString(startdate.getTime());
        if (startDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - startDateString.length()), 14, startDateString);
            startDateString = sb.toString();
        }
        String endDateString = Long.toString(enddate.getTime());
        if (endDateString.length() < 14) {
            StringBuffer sb = new StringBuffer(Util.ZERO_14);
            sb.replace((14 - endDateString.length()), 14, endDateString);
            endDateString = sb.toString();
        }
        String whereString = " WHERE sellDate BETWEEN '" + startDateString + "' AND '" + endDateString + "' ";

        // Create SQL statement.
        String sqlString = "SELECT inventoryID, name, category,"
                + " SUM(quantity * (price - cost)) as PROFIT FROM " + orderItemsTableName + whereString
                + " GROUP BY inventoryID, name, category ORDER BY PROFIT " + sortOrder + ", name";

        Util.debug("sqlstring=" + sqlString);

        sqlStatement = conn.prepareStatement(sqlString);
        results = sqlStatement.executeQuery();
        int i;

        // Initialize vectors to store data in.
        Vector[] vecs = new Vector[4];
        for (i = 0; i < vecs.length; i++) {
            vecs[i] = new Vector();
        }

        // Sift thru results.
        int count = 0;
        while ((results.next()) && (count < quantity)) {
            count++;
            i = 1;
            vecs[0].addElement(results.getString(i++));
            vecs[1].addElement(results.getString(i++));
            vecs[2].addElement(new Integer(results.getInt(i++)));
            vecs[3].addElement(new Float(results.getFloat(i++)));
        }

        // Create report.
        report = new Report();
        report.setReportFieldByRow(Report.ORDER_INVENTORY_ID, vecs[0]);
        report.setReportFieldByRow(Report.ORDER_INVENTORY_NAME, vecs[1]);
        report.setReportFieldByRow(Report.ORDER_INVENTORY_CATEGORY, vecs[2]);
        report.setReportFieldByRow(Report.PROFITS, vecs[3]);
    }

    catch (Exception e) {
        Util.debug("exception in ReportGeneratorBean:getTopSellersForDates.  " + e);
        e.printStackTrace();
    } finally { // Clean up.
        try {
            if (results != null)
                results.close();
        } catch (Exception ignore) {
        }

        try {
            if (sqlStatement != null)
                sqlStatement.close();
        } catch (Exception ignore) {
        }

        // Close Connection.
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ignore) {
        }
    }

    return report;
}

From source file:com.linkedin.databus2.producers.gg.GGEventGenerationFactory.java

public static Object convertToSimpleType(String fieldValue, Schema.Field avroField) throws DatabusException {
    String databaseFieldType = SchemaHelper.getMetaField(avroField, "dbFieldType");
    String recordFieldName = avroField.name();

    //return int/*from  www .  ja va2 s .  co  m*/
    if (databaseFieldType.equalsIgnoreCase("INTEGER")) {
        return new Integer(fieldValue);
    } //return long
    else if (databaseFieldType.equalsIgnoreCase("LONG")) {
        return new Long(fieldValue);
    } else if (databaseFieldType.equalsIgnoreCase("DATE")) {
        return ggDateStringToLong(fieldValue);
    } else if (databaseFieldType.equalsIgnoreCase("TIMESTAMP")) {
        return ggTimeStampStringToMilliSeconds(fieldValue);
    }
    //return float
    else if (databaseFieldType.equalsIgnoreCase("FLOAT")) {
        return new Float(fieldValue);
    }
    //return double
    else if (databaseFieldType.equalsIgnoreCase("DOUBLE")) {
        return new Double(fieldValue);
    }
    //return string
    else if (databaseFieldType.equalsIgnoreCase("CLOB")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("VARCHAR")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("VARCHAR2")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("NVARCHAR")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("NVARCHAR2")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("XMLTYPE")) {
        return fieldValue;
    } else if (databaseFieldType.equalsIgnoreCase("CHAR")) {
        return fieldValue;
    }
    //return bytes
    else if (databaseFieldType.equalsIgnoreCase("BLOB") || databaseFieldType.equalsIgnoreCase("RAW")) {
        if (fieldValue.length() == 0) {
            return fieldValue.getBytes(Charset.defaultCharset());
        }
        if (fieldValue.length() <= 2) {
            throw new DatabusException("Unable to decode the string because length is less than 2");
        }
        if (!isStringHex(fieldValue)) {
            throw new DatabusException("Unable to decode the string because it is not hex-encoded");
        }
        try {
            return stringToHex(fieldValue.substring(2, fieldValue.length() - 1));
        } catch (DecoderException e) {
            throw new DatabusException(
                    "Unable to decode a " + databaseFieldType + " field: " + recordFieldName);
        }
    }
    //return array
    else if (databaseFieldType.equalsIgnoreCase("ARRAY")) {
        throw new DatabusException("ARRAY type still not implemented!"); //TODO add support for array
    }
    //return record
    else if (databaseFieldType.equalsIgnoreCase("TABLE")) {
        throw new DatabusException("TABLE type still not implemented!"); //TODO add support for table
    } else {
        throw new DatabusException("unknown field type: " + recordFieldName + ":" + databaseFieldType);
    }
}

From source file:com.loadsensing.app.Chart.java

private void generaChart(WebView googleChartView, int checkedId, String SensorSelected) {
    SharedPreferences settings = getSharedPreferences("LoadSensingApp", Context.MODE_PRIVATE);
    String address = SERVER_HOST + "?session=" + settings.getString("session", "") + "&id=" + SensorSelected
            + "&TipusGrafic=" + checkedId;

    ArrayList<HashMap<String, String>> valorsURL = new ArrayList<HashMap<String, String>>();

    try {/*from   w  w w .  j av a  2 s. c  o m*/
        String jsonString = JsonClient.connectString(address);

        // Convertim la resposta string a un JSONArray
        JSONArray ValorsGrafica = new JSONArray(jsonString);

        // En esta llamada slo hay 1 objeto
        JSONObject Valors = new JSONObject();
        Valors = ValorsGrafica.getJSONObject(0);

        String grafica = Valors.getString("ValorsGrafica");

        // Sobre el string de ValorGrafica, volvemos a parsearlo
        JSONArray ValorGrafica = new JSONArray(grafica);
        for (int i = 0; i < ValorGrafica.length(); i++) {
            JSONObject Valor = new JSONObject();
            Valor = ValorGrafica.getJSONObject(i);

            HashMap<String, String> valorHashMap = new HashMap<String, String>();
            valorHashMap.put("date", Valor.getString("date"));
            valorHashMap.put("value", Valor.getString("value"));
            valorsURL.add(valorHashMap);
        }

    } catch (Exception e) {
        Log.d(DEB_TAG, "Error rebent xarxes");
    }

    // Montamos URL
    String mUrl = CHART_URL;

    // Etiquetas eje X, columna 0 y 1
    mUrl = mUrl + "chxl=0:";
    for (int i = 3; i < valorsURL.size(); i += 4) {
        mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date"));
    }
    mUrl = mUrl + "|Fecha";
    mUrl = mUrl + "|1:";
    for (int i = 1; i < valorsURL.size(); i += 4) {
        mUrl = mUrl + "|" + URLEncoder.encode(valorsURL.get(i).get("date"));
    }

    // Posicin etiquetas eje Y
    mUrl = mUrl + "&chxp=0,30,70,110|1,10,50,90";

    // Rango x,y

    // Coger valor mnimo y mximo
    float max = new Float(valorsURL.get(0).get("value"));
    float min = new Float(valorsURL.get(0).get("value"));
    for (int i = 1; i < valorsURL.size(); i++) {
        Float valueFloat = new Float(valorsURL.get(i).get("value"));
        max = Math.max(max, valueFloat);
        min = Math.min(min, valueFloat);
    }

    BigDecimal maxRounded = new BigDecimal(max);
    maxRounded = maxRounded.setScale(1, BigDecimal.ROUND_CEILING);
    BigDecimal minRounded = new BigDecimal(min);
    minRounded = minRounded.setScale(1, BigDecimal.ROUND_FLOOR);

    mUrl = mUrl + "&chxr=0,-5,110|1,-5,110|2," + minRounded + "," + maxRounded;

    // Ejes visibles
    mUrl = mUrl + "&chxt=x,x,y";

    // Tipo de grfico
    mUrl = mUrl + "&cht=lxy";

    // Medida del grfico
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth() - 170;
    int height = display.getHeight() - 390;
    mUrl = mUrl + "&chs=" + width + "x" + height;

    // Colores
    mUrl = mUrl + "&chco=3072F3";

    // Escala
    mUrl = mUrl + "&chds=0,9," + minRounded + "," + maxRounded;

    // Valores
    mUrl = mUrl + "&chd=t:0";
    for (int i = 1; i < valorsURL.size(); i++) {
        mUrl = mUrl + "," + i;
    }
    mUrl = mUrl + "|";
    mUrl = mUrl + valorsURL.get(0).get("value");
    for (int i = 1; i < valorsURL.size(); i++) {
        mUrl = mUrl + "," + valorsURL.get(i).get("value");
    }

    // Ttulo eyenda
    switch (checkedId) {
    case R.id.radio1:
        mUrl = mUrl + "&chdl=Sensor+strain+(V)&chdlp=b";
        break;
    case R.id.radio2:
        mUrl = mUrl + "&chdl=Excitation+power+(V)&chdlp=b";
        break;
    case R.id.radio3:
        mUrl = mUrl + "&chdl=Counter+(cnts)&chdlp=b";
        break;
    }

    // Estilo de lineas
    mUrl = mUrl + "&chls=2";

    // Mrgenes
    mUrl = mUrl + "&chma=0,5,5,25|5";

    // Marcador
    mUrl = mUrl + "&chm=r,FF0000,0,0,0";

    Log.d(DEB_TAG, "URL Chart " + mUrl);

    googleChartView.loadUrl(mUrl);
}

From source file:org.n52.oxf.render.sos.TimeSeriesChartRenderer.java

public JFreeChart renderChart(OXFFeatureCollection observationCollection, ParameterContainer paramCon) {
    String[] observedProperties;//from   w  w  w. j  av a2 s . co m
    // which observedProperty has been used?:
    ParameterShell observedPropertyPS = paramCon.getParameterShellWithServiceSidedName("observedProperty");
    if (observedPropertyPS.hasMultipleSpecifiedValues()) {
        observedProperties = observedPropertyPS.getSpecifiedTypedValueArray(String[].class);
    } else if (observedPropertyPS.hasSingleSpecifiedValue()) {
        observedProperties = new String[] { (String) observedPropertyPS.getSpecifiedValue() };
    } else {
        throw new IllegalArgumentException("no observedProperties found.");
    }

    phenomenon = observedProperties[0];

    String[] foiIdArray = paramCon.getParameterShellWithServiceSidedName("featureOfInterest")
            .getSpecifiedTypedValueArray(String[].class);

    TimeSeriesCollection dataset = new TimeSeriesCollection();

    ObservationSeriesCollection tuples4FOI = new ObservationSeriesCollection(observationCollection, foiIdArray,
            observedProperties, true);

    for (String featureID : foiIdArray) {
        Map<ITimePosition, ObservedValueTuple> tupleMap = tuples4FOI.getAllTuples(featureID);

        // for each selected feature construct a new TimeSeries:
        TimeSeries timeSeries = new TimeSeries(featureID, Second.class);

        if (tupleMap != null) {

            for (ITimePosition timePos : tupleMap.keySet()) {
                ObservedValueTuple tuple = tupleMap.get(timePos);

                double measurement = (Double) tuple.getValue(0);

                timeSeries.add(new Second(new Float(timePos.getSecond()).intValue(), timePos.getMinute(),
                        timePos.getHour(), timePos.getDay(), timePos.getMonth(),
                        new Long(timePos.getYear()).intValue()), measurement);
            }
            dataset.addSeries(timeSeries);
        }
    }
    dataset.setDomainIsPointsInTime(true);

    return drawChart(dataset);
}

From source file:com.judoscript.jamaica.MyUtils.java

public static Object value2object(Object val, String typeHint) {
    if (typeHint == null)
        return val;

    if (typeHint.equals("boolean") || val instanceof Boolean)
        return val; // leave type check to caller.

    double v;/*from  w ww.j a  v  a 2  s  .c o  m*/
    if (val instanceof Character)
        v = ((Character) val).charValue();
    else if (val instanceof Number)
        v = ((Number) val).doubleValue();
    else
        return val; // leave type check to caller.

    if (typeHint.equals("int"))
        return new Integer((int) v);
    if (typeHint.equals("long"))
        return new Long((long) v);
    if (typeHint.equals("short"))
        return new Short((short) v);
    if (typeHint.equals("char"))
        return new Character((char) v);
    if (typeHint.equals("byte"))
        return new Byte((byte) v);
    if (typeHint.equals("float"))
        return new Float((float) v);
    //  if (typeHint.equals("double"))
    return new Double(v);
}

From source file:org.openmrs.module.pmtct.web.view.chart.InfantPCRPieChartView.java

/**
 * @see org.openmrs.module.pmtct.web.view.chart.AbstractChartView#createChart(java.util.Map,
 *      javax.servlet.http.HttpServletRequest)
 *//*from w w w . ja  v a2  s . c o 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();

    //            Date myDate1 = new Date("1/1/" + ((new Date()).getYear() + 1900));
    //            String startDate1 = df.format(myDate1);

    Date today = new Date();
    Date oneYearFromNow = new Date(new Date().getTime() - PMTCTConstants.YEAR_IN_MILLISECONDS);

    String endDate1 = df.format(today);
    String startDate1 = df.format(oneYearFromNow);

    dateInterval = "(" + new SimpleDateFormat("dd-MMM-yyyy").format(oneYearFromNow) + " - "
            + new SimpleDateFormat("dd-MMM-yyyy").format(today) + ")";

    try {

        PmtctService pmtct;
        pmtct = Context.getService(PmtctService.class);
        try {
            res = pmtct.getGeneralStatForInfantTests_Charting_PCR(startDate1, endDate1);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (Exception 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()) : descriptionTitle),
            pieDataset, true, true, false);

    return chart;
}

From source file:com.krawler.br.nodes.Activity.java

/**
 * converts the given object value to the given primitive type's wrapper class
 * if possible (if it is a <tt>Number</tt>)
 *
 * @param type the premitive type name, may be:
 * <ul>//  ww  w  .jav  a2 s .  co m
 * <li><tt>byte</tt>
 * <li><tt>char</tt>
 * <li><tt>short</tt>
 * <li><tt>int</tt>
 * <li><tt>long</tt>
 * <li><tt>float</tt>
 * <li><tt>double</tt>
 * </ul>
 * @param value the original value
 * @return the converted value
 */
private Object convert(String type, Object value) {
    Object val = value;

    if (value instanceof Number) {
        Number num = (Number) value;

        if (Byte.class.getCanonicalName().equals(type))
            val = new Byte(num.byteValue());
        else if (Character.class.getCanonicalName().equals(type))
            val = new Character((char) num.intValue());
        else if (Short.class.getCanonicalName().equals(type))
            val = new Short(num.shortValue());
        else if (Integer.class.getCanonicalName().equals(type))
            val = new Integer(num.intValue());
        else if (Long.class.getCanonicalName().equals(type))
            val = new Long(num.longValue());
        else if (Float.class.getCanonicalName().equals(type))
            val = new Float(num.floatValue());
        else if (Double.class.getCanonicalName().equals(type))
            val = new Double(num.doubleValue());
    }
    return val;
}

From source file:com.turn.shapeshifter.AutoParser.java

/**
 * Reads the value of a JSON node and returns the corresponding Java
 * object./*from  w  w w .j a v  a2 s. co m*/
 *
 * @param jsonNode the node to convert to a Java object
 * @param field the protocol buffer field to which the resulting value will
 * be assigned
 * @param registry used as a source of schemas generated on the fly for
 * sub-objects
 * @return a Java object representing the field's value
 * @throws ParsingException
 * @throws UnmappableValueException in case the JSON value node cannot be
 * converted
 * to a Java object that could be assigned to {@code field}
 */
private Object parseValue(JsonNode jsonNode, FieldDescriptor field, ReadableSchemaRegistry registry)
        throws ParsingException {
    Object value = null;
    switch (field.getType()) {
    case BOOL:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_BOOLEAN_TOKENS);
        value = Boolean.valueOf(jsonNode.asBoolean());
        break;
    case BYTES:
        break;
    case DOUBLE:
        value = new Double(jsonNode.asDouble());
        break;
    case ENUM:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_ENUM_TOKENS);
        String enumValue = jsonNode.asText();
        String convertedValue = AutoSchema.JSON_ENUM_CASE_FORMAT.to(AutoSchema.PROTO_ENUM_CASE_FORMAT,
                enumValue);
        value = field.getEnumType().findValueByName(convertedValue);
        break;
    case FLOAT:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_FLOAT_TOKENS);
        value = new Float(jsonNode.asDouble());
        break;
    case GROUP:
        break;
    case FIXED32:
    case INT32:
    case SFIXED32:
    case SINT32:
    case UINT32:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Integer(jsonNode.asInt());
        break;
    case FIXED64:
    case INT64:
    case SFIXED64:
    case SINT64:
    case UINT64:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_INTEGER_TOKENS);
        value = new Long(jsonNode.asLong());
        break;
    case MESSAGE:
        if (!jsonNode.isObject()) {
            throw new IllegalArgumentException(
                    "Expected to parse object, found value of type " + jsonNode.asToken());
        }
        if (jsonNode.size() != 0) {
            try {
                value = registry.get(field.getMessageType()).getParser().parse(jsonNode, registry);
            } catch (SchemaObtentionException soe) {
                throw new ParsingException(soe);
            }
        }
        break;
    case STRING:
        JsonTokens.checkJsonValueConformance(jsonNode, JsonTokens.VALID_STRING_TOKENS);
        value = jsonNode.asText();
        break;
    default:
        break;
    }
    return value;
}

From source file:com.edgehometheater.IndexMoviesContext.java

public int IndexMovies(String directory) {
    int count = 0;

    File movieDir = new File(directory);
    String[] movieFiles = movieDir.list(new MovieFilter());

    for (String movieFile : movieFiles) {

        File file = new File(movieDir.toString() + "/" + movieFile);

        // Sub-directory
        if (file.isDirectory()) {
            int subCount = IndexMovies(directory + "/" + file.getName());

            count = count + subCount;//  w w  w.j  a  va  2s  . c om
            continue;
        }

        // check if we already indexed this file in the Sqlite3 DB
        String relativeMovieFile = file.getAbsolutePath().replace(moviesPath + "\\", "")
                .replace(moviesPath + "/", "").replace("\\", "/");
        if (MovieDB.MovieExists(relativeMovieFile).length() > 0) {
            // skip this movie
            continue;
        }

        // count of movies processed
        count++;

        MetaData metaData = new MetaData();
        metaData.setMovieID(GeneralUtils.getUniqueId());

        metaData.setMovieFile(relativeMovieFile);

        try {
            // Lookup media stream info, bitrate, width x height, framerate, duration, format, etc..
            MediaInfo info = new MediaInfo();
            info.open(file);

            int i = 0;

            //String format     = info.get(MediaInfo.StreamKind.Video, i, "Format", 
            //                        MediaInfo.InfoKind.Text, MediaInfo.InfoKind.Name);
            String bitRate = info.get(MediaInfo.StreamKind.Video, i, "BitRate", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);
            String frameRate = info.get(MediaInfo.StreamKind.Video, i, "FrameRate", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);
            String width = info.get(MediaInfo.StreamKind.Video, i, "Width", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);
            String height = info.get(MediaInfo.StreamKind.Video, i, "Height", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);
            String duration = info.get(MediaInfo.StreamKind.Video, i, "Duration", MediaInfo.InfoKind.Text,
                    MediaInfo.InfoKind.Name);

            info.close();
            info.dispose();

            // Convert values, BitRate to Kbps, Duration to seconds
            Float bitRateFloat = new Float(bitRate) / 1000;
            int bitRateKbps = Math.round(bitRateFloat);
            int durationSecs = Integer.parseInt(duration) / 1000;

            //metaData.setFormat(format);
            metaData.setFrameRate(frameRate);
            metaData.setBitRate(bitRateKbps);
            metaData.setWidth(Integer.parseInt(width));
            metaData.setHeight(Integer.parseInt(height));
            metaData.setDuration(durationSecs);

        } catch (Exception ex) {
            //System.out.println("Failed: " + ex.getMessage());
            continue;
        }

        // Get filename minus extension and then extension minus filename
        String nameMovie = file.getName().substring(0, file.getName().lastIndexOf(".")).replaceAll("_", " ");
        String extension = file.getName().substring(file.getName().lastIndexOf(".") + 1);

        // Hack for now
        metaData.setFormat(extension);

        // set initial title value based on filename. in case we can't lookup title from TMDb
        metaData.setTitle(nameMovie);

        // Lookup movie info from TMDb
        try {
            GeneralSettings.setApiKey("24498a4aee4e3f8205f29c0197261ce1");
            List<Movie> movies = Movie.search(nameMovie);
            if (movies != null && movies.size() > 0) {
                Movie movie = movies.get(0);
                Movie movieFull = Movie.getInfo(movie.getID());

                // Get movie info
                metaData.setTitle(movie.getName());
                metaData.setDescription(movie.getOverview());
                metaData.setRating(movie.getCertification());

                int year = movieFull.getReleasedDate().getYear();
                year = year + 1900;

                metaData.setReleaseDate(year);

                // Get movie genres
                Set<Genre> genres = movieFull.getGenres();
                for (Genre genre : genres) {
                    metaData.getGenres().add(genre.getName());
                }

                // Get cast of movie, actors, directors, etc.
                for (CastInfo cast : movieFull.getCast()) {
                    // job is 'Actor' or 'Director'
                    String job = cast.getJob();
                    if (job.toLowerCase().equals("actor")) {
                        metaData.getActors().add(cast.getName());
                    }
                    if (job.toLowerCase().equals("director")) {
                        metaData.getDirectors().add(cast.getName());
                    }
                }

                // Get first poster image for cover and save it to the disk
                MovieImages images = movie.getImages();
                if (images.posters.size() > 0) {
                    MoviePoster poster = (MoviePoster) images.posters.toArray()[0];
                    URL imageUrl = poster.getImage(MoviePoster.Size.COVER);

                    // Get image filename
                    String imageFile = imageUrl.getFile().substring(imageUrl.getFile().lastIndexOf("/") + 1);

                    // Create images folder if doesn't exist
                    File imageDir = new File("images");
                    imageDir.mkdirs();

                    // Save image file
                    GeneralUtils.saveImage(imageUrl, "images/" + imageFile);

                    metaData.setPosterImage("images/" + imageFile);
                }
            } else {
                //System.out.println("Failed to get TMDb data: " + metaData.getTitle());
            }
        } catch (Exception ex) {
            //System.out.println("Failed: " + ex.getMessage());
        }

        // If we make it this far, then we have data to store for this movie in the Sqlite3 DB
        MovieDB.MovieInsert(metaData);
    }

    return count;
}