Example usage for java.lang Byte toString

List of usage examples for java.lang Byte toString

Introduction

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

Prototype

public static String toString(byte b) 

Source Link

Document

Returns a new String object representing the specified byte .

Usage

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

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

    if (!prepared()) {

        return statementResult;
    }

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

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

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

    if (hasParameters) {

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

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

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

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

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

            }
        }

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

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

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

                sb.append(QUESTION_MARK);

                if (i < n - 1) {

                    sb.append(COMMA);
                }

            }

            sb.append(" = ");
        }

        sb.append(" call ");

        if (databaseExecutable.supportCatalogOrSchemaInFunctionOrProcedureCalls()) {

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

                namePrefix = databaseExecutable.getCatalogName();

            }
            if (databaseExecutable.supportSchemaInFunctionOrProcedureCalls()) {

                namePrefix = databaseExecutable.getSchemaName();

            }

            if (namePrefix != null) {

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

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

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

        sb.append(" ) }");

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

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

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

        procQuery = sb.toString();
    }

    //Log.debug(procQuery);

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

    // clear any warnings
    conn.clearWarnings();

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

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

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

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

        // the parameter input value
        String value = null;

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

        try {

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

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

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

                    // checking only for bit/bool for now

                    if (isTrueFalse(value)) {

                        dataType = Types.BOOLEAN;

                    } else if (isBit(value)) {

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

                }

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

                    cstmnt.setNull(index, dataType);

                } else {

                    switch (dataType) {

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

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

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

                    case Types.BIT:
                    case Types.BOOLEAN:

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

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

                                _boolean = true;
                            }

                        } else {

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

                        cstmnt.setBoolean(index, _boolean);
                        break;

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

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

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

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

                    default:
                        cstmnt.setObject(index, value);

                    }

                }

                // increment the index
                index++;
            }

        } catch (Exception e) {

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

    }

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

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

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

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

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

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

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

                    switch (dataType) {

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

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

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

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

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

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

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

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

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

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

                    }

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

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

            }

        }

        if (!hasResultSet) {

            statementResult.setUpdateCount(cstmnt.getUpdateCount());

        } else {

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

        useCount++;
        statementResult.setOtherResult(results);

    } catch (SQLException e) {

        statementResult.setSqlException(e);

    } catch (Exception e) {

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

    return statementResult;
}

From source file:com.rim.logdriver.util.MultiSearch.java

@Override
public int run(String[] args) throws Exception {
    Configuration conf = getConf(); // Configuration processed by ToolRunner
    // If run by Oozie, then load the Oozie conf too
    if (System.getProperty("oozie.action.conf.xml") != null) {
        conf.addResource(new URL("file://" + System.getProperty("oozie.action.conf.xml")));
    }/*from ww  w  .j  a v a 2  s  . c  o m*/

    FileSystem fs = FileSystem.get(conf);

    // The command line options
    String searchStringDir = null;
    List<Path> paths = new ArrayList<Path>();
    Path outputDir = null;

    // Load input files from the command line
    if (args.length < 3) {
        System.out.println("usage: [genericOptions] searchStringDirectory input [input ...] output");
        System.exit(1);
    }

    // Get the files we need from the command line.
    searchStringDir = args[0];
    // We are going to be reading all the files in this directory a lot. So
    // let's up the replication factor by a lot so that they're easy to read.
    for (FileStatus f : fs.listStatus(new Path(searchStringDir))) {
        fs.setReplication(f.getPath(), (short) 16);
    }

    for (int i = 1; i < args.length - 1; i++) {
        for (FileStatus f : fs.globStatus(new Path(args[i]))) {
            paths.add(f.getPath());
        }
    }

    outputDir = new Path(args[args.length - 1]);

    Job job = new Job(conf);
    Configuration jobConf = job.getConfiguration();

    job.setJarByClass(MultiSearch.class);
    jobConf.setIfUnset("mapred.job.name", "MultiSearch");

    // To propagate credentials within Oozie
    if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
        jobConf.set("mapreduce.job.credentials.binary", System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
    }

    // Good output separators include things that are unsupported by XML. So we
    // just send the byte value of the character through. The restriction here
    // is that it can't be more than 1 byte when UTF-8 encoded, since it will be
    // read by Pig which only deals with single byte separators.
    {
        String outputSeparator = jobConf.get("logdriver.output.field.separator", DEFAULT_OUTPUT_SEPARATOR);
        byte[] bytes = outputSeparator.getBytes(UTF_8);
        if (bytes.length != 1) {
            LOG.error("The output separator must be a single byte in UTF-8.");
            return 1;
        }

        jobConf.set("logdriver.output.field.separator", Byte.toString(bytes[0]));
    }

    jobConf.set("logdriver.search.string.dir", searchStringDir);

    // This search is generally too fast to make good use of 128MB blocks, so
    // let's set the value to 256MB (if it's not set already)
    if (jobConf.get("mapred.max.split.size") == null) {
        jobConf.setLong("mapred.max.split.size", 256 * 1024 * 1024);
    }

    job.setInputFormatClass(AvroBlockInputFormat.class);
    job.setMapperClass(SearchMapper.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(NullWritable.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(TextOutputFormat.class);
    TextOutputFormat.setOutputPath(job, outputDir);
    for (Path path : paths) {
        AvroBlockInputFormat.addInputPath(job, path);
    }

    // Run the job.
    if (conf.getBoolean("job.wait", DEFAULT_WAIT_JOB)) {
        return job.waitForCompletion(true) ? 0 : 1;
    } else {
        job.submit();
        return 0;
    }
}

From source file:com.blackberry.logdriver.util.MultiSearch.java

@Override
public int run(String[] args) throws Exception {
    Configuration conf = getConf(); // Configuration processed by ToolRunner
    // If run by Oozie, then load the Oozie conf too
    if (System.getProperty("oozie.action.conf.xml") != null) {
        conf.addResource(new URL("file://" + System.getProperty("oozie.action.conf.xml")));
    }/*from   ww  w . j a  va 2 s .  co  m*/

    FileSystem fs = FileSystem.get(conf);

    // The command line options
    String searchStringDir = null;
    List<Path> paths = new ArrayList<Path>();
    Path outputDir = null;

    // Load input files from the command line
    if (args.length < 3) {
        System.out.println("usage: [genericOptions] searchStringDirectory input [input ...] output");
        System.exit(1);
    }

    // Get the files we need from the command line.
    searchStringDir = args[0];
    // We are going to be reading all the files in this directory a lot. So
    // let's up the replication factor by a lot so that they're easy to read.
    for (FileStatus f : fs.listStatus(new Path(searchStringDir))) {
        fs.setReplication(f.getPath(), (short) 16);
    }

    for (int i = 1; i < args.length - 1; i++) {
        for (FileStatus f : fs.globStatus(new Path(args[i]))) {
            paths.add(f.getPath());
        }
    }

    outputDir = new Path(args[args.length - 1]);

    @SuppressWarnings("deprecation")
    Job job = new Job(conf);
    Configuration jobConf = job.getConfiguration();

    job.setJarByClass(MultiSearch.class);
    jobConf.setIfUnset("mapred.job.name", "MultiSearch");

    // To propagate credentials within Oozie
    if (System.getenv("HADOOP_TOKEN_FILE_LOCATION") != null) {
        jobConf.set("mapreduce.job.credentials.binary", System.getenv("HADOOP_TOKEN_FILE_LOCATION"));
    }

    // Good output separators include things that are unsupported by XML. So we
    // just send the byte value of the character through. The restriction here
    // is that it can't be more than 1 byte when UTF-8 encoded, since it will be
    // read by Pig which only deals with single byte separators.
    {
        String outputSeparator = jobConf.get("logdriver.output.field.separator", DEFAULT_OUTPUT_SEPARATOR);
        byte[] bytes = outputSeparator.getBytes(UTF_8);
        if (bytes.length != 1) {
            LOG.error("The output separator must be a single byte in UTF-8.");
            return 1;
        }

        jobConf.set("logdriver.output.field.separator", Byte.toString(bytes[0]));
    }

    jobConf.set("logdriver.search.string.dir", searchStringDir);

    // This search is generally too fast to make good use of 128MB blocks, so
    // let's set the value to 256MB (if it's not set already)
    if (jobConf.get("mapred.max.split.size") == null) {
        jobConf.setLong("mapred.max.split.size", 256 * 1024 * 1024);
    }

    job.setInputFormatClass(AvroBlockInputFormat.class);
    job.setMapperClass(SearchMapper.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(NullWritable.class);

    job.setNumReduceTasks(0);

    job.setOutputFormatClass(TextOutputFormat.class);
    TextOutputFormat.setOutputPath(job, outputDir);
    for (Path path : paths) {
        AvroBlockInputFormat.addInputPath(job, path);
    }

    // Run the job.
    if (conf.getBoolean("job.wait", DEFAULT_WAIT_JOB)) {
        return job.waitForCompletion(true) ? 0 : 1;
    } else {
        job.submit();
        return 0;
    }
}

From source file:com.sun.honeycomb.adm.client.AdminClientImpl.java

public void setCellProps(HCCell cell, HCCellProps newProps)
        throws MgmtException, ConnectException, PermissionException {

    if (!loggedIn())
        throw new PermissionException();

    boolean update = false;
    Level logLevel = ExtLevel.EXT_INFO;
    String logMethod = "setCellProps";
    String logCellId = Byte.toString(cell.getCellId());
    String logSessionId = Long.toString(this._sessionId);

    HCCellProps oldProps = cell.getCellProps();
    if (newProps.getAdminVIP() == null) {
        newProps.setAdminVIP(oldProps.getAdminVIP());
    } else {// w ww . ja va2s  . c  o  m
        update = true;
        this.logCellPropsChange(logLevel, AdminResourcesConstants.MSG_KEY_SET_ADMIN_IP, logSessionId, logCellId,
                newProps.getAdminVIP(), logMethod);
    }

    if (newProps.getDataVIP() == null) {
        newProps.setDataVIP(oldProps.getDataVIP());
    } else {
        update = true;
        this.logCellPropsChange(logLevel, AdminResourcesConstants.MSG_KEY_SET_DATA_IP, logSessionId, logCellId,
                newProps.getDataVIP(), logMethod);
    }

    if (newProps.getSpVIP() == null) {
        newProps.setSpVIP(oldProps.getSpVIP());
    } else {
        update = true;
        this.logCellPropsChange(logLevel, AdminResourcesConstants.MSG_KEY_SET_SERVICE_NODE_IP, logSessionId,
                logCellId, newProps.getSpVIP(), logMethod);
    }

    if (newProps.getSubnet() == null) {
        newProps.setSubnet(oldProps.getSubnet());
    } else {
        update = true;
        this.logCellPropsChange(logLevel, AdminResourcesConstants.MSG_KEY_SET_SUBNET_MASK, logSessionId,
                logCellId, newProps.getSubnet(), logMethod);
    }

    if (newProps.getGateway() == null) {
        newProps.setGateway(oldProps.getGateway());
    } else {
        update = true;
        this.logCellPropsChange(logLevel, AdminResourcesConstants.MSG_KEY_SET_GATEWAY_IP, logSessionId,
                logCellId, newProps.getGateway(), logMethod);
    }
    if (update == false) {
        return;
    }

    MultiCellOp[] setCellProps = allocateMultiCellOp(MultiCellSetCellProps.class);
    SetCellPropsCookie cookie = new SetCellPropsCookie(newProps, cell.getCellId());
    MultiCellRunner runner = new MultiCellRunner(setCellProps);
    runner.setCookie(cookie);
    runner.start();
    runner.waitForResult();
    SiloInfo.getInstance().updateCell(cell, newProps);
}

From source file:org.apache.pig.backend.hadoop.executionengine.tez.TezDagBuilder.java

/**
 * Return EdgeProperty that connects two vertices.
 *
 * @param from//from www.  j ava  2 s.c  o m
 * @param to
 * @return EdgeProperty
 * @throws IOException
 */
private EdgeProperty newEdge(TezOperator from, TezOperator to, boolean isMergedInput) throws IOException {
    TezEdgeDescriptor edge = to.inEdges.get(from.getOperatorKey());
    PhysicalPlan combinePlan = edge.combinePlan;

    InputDescriptor in = InputDescriptor.create(edge.inputClassName);
    OutputDescriptor out = OutputDescriptor.create(edge.outputClassName);

    Configuration conf = new Configuration(pigContextConf);

    if (edge.needsDistinctCombiner()) {
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_COMBINER_CLASS, MRCombiner.class.getName());
        conf.set(MRJobConfig.COMBINE_CLASS_ATTR, DistinctCombiner.Combine.class.getName());
        log.info("Setting distinct combiner class between " + from.getOperatorKey() + " and "
                + to.getOperatorKey());
    } else if (!combinePlan.isEmpty()) {
        udfContextSeparator.serializeUDFContextForEdge(conf, from, to, UDFType.USERFUNC);
        addCombiner(combinePlan, to, conf, isMergedInput);
    }

    List<POLocalRearrangeTez> lrs = PlanHelper.getPhysicalOperators(from.plan, POLocalRearrangeTez.class);

    for (POLocalRearrangeTez lr : lrs) {
        if (lr.getOutputKey().equals(to.getOperatorKey().toString())) {
            byte keyType = lr.getKeyType();
            setIntermediateOutputKeyValue(keyType, conf, to, lr.isConnectedToPackage(), isMergedInput);
            // In case of secondary key sort, main key type is the actual key type
            conf.set("pig.reduce.key.type", Byte.toString(lr.getMainKeyType()));
            break;
        }
    }

    conf.setIfUnset(TezRuntimeConfiguration.TEZ_RUNTIME_PARTITIONER_CLASS, MRPartitioner.class.getName());

    if (edge.getIntermediateOutputKeyClass() != null) {
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_KEY_CLASS, edge.getIntermediateOutputKeyClass());
    }

    if (edge.getIntermediateOutputValueClass() != null) {
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_VALUE_CLASS, edge.getIntermediateOutputValueClass());
    }

    if (edge.getIntermediateOutputKeyComparatorClass() != null) {
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_KEY_COMPARATOR_CLASS,
                edge.getIntermediateOutputKeyComparatorClass());
    }

    conf.setBoolean(MRConfiguration.MAPPER_NEW_API, true);
    conf.setBoolean(MRConfiguration.REDUCER_NEW_API, true);
    conf.setBoolean(PigImplConstants.PIG_EXECTYPE_MODE_LOCAL, pc.getExecType().isLocal());
    conf.set(PigImplConstants.PIG_LOG4J_PROPERTIES, ObjectSerializer.serialize(pc.getLog4jProperties()));
    conf.set("udf.import.list", serializedUDFImportList);

    if (to.isGlobalSort() || to.isLimitAfterSort()) {
        conf.set("pig.sortOrder", ObjectSerializer.serialize(to.getSortOrder()));
    }

    if (edge.isUseSecondaryKey()) {
        conf.set("pig.secondarySortOrder", ObjectSerializer.serialize(edge.getSecondarySortOrder()));
        conf.set(org.apache.hadoop.mapreduce.MRJobConfig.PARTITIONER_CLASS_ATTR,
                SecondaryKeyPartitioner.class.getName());
        // These needs to be on the vertex as well for POShuffleTezLoad to pick it up.
        // Tez framework also expects this to be per vertex and not edge. IFile.java picks
        // up keyClass and valueClass from vertex config. TODO - check with Tez folks
        // In MR - job.setSortComparatorClass() or MRJobConfig.KEY_COMPARATOR
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_KEY_COMPARATOR_CLASS,
                PigSecondaryKeyComparator.class.getName());
        // In MR - job.setOutputKeyClass() or MRJobConfig.OUTPUT_KEY_CLASS
        conf.set(TezRuntimeConfiguration.TEZ_RUNTIME_KEY_CLASS, NullableTuple.class.getName());
        setGroupingComparator(conf, PigSecondaryKeyGroupComparator.class.getName());
    }

    if (edge.partitionerClass != null) {
        conf.set(org.apache.hadoop.mapreduce.MRJobConfig.PARTITIONER_CLASS_ATTR,
                edge.partitionerClass.getName());
    }

    UserPayload payLoad = TezUtils.createUserPayloadFromConf(conf);
    out.setUserPayload(payLoad);

    if (!combinePlan.isEmpty()) {
        boolean noCombineInReducer = false;
        String reducerNoCombiner = globalConf.get(PigConfiguration.PIG_EXEC_NO_COMBINER_REDUCER);
        if (reducerNoCombiner == null || reducerNoCombiner.equals("auto")) {
            noCombineInReducer = TezCompilerUtil.bagDataTypeInCombinePlan(combinePlan);
        } else {
            noCombineInReducer = Boolean.parseBoolean(reducerNoCombiner);
        }
        if (noCombineInReducer) {
            log.info("Turning off combiner in reducer vertex " + to.getOperatorKey() + " for edge from "
                    + from.getOperatorKey());
            conf.unset(TezRuntimeConfiguration.TEZ_RUNTIME_COMBINER_CLASS);
            conf.unset(MRJobConfig.COMBINE_CLASS_ATTR);
            conf.unset("pig.combinePlan");
            conf.unset("pig.combine.package");
            conf.unset("pig.map.keytype");
            payLoad = TezUtils.createUserPayloadFromConf(conf);
        }
    }
    in.setUserPayload(payLoad);

    if (edge.dataMovementType != DataMovementType.BROADCAST && to.getEstimatedParallelism() != -1
            && to.getVertexParallelism() == -1 && (to.isGlobalSort() || to.isSkewedJoin())) {
        // Use custom edge
        return EdgeProperty.create((EdgeManagerPluginDescriptor) null, edge.dataSourceType, edge.schedulingType,
                out, in);
    }

    if (to.isUseGraceParallelism()) {
        // Put datamovement to null to prevent vertex "to" from starting. It will be started by PigGraceShuffleVertexManager
        return EdgeProperty.create((EdgeManagerPluginDescriptor) null, edge.dataSourceType, edge.schedulingType,
                out, in);
    }
    return EdgeProperty.create(edge.dataMovementType, edge.dataSourceType, edge.schedulingType, out, in);
}

From source file:org.ariose.util.SMPPSender.java

/**
 * Prompts the user to enter a byte value for a parameter.
 *///w  w w . j a  v  a  2  s. com
private byte getParam(String prompt, byte defaultValue) {
    return Byte.parseByte(getParam(prompt, Byte.toString(defaultValue)));
}

From source file:de.juwimm.cms.remote.ViewServiceSpringImpl.java

/**
 * @see de.juwimm.cms.remote.ViewServiceSpring#getViewComponentForLanguageOrShortlink(java.lang.String, java.lang.String, java.lang.Integer)
 */// w w w  . j a va2s . c om
@Override
protected String[] handleGetViewComponentForLanguageOrShortlink(String viewType, String lang, Integer siteId)
        throws Exception {
    if (log.isDebugEnabled())
        log.debug("GET VIEW COMPONET FOR LANGUAGE OR SHORTLINK");
    try {
        String[] retArr = new String[4];
        ViewDocumentHbm vd = null;
        ViewComponentHbm vcl = null;
        try {
            vd = super.getViewDocumentHbmDao().findByViewTypeAndLanguage(viewType, lang, siteId);
            vcl = vd.getViewComponent();
        } catch (Exception exe) {
            // maybe an Shortlink
            try {
                SiteHbm site = super.getSiteHbmDao().load(siteId);
                vd = site.getDefaultViewDocument();
                vcl = this.getViewComponentId4PathResolver(lang, vd.getViewComponent().getViewComponentId(),
                        false);
            } catch (Exception exee) {
            }
        }
        if (vd == null || vcl == null) {
            log.warn("Could not find viewComponent/shortlink for viewType: " + viewType + " language: " + lang
                    + " siteId: " + siteId);
        } else {
            retArr[0] = vcl.getViewComponentId().toString();
            retArr[1] = getPathForViewComponentId(vcl.getViewComponentId());
            retArr[2] = vd.getLanguage();
            retArr[3] = Byte.toString(vcl.getViewType());
        }
        return retArr;
    } catch (Exception e) {
        return null;
    }
}

From source file:org.ariose.util.SMPPSender.java

/**
 * Loads configuration parameters from the file with the given name. Sets
 * private variable to the loaded values.
 *//* w w  w .ja va2  s  . c  o  m*/
public void setPropertiesFromConfig(GmlcConfiguration config) throws Exception {
    log.info("Setting default parameters...");
    byte ton;
    byte npi;
    String addr;
    String bindMode;
    int rcvTimeout;

    operatorName = config.getOperatorname();
    shortCode = config.getShortcode();

    ipAddress = config.getIpaddress();
    //      CommonFunctions.checkNull("ipAddress", ipAddress);

    try {
        port = Integer.parseInt(config.getPort());
    } catch (Exception e) {
        throw new Exception("Cannot send sms..port is not configured properly");
    }

    // port = getIntProperty("port", port);
    systemId = config.getSystemid();// properties.getProperty("system-id");
    password = config.getPassword();// properties.getProperty("password");

    try {
        ton = Byte.parseByte(config.getAddrton());
    } catch (Exception e) {
        ton = Byte.parseByte(Byte.toString(addressRange.getTon()));
    }

    try {
        npi = Byte.parseByte(config.getAddrnpi());
    } catch (Exception e) {
        npi = Byte.parseByte(Byte.toString(addressRange.getNpi()));
    }

    if (config.getAddressrange() != null)
        addr = config.getAddressrange();
    else
        addr = addressRange.getAddressRange();

    // ton = getByteProperty("addr-ton", addressRange.getTon());
    // npi = getByteProperty("addr-npi", addressRange.getNpi());
    // addr = properties.getProperty("address-range", addressRange
    // .getAddressRange());
    addressRange.setTon(ton);
    addressRange.setNpi(npi);
    try {
        addressRange.setAddressRange(addr);
    } catch (WrongLengthOfStringException e) {
        log.error("The length of address-range parameter is wrong.");
    }

    try {
        ton = Byte.parseByte(config.getSourceton());
    } catch (Exception e) {
        ton = Byte.parseByte(Byte.toString(sourceAddress.getTon()));
    }
    try {
        npi = Byte.parseByte(config.getSourcenpi());
    } catch (Exception e) {
        npi = Byte.parseByte(Byte.toString(sourceAddress.getNpi()));
    }
    // ton = getByteProperty("source-ton", sourceAddress.getTon());
    // npi = getByteProperty("source-npi", sourceAddress.getNpi());

    if (config.getSourceaddress() != null)
        addr = config.getSourceaddress();
    else
        addr = sourceAddress.getAddress();

    // addr = properties.getProperty("source-address", sourceAddress
    // .getAddress());
    setAddressParameter("source-address", sourceAddress, ton, npi, addr);

    try {
        ton = Byte.parseByte(config.getDestinationton());
    } catch (Exception e) {
        ton = Byte.parseByte(Byte.toString(destAddress.getTon()));
    }
    try {
        npi = Byte.parseByte(config.getDestinationnpi());
    } catch (Exception e) {
        npi = Byte.parseByte(Byte.toString(destAddress.getNpi()));
    }
    // ton = getByteProperty("source-ton", sourceAddress.getTon());
    // npi = getByteProperty("source-npi", sourceAddress.getNpi());
    if (config.getDestinationaddress() != null)
        addr = config.getDestinationaddress();
    else
        addr = destAddress.getAddress();

    // ton = getByteProperty("destination-ton", destAddress.getTon());
    // npi = getByteProperty("destination-npi", destAddress.getNpi());
    // addr = properties.getProperty("destination-address", destAddress
    // .getAddress());
    setAddressParameter("destination-address", destAddress, ton, npi, addr);

    if (config.getServicetype() != null)
        serviceType = config.getServicetype();
    if (config.getSystemtype() != null)
        systemType = config.getSystemtype();
    if (config.getBindmode() != null)
        bindMode = config.getBindmode();
    else
        bindMode = bindOption;
    // serviceType = properties.getProperty("service-type", serviceType);
    // systemType = properties.getProperty("system-type", systemType);
    // bindMode = properties.getProperty("bind-mode", bindOption);
    if (bindMode.equalsIgnoreCase("transmitter")) {
        bindMode = "t";
    } else if (bindMode.equalsIgnoreCase("receiver")) {
        bindMode = "r";
    } else if (bindMode.equalsIgnoreCase("transciever")) {
        bindMode = "tr";
    } else if (!bindMode.equalsIgnoreCase("t") && !bindMode.equalsIgnoreCase("r")
            && !bindMode.equalsIgnoreCase("tr")) {
        log.info("The value of bind-mode parameter in " + "the database gmlc_configuration table is wrong. "
                + "Setting the default as t");
        bindMode = "t";
    }
    bindOption = bindMode;

    // receive timeout in the cfg file is in seconds, we need milliseconds
    // also conversion from -1 which indicates infinite blocking
    // in the cfg file to Data.RECEIVE_BLOCKING which indicates infinite
    // blocking in the library is needed.
    if (receiveTimeout == Data.RECEIVE_BLOCKING) {
        rcvTimeout = -1;
    } else {
        rcvTimeout = ((int) receiveTimeout) / 1000;
    }

    if (config.getReceivetimeout() != null)
        rcvTimeout = Integer.parseInt(config.getReceivetimeout());

    // rcvTimeout = getIntProperty("receive-timeout", rcvTimeout);
    if (rcvTimeout == -1) {
        receiveTimeout = Data.RECEIVE_BLOCKING;
    } else {
        receiveTimeout = rcvTimeout * 1000;
    }

    /*
     * scheduleDeliveryTime validityPeriod shortMessage numberOfDestination
     * messageId esmClass protocolId priorityFlag registeredDelivery
     * replaceIfPresentFlag dataCoding smDefaultMsgId
     */
}

From source file:edu.ku.brc.af.ui.forms.formatters.UIFieldFormatterMgr.java

/**
 * Constructs a the fields for a numeric formatter.
 * // w  ww .j a  v a2 s.  c  om
 * @param formatter the formatter to be augmented
 */
protected void addFieldsForNumeric(final UIFieldFormatter formatter) {
    int len;
    Class<?> cls = formatter.getDataClass();
    if (cls == BigDecimal.class) {
        len = formatter.getPrecision() + formatter.getScale() + 1;
    } else {
        if (cls == Long.class) {
            len = Long.toString(Long.MAX_VALUE).length();
        } else if (cls == Integer.class) {
            len = Integer.toString(Integer.MAX_VALUE).length();
        } else if (cls == Short.class) {
            len = Short.toString(Short.MAX_VALUE).length();
        } else if (cls == Byte.class) {
            len = Byte.toString(Byte.MAX_VALUE).length();
        } else if (cls == Double.class) {
            len = String.format("%f", Double.MAX_VALUE).length();
        } else if (cls == Float.class) {
            len = String.format("%f", Float.MAX_VALUE).length();

        } else {
            len = formatter.getLength();
            //throw new RuntimeException("Missing case for numeric class ["+ cls.getName() + "]");
        }
        len = Math.min(len, 10);
    }
    StringBuilder sb = new StringBuilder(len);
    for (int i = 0; i < len; i++) {
        sb.append(' ');
    }
    formatter.getFields()
            .add(new UIFieldFormatterField(UIFieldFormatterField.FieldType.numeric, len, sb.toString(), false));
}

From source file:paulscode.android.mupen64plusae.GalleryActivity.java

void refreshGrid() {

    final ConfigFile config = new ConfigFile(mGlobalPrefs.romInfoCache_cfg);

    final String query = mSearchQuery.toLowerCase(Locale.US);
    String[] searches = null;//from  w ww  .ja  v a  2  s  .  co  m
    if (query.length() > 0)
        searches = query.split(" ");

    List<GalleryItem> items = new ArrayList<>();
    List<GalleryItem> recentItems = null;
    int currentTime = 0;
    if (mGlobalPrefs.isRecentShown) {
        recentItems = new ArrayList<>();
        currentTime = (int) (new Date().getTime() / 1000);
    }

    for (final String md5 : config.keySet()) {
        if (!ConfigFile.SECTIONLESS_NAME.equals(md5)) {
            final ConfigSection section = config.get(md5);
            String goodName;
            if (mGlobalPrefs.isFullNameShown || !section.keySet().contains("baseName"))
                goodName = section.get("goodName");
            else
                goodName = section.get("baseName");

            boolean matchesSearch = true;
            if (searches != null && searches.length > 0) {
                // Make sure the ROM name contains every token in the query
                final String lowerName = goodName.toLowerCase(Locale.US);
                for (final String search : searches) {
                    if (search.length() > 0 && !lowerName.contains(search)) {
                        matchesSearch = false;
                        break;
                    }
                }
            }

            if (matchesSearch) {
                final String romPath = config.get(md5, "romPath");
                String zipPath = config.get(md5, "zipPath");
                final String artFullPath = config.get(md5, "artPath");
                String artPath = new File(artFullPath).getName();
                artPath = mGlobalPrefs.coverArtDir + "/" + artPath;

                String crc = config.get(md5, "crc");
                String headerName = config.get(md5, "headerName");
                final String countryCodeString = config.get(md5, "countryCode");
                byte countryCode = 0;

                //We can't really do much if the rompath is null
                if (romPath != null) {

                    if (countryCodeString != null) {
                        countryCode = Byte.parseByte(countryCodeString);
                    }
                    final String lastPlayedStr = config.get(md5, "lastPlayed");
                    String extracted = config.get(md5, "extracted");

                    if (zipPath == null || crc == null || headerName == null || countryCodeString == null
                            || extracted == null) {
                        final File file = new File(romPath);
                        final RomHeader header = new RomHeader(file);

                        zipPath = "";
                        crc = header.crc;
                        headerName = header.name;
                        countryCode = header.countryCode;
                        extracted = "false";

                        config.put(md5, "zipPath", zipPath);
                        config.put(md5, "crc", crc);
                        config.put(md5, "headerName", headerName);
                        config.put(md5, "countryCode", Byte.toString(countryCode));
                        config.put(md5, "extracted", extracted);
                    }

                    int lastPlayed = 0;
                    if (lastPlayedStr != null)
                        lastPlayed = Integer.parseInt(lastPlayedStr);

                    final GalleryItem item = new GalleryItem(this, md5, crc, headerName, countryCode, goodName,
                            romPath, zipPath, extracted.equals("true"), artPath, lastPlayed);
                    items.add(item);
                    if (mGlobalPrefs.isRecentShown && currentTime - item.lastPlayed <= 60 * 60 * 24 * 7) // 7
                                                                                                         // days
                    {
                        recentItems.add(item);
                    }
                    // Delete any old files that already exist inside a zip
                    // file
                    else if (!zipPath.equals("") && extracted.equals("true")) {
                        final File deleteFile = new File(romPath);
                        deleteFile.delete();

                        config.put(md5, "extracted", "false");
                    }
                }
            }
        }
    }

    config.save();

    Collections.sort(items, new GalleryItem.NameComparator());
    if (recentItems != null)
        Collections.sort(recentItems, new GalleryItem.RecentlyPlayedComparator());

    List<GalleryItem> combinedItems = items;
    if (mGlobalPrefs.isRecentShown && recentItems.size() > 0) {
        combinedItems = new ArrayList<>();

        combinedItems.add(new GalleryItem(this, getString(R.string.galleryRecentlyPlayed)));
        combinedItems.addAll(recentItems);

        combinedItems.add(new GalleryItem(this, getString(R.string.galleryLibrary)));
        combinedItems.addAll(items);

        items = combinedItems;
    }

    mGalleryItems = items;
    mGridView.setAdapter(new GalleryItem.Adapter(this, items));

    // Allow the headings to take up the entire width of the layout
    final List<GalleryItem> finalItems = items;
    final GridLayoutManager layoutManager = new GridLayoutManagerBetterScrolling(this, galleryColumns);
    layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
        @Override
        public int getSpanSize(int position) {
            // Headings will take up every span (column) in the grid
            if (finalItems.get(position).isHeading)
                return galleryColumns;

            // Games will fit in a single column
            return 1;
        }
    });

    mGridView.setLayoutManager(layoutManager);
}