Example usage for java.lang Float MAX_VALUE

List of usage examples for java.lang Float MAX_VALUE

Introduction

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

Prototype

float MAX_VALUE

To view the source code for java.lang Float MAX_VALUE.

Click Source Link

Document

A constant holding the largest positive finite value of type float , (2-2-23)·2127.

Usage

From source file:com.repeatability.pdf.PDFTextStripper.java

/**
 * This will print the text of the processed page to "output". It will estimate, based on the coordinates of the
 * text, where newlines and word spacings should be placed. The text will be sorted only if that feature was
 * enabled.//from w  ww.j a v  a2 s. com
 *
 * @throws IOException If there is an error writing the text.
 */
protected void writePage() throws IOException {
    float maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
    float minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
    float endOfLastTextX = END_OF_LAST_TEXT_X_RESET_VALUE;
    float lastWordSpacing = LAST_WORD_SPACING_RESET_VALUE;
    float maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
    PositionWrapper lastPosition = null;
    PositionWrapper lastLineStartPosition = null;

    boolean startOfPage = true; // flag to indicate start of page
    boolean startOfArticle;
    if (charactersByArticle.size() > 0) {
        writePageStart();
    }

    for (List<TextPosition> textList : charactersByArticle) {
        if (getSortByPosition()) {
            TextPositionComparator comparator = new TextPositionComparator();

            // because the TextPositionComparator is not transitive, but
            // JDK7+ enforces transitivity on comparators, we need to use
            // a custom quicksort implementation (which is slower, unfortunately).
            if (useCustomQuickSort) {
                QuickSort.sort(textList, comparator);
            } else {
                Collections.sort(textList, comparator);
            }
        }

        Iterator<TextPosition> textIter = textList.iterator();

        startArticle();
        startOfArticle = true;

        // Now cycle through to print the text.
        // We queue up a line at a time before we print so that we can convert
        // the line from presentation form to logical form (if needed).
        List<LineItem> line = new ArrayList<LineItem>();

        textIter = textList.iterator(); // start from the beginning again
        // PDF files don't always store spaces. We will need to guess where we should add
        // spaces based on the distances between TextPositions. Historically, this was done
        // based on the size of the space character provided by the font. In general, this
        // worked but there were cases where it did not work. Calculating the average character
        // width and using that as a metric works better in some cases but fails in some cases
        // where the spacing worked. So we use both. NOTE: Adobe reader also fails on some of
        // these examples.

        // Keeps track of the previous average character width
        float previousAveCharWidth = -1;
        while (textIter.hasNext()) {
            TextPosition position = textIter.next();
            PositionWrapper current = new PositionWrapper(position);
            String characterValue = position.getUnicode();

            // Resets the average character width when we see a change in font
            // or a change in the font size
            if (lastPosition != null && (position.getFont() != lastPosition.getTextPosition().getFont()
                    || position.getFontSize() != lastPosition.getTextPosition().getFontSize())) {
                previousAveCharWidth = -1;
            }

            float positionX;
            float positionY;
            float positionWidth;
            float positionHeight;

            // If we are sorting, then we need to use the text direction
            // adjusted coordinates, because they were used in the sorting.
            if (getSortByPosition()) {
                positionX = position.getXDirAdj();
                positionY = position.getYDirAdj();
                positionWidth = position.getWidthDirAdj();
                positionHeight = position.getHeightDir();
            } else {
                positionX = position.getX();
                positionY = position.getY();
                positionWidth = position.getWidth();
                positionHeight = position.getHeight();
            }

            // The current amount of characters in a word
            int wordCharCount = position.getIndividualWidths().length;

            // Estimate the expected width of the space based on the
            // space character with some margin.
            float wordSpacing = position.getWidthOfSpace();
            float deltaSpace;
            if (wordSpacing == 0 || Float.isNaN(wordSpacing)) {
                deltaSpace = Float.MAX_VALUE;
            } else {
                if (lastWordSpacing < 0) {
                    deltaSpace = wordSpacing * getSpacingTolerance();
                } else {
                    deltaSpace = (wordSpacing + lastWordSpacing) / 2f * getSpacingTolerance();
                }
            }

            // Estimate the expected width of the space based on the average character width
            // with some margin. This calculation does not make a true average (average of
            // averages) but we found that it gave the best results after numerous experiments.
            // Based on experiments we also found that .3 worked well.
            float averageCharWidth;
            if (previousAveCharWidth < 0) {
                averageCharWidth = positionWidth / wordCharCount;
            } else {
                averageCharWidth = (previousAveCharWidth + positionWidth / wordCharCount) / 2f;
            }
            float deltaCharWidth = averageCharWidth * getAverageCharTolerance();

            // Compares the values obtained by the average method and the wordSpacing method
            // and picks the smaller number.
            float expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
            if (endOfLastTextX != END_OF_LAST_TEXT_X_RESET_VALUE) {
                if (deltaCharWidth > deltaSpace) {
                    expectedStartOfNextWordX = endOfLastTextX + deltaSpace;
                } else {
                    expectedStartOfNextWordX = endOfLastTextX + deltaCharWidth;
                }
            }

            if (lastPosition != null) {
                if (startOfArticle) {
                    lastPosition.setArticleStart();
                    startOfArticle = false;
                }
                // RDD - Here we determine whether this text object is on the current
                // line. We use the lastBaselineFontSize to handle the superscript
                // case, and the size of the current font to handle the subscript case.
                // Text must overlap with the last rendered baseline text by at least
                // a small amount in order to be considered as being on the same line.

                // XXX BC: In theory, this check should really check if the next char is in
                // full range seen in this line. This is what I tried to do with minYTopForLine,
                // but this caused a lot of regression test failures. So, I'm leaving it be for
                // now
                if (!overlap(positionY, positionHeight, maxYForLine, maxHeightForLine)) {
                    writeLine(normalize(line));
                    line.clear();
                    lastLineStartPosition = handleLineSeparation(current, lastPosition, lastLineStartPosition,
                            maxHeightForLine);
                    expectedStartOfNextWordX = EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE;
                    maxYForLine = MAX_Y_FOR_LINE_RESET_VALUE;
                    maxHeightForLine = MAX_HEIGHT_FOR_LINE_RESET_VALUE;
                    minYTopForLine = MIN_Y_TOP_FOR_LINE_RESET_VALUE;
                }
                // test if our TextPosition starts after a new word would be expected to start
                if (expectedStartOfNextWordX != EXPECTED_START_OF_NEXT_WORD_X_RESET_VALUE
                        && expectedStartOfNextWordX < positionX &&
                        // only bother adding a space if the last character was not a space
                        lastPosition.getTextPosition().getUnicode() != null
                        && !lastPosition.getTextPosition().getUnicode().endsWith(" ")) {
                    line.add(LineItem.getWordSeparator());
                }
            }
            if (positionY >= maxYForLine) {
                maxYForLine = positionY;
            }
            // RDD - endX is what PDF considers to be the x coordinate of the
            // end position of the text. We use it in computing our metrics below.
            endOfLastTextX = positionX + positionWidth;

            // add it to the list
            if (characterValue != null) {
                if (startOfPage && lastPosition == null) {
                    writeParagraphStart();// not sure this is correct for RTL?
                }
                line.add(new LineItem(position));
            }
            maxHeightForLine = Math.max(maxHeightForLine, positionHeight);
            minYTopForLine = Math.min(minYTopForLine, positionY - positionHeight);
            lastPosition = current;
            if (startOfPage) {
                lastPosition.setParagraphStart();
                lastPosition.setLineStart();
                lastLineStartPosition = lastPosition;
                startOfPage = false;
            }
            lastWordSpacing = wordSpacing;
            previousAveCharWidth = averageCharWidth;
        }
        // print the final line
        if (line.size() > 0) {
            writeLine(normalize(line));
            writeParagraphEnd();
        }
        endArticle();
    }
    writePageEnd();
}

From source file:mil.jpeojtrs.sca.util.tests.AnyUtilsTest.java

@Test
public void test_convertAnySequences() throws Exception {
    // Test Strings
    Object obj = null;/* www .  j a v a  2s  .co m*/
    Any theAny = JacorbUtil.init().create_any();

    final String[] stringInitialValue = new String[] { "a", "b", "c" };
    StringSeqHelper.insert(theAny, stringInitialValue);
    final String[] stringExtractedValue = StringSeqHelper.extract(theAny);
    // Sanity Check
    Assert.assertTrue(Arrays.equals(stringInitialValue, stringExtractedValue));

    // The real test
    obj = AnyUtils.convertAny(theAny);
    Assert.assertTrue(obj instanceof String[]);
    Assert.assertTrue(Arrays.equals(stringInitialValue, (String[]) obj));

    // Test Doubles
    obj = null;
    theAny = JacorbUtil.init().create_any();

    final double[] doubleInitialValue = new double[] { 0.1, 0.2, 0.3 };
    DoubleSeqHelper.insert(theAny, doubleInitialValue);
    final double[] doubleExtractedValue = DoubleSeqHelper.extract(theAny);
    // Sanity Check
    Assert.assertTrue(Arrays.equals(doubleInitialValue, doubleExtractedValue));

    // The real test
    obj = AnyUtils.convertAny(theAny);
    Assert.assertTrue(obj instanceof Double[]);
    Assert.assertTrue(Arrays.equals(ArrayUtils.toObject(doubleInitialValue), (Double[]) obj));

    // Test Integers
    obj = null;
    theAny = JacorbUtil.init().create_any();

    final int[] intInitialValue = new int[] { 1, 2, 3 };
    LongSeqHelper.insert(theAny, intInitialValue);
    final int[] intExtractedValue = LongSeqHelper.extract(theAny);
    // Sanity Check
    Assert.assertTrue(Arrays.equals(intInitialValue, intExtractedValue));

    // The real test
    obj = AnyUtils.convertAny(theAny);
    Assert.assertTrue(obj instanceof Integer[]);
    Assert.assertTrue(Arrays.equals(ArrayUtils.toObject(intInitialValue), (Integer[]) obj));

    // Test Recursive Sequence
    obj = null;
    final Any[] theAnys = new Any[2];
    theAnys[0] = JacorbUtil.init().create_any();
    theAnys[1] = JacorbUtil.init().create_any();

    LongSeqHelper.insert(theAnys[0], intInitialValue);
    LongSeqHelper.insert(theAnys[1], intInitialValue);
    AnySeqHelper.insert(theAny, theAnys);

    // The real test
    obj = AnyUtils.convertAny(theAny);
    Assert.assertTrue(obj instanceof Object[]);
    int[] extractedIntArray = ArrayUtils.toPrimitive((Integer[]) ((Object[]) obj)[0]);
    Assert.assertTrue(Arrays.equals(intInitialValue, extractedIntArray));
    extractedIntArray = ArrayUtils.toPrimitive((Integer[]) ((Object[]) obj)[1]);
    Assert.assertTrue(Arrays.equals(intInitialValue, extractedIntArray));

    String[] str = (String[]) AnyUtils
            .convertAny(AnyUtils.toAnySequence(new String[] { "2", "3" }, TCKind.tk_string));
    Assert.assertEquals("2", str[0]);
    str = (String[]) AnyUtils.convertAny(AnyUtils.toAnySequence(new String[] { "3", "4" }, TCKind.tk_wstring));
    Assert.assertEquals("3", str[0]);
    final Boolean[] bool = (Boolean[]) AnyUtils
            .convertAny(AnyUtils.toAnySequence(new boolean[] { false, true }, TCKind.tk_boolean));
    Assert.assertTrue(bool[1].booleanValue());
    final Short[] b = (Short[]) AnyUtils
            .convertAny(AnyUtils.toAnySequence(new byte[] { Byte.MIN_VALUE, Byte.MAX_VALUE }, TCKind.tk_octet));
    Assert.assertEquals(Byte.MAX_VALUE, b[1].byteValue());
    Character[] c = (Character[]) AnyUtils
            .convertAny(AnyUtils.toAnySequence(new char[] { 'r', 'h' }, TCKind.tk_char));
    Assert.assertEquals('h', c[1].charValue());
    c = (Character[]) AnyUtils
            .convertAny(AnyUtils.toAnySequence(new Character[] { '2', '3' }, TCKind.tk_wchar));
    Assert.assertEquals('2', c[0].charValue());
    final Short[] s = (Short[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }, TCKind.tk_short));
    Assert.assertEquals(Short.MAX_VALUE, s[1].shortValue());
    final Integer[] i = (Integer[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }, TCKind.tk_long));
    Assert.assertEquals(Integer.MAX_VALUE, i[1].intValue());
    final Long[] l = (Long[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new long[] { Long.MIN_VALUE, Long.MAX_VALUE }, TCKind.tk_longlong));
    Assert.assertEquals(Long.MAX_VALUE, l[1].longValue());
    final Float[] f = (Float[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new float[] { Float.MIN_VALUE, Float.MAX_VALUE }, TCKind.tk_float));
    Assert.assertEquals(Float.MAX_VALUE, f[1].floatValue(), 0.00001);
    final Double[] d = (Double[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new double[] { Double.MIN_VALUE, Double.MAX_VALUE }, TCKind.tk_double));
    Assert.assertEquals(Double.MAX_VALUE, d[1].doubleValue(), 0.00001);
    final Integer[] us = (Integer[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new short[] { Short.MIN_VALUE, Short.MAX_VALUE }, TCKind.tk_ushort));
    Assert.assertEquals(Short.MAX_VALUE, us[1].intValue());
    final Long[] ui = (Long[]) AnyUtils.convertAny(
            AnyUtils.toAnySequence(new int[] { Integer.MIN_VALUE, Integer.MAX_VALUE }, TCKind.tk_ulong));
    Assert.assertEquals(Integer.MAX_VALUE, ui[1].longValue());
    final BigInteger[] ul = (BigInteger[]) AnyUtils.convertAny(AnyUtils
            .toAnySequence(new BigInteger[] { new BigInteger("2"), new BigInteger("3") }, TCKind.tk_ulonglong));
    Assert.assertEquals(3L, ul[1].longValue());

}

From source file:org.noise_planet.noisecapture.CalibrationLinearityActivity.java

private void updateLineChart() {
    LineChart lineChart = getLineChart();
    if (lineChart == null) {
        return;/* w ww.  j  a  v  a  2  s  . co m*/
    }
    if (freqLeqStats.isEmpty()) {
        return;
    }
    float YMin = Float.MAX_VALUE;
    float YMax = Float.MIN_VALUE;

    ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();

    // Read all white noise values for indexing before usage
    int idStep = 0;
    double referenceLevel = freqLeqStats.get(0).whiteNoiseLevel.getGlobaldBaValue();
    for (LinearCalibrationResult result : freqLeqStats) {
        ArrayList<Entry> yMeasure = new ArrayList<Entry>();
        int idfreq = 0;
        for (LeqStats leqStat : result.measure) {
            float dbLevel = (float) leqStat.getLeqMean();
            YMax = Math.max(YMax, dbLevel);
            YMin = Math.min(YMin, dbLevel);
            yMeasure.add(new Entry(dbLevel, idfreq++));
        }
        LineDataSet freqSet = new LineDataSet(yMeasure, String.format(Locale.getDefault(), "%d dB",
                (int) (result.whiteNoiseLevel.getGlobaldBaValue() - referenceLevel)));
        freqSet.setColor(ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setFillColor(ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setValueTextColor(Color.WHITE);
        freqSet.setCircleColorHole(
                ColorTemplate.COLORFUL_COLORS[idStep % ColorTemplate.COLORFUL_COLORS.length]);
        freqSet.setDrawValues(false);
        freqSet.setDrawFilled(true);
        freqSet.setFillAlpha(255);
        freqSet.setDrawCircles(true);
        freqSet.setMode(LineDataSet.Mode.LINEAR);
        dataSets.add(freqSet);
        idStep++;
    }

    ArrayList<String> xVals = new ArrayList<String>();
    double[] freqs = FFTSignalProcessing
            .computeFFTCenterFrequency(AudioProcess.REALTIME_SAMPLE_RATE_LIMITATION);
    for (double freqValue : freqs) {
        xVals.add(Spectrogram.formatFrequency((int) freqValue));
    }

    // create a data object with the datasets
    LineData data = new LineData(xVals, dataSets);
    lineChart.setData(data);
    YAxis yl = lineChart.getAxisLeft();
    yl.setAxisMinValue(YMin - 3);
    yl.setAxisMaxValue(YMax + 3);
    lineChart.invalidate();
}

From source file:gr.iti.mklab.reveal.forensics.util.Util.java

public static float minDouble3DArray(float[][][] arrayIn) {
    // Calculate the minimum value of a 3D float array
    float min = Float.MAX_VALUE;
    float colMin;
    for (float[][] twoDInRow : arrayIn) {
        for (float[] arrayInRow : twoDInRow) {
            List b = Arrays.asList(ArrayUtils.toObject(arrayInRow));
            colMin = (float) Collections.min(b);
            if (colMin < min) {
                min = colMin;/*from  www.ja v  a  2  s.c o m*/
            }
        }
    }
    return min;
}

From source file:ArrayUtils.java

public static int minIndex(final float[] scores) {
    int index = -1;
    float min = Float.MAX_VALUE;
    for (int i = 0; i < scores.length; i++) {
        final float f = scores[i];
        if (f < min) {
            min = f;//w  w  w  .ja v a  2s . c om
            index = i;
        }
    }
    return index;
}

From source file:com.dngames.mobilewebcam.PhotoSettings.java

@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
    if (key == "cam_refresh") {
        int new_refresh = getEditInt(mContext, prefs, "cam_refresh", 60);
        String msg = "Camera refresh set to " + new_refresh + " seconds!";
        if (MobileWebCam.gIsRunning) {
            if (!mNoToasts && new_refresh != mRefreshDuration) {
                try {
                    Toast.makeText(mContext.getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                } catch (RuntimeException e) {
                    e.printStackTrace();
                }//  w  w w .  j  a  v a 2 s . c  om
            }
        } else if (new_refresh != mRefreshDuration) {
            MobileWebCam.LogI(msg);
        }
    }

    // get all preferences
    for (Field f : getClass().getFields()) {
        {
            BooleanPref bp = f.getAnnotation(BooleanPref.class);
            if (bp != null) {
                try {
                    f.setBoolean(this, prefs.getBoolean(bp.key(), bp.val()));
                } catch (Exception e) {
                    Log.e("MobileWebCam", "Exception: " + bp.key() + " <- " + bp.val());
                    e.printStackTrace();
                }
            }
        }
        {
            EditIntPref ip = f.getAnnotation(EditIntPref.class);
            if (ip != null) {
                try {
                    int eval = getEditInt(mContext, prefs, ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            IntPref ip = f.getAnnotation(IntPref.class);
            if (ip != null) {
                try {
                    int eval = prefs.getInt(ip.key(), ip.val()) * ip.factor();
                    if (ip.max() != Integer.MAX_VALUE)
                        eval = Math.min(eval, ip.max());
                    if (ip.min() != Integer.MIN_VALUE)
                        eval = Math.max(eval, ip.min());
                    f.setInt(this, eval);
                } catch (Exception e) {
                    // handle wrong set class
                    e.printStackTrace();
                    Editor edit = prefs.edit();
                    edit.remove(ip.key());
                    edit.putInt(ip.key(), ip.val());
                    edit.commit();
                    try {
                        f.setInt(this, ip.val());
                    } catch (IllegalArgumentException e1) {
                        e1.printStackTrace();
                    } catch (IllegalAccessException e1) {
                        e1.printStackTrace();
                    }
                }
            }
        }
        {
            EditFloatPref fp = f.getAnnotation(EditFloatPref.class);
            if (fp != null) {
                try {
                    float eval = getEditFloat(mContext, prefs, fp.key(), fp.val());
                    if (fp.max() != Float.MAX_VALUE)
                        eval = Math.min(eval, fp.max());
                    if (fp.min() != Float.MIN_VALUE)
                        eval = Math.max(eval, fp.min());
                    f.setFloat(this, eval);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        {
            StringPref sp = f.getAnnotation(StringPref.class);
            if (sp != null) {
                try {
                    f.set(this, prefs.getString(sp.key(), getDefaultString(mContext, sp)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    mCustomImageScale = Enum.valueOf(ImageScaleMode.class, prefs.getString("custompicscale", "CROP"));

    mAutoStart = prefs.getBoolean("autostart", false);
    mCameraStartupEnabled = prefs.getBoolean("cam_autostart", true);
    mShutterSound = prefs.getBoolean("shutter", true);
    mDateTimeColor = GetPrefColor(prefs, "datetime_color", "#FFFFFFFF", Color.WHITE);
    mDateTimeShadowColor = GetPrefColor(prefs, "datetime_shadowcolor", "#FF000000", Color.BLACK);
    mDateTimeBackgroundColor = GetPrefColor(prefs, "datetime_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mDateTimeBackgroundLine = prefs.getBoolean("datetime_fillline", true);
    mDateTimeX = prefs.getInt("datetime_x", 98);
    mDateTimeY = prefs.getInt("datetime_y", 98);
    mDateTimeAlign = Paint.Align.valueOf(prefs.getString("datetime_imprintalign", "RIGHT"));

    mDateTimeFontScale = (float) prefs.getInt("datetime_fontsize", 6);

    mTextColor = GetPrefColor(prefs, "text_color", "#FFFFFFFF", Color.WHITE);
    mTextShadowColor = GetPrefColor(prefs, "text_shadowcolor", "#FF000000", Color.BLACK);
    mTextBackgroundColor = GetPrefColor(prefs, "text_backcolor", "#80FF0000",
            Color.argb(0x80, 0xFF, 0x00, 0x00));
    mTextBackgroundLine = prefs.getBoolean("text_fillline", true);
    mTextX = prefs.getInt("text_x", 2);
    mTextY = prefs.getInt("text_y", 2);
    mTextAlign = Paint.Align.valueOf(prefs.getString("text_imprintalign", "LEFT"));
    mTextFontScale = (float) prefs.getInt("infotext_fontsize", 6);
    mTextFontname = prefs.getString("infotext_fonttypeface", "");

    mStatusInfoColor = GetPrefColor(prefs, "statusinfo_color", "#FFFFFFFF", Color.WHITE);
    mStatusInfoShadowColor = GetPrefColor(prefs, "statusinfo_shadowcolor", "#FF000000", Color.BLACK);
    mStatusInfoX = prefs.getInt("statusinfo_x", 2);
    mStatusInfoY = prefs.getInt("statusinfo_y", 98);
    mStatusInfoAlign = Paint.Align.valueOf(prefs.getString("statusinfo_imprintalign", "LEFT"));
    mStatusInfoBackgroundColor = GetPrefColor(prefs, "statusinfo_backcolor", "#00000000", Color.TRANSPARENT);
    mStatusInfoFontScale = (float) prefs.getInt("statusinfo_fontsize", 6);
    mStatusInfoBackgroundLine = prefs.getBoolean("statusinfo_fillline", false);

    mGPSColor = GetPrefColor(prefs, "gps_color", "#FFFFFFFF", Color.WHITE);
    mGPSShadowColor = GetPrefColor(prefs, "gps_shadowcolor", "#FF000000", Color.BLACK);
    mGPSX = prefs.getInt("gps_x", 98);
    mGPSY = prefs.getInt("gps_y", 2);
    mGPSAlign = Paint.Align.valueOf(prefs.getString("gps_imprintalign", "RIGHT"));
    mGPSBackgroundColor = GetPrefColor(prefs, "gps_backcolor", "#00000000", Color.TRANSPARENT);
    mGPSFontScale = (float) prefs.getInt("gps_fontsize", 6);
    mGPSBackgroundLine = prefs.getBoolean("gps_fillline", false);

    mImprintPictureX = prefs.getInt("imprint_picture_x", 0);
    mImprintPictureY = prefs.getInt("imprint_picture_y", 0);

    mNightAutoConfigEnabled = prefs.getBoolean("night_auto_enabled", false);

    mSetNightConfiguration = prefs.getBoolean("cam_nightconfiguration", false);
    // override night camera parameters (read again with postfix)
    getCurrentNightSettings();

    mFilterPicture = false; //***prefs.getBoolean("filter_picture", false);
    mFilterType = getEditInt(mContext, prefs, "filter_sel", 0);

    if (mImprintPicture) {
        if (mImprintPictureURL.length() == 0) {
            // sdcard image
            File path = new File(Environment.getExternalStorageDirectory() + "/MobileWebCam/");
            if (path.exists()) {
                synchronized (gImprintBitmapLock) {
                    if (gImprintBitmap != null)
                        gImprintBitmap.recycle();
                    gImprintBitmap = null;

                    File file = new File(path, "imprint.png");
                    try {
                        FileInputStream in = new FileInputStream(file);
                        gImprintBitmap = BitmapFactory.decodeStream(in);
                        in.close();
                    } catch (IOException e) {
                        Toast.makeText(mContext, "Error: unable to read imprint bitmap " + file.getName() + "!",
                                Toast.LENGTH_SHORT).show();
                        gImprintBitmap = null;
                    } catch (OutOfMemoryError e) {
                        Toast.makeText(mContext, "Error: imprint bitmap " + file.getName() + " too large!",
                                Toast.LENGTH_LONG).show();
                        gImprintBitmap = null;
                    }
                }
            }
        } else {
            DownloadImprintBitmap();
        }

        synchronized (gImprintBitmapLock) {
            if (gImprintBitmap == null) {
                // last resort: resource default
                try {
                    gImprintBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.imprint);
                } catch (OutOfMemoryError e) {
                    Toast.makeText(mContext, "Error: default imprint bitmap too large!", Toast.LENGTH_LONG)
                            .show();
                    gImprintBitmap = null;
                }
            }
        }
    }

    mNoToasts = prefs.getBoolean("no_messages", false);
    mFullWakeLock = prefs.getBoolean("full_wakelock", true);

    switch (getEditInt(mContext, prefs, "camera_mode", 1)) {
    case 0:
        mMode = Mode.MANUAL;
        break;
    case 2:
        mMode = Mode.HIDDEN;
        break;
    case 3:
        mMode = Mode.BACKGROUND;
        break;
    case 1:
    default:
        mMode = Mode.NORMAL;
        break;
    }
}

From source file:org.loklak.objects.MessageEntry.java

public JSONObject toJSON(final UserEntry user, final boolean calculatedData, final int iflinkexceedslength,
        final String urlstub) {
    JSONObject m = new JSONObject(true);

    // tweet data
    m.put(AbstractObjectEntry.TIMESTAMP_FIELDNAME, utcFormatter.print(getTimestamp().getTime()));
    m.put("created_at", utcFormatter.print(getCreatedAt().getTime()));
    if (this.on != null)
        m.put("on", utcFormatter.print(this.on.getTime()));
    if (this.to != null)
        m.put("to", utcFormatter.print(this.to.getTime()));
    m.put("screen_name", this.screen_name);
    if (this.retweet_from != null && this.retweet_from.length() > 0)
        m.put("retweet_from", this.retweet_from);
    m.put("text", this.getText(iflinkexceedslength, urlstub)); // the tweet; the cleanup is a helper function which cleans mistakes from the past in scraping
    if (this.status_id_url != null)
        m.put("link", this.status_id_url.toExternalForm());
    m.put("id_str", this.id_str);
    if (this.canonical_id != null)
        m.put("canonical_id", this.canonical_id);
    if (this.parent != null)
        m.put("parent", this.parent);
    m.put("source_type", this.source_type.toString());
    m.put("provider_type", this.provider_type.name());
    if (this.provider_hash != null && this.provider_hash.length() > 0)
        m.put("provider_hash", this.provider_hash);
    m.put("retweet_count", this.retweet_count);
    m.put("favourites_count", this.favourites_count); // there is a slight inconsistency here in the plural naming but thats how it is noted in the twitter api
    m.put("place_name", this.place_name);
    m.put("place_id", this.place_id);

    // add statistic/calculated data
    if (calculatedData) {

        // location data
        if (this.place_context != null)
            m.put("place_context", this.place_context.name());
        if (this.place_country != null && this.place_country.length() == 2) {
            m.put("place_country", DAO.geoNames.getCountryName(this.place_country));
            m.put("place_country_code", this.place_country);
            m.put("place_country_center", DAO.geoNames.getCountryCenter(this.place_country));
        }//ww  w. j a v  a2 s . c  o m

        // add optional location data. This is written even if calculatedData == false if the source is from REPORT to prevent that it is lost
        if (this.location_point != null && this.location_point.length == 2 && this.location_mark != null
                && this.location_mark.length == 2) {
            // reference for this format: https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-geo-point-type.html#_lat_lon_as_array_5
            m.put("location_point", this.location_point); // [longitude, latitude]
            m.put("location_radius", this.location_radius);
            m.put("location_mark", this.location_mark);
            m.put("location_source", this.location_source.name());
        }

        // redundant data for enhanced navigation with aggregations
        m.put("hosts", this.hosts);
        m.put("hosts_count", this.hosts.length);
        m.put("links", this.links);
        m.put("links_count", this.links.length);
        m.put("images", this.images);
        m.put("images_count", this.images.size());
        m.put("audio", this.audio);
        m.put("audio_count", this.audio.size());
        m.put("videos", this.videos);
        m.put("videos_count", this.videos.size());
        m.put("mentions", this.mentions);
        m.put("mentions_count", this.mentions.length);
        m.put("hashtags", this.hashtags);
        m.put("hashtags_count", this.hashtags.length);

        // text classifier
        if (this.classifier != null) {
            for (Map.Entry<Context, Classification<String, Category>> c : this.classifier.entrySet()) {
                assert c.getValue() != null;
                if (c.getValue().getCategory() == Classifier.Category.NONE)
                    continue; // we don't store non-existing classifications
                m.put("classifier_" + c.getKey().name(), c.getValue().getCategory());
                m.put("classifier_" + c.getKey().name() + "_probability",
                        c.getValue().getProbability() == Float.POSITIVE_INFINITY ? Float.MAX_VALUE
                                : c.getValue().getProbability());
            }
        }

        // experimental, for ranking
        m.put("without_l_len", this.without_l_len);
        m.put("without_lu_len", this.without_lu_len);
        m.put("without_luh_len", this.without_luh_len);
    }

    // add user
    if (user != null)
        m.put("user", user.toJSON());
    return m;
}

From source file:org.alfresco.serializers.PropertiesTypeConverter.java

@SuppressWarnings("rawtypes")
private PropertiesTypeConverter() {
    ///*from   w  w  w  .j a va 2 s.c om*/
    // From string
    //
    addConverter(String.class, Class.class, new TypeConverter.Converter<String, Class>() {
        public Class convert(String source) {
            try {
                return Class.forName(source);
            } catch (ClassNotFoundException e) {
                throw new TypeConversionException("Failed to convert string to class: " + source, e);
            }
        }
    });
    addConverter(String.class, Boolean.class, new TypeConverter.Converter<String, Boolean>() {
        public Boolean convert(String source) {
            return Boolean.valueOf(source);
        }
    });
    addConverter(String.class, Character.class, new TypeConverter.Converter<String, Character>() {
        public Character convert(String source) {
            if ((source == null) || (source.length() == 0)) {
                return null;
            }
            return Character.valueOf(source.charAt(0));
        }
    });
    addConverter(String.class, Number.class, new TypeConverter.Converter<String, Number>() {
        public Number convert(String source) {
            try {
                return DecimalFormat.getNumberInstance().parse(source);
            } catch (ParseException e) {
                throw new TypeConversionException("Failed to parse number " + source, e);
            }
        }
    });
    addConverter(String.class, Byte.class, new TypeConverter.Converter<String, Byte>() {
        public Byte convert(String source) {
            return Byte.valueOf(source);
        }
    });
    addConverter(String.class, Short.class, new TypeConverter.Converter<String, Short>() {
        public Short convert(String source) {
            return Short.valueOf(source);
        }
    });
    addConverter(String.class, Integer.class, new TypeConverter.Converter<String, Integer>() {
        public Integer convert(String source) {
            return Integer.valueOf(source);
        }
    });
    addConverter(String.class, Long.class, new TypeConverter.Converter<String, Long>() {
        public Long convert(String source) {
            return Long.valueOf(source);
        }
    });
    addConverter(String.class, Float.class, new TypeConverter.Converter<String, Float>() {
        public Float convert(String source) {
            return Float.valueOf(source);
        }
    });
    addConverter(String.class, Double.class, new TypeConverter.Converter<String, Double>() {
        public Double convert(String source) {
            return Double.valueOf(source);
        }
    });
    addConverter(String.class, BigInteger.class, new TypeConverter.Converter<String, BigInteger>() {
        public BigInteger convert(String source) {
            return new BigInteger(source);
        }
    });
    addConverter(String.class, BigDecimal.class, new TypeConverter.Converter<String, BigDecimal>() {
        public BigDecimal convert(String source) {
            return new BigDecimal(source);
        }
    });
    addConverter(JSON.class, BigDecimal.class, new TypeConverter.Converter<JSON, BigDecimal>() {
        public BigDecimal convert(JSON source) {
            String type = (String) source.get("t");
            if (type.equals("FIXED_POINT")) {
                String number = (String) source.get("n");
                Integer precision = (Integer) source.get("p");
                MathContext ctx = new MathContext(precision);
                return new BigDecimal(number, ctx);
            } else {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a Fixed Decimal object");
            }
        }
    });
    addConverter(String.class, Date.class, new TypeConverter.Converter<String, Date>() {
        public Date convert(String source) {
            try {
                Date date = ISO8601DateFormat.parse(source);
                return date;
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            } catch (AlfrescoRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(String.class, Duration.class, new TypeConverter.Converter<String, Duration>() {
        public Duration convert(String source) {
            return new Duration(source);
        }
    });
    addConverter(String.class, QName.class, new TypeConverter.Converter<String, QName>() {
        public QName convert(String source) {
            return QName.createQName(source);
        }
    });
    addConverter(JSON.class, QName.class, new TypeConverter.Converter<JSON, QName>() {
        public QName convert(JSON source) {
            String type = (String) source.get("t");
            if (type.equals("QNAME")) {
                String qname = (String) source.get("v");
                return QName.createQName(qname);
            } else {
                throw new IllegalArgumentException();
            }
        }
    });
    addConverter(String.class, ContentData.class, new TypeConverter.Converter<String, ContentData>() {
        public ContentData convert(String source) {
            return ContentData.createContentProperty(source);
        }
    });
    addConverter(String.class, NodeRef.class, new TypeConverter.Converter<String, NodeRef>() {
        public NodeRef convert(String source) {
            return new NodeRef(source);
        }
    });
    addConverter(JSON.class, NodeRef.class, new TypeConverter.Converter<JSON, NodeRef>() {
        public NodeRef convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("NODEREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            String id = (String) source.get("id");
            NodeRef nodeRef = new NodeRef(new StoreRef(protocol, storeId), id);
            return nodeRef;
        }
    });
    addConverter(String.class, StoreRef.class, new TypeConverter.Converter<String, StoreRef>() {
        public StoreRef convert(String source) {
            return new StoreRef(source);
        }
    });
    addConverter(JSON.class, StoreRef.class, new TypeConverter.Converter<JSON, StoreRef>() {
        public StoreRef convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("STOREREF")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a StoreRef object");
            }
            String protocol = (String) source.get("p");
            String storeId = (String) source.get("s");
            return new StoreRef(protocol, storeId);
        }
    });
    addConverter(String.class, ChildAssociationRef.class,
            new TypeConverter.Converter<String, ChildAssociationRef>() {
                public ChildAssociationRef convert(String source) {
                    return new ChildAssociationRef(source);
                }
            });
    addConverter(String.class, AssociationRef.class, new TypeConverter.Converter<String, AssociationRef>() {
        public AssociationRef convert(String source) {
            return new AssociationRef(source);
        }
    });
    addConverter(String.class, InputStream.class, new TypeConverter.Converter<String, InputStream>() {
        public InputStream convert(String source) {
            try {
                return new ByteArrayInputStream(source.getBytes("UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Encoding not supported", e);
            }
        }
    });
    addConverter(String.class, MLText.class, new TypeConverter.Converter<String, MLText>() {
        public MLText convert(String source) {
            return new MLText(source);
        }
    });
    addConverter(JSON.class, MLText.class, new TypeConverter.Converter<JSON, MLText>() {
        public MLText convert(JSON source) {
            String type = (String) source.get("t");
            if (!type.equals("MLTEXT")) {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a NodeRef object");
            }

            MLText mlText = new MLText();
            for (String languageTag : source.keySet()) {
                String text = (String) source.get(languageTag);
                Locale locale = Locale.forLanguageTag(languageTag);
                mlText.put(locale, text);
            }

            return mlText;
        }
    });
    //        addConverter(JSON.class, ContentDataWithId.class, new TypeConverter.Converter<JSON, ContentDataWithId>()
    //        {
    //            public ContentDataWithId convert(JSON source)
    //            {
    //                String type = (String)source.get("t");
    //                if(!type.equals("CONTENT_DATA_ID"))
    //                {
    //                    throw new IllegalArgumentException("Invalid source object for conversion "
    //                            + source 
    //                            + ", expected a ContentDataWithId object");
    //                }
    //                String contentUrl = (String)source.get("u");
    //                String mimeType = (String)source.get("m");
    //                Long size = (Long)source.get("s");
    //                String encoding = (String)source.get("e");
    //                String languageTag = (String)source.get("l");
    //                Long id = (Long)source.get("id");
    //                Locale locale = Locale.forLanguageTag(languageTag);
    //
    //                ContentData contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
    //                ContentDataWithId contentDataWithId = new ContentDataWithId(contentData, id);
    //                return contentDataWithId;
    //            }
    //        });
    addConverter(JSON.class, ContentData.class, new TypeConverter.Converter<JSON, ContentData>() {
        public ContentData convert(JSON source) {
            ContentData contentData = null;

            String type = (String) source.get("t");
            if (type.equals("CONTENT")) {
                String contentUrl = (String) source.get("u");
                String mimeType = (String) source.get("m");
                Long size = (Long) source.get("s");
                String encoding = (String) source.get("e");
                String languageTag = (String) source.get("l");
                Locale locale = Locale.forLanguageTag(languageTag);
                contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
            } else if (type.equals("CONTENT_DATA_ID")) {
                String contentUrl = (String) source.get("u");
                String mimeType = (String) source.get("m");
                Long size = (Long) source.get("s");
                String encoding = (String) source.get("e");
                String languageTag = (String) source.get("l");
                Locale locale = Locale.forLanguageTag(languageTag);
                contentData = new ContentData(contentUrl, mimeType, size, encoding, locale);
            } else {
                throw new IllegalArgumentException(
                        "Invalid source object for conversion " + source + ", expected a ContentData object");
            }

            return contentData;
        }
    });
    addConverter(JSON.class, String.class, new TypeConverter.Converter<JSON, String>() {
        public String convert(JSON source) {
            // TODO distinguish between different BasicDBObject representations e.g. for MLText, ...

            Set<String> languageTags = source.keySet();
            if (languageTags.size() == 0) {
                throw new IllegalArgumentException("Persisted MLText is invalid " + source);
            } else if (languageTags.size() > 1) {
                // TODO
                logger.warn("Persisted MLText has more than 1 locale " + source);
            }

            String languageTag = languageTags.iterator().next();
            String text = (String) source.get(languageTag);
            return text;
        }
    });
    addConverter(String.class, Locale.class, new TypeConverter.Converter<String, Locale>() {
        public Locale convert(String source) {
            return I18NUtil.parseLocale(source);
        }
    });
    addConverter(String.class, Period.class, new TypeConverter.Converter<String, Period>() {
        public Period convert(String source) {
            return new Period(source);
        }
    });
    addConverter(String.class, VersionNumber.class, new TypeConverter.Converter<String, VersionNumber>() {
        public VersionNumber convert(String source) {
            return new VersionNumber(source);
        }
    });

    //
    // From Locale
    //
    addConverter(Locale.class, String.class, new TypeConverter.Converter<Locale, String>() {
        public String convert(Locale source) {
            String localeStr = source.toString();
            if (localeStr.length() < 6) {
                localeStr += "_";
            }
            return localeStr;
        }
    });

    //
    // From VersionNumber
    //
    addConverter(VersionNumber.class, String.class, new TypeConverter.Converter<VersionNumber, String>() {
        public String convert(VersionNumber source) {
            return source.toString();
        }
    });

    //
    // From MLText
    //
    addConverter(MLText.class, String.class, new TypeConverter.Converter<MLText, String>() {
        public String convert(MLText source) {
            return source.getDefaultValue();
        }
    });

    addConverter(MLText.class, JSON.class, new TypeConverter.Converter<MLText, JSON>() {
        public JSON convert(MLText source) {
            JSON map = new JSON();
            map.put("t", "MLTEXT");
            for (Map.Entry<Locale, String> entry : source.entrySet()) {
                map.put(entry.getKey().toLanguageTag(), entry.getValue());
            }
            return map;
        }
    });

    //        addConverter(ContentDataWithId.class, JSON.class, new TypeConverter.Converter<ContentDataWithId, JSON>()
    //        {
    //            public JSON convert(ContentDataWithId source)
    //            {
    //                JSON map = new JSON();
    //
    //                String contentUrl = source.getContentUrl();
    //                Long id = source.getId();
    //                String languageTag = source.getLocale().toLanguageTag();
    //                String encoding = source.getEncoding();
    //                long size = source.getSize();
    //                String mimeType = source.getMimetype();
    //
    //                map.put("t", "CONTENT_DATA_ID");
    //                map.put("u", contentUrl);
    //                map.put("m", mimeType);
    //                map.put("s", size);
    //                map.put("e", encoding);
    //                map.put("l", languageTag);
    //                map.put("id", id);
    //                return map;
    //            }
    //        });

    addConverter(ContentData.class, JSON.class, new TypeConverter.Converter<ContentData, JSON>() {
        public JSON convert(ContentData source) {
            JSON map = new JSON();

            String contentUrl = source.getContentUrl();
            String languageTag = source.getLocale().toLanguageTag();
            String encoding = source.getEncoding();
            long size = source.getSize();
            String mimeType = source.getMimetype();

            map.put("t", "CONTENT_DATA");
            map.put("u", contentUrl);
            map.put("m", mimeType);
            map.put("s", size);
            map.put("e", encoding);
            map.put("l", languageTag);
            return map;
        }
    });

    //
    // From enum
    //
    addConverter(Enum.class, String.class, new TypeConverter.Converter<Enum, String>() {
        public String convert(Enum source) {
            return source.toString();
        }
    });

    // From Period
    addConverter(Period.class, String.class, new TypeConverter.Converter<Period, String>() {
        public String convert(Period source) {
            return source.toString();
        }
    });

    // From Class
    addConverter(Class.class, String.class, new TypeConverter.Converter<Class, String>() {
        public String convert(Class source) {
            return source.getName();
        }
    });

    //
    // Number to Subtypes and Date
    //
    addConverter(Number.class, Boolean.class, new TypeConverter.Converter<Number, Boolean>() {
        public Boolean convert(Number source) {
            return new Boolean(source.longValue() > 0);
        }
    });
    addConverter(Number.class, Byte.class, new TypeConverter.Converter<Number, Byte>() {
        public Byte convert(Number source) {
            return Byte.valueOf(source.byteValue());
        }
    });
    addConverter(Number.class, Short.class, new TypeConverter.Converter<Number, Short>() {
        public Short convert(Number source) {
            return Short.valueOf(source.shortValue());
        }
    });
    addConverter(Number.class, Integer.class, new TypeConverter.Converter<Number, Integer>() {
        public Integer convert(Number source) {
            return Integer.valueOf(source.intValue());
        }
    });
    addConverter(Number.class, Long.class, new TypeConverter.Converter<Number, Long>() {
        public Long convert(Number source) {
            return Long.valueOf(source.longValue());
        }
    });
    addConverter(Number.class, Float.class, new TypeConverter.Converter<Number, Float>() {
        public Float convert(Number source) {
            return Float.valueOf(source.floatValue());
        }
    });
    addConverter(Number.class, Double.class, new TypeConverter.Converter<Number, Double>() {
        public Double convert(Number source) {
            return Double.valueOf(source.doubleValue());
        }
    });
    addConverter(Number.class, Date.class, new TypeConverter.Converter<Number, Date>() {
        public Date convert(Number source) {
            return new Date(source.longValue());
        }
    });
    addConverter(Number.class, String.class, new TypeConverter.Converter<Number, String>() {
        public String convert(Number source) {
            return source.toString();
        }
    });
    addConverter(Number.class, BigInteger.class, new TypeConverter.Converter<Number, BigInteger>() {
        public BigInteger convert(Number source) {
            if (source instanceof BigDecimal) {
                return ((BigDecimal) source).toBigInteger();
            } else {
                return BigInteger.valueOf(source.longValue());
            }
        }
    });
    addConverter(Number.class, BigDecimal.class, new TypeConverter.Converter<Number, BigDecimal>() {
        public BigDecimal convert(Number source) {
            if (source instanceof BigInteger) {
                return new BigDecimal((BigInteger) source);
            } else if (source instanceof Double) {
                return BigDecimal.valueOf((Double) source);
            } else if (source instanceof Float) {
                Float val = (Float) source;
                if (val.isInfinite()) {
                    // What else can we do here?  this is 3.4 E 38 so is fairly big
                    return new BigDecimal(Float.MAX_VALUE);
                }
                return BigDecimal.valueOf((Float) source);
            } else {
                return BigDecimal.valueOf(source.longValue());
            }
        }
    });
    addDynamicTwoStageConverter(Number.class, String.class, InputStream.class);

    //
    // Date, Timestamp ->
    //
    addConverter(Timestamp.class, Date.class, new TypeConverter.Converter<Timestamp, Date>() {
        public Date convert(Timestamp source) {
            return new Date(source.getTime());
        }
    });
    addConverter(Date.class, Number.class, new TypeConverter.Converter<Date, Number>() {
        public Number convert(Date source) {
            return Long.valueOf(source.getTime());
        }
    });
    addConverter(Date.class, String.class, new TypeConverter.Converter<Date, String>() {
        public String convert(Date source) {
            try {
                return ISO8601DateFormat.format(source);
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });
    addConverter(Date.class, Calendar.class, new TypeConverter.Converter<Date, Calendar>() {
        public Calendar convert(Date source) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(source);
            return calendar;
        }
    });

    addConverter(Date.class, GregorianCalendar.class, new TypeConverter.Converter<Date, GregorianCalendar>() {
        public GregorianCalendar convert(Date source) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(source);
            return calendar;
        }
    });
    addDynamicTwoStageConverter(Date.class, String.class, InputStream.class);

    //
    // Boolean ->
    //
    final Long LONG_FALSE = new Long(0L);
    final Long LONG_TRUE = new Long(1L);
    addConverter(Boolean.class, Long.class, new TypeConverter.Converter<Boolean, Long>() {
        public Long convert(Boolean source) {
            return source.booleanValue() ? LONG_TRUE : LONG_FALSE;
        }
    });
    addConverter(Boolean.class, String.class, new TypeConverter.Converter<Boolean, String>() {
        public String convert(Boolean source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Boolean.class, String.class, InputStream.class);

    //
    // Character ->
    //
    addConverter(Character.class, String.class, new TypeConverter.Converter<Character, String>() {
        public String convert(Character source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Character.class, String.class, InputStream.class);

    //
    // Duration ->
    //
    addConverter(Duration.class, String.class, new TypeConverter.Converter<Duration, String>() {
        public String convert(Duration source) {
            return source.toString();
        }

    });
    addDynamicTwoStageConverter(Duration.class, String.class, InputStream.class);

    //
    // Byte
    //
    addConverter(Byte.class, String.class, new TypeConverter.Converter<Byte, String>() {
        public String convert(Byte source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Byte.class, String.class, InputStream.class);

    //
    // Short
    //
    addConverter(Short.class, String.class, new TypeConverter.Converter<Short, String>() {
        public String convert(Short source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Short.class, String.class, InputStream.class);

    //
    // Integer
    //
    addConverter(Integer.class, String.class, new TypeConverter.Converter<Integer, String>() {
        public String convert(Integer source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Integer.class, String.class, InputStream.class);

    //
    // Long
    //
    addConverter(Long.class, String.class, new TypeConverter.Converter<Long, String>() {
        public String convert(Long source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Long.class, String.class, InputStream.class);

    //
    // Float
    //
    addConverter(Float.class, String.class, new TypeConverter.Converter<Float, String>() {
        public String convert(Float source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Float.class, String.class, InputStream.class);

    //
    // Double
    //
    addConverter(Double.class, String.class, new TypeConverter.Converter<Double, String>() {
        public String convert(Double source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Double.class, String.class, InputStream.class);

    //
    // BigInteger
    //
    addConverter(BigInteger.class, String.class, new TypeConverter.Converter<BigInteger, String>() {
        public String convert(BigInteger source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigInteger.class, String.class, InputStream.class);

    //
    // Calendar
    //
    addConverter(Calendar.class, Date.class, new TypeConverter.Converter<Calendar, Date>() {
        public Date convert(Calendar source) {
            return source.getTime();
        }
    });
    addConverter(Calendar.class, String.class, new TypeConverter.Converter<Calendar, String>() {
        public String convert(Calendar source) {
            try {
                return ISO8601DateFormat.format(source.getTime());
            } catch (PlatformRuntimeException e) {
                throw new TypeConversionException("Failed to convert date " + source + " to string", e);
            }
        }
    });

    //
    // BigDecimal
    //
    addConverter(BigDecimal.class, JSON.class, new TypeConverter.Converter<BigDecimal, JSON>() {
        public JSON convert(BigDecimal source) {
            String number = source.toPlainString();
            int precision = source.precision();
            JSON map = new JSON();
            map.put("t", "FIXED_POINT");
            map.put("n", number);
            map.put("p", precision);
            return map;
        }
    });
    addConverter(BigDecimal.class, String.class, new TypeConverter.Converter<BigDecimal, String>() {
        public String convert(BigDecimal source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(BigDecimal.class, String.class, InputStream.class);

    //
    // QName
    //
    addConverter(QName.class, String.class, new TypeConverter.Converter<QName, String>() {
        public String convert(QName source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(QName.class, String.class, InputStream.class);

    //
    // EntityRef (NodeRef, ChildAssociationRef, NodeAssociationRef)
    //
    addConverter(EntityRef.class, String.class, new TypeConverter.Converter<EntityRef, String>() {
        public String convert(EntityRef source) {
            return source.toString();
        }
    });
    addConverter(EntityRef.class, JSON.class, new TypeConverter.Converter<EntityRef, JSON>() {
        public JSON convert(EntityRef source) {
            JSON ret = null;

            if (source instanceof NodeRef) {
                NodeRef nodeRef = (NodeRef) source;

                JSON map = new JSON();
                map.put("t", "NODEREF");
                map.put("p", nodeRef.getStoreRef().getProtocol());
                map.put("s", nodeRef.getStoreRef().getIdentifier());
                map.put("id", nodeRef.getId());
                ret = map;
            } else if (source instanceof StoreRef) {
                StoreRef storeRef = (StoreRef) source;

                JSON map = new JSON();
                map.put("t", "STOREREF");
                map.put("p", storeRef.getProtocol());
                map.put("s", storeRef.getIdentifier());
                ret = map;
            } else {
                throw new IllegalArgumentException();
            }

            return ret;
        }
    });
    addDynamicTwoStageConverter(EntityRef.class, String.class, InputStream.class);

    //
    // ContentData
    //
    addConverter(ContentData.class, String.class, new TypeConverter.Converter<ContentData, String>() {
        public String convert(ContentData source) {
            return source.getInfoUrl();
        }
    });
    addDynamicTwoStageConverter(ContentData.class, String.class, InputStream.class);

    //
    // Path
    //
    addConverter(Path.class, String.class, new TypeConverter.Converter<Path, String>() {
        public String convert(Path source) {
            return source.toString();
        }
    });
    addDynamicTwoStageConverter(Path.class, String.class, InputStream.class);

    //
    // Content Reader
    //
    addConverter(ContentReader.class, InputStream.class,
            new TypeConverter.Converter<ContentReader, InputStream>() {
                public InputStream convert(ContentReader source) {
                    return source.getContentInputStream();
                }
            });
    addConverter(ContentReader.class, String.class, new TypeConverter.Converter<ContentReader, String>() {
        public String convert(ContentReader source) {
            // Getting the string from the ContentReader binary is meaningless
            return source.toString();
        }
    });

    //
    // Content Writer
    //
    addConverter(ContentWriter.class, String.class, new TypeConverter.Converter<ContentWriter, String>() {
        public String convert(ContentWriter source) {
            return source.toString();
        }
    });

    //        addConverter(Collection.class, BasicDBList.class, new TypeConverter.Converter<Collection, BasicDBList>()
    //        {
    //            public BasicDBList convert(Collection source)
    //            {
    //                BasicDBList ret = new BasicDBList();
    //                for(Object o : source)
    //                {
    //                    ret.add(o);
    //                }
    //                return ret;
    //            }
    //        });

    //        addConverter(BasicDBList.class, Collection.class, new TypeConverter.Converter<BasicDBList, Collection>()
    //        {
    //            @SuppressWarnings("unchecked")
    //            public Collection convert(BasicDBList source)
    //            {
    //                Collection ret = new LinkedList();
    //                for(Object o : source)
    //                {
    //                    ret.add(o);
    //                }
    //                return ret;
    //            }
    //        });

    //
    // Input Stream
    //
    addConverter(InputStream.class, String.class, new TypeConverter.Converter<InputStream, String>() {
        public String convert(InputStream source) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[8192];
                int read;
                while ((read = source.read(buffer)) > 0) {
                    out.write(buffer, 0, read);
                }
                byte[] data = out.toByteArray();
                return new String(data, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new TypeConversionException("Cannot convert input stream to String.", e);
            } catch (IOException e) {
                throw new TypeConversionException("Conversion from stream to string failed", e);
            } finally {
                if (source != null) {
                    try {
                        source.close();
                    } catch (IOException e) {
                        //NOOP
                    }
                }
            }
        }
    });
    addDynamicTwoStageConverter(InputStream.class, String.class, Date.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Double.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Long.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Boolean.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, QName.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, Path.class);

    addDynamicTwoStageConverter(InputStream.class, String.class, NodeRef.class);

}

From source file:org.mapfish.print.config.layout.LegendsBlock.java

/**
 * maximum width a legend icon/image can have
 * currently SVG icons are scaled to fit this
 * @param iconMaxWidth//from  w w w . j a v a 2s. co m
 */
public void setIconMaxWidth(double maxIconWidth) {
    this.iconMaxWidth = (float) maxIconWidth;
    if (maxIconWidth < 0.0) {
        throw new InvalidValueException("maxIconWidth", maxIconWidth);
    }
    if (maxIconWidth == 0f) {
        this.iconMaxWidth = Float.MAX_VALUE;
    }
}

From source file:gov.nist.itl.versus.similarity.transforms.ColorModels.java

public ImageObject convertRGBToEuclidDistImage(ImageObject image) {
    if (image == null || image.getNumCols() <= 0 || image.getNumRows() <= 0) {
        logger.debug("ERROR: no image \n");
        System.out.println("Error");

        return null;
    }//from  w w  w  .j  a  v a2s .  c o m

    int numrows, numcols;
    numrows = image.getNumRows();
    numcols = image.getNumCols();

    ImageObject imageGray = null;
    try {
        imageGray = ImageObject.createImage(image.getNumRows(), image.getNumCols(), 1, ImageObject.TYPE_FLOAT);

        long size = image.getSize() / image.getNumBands();
        double sum;
        _MaxVal = 0.0F; //norm = 4072.0234; // this is sqrt(255^3)
        _MinVal = Float.MAX_VALUE; //5000
        int index, indexColor;
        boolean signal = true;
        int num_bands = image.getNumBands();
        for (index = 0, indexColor = 0; index < size; index++, indexColor += num_bands) {

            sum = image.getFloat(indexColor) * image.getFloat(indexColor);
            sum += image.getFloat(indexColor + 1) * image.getFloat(indexColor + 1);
            sum += image.getFloat(indexColor + 2) * image.getFloat(indexColor + 2);
            sum = Math.sqrt(sum);

            imageGray.setFloat(index, (float) sum);

            if (sum > _MaxVal)
                _MaxVal = (float) sum;

            if (sum < _MinVal)
                _MinVal = (float) sum;
        }

        signal = false;

        logger.debug("Max dist in 3D = " + _MaxVal);
        logger.debug("Min dist in 3D = " + _MinVal);

        if (signal)
            return null;
    } catch (Exception e) {
        logger.error("Error in ConvertRGBToEuclidDistImage()", e);
        System.out.println("Error");
    }

    return (imageGray);
}