Example usage for java.lang Float toString

List of usage examples for java.lang Float toString

Introduction

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

Prototype

public static String toString(float f) 

Source Link

Document

Returns a string representation of the float argument.

Usage

From source file:org.executequery.databasemediators.spi.DefaultStatementExecutor.java

/** <p>Executes the specified procedure.
 *
 *  @param  the SQL procedure to execute
 *  @return the query result/*from   w w w .j  av a 2s . c  o m*/
 */
public SqlStatementResult execute(DatabaseExecutable databaseExecutable) throws SQLException {

    if (!prepared()) {

        return statementResult;
    }

    ProcedureParameter[] param = databaseExecutable.getParametersArray();
    Arrays.sort(param, new ProcedureParameterSorter());

    String procQuery = null;
    boolean hasOut = false;
    boolean hasParameters = (param != null && param.length > 0);

    List<ProcedureParameter> outs = null;
    List<ProcedureParameter> ins = null;

    if (hasParameters) {

        // split the params into ins and outs
        outs = new ArrayList<ProcedureParameter>();
        ins = new ArrayList<ProcedureParameter>();

        int type = -1;
        for (int i = 0; i < param.length; i++) {
            type = param[i].getType();
            if (type == DatabaseMetaData.procedureColumnIn || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the ins list
                ins.add(param[i]);

            } else if (type == DatabaseMetaData.procedureColumnOut
                    || type == DatabaseMetaData.procedureColumnResult
                    || type == DatabaseMetaData.procedureColumnReturn
                    || type == DatabaseMetaData.procedureColumnUnknown
                    || type == DatabaseMetaData.procedureColumnInOut) {

                // add to the outs list
                outs.add(param[i]);

            }
        }

        char QUESTION_MARK = '?';
        String COMMA = ", ";

        // init the string buffer
        StringBuilder sb = new StringBuilder("{ ");
        if (!outs.isEmpty()) {

            // build the out params place holders
            for (int i = 0, n = outs.size(); i < n; i++) {

                sb.append(QUESTION_MARK);

                if (i < n - 1) {

                    sb.append(COMMA);
                }

            }

            sb.append(" = ");
        }

        sb.append(" call ");

        if (databaseExecutable.supportCatalogOrSchemaInFunctionOrProcedureCalls()) {

            String namePrefix = null;
            if (databaseExecutable.supportCatalogInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getCatalogName();

            }
            if (databaseExecutable.supportSchemaInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getSchemaName();

            }

            if (namePrefix != null) {

                sb.append(namePrefix).append('.');
            }
        }

        sb.append(databaseExecutable.getName()).append("( ");

        // build the ins params place holders
        for (int i = 0, n = ins.size(); i < n; i++) {
            sb.append(QUESTION_MARK);
            if (i < n - 1) {
                sb.append(COMMA);
            }
        }

        sb.append(" ) }");

        // determine if we have out params
        hasOut = !(outs.isEmpty());
        procQuery = sb.toString();
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("{ call ");

        if (databaseExecutable.getSchemaName() != null) {
            sb.append(databaseExecutable.getSchemaName()).append('.');
        }

        sb.append(databaseExecutable.getName()).append("( ) }");

        procQuery = sb.toString();
    }

    //Log.debug(procQuery);

    // null value literal
    String NULL = "null";

    // clear any warnings
    conn.clearWarnings();

    Log.info("Executing: " + procQuery);

    CallableStatement cstmnt = null;
    try {
        // prepare the statement
        cstmnt = conn.prepareCall(procQuery);
        stmnt = cstmnt;
    } catch (SQLException e) {
        handleException(e);
        statementResult.setSqlException(e);
        return statementResult;
    }

    // check if we are passing parameters
    if (hasParameters) {
        // the parameter index counter
        int index = 1;

        // the java.sql.Type value
        int dataType = -1;

        // the parameter input value
        String value = null;

        // register the out params
        for (int i = 0, n = outs.size(); i < n; i++) {
            //Log.debug("setting out at index: " + index);
            cstmnt.registerOutParameter(index, outs.get(i).getDataType());
            index++;
        }

        try {

            // register the in params
            for (int i = 0, n = ins.size(); i < n; i++) {

                ProcedureParameter procedureParameter = ins.get(i);
                value = procedureParameter.getValue();
                dataType = procedureParameter.getDataType();

                // try infer a type if OTHER
                if (dataType == Types.OTHER) {

                    // checking only for bit/bool for now

                    if (isTrueFalse(value)) {

                        dataType = Types.BOOLEAN;

                    } else if (isBit(value)) {

                        dataType = Types.BIT;
                        value = value.substring(2, value.length() - 1);
                    }

                }

                if (MiscUtils.isNull(value) || value.equalsIgnoreCase(NULL)) {

                    cstmnt.setNull(index, dataType);

                } else {

                    switch (dataType) {

                    case Types.TINYINT:
                        byte _byte = Byte.valueOf(value).byteValue();
                        cstmnt.setShort(index, _byte);
                        break;

                    case Types.SMALLINT:
                        short _short = Short.valueOf(value).shortValue();
                        cstmnt.setShort(index, _short);
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        cstmnt.setString(index, value);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:

                        boolean _boolean = false;
                        if (NumberUtils.isNumber(value)) {

                            int number = Integer.valueOf(value);
                            if (number > 0) {

                                _boolean = true;
                            }

                        } else {

                            _boolean = Boolean.valueOf(value).booleanValue();
                        }

                        cstmnt.setBoolean(index, _boolean);
                        break;

                    case Types.BIGINT:
                        long _long = Long.valueOf(value).longValue();
                        cstmnt.setLong(index, _long);
                        break;

                    case Types.INTEGER:
                        int _int = Integer.valueOf(value).intValue();
                        cstmnt.setInt(index, _int);
                        break;

                    case Types.REAL:
                        float _float = Float.valueOf(value).floatValue();
                        cstmnt.setFloat(index, _float);
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        cstmnt.setBigDecimal(index, new BigDecimal(value));
                        break;
                    /*
                                      case Types.DATE:
                                      case Types.TIMESTAMP:
                                      case Types.TIME:
                                        cstmnt.setTimestamp(index, new Timestamp( BigDecimal(value));
                    */
                    case Types.FLOAT:
                    case Types.DOUBLE:
                        double _double = Double.valueOf(value).doubleValue();
                        cstmnt.setDouble(index, _double);
                        break;

                    default:
                        cstmnt.setObject(index, value);

                    }

                }

                // increment the index
                index++;
            }

        } catch (Exception e) {

            statementResult.setOtherErrorMessage(e.getClass().getName() + ": " + e.getMessage());
            return statementResult;
        }

    }

    /*
    test creating function for postgres:
            
    CREATE FUNCTION concat_lower_or_upper(a text, b text, uppercase boolean DEFAULT false)
    RETURNS text
    AS
    $$
     SELECT CASE
        WHEN $3 THEN UPPER($1 || ' ' || $2)
        ELSE LOWER($1 || ' ' || $2)
        END;
    $$
    LANGUAGE SQL IMMUTABLE STRICT;
    */

    try {
        cstmnt.clearWarnings();
        boolean hasResultSet = cstmnt.execute();
        Map<String, Object> results = new HashMap<String, Object>();

        if (hasOut) {
            // incrementing index
            int index = 1;

            // return value from each registered out
            String returnValue = null;

            for (int i = 0; i < param.length; i++) {

                int type = param[i].getType();
                int dataType = param[i].getDataType();

                if (type == DatabaseMetaData.procedureColumnOut
                        || type == DatabaseMetaData.procedureColumnResult
                        || type == DatabaseMetaData.procedureColumnReturn
                        || type == DatabaseMetaData.procedureColumnUnknown
                        || type == DatabaseMetaData.procedureColumnInOut) {

                    switch (dataType) {

                    case Types.TINYINT:
                        returnValue = Byte.toString(cstmnt.getByte(index));
                        break;

                    case Types.SMALLINT:
                        returnValue = Short.toString(cstmnt.getShort(index));
                        break;

                    case Types.LONGVARCHAR:
                    case Types.CHAR:
                    case Types.VARCHAR:
                        returnValue = cstmnt.getString(index);
                        break;

                    case Types.BIT:
                    case Types.BOOLEAN:
                        returnValue = Boolean.toString(cstmnt.getBoolean(index));
                        break;

                    case Types.INTEGER:
                        returnValue = Integer.toString(cstmnt.getInt(index));
                        break;

                    case Types.BIGINT:
                        returnValue = Long.toString(cstmnt.getLong(index));
                        break;

                    case Types.REAL:
                        returnValue = Float.toString(cstmnt.getFloat(index));
                        break;

                    case Types.NUMERIC:
                    case Types.DECIMAL:
                        returnValue = cstmnt.getBigDecimal(index).toString();
                        break;

                    case Types.DATE:
                    case Types.TIME:
                    case Types.TIMESTAMP:
                        returnValue = cstmnt.getDate(index).toString();
                        break;

                    case Types.FLOAT:
                    case Types.DOUBLE:
                        returnValue = Double.toString(cstmnt.getDouble(index));
                        break;

                    }

                    if (returnValue == null) {
                        returnValue = "NULL";
                    }

                    results.put(param[i].getName(), returnValue);
                    index++;
                }

            }

        }

        if (!hasResultSet) {

            statementResult.setUpdateCount(cstmnt.getUpdateCount());

        } else {

            statementResult.setResultSet(cstmnt.getResultSet());
        }

        useCount++;
        statementResult.setOtherResult(results);

    } catch (SQLException e) {

        statementResult.setSqlException(e);

    } catch (Exception e) {

        statementResult.setMessage(e.getMessage());
    }

    return statementResult;
}

From source file:org.paxle.tools.charts.impl.gui.ChartServlet.java

/**
 * Add the full-path of all {@link StatusVariable variables} of the given {@link Monitorable} into the set
 * @param reference a reference to a {@link Monitorable}
 * @param variableNames the set where the variable-names should be appended
 * @param determineType if <code>true</code> the type of the {@link StatusVariable} is determined via call to
 *                    {@link StatusVariable#getType()} and stored into {@link #typeList}
 * @param updateCharts if determineType was enabled and this is <code>true</code> the current value of the {@link StatusVariable}
 *                       is used to update the chart via call to {@link #updateValue(String, Object)}
 *///from  ww w  .  j a  v  a  2  s  . com
private void addVariables4Monitor(ServiceReference reference, HashSet<String> variableNames,
        boolean determineType, boolean updateCharts) {
    String pid = (String) reference.getProperty(Constants.SERVICE_PID);
    if (!variableTree.containsKey(pid))
        return;

    for (String name : variableTree.get(pid)) {
        final String fullPath = pid + "/" + name;

        // append full-path
        variableNames.add(fullPath);

        // getting the type of the status-variable
        if (determineType) {
            try {
                Monitorable mon = (Monitorable) this.context.getService(reference);
                StatusVariable var = mon.getStatusVariable(name);
                Integer type = Integer.valueOf(var.getType());

                this.typeList.put(fullPath, type);

                // updating charts if requested
                if (updateCharts) {
                    String value = null;
                    switch (type.intValue()) {
                    case StatusVariable.TYPE_FLOAT:
                        value = Float.toString(var.getFloat());
                        break;
                    case StatusVariable.TYPE_INTEGER:
                        value = Integer.toString(var.getInteger());
                        break;
                    case StatusVariable.TYPE_BOOLEAN:
                        value = Boolean.toString(var.getBoolean());
                        break;
                    case StatusVariable.TYPE_STRING:
                        value = var.getString();
                        break;
                    default:
                        break;
                    }

                    this.updateValue(fullPath, value);
                }
            } catch (Exception e) {
                this.logger.error(
                        String.format("Unexpected '%s' while trying to determine type of statusvariable '%s'.",
                                e.getClass().getName(), fullPath),
                        e);
            }
        }
    }
}

From source file:org.opendatakit.aggregate.odktables.impl.api.TableServiceImpl.java

@Override
public Response putJsonTableProperties(ArrayList<Map<String, Object>> propertiesList)
        throws ODKDatastoreException, PermissionDeniedException, ODKTaskLockException, TableNotFoundException {
    ArrayList<PropertyEntryXml> properties = new ArrayList<PropertyEntryXml>();
    for (Map<String, Object> tpe : propertiesList) {
        // bogus type and value...
        String partition = (String) tpe.get("partition");
        String aspect = (String) tpe.get("aspect");
        String key = (String) tpe.get("key");
        String type = (String) tpe.get("type");
        PropertyEntryXml e = new PropertyEntryXml(partition, aspect, key, type, null);

        // and figure out the correct type and value...
        Object value = tpe.get("value");
        if (value == null) {
            e.setValue(null);/*from w  w w .  java  2s .com*/
        } else if (value instanceof Boolean) {
            e.setValue(Boolean.toString((Boolean) value));
        } else if (value instanceof Integer) {
            e.setValue(Integer.toString((Integer) value));
        } else if (value instanceof Float) {
            e.setValue(Float.toString((Float) value));
        } else if (value instanceof Double) {
            e.setValue(Double.toString((Double) value));
        } else if (value instanceof List) {
            try {
                e.setValue(mapper.writeValueAsString(value));
            } catch (JsonProcessingException ex) {
                ex.printStackTrace();
                e.setValue("[]");
            }
        } else {
            try {
                e.setValue(mapper.writeValueAsString(value));
            } catch (JsonProcessingException ex) {
                ex.printStackTrace();
                e.setValue("{}");
            }
        }

        properties.add(e);
    }
    PropertyEntryXmlList pl = new PropertyEntryXmlList(properties);
    return putInternalTableProperties(pl);
}

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromFloat(Type targetType, float value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Float:
        return Float.valueOf(value);
    case Byte:
        return new Byte(Float.valueOf(value).byteValue());
    case Double:
        return new Double(Float.valueOf(value).doubleValue());
    case Int://w  w  w  .  ja  v  a 2  s  . co  m
        return new Integer(Float.valueOf(value).intValue());
    case Long:
        return new Long(Float.valueOf(value).longValue());
    case Short:
        return new Short(Float.valueOf(value).shortValue());
    case Decimal:
        return BigDecimal.valueOf(value);
    case Integer:
        return BigInteger.valueOf(Double.valueOf(value).longValue());
    case String:
        // as per spec:  Decimal | 'NaN' | '-NaN' | 'Infinity' | '-Infinity'
        return Float.toString(value);
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Float, value);
    }
}

From source file:de.uni_weimar.m18.anatomiederstadt.LevelPageFragment.java

private String replaceStringWithVars(String expression, boolean printFloat) {
    Matcher m = Pattern.compile("\\$([_a-zA-Z][_a-zA-Z0-9]{0,30})").matcher(expression);
    LevelStateManager stateManager = ((AnatomieDerStadtApplication) getActivity().getApplicationContext())
            .getStateManager(getActivity());
    String replacedExpr = expression;
    while (m.find()) {
        float value = stateManager.getFloat(m.group(1));
        if (printFloat) {
            String floatValue = new DecimalFormat("#.##").format(value);
            replacedExpr = replacedExpr.replace(m.group(0), floatValue);
        } else {/*from w  w w . j  a va2  s  . c o m*/
            replacedExpr = replacedExpr.replace(m.group(0), Float.toString(value));
        }
    }
    return replacedExpr;
}

From source file:com.limewoodmedia.nsdroid.activities.Nation.java

private void doPeopleSetup() {
    // Chart/*  ww w  .j a v a 2  s . c om*/
    peopleSeries.clear();
    peopleRenderer.removeAllRenderers();
    Set<Map.Entry<CauseOfDeath, Float>> deaths = data.deaths.entrySet();
    NumberFormat format = NumberFormat.getPercentInstance();
    format.setMaximumFractionDigits(1);
    Map<CauseOfDeath, String> legends = new HashMap<CauseOfDeath, String>();
    StringBuilder legend;
    String desc;
    int colour;
    for (Map.Entry<CauseOfDeath, Float> d : deaths) {
        desc = d.getKey() == CauseOfDeath.ANIMAL_ATTACK
                ? d.getKey().getDescription().replace("Animal",
                        data.animal.substring(0, 1).toUpperCase() + data.animal.substring(1))
                : d.getKey().getDescription();
        peopleSeries.add(desc, d.getValue() / 100f);
        SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
        colour = CHART_COLOURS[(peopleSeries.getItemCount() - 1) % CHART_COLOURS.length];
        renderer.setColor(colour);
        renderer.setChartValuesFormat(format);
        peopleRenderer.addSeriesRenderer(renderer);
        legend = new StringBuilder();
        legend.append("<b><font color='").append(Integer.toString(colour)).append("'>").append(desc);
        legends.put(d.getKey(), legend.toString());
    }
    peopleChart.repaint();

    // Legend
    legend = new StringBuilder();
    for (CauseOfDeath cod : CauseOfDeath.values()) {
        if (legend.length() > 0) {
            legend.append("<br/>");
        }
        if (legends.containsKey(cod)) {
            legend.append(legends.get(cod)).append(": ").append(Float.toString(data.deaths.get(cod)))
                    .append("%</font></b>");
        } else {
            legend.append("<font color='grey'>").append(cod.getDescription()).append(": ").append("0%</font>");
        }
    }
    peopleLegend.setText(Html.fromHtml(legend.toString()), TextView.BufferType.SPANNABLE);
}

From source file:com.jogden.spunkycharts.pricebyvolumechart.PriceByVolumeChartFragmentAdapter.java

private Thread _createPriceAxisAndMainPanel() {
    Thread thisThread = new Thread() {
        public void run() {
            ///////////////////////////////////
            /*     START PREEMPTION LOGIC     */
            /////////////////////////////////
            boolean noWait;
            final int MAX_PREEMPT_COUNT = ApplicationPreferences.getMaxPreemptCount();
            if (!(noWait = _priceAxisLck.tryLock())) {
                synchronized (_priceAxisThrdMntr) {
                    if (_priceAxisPrmptCnt++ > MAX_PREEMPT_COUNT)
                        return;
                    if (_priceAxisThrd != null)
                        _priceAxisThrd.interrupt();
                }// w w  w.j a v  a 2s  .c om
                _priceAxisPrmptStck.offer(this);
                _priceAxisLck.lock();
            }
            try { /* everything that follows should assume we own monitor */
                if (!noWait) {
                    if (this != _priceAxisPrmptStck.peekLast())
                        return;
                    else { /* don't assume stack hasn't grown since the peek */
                        Iterator<Thread> dIter = _priceAxisPrmptStck.iterator();
                        do {
                            _priceAxisPrmptStck.poll();
                        } while (dIter.next() != this);
                    }
                }
                synchronized (_priceAxisThrdMntr) {
                    _priceAxisThrd = this;
                }
                /////////////////////////////////
                /*     END PREEMPTION LOGIC     */
                //////////////////////////////                            

                float rangeDiff = _highPrice - _lowPrice;
                /* deal with problematic high/low parameters */
                if (rangeDiff <= 0 || _highPrice < 0 || _lowPrice < 0)
                    if (rangeDiff == 0 && _highPrice > 0) {
                        _highPrice *= 1.001;
                        _lowPrice *= .999;
                        rangeDiff = _highPrice - _lowPrice;
                    } else
                        throw new IllegalStateException("Invalid high and/or low price in the ChartAdapter");
                /* if we haven't calculated the height of a price-label view */
                if (_priceElemHght == 0) {/* can cached value doesn't go stale? */
                    final YAxisPriceLabel tv1 = (YAxisPriceLabel) _inflater.inflate(R.layout.y_axis_price_label,
                            null);
                    tv1.setText("X");
                    tv1.setTextSize(_axisFontSz);
                    tv1.setVisibility(View.INVISIBLE);
                    final ConditionVariable cond = new ConditionVariable();
                    _guiThrdHndlr.post(new Runnable() {
                        public void run() {
                            _priceAxis.removeAllViews();
                            _priceAxis.addView(tv1);
                            cond.open();
                        }
                    });
                    cond.block();
                    cond.close();
                    YAxisPriceLabel tv1b = (YAxisPriceLabel) _priceAxis.getChildAt(0);
                    /* make sure a valid priceElemHeightt, or quit entirely */
                    /* just spin, a new thread preempts us anyway */
                    while ((_priceElemHght = tv1b.getHeight()) == 0)
                        Thread.sleep(_axisTimeoutIncr);
                }
                _guiThrdHndlr.post(new Runnable() {
                    public void run() {
                        _priceAxis.removeAllViews();
                    }
                });
                int totalHeight;
                /* make sure a valid totalHeight, or quit entirely */
                /* just spin, a new thread preempts us anyway */
                while ((totalHeight = _priceAxis.getHeight()) == 0 || totalHeight > _myContainer.getHeight())
                    Thread.sleep(_axisTimeoutIncr);
                float[] incrVals = new float[2];
                try {
                    int maxNodes = (int) (totalHeight / _priceElemHght);
                    if (rangeDiff < 0 || maxNodes < 0)
                        throw new PriceByVolumeChartLogicError("rangeDiff and maxNodes can't be negative.");
                    incrVals = /* call down to our native sub to find increment values */
                            MainApplication.IncrementRegressNative(rangeDiff, maxNodes);
                    if (incrVals[0] < 0 || incrVals[1] <= 0)
                        throw new PriceByVolumeChartLogicError("IncrementRegressNative() sub-routine aborted. "
                                + "retVals[0]: " + incrVals[0] + "retVals[1]: " + incrVals[1] + "adjRangeDiff: "
                                + rangeDiff + "maxNodes" + maxNodes);
                    _segCount = (int) incrVals[1];
                    _segSize = incrVals[0];
                } catch (PriceByVolumeChartLogicError e) {
                    Log.e("PriceByVolumeChartLogicError", e.getMessage());
                    return; /* just leave the axis empty*/
                }

                /* adjust height to new increment values */
                final int adjPriceElemHeight = (int) (totalHeight / _segCount);
                /* we'll need to account for any unused spaced in the axis */
                final int vacantHeight = totalHeight - (int) (adjPriceElemHeight * _segCount);
                double distFromIncr = Math.IEEEremainder((double) _highPrice,
                        (double) _segSize); /* distance from rounded incr value */
                double adjTopNodeVal = (double) _highPrice - distFromIncr;
                if (distFromIncr > 0) /* be sure to round to the upper incr */
                    adjTopNodeVal += _segSize;
                DecimalFormat df = new DecimalFormat("0.00");
                double lastNodeVal = adjTopNodeVal;
                int count = 0;
                do { /* loop through the increments */
                    final YAxisPriceLabel tv = (YAxisPriceLabel) _inflater.inflate(R.layout.y_axis_price_label,
                            null);
                    tv.setTextSize(_axisFontSz);
                    tv.setText(df.format(lastNodeVal));
                    tv.setTextColor(_axisFontColor);
                    tv.setLayoutParams(
                            new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, 0, 1));
                    _guiThrdHndlr.post(new Runnable() {
                        public void run() {
                            _priceAxis.addView(tv);
                        }
                    }); /* for the loop-contingent side-effect */
                } while (++count < (int) _segCount && (lastNodeVal -= _segSize) > 0);
                final float halfVacantHeight = vacantHeight / 2;
                _mainSgmnt.setVerticalBuffers((int) halfVacantHeight, (int) halfVacantHeight);
                _guiThrdHndlr.post(new Runnable() {
                    public void run() {
                        _priceAxis.setPadding( /* center price-views */
                                0, (int) halfVacantHeight, 0, (int) halfVacantHeight);
                        _priceAxis.setClipChildren(false);
                        _priceAxis.setClipToPadding(false);
                        _priceAxis.invalidate();
                    }
                });

                synchronized (_priceAxisThrdMntr) {
                    _priceAxisPrmptCnt = 0;
                }
            } catch (InterruptedException e) {
            } catch (IllegalStateException e) {
                Log.d("IllegalState(High, Low): ",
                        "IllegalStateException caught in _createPriceAxisAndMainPanelY: "
                                + Float.toString(_highPrice) + " - " + Float.toString(_lowPrice));
            } catch (RuntimeException e) {
                e.printStackTrace();
                throw e;
            } finally {

                synchronized (_priceAxisThrdMntr) {
                    _priceAxisThrd = null;
                }
                _activeThreads.remove(this);
                _priceAxisLck.unlock();
            }
        }
    };
    _activeThreads.add(thisThread);
    thisThread.start();
    return thisThread;
}

From source file:com.timemachine.controller.ControllerActivity.java

/**
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */// w ww . ja v  a  2s.c  o m
private void setUpMap() {
    if (!isMapTimedUpdate) {
        // Send the new lat lng and zoom to the server when the view is changed
        GoogleMap.OnCameraChangeListener listener = new GoogleMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition position) {
                if (socket != null) {
                    socket.emit("mapViewUpdate",
                            Double.toString(position.target.latitude) + " "
                                    + Double.toString(position.target.longitude) + " "
                                    + Float.toString(position.zoom - timeMachineAndGoogleMapZoomOffset));
                    // Limit the max zoom
                    if (position.zoom > maxZoom) {
                        mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                    }
                }
            }
        };
        mMap.setOnCameraChangeListener(listener);
    } else {
        // Setup a timer to update the map location
        Timer updateMapTimer = new Timer();
        updateMapTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mapUpdateHandler.post(new Runnable() {
                    public void run() {
                        if (socket != null && isMapTimedUpdate) {
                            CameraPosition position = mMap.getCameraPosition();
                            double currentLat = Math.round(position.target.latitude * roundTo) / roundTo;
                            double currentLng = Math.round(position.target.longitude * roundTo) / roundTo;
                            float currentZoom = Math.round(position.zoom * (float) roundTo) / (float) roundTo;
                            if (currentLat != lastLat || currentLng != lastLng || currentZoom != lastZoom) {
                                socket.emit("mapViewUpdate", Double.toString(currentLat) + " "
                                        + Double.toString(currentLng) + " "
                                        + Double.toString(currentZoom - timeMachineAndGoogleMapZoomOffset));
                            }
                            // Limit the max zoom
                            if (position.zoom > maxZoom) {
                                mMap.moveCamera(CameraUpdateFactory.zoomTo(maxZoom));
                            }
                            lastLat = currentLat;
                            lastLng = currentLng;
                            lastZoom = currentZoom;
                        }
                    }
                });
            }
        }, mapUpdateTime, mapUpdateTime);
    }
    mMap.getUiSettings().setRotateGesturesEnabled(false);
    mMap.getUiSettings().setTiltGesturesEnabled(false);
    mMap.getUiSettings().setZoomControlsEnabled(false);
}

From source file:org.opencommercesearch.RuleManager.java

/**
 * Initializes the strenght map./*from w w w . ja  v  a 2 s  .  c  om*/
 *
 * TODO move this mappings to configuration file
 */
private void initializeStrengthMap() {
    strengthMap = new HashMap<String, String>(STRENGTH_LEVELS);

    strengthMap.put(STRENGTH_MAXIMUM_DEMOTE, Float.toString(1 / 10f));
    strengthMap.put(STRENGTH_STRONG_DEMOTE, Float.toString(1 / 5f));
    strengthMap.put(STRENGTH_MEDIUM_DEMOTE, Float.toString(1 / 2f));
    strengthMap.put(STRENGTH_WEAK_DEMOTE, Float.toString(1 / 1.5f));
    strengthMap.put(STRENGTH_NEUTRAL, Float.toString(1f));
    strengthMap.put(STRENGTH_WEAK_BOOST, Float.toString(1.5f));
    strengthMap.put(STRENGTH_MEDIUM_BOOST, Float.toString(2f));
    strengthMap.put(STRENGTH_STRONG_BOOST, Float.toString(5f));
    strengthMap.put(STRENGTH_MAXIMUM_BOOST, Float.toString(10f));
}