alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (Basic-X.java.template)

This example Java source code file (Basic-X.java.template) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

bigdecimal, biginteger, birthday, calendar, duke, duke\'s, formatter, gregoriancalendar, hello, infinity, math, may, nan, object, regex, string, text, util

The Basic-X.java.template Java example source code

/*
 * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/* Type-specific source code for unit test
 *
 * Regenerate the BasicX classes via genBasic.sh whenever this file changes.
 * We check in the generated source files so that the test tree can be used
 * independently of the rest of the source tree.
 */

#warn This file is preprocessed before being compiled

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormatSymbols;
import java.util.*;
#if[double]
import sun.misc.DoubleConsts;
#end[double]

import static java.util.Calendar.*;
#if[datetime]
import static java.util.SimpleTimeZone.*;
import java.util.regex.Pattern;
#end[datetime]

public class Basic$Type$ extends Basic {

    private static void test(String fs, String exp, Object ... args) {
        Formatter f = new Formatter(new StringBuilder(), Locale.US);
        f.format(fs, args);
        ck(fs, exp, f.toString());
    }

    private static void test(Locale l, String fs, String exp, Object ... args)
    {
        Formatter f = new Formatter(new StringBuilder(), l);
        f.format(fs, args);
        ck(fs, exp, f.toString());
    }

    private static void test(String fs, Object ... args) {
        Formatter f = new Formatter(new StringBuilder(), Locale.US);
        f.format(fs, args);
        ck(fs, "fail", f.toString());
    }

    private static void test(String fs) {
        Formatter f = new Formatter(new StringBuilder(), Locale.US);
        f.format(fs, "fail");
        ck(fs, "fail", f.toString());
    }

    private static void testSysOut(String fs, String exp, Object ... args) {
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            PrintStream saveOut = System.out;
            fos = new FileOutputStream("testSysOut");
            System.setOut(new PrintStream(fos));
            System.out.format(Locale.US, fs, args);
            fos.close();

            fis = new FileInputStream("testSysOut");
            byte [] ba = new byte[exp.length()];
            int len = fis.read(ba);
            String got = new String(ba);
            if (len != ba.length)
                fail(fs, exp, got);
            ck(fs, exp, got);

            System.setOut(saveOut);
        } catch (FileNotFoundException ex) {
            fail(fs, ex.getClass());
        } catch (IOException ex) {
            fail(fs, ex.getClass());
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                fail(fs, ex.getClass());
            }
        }
    }

    private static void tryCatch(String fs, Class<?> ex) {
        boolean caught = false;
        try {
            test(fs);
        } catch (Throwable x) {
            if (ex.isAssignableFrom(x.getClass()))
                caught = true;
        }
        if (!caught)
            fail(fs, ex);
        else
            pass();
    }

    private static void tryCatch(String fs, Class<?> ex, Object ... args) {
        boolean caught = false;
        try {
            test(fs, args);
        } catch (Throwable x) {
            if (ex.isAssignableFrom(x.getClass()))
                caught = true;
        }
        if (!caught)
            fail(fs, ex);
        else
            pass();
    }

#if[datetime]
    private static void testDateTime(String fs, String exp, Calendar c) {
        testDateTime(fs, exp, c, true);
    }

    private static void testDateTime(String fs, String exp, Calendar c, boolean upper) {
        //---------------------------------------------------------------------
        // Date/Time conversions applicable to Calendar, Date, and long.
        //---------------------------------------------------------------------

        // Calendar
        test(fs, exp, c);
        test((Locale)null, fs, exp, c);
        test(Locale.US, fs, exp, c);

        // Date/long do not have timezone information so they will always use
        // the default timezone.
        String nexp = (fs.equals("%tZ") || fs.equals("%TZ")
                       || fs.equals("%tc") || fs.equals("%Tc")
                       ? exp.replace("PST", "GMT-08:00")
                       : exp);

        // Date (implemented via conversion to Calendar)
        Date d = c.getTime();
        test(fs, nexp, d);
        test((Locale)null, fs, nexp, d);
        test(Locale.US, fs, nexp, d);

        // long (implemented via conversion to Calendar)
        long l = c.getTimeInMillis();
        test(fs, nexp, l);
        test((Locale)null, fs, nexp, l);
        test(Locale.US, fs, nexp, l);

        if (upper)
            // repeat all tests for upper case variant (%T)
            testDateTime(Pattern.compile("t").matcher(fs).replaceFirst("T"),
                         exp.toUpperCase(), c, false);
    }

    private static void testHours() {
        for (int i = 0; i < 24; i++) {
            // GregorianCalendar(int year, int month, int dayOfMonth,
            //    int hourOfDay, int minute, int second);
            Calendar c = new GregorianCalendar(1995, MAY, 23, i, 48, 34);

            //-----------------------------------------------------------------
            // DateTime.HOUR_OF_DAY - 'k' (0 - 23) -- like H
            //-----------------------------------------------------------------
            String exp = Integer.toString(i);
            testDateTime("%tk", exp, c);

            //-----------------------------------------------------------------
            // DateTime.HOUR - 'l' (1 - 12) -- like I
            //-----------------------------------------------------------------
            int v = i % 12;
            v = (v == 0 ? 12 : v);
            String exp2 = Integer.toString(v);
            testDateTime("%tl", exp2, c);

            //-----------------------------------------------------------------
            // DateTime.HOUR_OF_DAY_0 - 'H' (00 - 23) [zero padded]
            //-----------------------------------------------------------------
            if (exp.length() < 2) exp = "0" + exp;
            testDateTime("%tH", exp, c);

            //-----------------------------------------------------------------
            // DateTime.HOUR_0 - 'I' (01 - 12)
            //-----------------------------------------------------------------
            if (exp2.length() < 2) exp2 = "0" + exp2;
            testDateTime("%tI", exp2, c);

            //-----------------------------------------------------------------
            // DateTime.AM_PM - (am or pm)
            //-----------------------------------------------------------------
            testDateTime("%tp", (i <12 ? "am" : "pm"), c);
        }
    }
#end[datetime]

#if[dec]
#if[prim]
    private static $type$ negate($type$ v) {
        return ($type$) -v;
    }
#end[prim]
#end[dec]
#if[Byte]
    private static $type$ negate($type$ v) {
        return new $type$((byte) -v.byteValue());
    }
#end[Byte]
#if[Short]
    private static $type$ negate($type$ v) {
        return new $type$((short) -v.shortValue());
    }
#end[Short]
#if[Integer]
    private static $type$ negate($type$ v) {
        return new $type$(-v.intValue());
    }
#end[Integer]
#if[Long]
    private static $type$ negate($type$ v) {
        return new $type$(-v.longValue());
    }
#end[Long]

#if[BigDecimal]
    private static $type$ create(double v) {
        return new $type$(v);
    }

    private static $type$ negate($type$ v) {
        return v.negate();
    }

    private static $type$ mult($type$ v, double mul) {
        return v.multiply(new $type$(mul));
    }

    private static $type$ recip($type$ v) {
        return BigDecimal.ONE.divide(v);
    }
#end[BigDecimal]
#if[float]
    private static $type$ create(double v) {
        return ($type$) v;
    }

    private static $type$ negate(double v) {
        return ($type$) -v;
    }

    private static $type$ mult($type$ v, double mul) {
        return v * ($type$) mul;
    }

    private static $type$ recip($type$ v) {
        return 1.0f / v;
    }
#end[float]
#if[Float]
    private static $type$ create(double v) {
        return new $type$(v);
    }

    private static $type$ negate($type$ v) {
        return new $type$(-v.floatValue());
    }

    private static $type$ mult($type$ v, double mul) {
        return new $type$(v.floatValue() * (float) mul);
    }

    private static $type$ recip($type$ v) {
        return new $type$(1.0f / v.floatValue());
    }
#end[Float]
#if[double]
    private static $type$ create(double v) {
        return ($type$) v;
    }


    private static $type$ negate(double v) {
        return -v;
    }

    private static $type$ mult($type$ v, double mul) {
        return v * mul;
    }

    private static $type$ recip($type$ v) {
        return 1.0 / v;
    }
#end[double]
#if[Double]
    private static $type$ create(double v) {
        return new $type$(v);
    }

    private static $type$ negate($type$ v) {
        return new $type$(-v.doubleValue());
    }

    private static $type$ mult($type$ v, double mul) {
        return new $type$(v.doubleValue() * mul);
    }

    private static $type$ recip($type$ v) {
        return new $type$(1.0 / v.doubleValue());
    }
#end[Double]

    public static void test() {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT-0800"));

        // Any characters not explicitly defined as conversions, date/time
        // conversion suffixes, or flags are illegal and are reserved for
        // future extensions.  Use of such a character in a format string will
        // cause an UnknownFormatConversionException or
        // UnknownFormatFlagsException to be thrown.
        tryCatch("%q", UnknownFormatConversionException.class);
        tryCatch("%t&", UnknownFormatConversionException.class);
        tryCatch("%&d", UnknownFormatConversionException.class);
        tryCatch("%^b", UnknownFormatConversionException.class);

        //---------------------------------------------------------------------
        // Formatter.java class javadoc examples
        //---------------------------------------------------------------------
        test(Locale.FRANCE, "e = %+10.4f", "e =    +2,7183", Math.E);
        test("%4$2s %3$2s %2$2s %1$2s", " d  c  b  a", "a", "b", "c", "d");
        test("Amount gained or lost since last statement: $ %,(.2f",
             "Amount gained or lost since last statement: $ (6,217.58)",
             (new BigDecimal("-6217.58")));
        Calendar c = new GregorianCalendar(1969, JULY, 20, 16, 17, 0);
        testSysOut("Local time: %tT", "Local time: 16:17:00", c);

        test("Unable to open file '%1$s': %2$s",
             "Unable to open file 'food': No such file or directory",
             "food", "No such file or directory");
        Calendar duke = new GregorianCalendar(1995, MAY, 23, 19, 48, 34);
        duke.set(Calendar.MILLISECOND, 584);
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke);
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke.getTime());
        test("Duke's Birthday: %1$tB %1$te, %1$tY",
             "Duke's Birthday: May 23, 1995",
             duke.getTimeInMillis());

        test("%4$s %3$s %2$s %1$s %4$s %3$s %2$s %1$s",
             "d c b a d c b a", "a", "b", "c", "d");
        test("%s %s %<s %

Other Java examples (source code examples)

Here is a short list of links related to this Java Basic-X.java.template source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.