Example usage for java.lang Character valueOf

List of usage examples for java.lang Character valueOf

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public static Character valueOf(char c) 

Source Link

Document

Returns a Character instance representing the specified char value.

Usage

From source file:immf.EmojiUtil.java

private static void add(int unicode, String label, String googleImage) {
    char c = (char) unicode;
    map.put(Character.valueOf(c), new Emoji(c, label, googleImage));
}

From source file:com.workday.autoparse.xml.demo.XmlParserTest.java

@Test
public void testMissingAttributesAreNotSet()
        throws ParseException, UnexpectedChildException, UnknownElementException {
    XmlStreamParser parser = XmlStreamParserFactory.newXmlStreamParser();
    InputStream in = getInputStreamOf("missing-attributes.xml");

    DemoModel model = (DemoModel) parser.parseStream(in);

    assertTrue(model.myBoxedBoolean);/* w  ww . jav  a  2 s.co m*/
    assertTrue(model.myPrimitiveBoolean);
    assertEquals(BigDecimal.ONE, model.myBigDecimal);
    assertEquals(BigInteger.TEN, model.myBigInteger);
    assertEquals(-1, model.myPrimitiveByte);
    assertEquals(Byte.valueOf((byte) -1), model.myBoxedByte);
    assertEquals('a', model.myPrimitiveChar);
    assertEquals(Character.valueOf('a'), model.myBoxedChar);
    assertEquals(-1.0, model.myPrimitiveDouble, DOUBLE_E);
    assertEquals(Double.valueOf(-1.0), model.myBoxedDouble);
    assertEquals(-1f, model.myPrimitiveFloat, FLOAT_E);
    assertEquals(Float.valueOf(-1f), model.myBoxedFloat);
    assertEquals(-1, model.myPrimitiveInt);
    assertEquals(Integer.valueOf(-1), model.myBoxedInt);
    assertEquals(-1, model.myPrimitiveLong);
    assertEquals(Long.valueOf(-1), model.myBoxedLong);
    assertEquals(-1, model.myPrimitiveShort);
    assertEquals(Short.valueOf((short) -1), model.myBoxedShort);
    assertEquals("default", model.myString);
    assertEquals("default", model.myTextContent);
}

From source file:org.cloudata.core.common.io.CObjectWritable.java

/** Read a {@link CWritable}, {@link String}, primitive type, or an array of
 * the preceding. *///www . jav  a 2 s.  c o m
@SuppressWarnings("unchecked")
public static Object readObject(DataInput in, CObjectWritable objectWritable, CloudataConf conf,
        boolean arrayComponent, Class componentClass) throws IOException {
    String className;
    if (arrayComponent) {
        className = componentClass.getName();
    } else {
        className = CUTF8.readString(in);
        //SANGCHUL
        //   System.out.println("SANGCHUL] className:" + className);
    }

    Class<?> declaredClass = PRIMITIVE_NAMES.get(className);
    if (declaredClass == null) {
        try {
            declaredClass = conf.getClassByName(className);
        } catch (ClassNotFoundException e) {
            //SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class[className=" + className + "]", e);
        }
    }

    Object instance;

    if (declaredClass.isPrimitive()) { // primitive types

        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }

    } else if (declaredClass.isArray()) { // array
        //System.out.println("SANGCHUL] is array");
        int length = in.readInt();
        //System.out.println("SANGCHUL] array length : " + length);
        //System.out.println("Read:in.readInt():" + length);
        if (declaredClass.getComponentType() == Byte.TYPE) {
            byte[] bytes = new byte[length];
            in.readFully(bytes);
            instance = bytes;
        } else if (declaredClass.getComponentType() == ColumnValue.class) {
            instance = readColumnValue(in, conf, declaredClass, length);
        } else {
            Class componentType = declaredClass.getComponentType();

            // SANGCHUL
            //System.out.println("SANGCHUL] componentType : " + componentType.getName());

            instance = Array.newInstance(componentType, length);
            for (int i = 0; i < length; i++) {
                Object arrayComponentInstance = readObject(in, null, conf, !componentType.isArray(),
                        componentType);
                Array.set(instance, i, arrayComponentInstance);
                //Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass == String.class) { // String
        instance = CUTF8.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, CUTF8.readString(in));
    } else if (declaredClass == ColumnValue.class) {
        //ColumnValue?  ?? ?? ?  ? ?.
        //? ?   ? ? ? ? . 
        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            if (typeDiff == TYPE_DIFF) {
                instanceClass = conf.getClassByName(CUTF8.readString(in));
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("readObject can't find class", e);
        }
        ColumnValue columnValue = new ColumnValue();
        columnValue.readFields(in);
        instance = columnValue;
    } else { // Writable

        Class instanceClass = null;
        try {
            short typeDiff = in.readShort();
            // SANGCHUL
            //System.out.println("SANGCHUL] typeDiff : " + typeDiff);
            //System.out.println("Read:in.readShort():" + typeDiff);
            if (typeDiff == TYPE_DIFF) {
                // SANGCHUL
                String classNameTemp = CUTF8.readString(in);
                //System.out.println("SANGCHUL] typeDiff : " + classNameTemp);
                instanceClass = conf.getClassByName(classNameTemp);
                //System.out.println("Read:UTF8.readString(in):" + instanceClass.getClass());
            } else {
                instanceClass = declaredClass;
            }
        } catch (ClassNotFoundException e) {

            // SANGCHUL
            e.printStackTrace();
            throw new RuntimeException("readObject can't find class", e);
        }

        CWritable writable = CWritableFactories.newInstance(instanceClass, conf);
        writable.readFields(in);
        //System.out.println("Read:writable.readFields(in)");
        instance = writable;

        if (instanceClass == NullInstance.class) { // null
            declaredClass = ((NullInstance) instance).declaredClass;
            instance = null;
        }
    }

    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }

    return instance;
}

From source file:org.fourthline.cling.osgi.test.data.OSGiUPnPStringConverter.java

private static Character toCharacter(String string, Character value) {
    return string != null ? Character.valueOf(string.charAt(0)) : value != null ? value : new Character('A');
}

From source file:com.edgenius.wiki.render.filter.ListFilter.java

/**
 * Adds a list to a buffer/*w w  w  . j  a  v a2s .c  o  m*/
 */
private void addList(StringBuffer buffer, BufferedReader reader) throws IOException {
    char[] lastBullet = new char[0];
    String line = null;
    String trimLine = null;
    boolean requireLiEnd = false;
    while ((line = reader.readLine()) != null) {
        if (StringUtils.trim(line).length() == 0) {
            //new empty line - end of list
            break;
        }
        //only trim leading spaces, keep tailed spaces
        trimLine = StringUtil.trimStartSpace(line);

        int bulletEnd = StringUtils.indexOfAny(trimLine, new String[] { " ", "\t" });
        if (bulletEnd < 1) {
            //if this line is not valid bullet line, then means this li has multiple lines...
            //please note, here append original line rather than trimmed and with newline - that eat by read.readLine()
            buffer.append("\n").append(line);
            continue;
        }

        String bStr = trimLine.substring(0, bulletEnd).trim();
        if (!bulletPattern.matcher(bStr).matches()) {
            //if this line is not valid bullet line, then means this li has multiple lines...
            //please note, here append original line rather than trimmed and with newline - that eat by read.readLine()
            buffer.append("\n").append(line);
            continue;
        }

        //remove the possible dot, for example, #i. 
        if (bStr.charAt(bStr.length() - 1) == '.') {
            bStr = bStr.substring(0, bStr.length() - 1);
        }

        char[] bullet = bStr.toCharArray();
        if (requireLiEnd) {
            buffer.append("</li>");
            requireLiEnd = false;
        }

        // check whether we find a new sub list, for example 
        //* list
        //** sublist
        int sharedPrefixEnd;
        for (sharedPrefixEnd = 0;; sharedPrefixEnd++) {
            if (bullet.length <= sharedPrefixEnd || lastBullet.length <= sharedPrefixEnd
                    || bullet[sharedPrefixEnd] != lastBullet[sharedPrefixEnd]) {
                break;
            }
        }

        for (int i = sharedPrefixEnd; i < lastBullet.length; i++) {
            // Logger.log("closing " + lastBullet[i]);
            buffer.append(closeList.get(Character.valueOf(lastBullet[i])));
        }

        for (int i = sharedPrefixEnd; i < bullet.length; i++) {
            // Logger.log("opening " + bullet[i]);
            buffer.append(openList.get(Character.valueOf(bullet[i])));
        }
        buffer.append("<li>");
        buffer.append(trimLine.substring(StringUtils.indexOfAny(trimLine, new String[] { " ", "\t" }) + 1));
        requireLiEnd = true;
        lastBullet = bullet;
    }

    if (requireLiEnd) {
        buffer.append("</li>");
    }
    for (int i = lastBullet.length - 1; i >= 0; i--) {
        buffer.append(closeList.get(Character.valueOf(lastBullet[i])));
    }

}

From source file:com.github.gerbsen.math.Frequency.java

/**
 * Returns the cumulative frequency of values less than or equal to v.
 * <p>/*from   ww  w .j ava 2  s .  com*/
 * Returns 0 if v is not comparable to the values set.</p>
 *
 * @param v the value to lookup
 * @return the proportion of values equal to v
 */
public long getCumFreq(char v) {
    return getCumFreq(Character.valueOf(v));
}

From source file:com.wavemaker.commons.util.TypeConversionUtils.java

public static Object fromString(Class<?> type, String s, boolean isList) {

    if (isList || !isPrimitiveOrWrapper(type)) {
        if (s == null) {
            return null;
        }//from  ww w  .j  a v  a  2 s. com
        ObjectLiteralParser p = new ObjectLiteralParser(s, type);
        Object o = p.parse();
        return o;
    }

    if (s == null) {
        return null;
    } else if (type == AtomicInteger.class) {
        return null;
    } else if (type == AtomicLong.class) {
        return null;
    } else if (type == BigDecimal.class) {
        return new BigDecimal(s);
    } else if (type == BigInteger.class) {
        return new BigDecimal(s);
    } else if (type == Boolean.class || type == boolean.class) {
        return Boolean.valueOf(s);
    } else if (type == Byte.class || type == byte.class) {
        return Byte.valueOf(s);
    } else if (type == Date.class) {
        if (StringUtils.isNumber(s)) {
            return new Date(Long.parseLong(s));
        } else {
            throw new IllegalArgumentException("Unable to convert " + s + " to " + Date.class.getName());
        }
    } else if (type == java.sql.Date.class) {
        return WMDateDeSerializer.getDate(s);
    } else if (type == Time.class) {
        return WMDateDeSerializer.getDate(s);
    } else if (type == Timestamp.class) {
        if (StringUtils.isNumber(s)) {
            return new Timestamp(Long.valueOf(s));
        } else {
            throw new IllegalArgumentException("Unable to convert " + s + " to " + Timestamp.class.getName());
        }
    } else if (type == LocalDateTime.class) {
        return WMLocalDateTimeDeSerializer.getLocalDateTime(s);
    } else if (type == Double.class || type == double.class) {
        return Double.valueOf(s);
    } else if (type == Float.class || type == float.class) {
        return Float.valueOf(s);
    } else if (type == Integer.class || type == int.class) {
        return Integer.valueOf(s);
    } else if (type == Long.class || type == long.class) {
        return Long.valueOf(s);
    } else if (type == Short.class || type == short.class) {
        return Short.valueOf(s);
    } else if (type == String.class || type == StringBuffer.class) {
        return s;
    } else if (type == Character.class || type == char.class) {
        return Character.valueOf(s.charAt(0));
    } else {
        throw new AssertionError("Unable to convert \"" + s + "\" to " + type + " - unknown type: " + type);
    }
}

From source file:org.plasma.text.lang3gl.java.DefaultFactory.java

protected String toConstantName(String name) {
    name = name.trim();//from w  w w. j  a v a  2s  .c om
    StringBuilder buf = new StringBuilder();
    char[] array = name.toCharArray();
    for (int i = 0; i < array.length; i++) {
        String lit = reservedJavaCharToLiteralMap.get(Character.valueOf(array[i]));
        if (lit != null) {
            buf.append(lit.toUpperCase());
            continue;
        }
        if (i > 0) {
            if (Character.isLetter(array[i]) && Character.isUpperCase(array[i])) {
                if (!Character.isUpperCase(array[i - 1]))
                    buf.append("_");
            }
        }
        if (Character.isLetterOrDigit(array[i])) {
            buf.append(Character.toUpperCase(array[i]));
        } else
            buf.append("_");
    }
    return buf.toString();
}

From source file:com.netflix.lipstick.Main.java

static int run(String args[], PigProgressNotificationListener listener) {
    int rc = 1;/*from  w w w. j av a  2s .  c  o  m*/
    boolean verbose = false;
    boolean gruntCalled = false;
    String logFileName = null;

    try {
        Configuration conf = new Configuration(false);
        GenericOptionsParser parser = new GenericOptionsParser(conf, args);
        conf = parser.getConfiguration();

        Properties properties = new Properties();
        PropertiesUtil.loadDefaultProperties(properties);
        properties.putAll(ConfigurationUtil.toProperties(conf));

        String[] pigArgs = parser.getRemainingArgs();

        boolean userSpecifiedLog = false;
        boolean checkScriptOnly = false;

        BufferedReader pin = null;
        boolean debug = false;
        boolean dryrun = false;
        boolean embedded = false;
        List<String> params = new ArrayList<String>();
        List<String> paramFiles = new ArrayList<String>();
        HashSet<String> optimizerRules = new HashSet<String>();

        CmdLineParser opts = new CmdLineParser(pigArgs);
        opts.registerOpt('4', "log4jconf", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('b', "brief", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('c', "check", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('d', "debug", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('e', "execute", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('f', "file", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('g', "embedded", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('h', "help", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('i', "version", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('l', "logfile", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('m', "param_file", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('p', "param", CmdLineParser.ValueExpected.OPTIONAL);
        opts.registerOpt('r', "dryrun", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('t', "optimizer_off", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('v', "verbose", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('w', "warning", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('x', "exectype", CmdLineParser.ValueExpected.REQUIRED);
        opts.registerOpt('F', "stop_on_failure", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('M', "no_multiquery", CmdLineParser.ValueExpected.NOT_ACCEPTED);
        opts.registerOpt('P', "propertyFile", CmdLineParser.ValueExpected.REQUIRED);

        ExecMode mode = ExecMode.UNKNOWN;
        String file = null;
        String engine = null;
        ExecType execType = ExecType.MAPREDUCE;
        String execTypeString = properties.getProperty("exectype");
        if (execTypeString != null && execTypeString.length() > 0) {
            execType = ExecType.fromString(execTypeString);
        }

        // set up client side system properties in UDF context
        UDFContext.getUDFContext().setClientSystemProps(properties);

        char opt;
        while ((opt = opts.getNextOpt()) != CmdLineParser.EndOfOpts) {
            switch (opt) {
            case '4':
                String log4jconf = opts.getValStr();
                if (log4jconf != null) {
                    properties.setProperty(LOG4J_CONF, log4jconf);
                }
                break;

            case 'b':
                properties.setProperty(BRIEF, "true");
                break;

            case 'c':
                checkScriptOnly = true;
                break;

            case 'd':
                String logLevel = opts.getValStr();
                if (logLevel != null) {
                    properties.setProperty(DEBUG, logLevel);
                }
                debug = true;
                break;

            case 'e':
                mode = ExecMode.STRING;
                break;

            case 'f':
                mode = ExecMode.FILE;
                file = opts.getValStr();
                break;

            case 'g':
                embedded = true;
                engine = opts.getValStr();
                break;

            case 'F':
                properties.setProperty("stop.on.failure", "" + true);
                break;

            case 'h':
                String topic = opts.getValStr();
                if (topic != null)
                    if (topic.equalsIgnoreCase("properties"))
                        printProperties();
                    else {
                        System.out.println("Invalide help topic - " + topic);
                        usage();
                    }
                else
                    usage();
                return ReturnCode.SUCCESS;

            case 'i':
                System.out.println(getVersionString());
                return ReturnCode.SUCCESS;

            case 'l':
                // call to method that validates the path to the log file
                // and sets up the file to store the client side log file
                String logFileParameter = opts.getValStr();
                if (logFileParameter != null && logFileParameter.length() > 0) {
                    logFileName = validateLogFile(logFileParameter, null);
                } else {
                    logFileName = validateLogFile(logFileName, null);
                }
                userSpecifiedLog = true;
                properties.setProperty("pig.logfile", (logFileName == null ? "" : logFileName));
                break;

            case 'm':
                paramFiles.add(opts.getValStr());
                break;

            case 'M':
                // turns off multiquery optimization
                properties.setProperty("opt.multiquery", "" + false);
                break;

            case 'p':
                params.add(opts.getValStr());
                break;

            case 'r':
                // currently only used for parameter substitution
                // will be extended in the future
                dryrun = true;
                break;

            case 't':
                optimizerRules.add(opts.getValStr());
                break;

            case 'v':
                properties.setProperty(VERBOSE, "" + true);
                verbose = true;
                break;

            case 'w':
                properties.setProperty("aggregate.warning", "" + false);
                break;

            case 'x':
                try {
                    execType = ExecType.fromString(opts.getValStr());
                } catch (IOException e) {
                    throw new RuntimeException("ERROR: Unrecognized exectype.", e);
                }
                break;

            case 'P': {
                InputStream inputStream = null;
                try {
                    FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties,
                            opts.getValStr());
                    inputStream = new BufferedInputStream(new FileInputStream(localFileRet.file));
                    properties.load(inputStream);
                } catch (IOException e) {
                    throw new RuntimeException("Unable to parse properties file '" + opts.getValStr() + "'");
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
                break;

            default: {
                Character cc = Character.valueOf(opt);
                throw new AssertionError("Unhandled option " + cc.toString());
            }
            }
        }
        // create the context with the parameter
        PigContext pigContext = new PigContext(execType, properties);

        // create the static script state object
        String commandLine = LoadFunc.join((AbstractList<String>) Arrays.asList(args), " ");
        ScriptState scriptState = ScriptState.start(commandLine, pigContext);

        pigContext.getProperties().setProperty("pig.cmd.args", commandLine);

        if (logFileName == null && !userSpecifiedLog) {
            logFileName = validateLogFile(properties.getProperty("pig.logfile"), null);
        }

        pigContext.getProperties().setProperty("pig.logfile", (logFileName == null ? "" : logFileName));

        // configure logging
        configureLog4J(properties, pigContext);
        log.info(getVersionString().replace("\n", ""));

        if (logFileName != null) {
            log.info("Logging error messages to: " + logFileName);
        }

        if (!Boolean.valueOf(properties.getProperty(PROP_FILT_SIMPL_OPT, "false"))) {
            // turn off if the user has not explicitly turned on this
            // optimization
            optimizerRules.add("FilterLogicExpressionSimplifier");
        }

        if (optimizerRules.size() > 0) {
            pigContext.getProperties().setProperty("pig.optimizer.rules",
                    ObjectSerializer.serialize(optimizerRules));
        }

        if (properties.get("udf.import.list") != null)
            PigContext.initializeImportList((String) properties.get("udf.import.list"));

        PigContext.setClassLoader(pigContext.createCl(null));
        if (listener != null) {
            scriptState.registerListener(listener);
        }
        if (properties.getProperty("pig.listeners") != null) {
            for (String clsName : properties.getProperty("pig.listeners").split(":")) {
                // TODO: Is there a better/cleaner way to create these
                // listeners?
                scriptState.registerListener((PigProgressNotificationListener) PigContext.getClassLoader()
                        .loadClass(clsName).newInstance());
            }
        } else {
            scriptState.registerListener(new com.netflix.lipstick.listeners.LipstickPPNL());
        }

        // construct the parameter substitution preprocessor
        LipstickGrunt grunt = null;
        BufferedReader in;
        String substFile = null;

        paramFiles = fetchRemoteParamFiles(paramFiles, properties);
        pigContext.setParams(params);
        pigContext.setParamFiles(paramFiles);

        switch (mode) {

        case FILE: {
            String remainders[] = opts.getRemainingArgs();
            pigContext.getProperties().setProperty(PigContext.PIG_CMD_ARGS_REMAINDERS,
                    ObjectSerializer.serialize(remainders));
            FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, file);
            if (localFileRet.didFetch) {
                properties.setProperty("pig.jars.relative.to.dfs", "true");
            }

            scriptState.setFileName(file);

            if (embedded) {
                return runEmbeddedScript(pigContext, localFileRet.file.getPath(), engine);
            } else {
                SupportedScriptLang type = determineScriptType(localFileRet.file.getPath());
                if (type != null) {
                    return runEmbeddedScript(pigContext, localFileRet.file.getPath(),
                            type.name().toLowerCase());
                }
            }

            in = new BufferedReader(new FileReader(localFileRet.file));

            // run parameter substitution preprocessor first
            substFile = file + ".substituted";

            pin = runParamPreprocessor(pigContext, in, substFile, debug || dryrun || checkScriptOnly);
            if (dryrun) {
                if (dryrun(substFile, pigContext)) {
                    log.info("Dry run completed. Substituted pig script is at " + substFile
                            + ". Expanded pig script is at " + file + ".expanded");
                } else {
                    log.info("Dry run completed. Substituted pig script is at " + substFile);
                }
                return ReturnCode.SUCCESS;
            }

            logFileName = validateLogFile(logFileName, file);
            pigContext.getProperties().setProperty("pig.logfile", logFileName);

            // Set job name based on name of the script
            pigContext.getProperties().setProperty(PigContext.JOB_NAME, "PigLatin:" + new File(file).getName());

            if (!debug) {
                new File(substFile).deleteOnExit();
            }

            scriptState.setScript(new File(file));

            grunt = new LipstickGrunt(pin, pigContext);
            gruntCalled = true;

            if (checkScriptOnly) {
                grunt.checkScript(substFile);
                System.err.println(file + " syntax OK");
                rc = ReturnCode.SUCCESS;
            } else {
                int results[] = grunt.exec();
                rc = getReturnCodeForStats(results);
            }

            return rc;
        }

        case STRING: {
            if (checkScriptOnly) {
                System.err.println("ERROR:" + "-c (-check) option is only valid "
                        + "when executing pig with a pig script file)");
                return ReturnCode.ILLEGAL_ARGS;
            }
            // Gather up all the remaining arguments into a string and pass
            // them into
            // grunt.
            StringBuffer sb = new StringBuffer();
            String remainders[] = opts.getRemainingArgs();
            for (int i = 0; i < remainders.length; i++) {
                if (i != 0)
                    sb.append(' ');
                sb.append(remainders[i]);
            }

            scriptState.setScript(sb.toString());

            in = new BufferedReader(new StringReader(sb.toString()));

            grunt = new LipstickGrunt(in, pigContext);
            gruntCalled = true;
            int results[] = grunt.exec();
            return getReturnCodeForStats(results);
        }

        default:
            break;
        }

        // If we're here, we don't know yet what they want. They may have
        // just
        // given us a jar to execute, they might have given us a pig script
        // to
        // execute, or they might have given us a dash (or nothing) which
        // means to
        // run grunt interactive.
        String remainders[] = opts.getRemainingArgs();
        if (remainders == null) {
            if (checkScriptOnly) {
                System.err.println("ERROR:" + "-c (-check) option is only valid "
                        + "when executing pig with a pig script file)");
                return ReturnCode.ILLEGAL_ARGS;
            }
            // Interactive
            mode = ExecMode.SHELL;
            ConsoleReader reader = new ConsoleReader(System.in, new OutputStreamWriter(System.out));
            reader.setDefaultPrompt("grunt> ");
            final String HISTORYFILE = ".pig_history";
            String historyFile = System.getProperty("user.home") + File.separator + HISTORYFILE;
            reader.setHistory(new History(new File(historyFile)));
            ConsoleReaderInputStream inputStream = new ConsoleReaderInputStream(reader);
            grunt = new LipstickGrunt(new BufferedReader(new InputStreamReader(inputStream)), pigContext);
            grunt.setConsoleReader(reader);
            gruntCalled = true;
            grunt.run();
            return ReturnCode.SUCCESS;
        } else {
            pigContext.getProperties().setProperty(PigContext.PIG_CMD_ARGS_REMAINDERS,
                    ObjectSerializer.serialize(remainders));

            // They have a pig script they want us to run.
            mode = ExecMode.FILE;

            FileLocalizer.FetchFileRet localFileRet = FileLocalizer.fetchFile(properties, remainders[0]);
            if (localFileRet.didFetch) {
                properties.setProperty("pig.jars.relative.to.dfs", "true");
            }

            scriptState.setFileName(remainders[0]);

            if (embedded) {
                return runEmbeddedScript(pigContext, localFileRet.file.getPath(), engine);
            } else {
                SupportedScriptLang type = determineScriptType(localFileRet.file.getPath());
                if (type != null) {
                    return runEmbeddedScript(pigContext, localFileRet.file.getPath(),
                            type.name().toLowerCase());
                }
            }

            in = new BufferedReader(new FileReader(localFileRet.file));

            // run parameter substitution preprocessor first
            substFile = remainders[0] + ".substituted";
            pin = runParamPreprocessor(pigContext, in, substFile, debug || dryrun || checkScriptOnly);
            if (dryrun) {
                if (dryrun(substFile, pigContext)) {
                    log.info("Dry run completed. Substituted pig script is at " + substFile
                            + ". Expanded pig script is at " + remainders[0] + ".expanded");
                } else {
                    log.info("Dry run completed. Substituted pig script is at " + substFile);
                }
                return ReturnCode.SUCCESS;
            }

            logFileName = validateLogFile(logFileName, remainders[0]);
            pigContext.getProperties().setProperty("pig.logfile", logFileName);

            if (!debug) {
                new File(substFile).deleteOnExit();
            }

            // Set job name based on name of the script
            pigContext.getProperties().setProperty(PigContext.JOB_NAME,
                    "PigLatin:" + new File(remainders[0]).getName());

            scriptState.setScript(localFileRet.file);

            grunt = new LipstickGrunt(pin, pigContext);
            gruntCalled = true;

            if (checkScriptOnly) {
                grunt.checkScript(substFile);
                System.err.println(remainders[0] + " syntax OK");
                rc = ReturnCode.SUCCESS;
            } else {
                int results[] = grunt.exec();
                rc = getReturnCodeForStats(results);
            }
            return rc;
        }

        // Per Utkarsh and Chris invocation of jar file via pig depricated.
    } catch (ParseException e) {
        usage();
        rc = ReturnCode.PARSE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
    } catch (org.apache.pig.tools.parameters.ParseException e) {
        // usage();
        rc = ReturnCode.PARSE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        if (e instanceof PigException) {
            PigException pe = (PigException) e;
            rc = (pe.retriable()) ? ReturnCode.RETRIABLE_EXCEPTION : ReturnCode.PIG_EXCEPTION;
            PigStatsUtil.setErrorMessage(pe.getMessage());
            PigStatsUtil.setErrorCode(pe.getErrorCode());
        } else {
            rc = ReturnCode.IO_EXCEPTION;
            PigStatsUtil.setErrorMessage(e.getMessage());
        }

        if (!gruntCalled) {
            LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched");
        }
    } catch (Throwable e) {
        rc = ReturnCode.THROWABLE_EXCEPTION;
        PigStatsUtil.setErrorMessage(e.getMessage());
        if (!gruntCalled) {
            LogUtils.writeLog(e, logFileName, log, verbose, "Error before Pig is launched");
        }
    } finally {
        // clear temp files
        FileLocalizer.deleteTempFiles();
        // PerformanceTimerFactory.getPerfTimerFactory().dumpTimers();
    }

    return rc;
}

From source file:org.brekka.stillingar.spring.bpp.ConfigurationBeanPostProcessorTest.java

@Test
public void primitiveDefaultCharacter() {
    assertEquals(ConfigurationBeanPostProcessor.primitiveDefault(Character.TYPE), Character.valueOf((char) 0));
}