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:com.blackberry.logdriver.util.Grep.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")));
    }/*  w w  w. j  a  v a 2s  .  c o m*/

    FileSystem fs = FileSystem.get(conf);

    // The command line options
    String regex = 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] regex input [input ...] output");
        System.exit(1);
    }

    // Get the files we need from the command line.
    regex = args[0];
    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(Grep.class);
    jobConf.setIfUnset("mapred.job.name", "Grep Files");

    // 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.grep.regex", Base64.encodeBase64String(regex.getBytes("UTF-8")));

    job.setInputFormatClass(BoomInputFormat.class);
    job.setMapperClass(GrepMapper.class);
    job.setMapOutputKeyClass(Text.class);
    job.setMapOutputValueClass(NullWritable.class);

    job.setNumReduceTasks(0);

    // And set the output as usual
    job.setOutputFormatClass(TextOutputFormat.class);
    TextOutputFormat.setOutputPath(job, outputDir);
    for (Path path : paths) {
        BoomInputFormat.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:de.unistuttgart.ipvs.pmp.infoapp.webservice.properties.DeviceProperties.java

@Override
public void commit() throws InternalDatabaseException, InvalidParameterException, IOException {
    try {//  w ww. j  a  v  a  2s . co m
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
        params.add(new BasicNameValuePair("manufacturer", this.deviceOem.manufacturer));
        params.add(new BasicNameValuePair("apiLevel", Byte.toString(this.api)));
        params.add(new BasicNameValuePair("kernel", this.kernel));
        params.add(new BasicNameValuePair("model", this.deviceOem.model));
        params.add(new BasicNameValuePair("ui", this.deviceOem.ui));
        params.add(new BasicNameValuePair("displayResX", Short.toString(this.display.x)));
        params.add(new BasicNameValuePair("displayResY", Short.toString(this.display.y)));
        params.add(new BasicNameValuePair("cpuFrequency", Short.toString(this.cpu)));
        params.add(new BasicNameValuePair("memoryInternal", Short.toString(this.memoryInternal.total)));
        params.add(new BasicNameValuePair("memoryInternalFree", Short.toString(this.memoryInternal.free)));
        params.add(new BasicNameValuePair("memoryExternal", Short.toString(this.memoryExternal.total)));
        params.add(new BasicNameValuePair("memoryExternalFree", Short.toString(this.memoryExternal.free)));
        params.add(new BasicNameValuePair("cameraResolution", Float.toString(this.cameraRes)));

        StringBuilder sensorsSb = new StringBuilder();
        boolean first = true;
        for (String sensor : this.sensors) {
            if (first) {
                first = false;
            } else {
                sensorsSb.append(",");
            }
            sensorsSb.append(sensor);
        }
        params.add(new BasicNameValuePair("sensors", sensorsSb.toString()));

        params.add(new BasicNameValuePair("runtime", Float.toString(this.runtime)));

        super.service.requestPostService("update_device.php", params);
    } catch (JSONException e) {
        throw new IOException("Server returned no valid JSON object: " + e);
    }
}

From source file:com.npower.dm.util.TestImportMToneUsers.java

public void testImport() throws Exception {
    ManagementBeanFactory factory = null;
    try {//ww  w .  j  av  a2s  .  c om
        factory = AllTests.getManagementBeanFactory();
        DeviceBean bean = factory.createDeviceBean();
        SubscriberBean subscriberBean = factory.createSubcriberBean();
        ModelBean modelBean = factory.createModelBean();

        CarrierBean carrierBean = factory.createCarrierBean();
        Carrier carrier = carrierBean.getCarrierByExternalID("ChinaMobile");

        ServiceProviderBean spBean = factory.createServiceProviderBean();
        ServiceProvider sp = spBean.getServiceProviderByExternalID(Service_Provider_External_ID);

        DeviceDataReader in = new MToneDeviceDataReader(new File(
                "D:/Zhao/MyWorkspace/nWave-DM-Common/test/com/npower/dm/util/mtone_10000_200804_part3.csv"));
        //DeviceDataReader in = new MToneDeviceDataReaderV2(new File("D:/Zhao/MyWorkspace/nWave-DM-Common/test/com/npower/dm/util/mtone_jiangsu_20080605.csv"));
        in.open();

        DeviceData item = in.read();
        Device device = null;
        int total = 0;
        long begin = System.currentTimeMillis();
        while (item != null) {
            if (StringUtils.isNotEmpty(item.getImei())) {
                device = bean.getDeviceByExternalID(item.getImei());
                if (device != null) {
                    System.err.println(
                            "Device exists, imei: " + item.getImei() + ", msidn: " + item.getPhoneNumber());
                    // Get Next
                    item = in.read();
                    continue;
                }
            }

            String phoneNumber = item.getPhoneNumber();
            String manufacturerName = item.getManufacturer();
            String modelName = item.getModel();
            Manufacturer manufacturer = modelBean.getManufacturerByExternalID(manufacturerName);
            if (manufacturer == null) {
                System.err
                        .println(item.getLineNumber() + "#:Could not found manufacturer: " + manufacturerName);
                return;
            }

            Model model = modelBean.getModelByManufacturerModelID(manufacturer, modelName);
            if (model == null) {
                model = modelBean.getModelByName(manufacturer, modelName);
            }
            if (model == null) {
                System.err.println(item.getLineNumber() + "#:Could not found model: " + manufacturerName + " "
                        + modelName);
                //return;
            }

            // Add a device and a subscriber
            factory.beginTransaction();
            device = bean.enroll(phoneNumber, model, carrier, sp);
            if (StringUtils.isNotEmpty(item.getImei())) {
                device.setExternalId(item.getImei());
            }
            bean.update(device);
            Subscriber subscriber = device.getSubscriber();
            if (StringUtils.isNotEmpty(item.getImsi())) {
                subscriber.setIMSI(item.getImsi());
                subscriber.setBootstrapPinType(Byte.toString(OMACPSecurityMethod.NETWPIN.getValue()));
                subscriberBean.update(subscriber);
            }
            factory.commit();
            total++;

            if (total % 100 == 0) {
                long now = System.currentTimeMillis();
                double pref = ((double) total) / ((now - begin) / 1000.0);
                System.err.println(total + " records finished, performance: " + pref + "recs/sec");
            }

            // Get Next
            item = in.read();
        }

        in.close();
        System.out.println("Total records: " + total);
    } catch (Exception ex) {
        throw ex;
    } finally {
        if (factory != null) {
            factory.release();
        }
    }
}

From source file:com.ibm.bi.dml.runtime.matrix.MMCJMR.java

public static JobReturn runJob(MRJobInstruction inst, String[] inputs, InputInfo[] inputInfos, long[] rlens,
        long[] clens, int[] brlens, int[] bclens, String instructionsInMapper, String aggInstructionsInReducer,
        String aggBinInstrction, int numReducers, int replication, String output, OutputInfo outputinfo)
        throws Exception {
    JobConf job = new JobConf(MMCJMR.class);

    // TODO: check w/ yuanyuan. This job always runs in blocked mode, and hence derivation is not necessary.
    boolean inBlockRepresentation = MRJobConfiguration.deriveRepresentation(inputInfos);

    // by default, assume that dimensions of MMCJ's output are known at compile time
    byte resultDimsUnknown = (byte) 0;
    MatrixCharacteristics[] stats = commonSetup(job, inBlockRepresentation, inputs, inputInfos, rlens, clens,
            brlens, bclens, instructionsInMapper, aggInstructionsInReducer, aggBinInstrction, numReducers,
            replication, resultDimsUnknown, output, outputinfo);

    // Print the complete instruction
    if (LOG.isTraceEnabled())
        inst.printCompleteMRJobInstruction(stats);

    // Update resultDimsUnknown based on computed "stats"
    // There is always a single output
    if (stats[0].getRows() == -1 || stats[0].getCols() == -1) {
        resultDimsUnknown = (byte) 1;

        // if the dimensions are unknown, then setup done in commonSetup() must be updated
        byte[] resultIndexes = new byte[] {
                MRInstructionParser.parseSingleInstruction(aggBinInstrction).output };
        byte[] resultDimsUnknown_Array = new byte[] { resultDimsUnknown };
        //set up the multiple output files, and their format information
        MRJobConfiguration.setUpMultipleOutputs(job, resultIndexes, resultDimsUnknown_Array,
                new String[] { output }, new OutputInfo[] { outputinfo }, inBlockRepresentation);
    }//  w w  w  .  j a v  a 2  s  .  c o m

    AggregateBinaryInstruction ins = (AggregateBinaryInstruction) MRInstructionParser
            .parseSingleInstruction(aggBinInstrction);
    MatrixCharacteristics dim1 = MRJobConfiguration.getMatrixCharactristicsForBinAgg(job, ins.input1);
    MatrixCharacteristics dim2 = MRJobConfiguration.getMatrixCharactristicsForBinAgg(job, ins.input2);

    if (dim1.getRowsPerBlock() > dim1.getRows())
        dim1.setRowsPerBlock((int) dim1.getRows());
    if (dim1.getColsPerBlock() > dim1.getCols())
        dim1.setColsPerBlock((int) dim1.getCols());
    if (dim2.getRowsPerBlock() > dim2.getRows())
        dim2.setRowsPerBlock((int) dim2.getRows());
    if (dim2.getColsPerBlock() > dim2.getCols())
        dim2.setColsPerBlock((int) dim2.getCols());

    long blockSize1 = 77 + 8 * dim1.getRowsPerBlock() * dim1.getColsPerBlock();
    long blockSize2 = 77 + 8 * dim2.getRowsPerBlock() * dim2.getColsPerBlock();
    long blockSizeResult = 77 + 8 * dim1.getRowsPerBlock() * dim2.getColsPerBlock();

    long cacheSize = -1;
    //cache the first result
    if (dim1.getRows() < dim2.getCols()) {
        long numBlocks = (long) Math.ceil((double) dim1.getRows() / (double) dim1.getRowsPerBlock());
        cacheSize = numBlocks * (20 + blockSize1) + 32;
    } else //cache the second result
    {
        long numBlocks = (long) Math.ceil((double) dim2.getCols() / (double) dim2.getColsPerBlock());
        cacheSize = numBlocks * (20 + blockSize2) + 32;
    }
    //add known memory consumption (will be substracted from output buffer)
    cacheSize += 2 * Math.max(blockSize1, blockSize2) //the cached key-value pair  (plus input instance)
            + blockSizeResult //the cached single result
            + MRJobConfiguration.getMiscMemRequired(job); //misc memory requirement by hadoop
    MRJobConfiguration.setMMCJCacheSize(job, (int) cacheSize);

    //set unique working dir
    MRJobConfiguration.setUniqueWorkingDir(job);

    //run mmcj job
    RunningJob runjob = JobClient.runJob(job);

    /* Process different counters */

    // NOTE: MMCJ job always has only a single output. 
    // Hence, no need to scan resultIndexes[] like other jobs

    int outputIndex = 0;
    Byte outputMatrixID = MRInstructionParser.parseSingleInstruction(aggBinInstrction).output;

    Group group = runjob.getCounters().getGroup(MRJobConfiguration.NUM_NONZERO_CELLS);

    // number of non-zeros
    stats[outputIndex].setNonZeros(group.getCounter(Byte.toString(outputMatrixID)));

    return new JobReturn(stats[outputIndex], outputinfo, runjob.isSuccessful());
}

From source file:net.sf.morph.util.TestUtils.java

/**
 * Return a "not-same" instance.// w w w .ja  v  a  2s.c o  m
 * @param type
 * @param o
 * @return
 */
public static Object getDifferentInstance(Class type, Object o) {
    if (type == null) {
        throw new IllegalArgumentException("Non-null type must be specified");
    }
    if (type.isPrimitive()) {
        type = ClassUtils.getPrimitiveWrapper(type);
    }
    if (o != null && !type.isInstance(o)) {
        throw new IllegalArgumentException("Negative example object should be of type " + type);
    }
    if (type == Number.class) {
        type = Integer.class;
    }
    if (Number.class.isAssignableFrom(type)) {
        byte b = (byte) (o == null ? 0 : ((Number) o).byteValue() + 1);
        try {
            return type.getConstructor(ONE_STRING).newInstance(new Object[] { Byte.toString(b) });
        } catch (Exception e) {
            throw e instanceof RuntimeException ? (RuntimeException) e : new NestableRuntimeException(e);
        }
    }
    if (type == Character.class) {
        char c = (char) (o == null ? 0 : ((Character) o).charValue() + 1);
        return new Character(c);
    }
    if (type == Boolean.class) {
        return o != null && ((Boolean) o).booleanValue() ? Boolean.FALSE : Boolean.TRUE;
    }
    if (type.isArray()) {
        return Array.newInstance(type.getComponentType(), 0);
    }
    if (type == Class.class) {
        return o == Object.class ? Class.class : Object.class;
    }
    return ClassUtils.newInstance(convertCommonInterfaces(type));
}

From source file:de.hybris.platform.test.MediaTest.java

@Test
public void testGetData() throws Exception {
    Media somemedia = null;// ww w  .j  av a 2s  .com
    assertNotNull(somemedia = jaloSession.getMediaManager().createMedia("MediaData"));
    final byte[] data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    somemedia.setData(data);

    final byte[] readData = somemedia.getData();

    final StringBuilder dataBuffer = new StringBuilder("[");
    for (int i = 0; i < data.length; i++) {
        dataBuffer.append(Byte.toString(data[i]) + ",");
    }
    dataBuffer.append("]");
    final StringBuilder readBuffer = new StringBuilder("[");
    for (int i = 0; i < readData.length; i++) {
        readBuffer.append(Byte.toString(readData[i]) + ",");
    }
    readBuffer.append("]");
    assertTrue("Expected " + dataBuffer + " but got " + readBuffer, Arrays.equals(data, readData));
}

From source file:jp.terasoluna.fw.util.ConvertUtil.java

/**
 * <code>value</code>???????
 * ?<code>String</code>????<code>List</code>??
 * ?// w  w w.j  a  va  2 s.  c  o m
 * 
 * @param value ??
 * @return ??????????<code>List</code>
 *          ??????<code>value</code>????
 */
public static Object convertPrimitiveArrayToList(Object value) {
    if (value == null) {
        return value;
    }
    Class<?> type = value.getClass().getComponentType();

    // value???????
    if (type == null) {
        return value;
    }

    // ?????????
    if (!type.isPrimitive()) {
        return value;
    }

    List<Object> list = new ArrayList<Object>();

    if (value instanceof boolean[]) {
        for (boolean data : (boolean[]) value) {
            // String???????
            list.add(data);
        }
    } else if (value instanceof byte[]) {
        for (byte data : (byte[]) value) {
            list.add(Byte.toString(data));
        }
    } else if (value instanceof char[]) {
        for (char data : (char[]) value) {
            list.add(Character.toString(data));
        }
    } else if (value instanceof double[]) {
        for (double data : (double[]) value) {
            list.add(Double.toString(data));
        }
    } else if (value instanceof float[]) {
        for (float data : (float[]) value) {
            list.add(Float.toString(data));
        }
    } else if (value instanceof int[]) {
        for (int data : (int[]) value) {
            list.add(Integer.toString(data));
        }
    } else if (value instanceof long[]) {
        for (long data : (long[]) value) {
            list.add(Long.toString(data));
        }
    } else if (value instanceof short[]) {
        for (short data : (short[]) value) {
            list.add(Short.toString(data));
        }
    }
    return list;
}

From source file:org.jts.eclipse.conversion.cjsidl.ConversionUtil.java

/**
 * Used to fill a gap where a minimum value isn't specified in a range.
 * @param val - the current value, if there is one.
 * @param inputType - the input data type that the minimum should fit within
 * // w w w  .ja  v a 2 s .co m
 * @return - the original value if it exists, or the minimum value allowed within
 * the inputType specified.
 */
public static String getCountMin(String val, String inputType) {
    String result = val;
    if (result == null || result.isEmpty()) {
        if (inputType.equals("byte") || inputType.equals("int8")) {
            result = Byte.toString(Byte.MIN_VALUE);
        } else if (inputType.equals("short integer") || inputType.equals("int16")) {
            result = Short.toString(Short.MIN_VALUE);
        } else if (inputType.equals("integer") || inputType.equals("int32")) {
            result = Integer.toString(Integer.MIN_VALUE);
        } else if (inputType.equals("long integer") || inputType.equals("int64")) {
            result = Long.toString(Long.MIN_VALUE);
        } else if (inputType.equals("unsigned byte") || inputType.equals("uint8")) {
            result = "0";
        } else if (inputType.equals("unsigned short integer") || inputType.equals("uint16")) {
            result = "0";
        } else if (inputType.equals("unsigned integer") || inputType.equals("uint32")) {
            result = "0";
        } else if (inputType.equals("unsigned long integer") || inputType.equals("uint64")) {
            result = "0";
        } else if (inputType.equals("float") || inputType.equals("float")) {
            result = Float.toString(Float.MIN_VALUE);
        } else if (inputType.equals("long float") || inputType.equals("double")) {
            result = Double.toString(Double.MIN_VALUE);
        }
    }

    return result;
}

From source file:org.apache.giraph.debugger.mock.FormatHelper.java

/**
 * Generates a line constructing a byte array.
 * @param byteArray byte array to construct in the unit test.
 * @return string generating the line that constructs the given byte array.
 *///from w w w. ja  va2  s .c  om
private String toByteArrayString(byte[] byteArray) {
    StringBuilder strBuilder = new StringBuilder();
    for (int i = 0; i < byteArray.length; i++) {
        if (i != 0) {
            strBuilder.append(',');
        }
        strBuilder.append(Byte.toString(byteArray[i]));
    }
    return strBuilder.toString();
}

From source file:com.magnet.android.mms.request.GenericResponseParserPrimitiveTest.java

@SmallTest
public void testNumberResponse() throws MobileException, JSONException {
    GenericResponseParser<Integer> parser = new GenericResponseParser<Integer>(Integer.class);
    String response = Integer.toString(Integer.MIN_VALUE);

    Integer result = (Integer) parser.parseResponse(response.toString().getBytes());
    assertEquals(Integer.MIN_VALUE, result.intValue());

    Object nullresult = parser.parseResponse((byte[]) null);
    assertEquals(null, nullresult);//from  w w  w. ja v  a  2s. c  o  m

    long longvalue = new Random().nextLong();
    GenericResponseParser<Long> lparser = new GenericResponseParser<Long>(Long.class);
    long longresult = (Long) lparser.parseResponse(Long.toString(longvalue).getBytes());
    assertEquals(longvalue, longresult);

    short shortvalue = Short.MAX_VALUE;
    GenericResponseParser<Short> sparser = new GenericResponseParser<Short>(short.class);
    short shortresult = (Short) sparser.parseResponse(Short.toString(shortvalue).getBytes());
    assertEquals(shortvalue, shortresult);

    float floatvalue = new Random().nextFloat();
    GenericResponseParser<Float> fparser = new GenericResponseParser<Float>(Float.class);
    float floatresult = (Float) fparser.parseResponse(Float.toString(floatvalue).getBytes());
    assertEquals(String.valueOf(floatvalue), String.valueOf(floatresult));
    // use string as the value of the float

    double doublevalue = new Random().nextDouble();
    GenericResponseParser<Double> dparser = new GenericResponseParser<Double>(double.class);
    Double doubleresult = (Double) dparser.parseResponse(Double.toString(doublevalue).getBytes());
    assertEquals(String.valueOf(doublevalue), String.valueOf(doubleresult));

    byte bytevalue = Byte.MIN_VALUE + 10;
    GenericResponseParser<Byte> bparser = new GenericResponseParser<Byte>(Byte.class);
    Byte byteresult = (Byte) bparser.parseResponse(Byte.toString(bytevalue).getBytes());
    assertEquals(bytevalue, byteresult.byteValue());

}