Example usage for java.lang Byte Byte

List of usage examples for java.lang Byte Byte

Introduction

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

Prototype

@Deprecated(since = "9")
public Byte(String s) throws NumberFormatException 

Source Link

Document

Constructs a newly allocated Byte object that represents the byte value indicated by the String parameter.

Usage

From source file:com.tesora.dve.db.ValueConverter.java

public static List<Byte> toObject(byte[] in) {
    ArrayList<Byte> out = new ArrayList<Byte>();
    for (int i = 0; i < in.length; i++)
        out.add(new Byte(in[i]));
    return out;// w  w w  .j a v  a 2s.c  o m
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private HttpResponse handleResponse(Socket destinationSocket, BufferedOutputStream proxyClientStream)
        throws IOException {
    HttpResponse response = new HttpResponse();
    BufferedInputStream responseInputStream = new BufferedInputStream(destinationSocket.getInputStream());
    int readInt;/*from  w  ww .  j a va 2s  .  c om*/
    int length = -1;
    String previousLine;
    byte b = -1;
    boolean hasCompleted = false;
    ArrayList<Byte> list = new ArrayList<Byte>(10000);
    ArrayList<Byte> responseContentList = new ArrayList<Byte>(10000);
    boolean isContent = false;
    boolean hasChunkedEncoding = false;
    int lineNo = 0;
    int lastCRPos = 0;
    while (!isInterrupted && !hasCompleted && (readInt = responseInputStream.read()) != -1) {
        b = (byte) readInt;
        list.add(new Byte(b));
        if (isContent) {
            responseContentList.add(new Byte(b));
        }
        proxyClientStream.write(readInt);
        if (b == 13) {
            if (list.size() > 1) {
                // try to analyze the previous line
                byte[] bytes = new byte[list.size() - lastCRPos];
                for (int i = lastCRPos; i < list.size() - 1; i++) {
                    bytes[i - lastCRPos] = list.get(i).byteValue();
                }
                // requests are always in ASCII
                previousLine = new String(bytes, "ISO-8859-1");
                if (lineNo == 0) {
                    // we must have here s.th. like 
                    // HTTP/1.0 200 OK
                    String[] components = previousLine.split(" ");
                    if (components.length > 2) {
                        response.setStatusCode(Integer.parseInt(components[1]));
                        response.setHttpVersion(components[0]);
                    }
                }
                if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) {
                    String lengthStr = previousLine.substring(16, previousLine.length() - 1);
                    length = Integer.parseInt(lengthStr);
                }
                if (previousLine.matches("^[Tt]ransfer-[Ee]ncoding: [Cc]hunked.+")) {
                    hasChunkedEncoding = true;
                }
                //logger.debug("response: " + previousLine);
                // the CR should be ignored;
                lastCRPos = list.size() + 1;
                lineNo++;
            }
        }
        if (b == 10) {
            // check for two line breaks with form feed
            if (list.get(list.size() - 2).equals(new Byte((byte) 13))
                    && list.get(list.size() - 3).equals(new Byte((byte) 10))
                    && list.get(list.size() - 4).equals(new Byte((byte) 13))) {
                // section 4.3 of the http-spec states:
                // All responses to the HEAD request method
                // MUST NOT include a message-body, even though 
                // the presence of entity-header fields might lead
                // one to believe they do. All 1xx (informational),
                // 204 (no content), and 304 (not modified) responses
                // MUST NOT include a message-body. All other 
                // responses do include a message-body, although it 
                // MAY be of zero length.
                // (s. http://www.ietf.org/rfc/rfc2616.txt)
                if ("HEAD".equals(request.getMethod()) || response.getStatusCode() == 204
                        || response.getStatusCode() == 304
                        || (response.getStatusCode() > 99 && response.getStatusCode() < 200)) {
                    // no content allowed:
                    hasCompleted = true;
                } else if (length == 0) {
                    hasCompleted = true;
                } else if (length == -1) {
                    isContent = true;
                    if (hasChunkedEncoding) {
                        list.addAll(getAllChunks(responseInputStream, proxyClientStream));
                        hasCompleted = true;
                    }
                } else {
                    for (int i = 0; i < length; i++) {
                        readInt = responseInputStream.read();
                        b = (byte) readInt;
                        list.add(new Byte(b));
                        proxyClientStream.write(readInt);
                    }
                    hasCompleted = true;
                }
            }
        }
    }
    byte[] byteArray = getByteArrayFromList(list);
    //logger.debug("response: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray));

    response.setResponse(byteArray);

    return response;
}

From source file:ubic.basecode.util.FileToolsTest.java

@Test
public void testUnzipFile() throws Exception {
    zipped = File.createTempFile("test", ".zip");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipped));
    for (int i = 0; i < 3; i++) {
        out.putNextEntry(new ZipEntry("foo" + i));
        out.write((new Byte("34")).byteValue());
        out.closeEntry();//  w ww .j  a  v a 2  s  . c  o  m
    }
    out.close();
    Collection<File> result = FileTools.unZipFiles(zipped.getAbsolutePath());
    assertEquals(3, result.size());
}

From source file:Unsigned.java

/**
 * Parse a binary number into a Number object. If up to 8 bits are parsed,
 * returns a Byte. If more than 8 and up to 16 bits are parsed, return a
 * Short. If more than 16 and up to 32 bits are parsed, return an Integer.
 * If more than 32 and up to 64 bits are parsed, return a Long.
 * //from  w ww  . ja v a2s .  c  om
 * @param text
 *            a binary number
 * @param parsePosition
 *            position to start parsing from
 * @return return an integer form of Number object if parse is successful;
 *         <CODE>null</CODE> otherwise
 * 
 * @since 1.0
 */
public Number parse(String text, ParsePosition parsePosition) {
    boolean skipWhitespace = true;
    int startIndex, bits;

    // remove whitespace
    StringCharacterIterator iter = new StringCharacterIterator(text, parsePosition.getIndex());
    for (char c = iter.current(); c != CharacterIterator.DONE; c = iter.next()) {
        if (skipWhitespace && Character.isWhitespace(c)) {
            // skip whitespace
            continue;
        }
    }
    parsePosition.setIndex(iter.getIndex());

    startIndex = parsePosition.getIndex();
    Number result = (Number) parseObject(text, parsePosition);

    if (result == null) {
        return (result);
    }

    bits = parsePosition.getIndex() - startIndex;
    if (bits <= 8) {
        result = new Byte(result.byteValue());
    } else if (bits <= 16) {
        result = new Short(result.shortValue());
    } else if (bits <= 32) {
        result = new Integer(result.intValue());
    } else if (bits <= 64) {
        result = new Long(result.longValue());
    }
    return (result);
}

From source file:net.sf.jrf.domain.PersistentObjectDynaProperty.java

/** Gets default value.
 * @return default value.//from  ww  w .  j  a v  a 2  s .  c om
 */
public Object getDefaultValue() {
    if (defaultValue != null)
        return this.defaultValue;
    Class cls = getType();
    if (primitiveWrapperClass != null) {
        if (cls.equals(Boolean.TYPE))
            return new Boolean(false);
        else if (cls.equals(Byte.TYPE))
            return new Byte((byte) 0);
        else if (cls.equals(Character.TYPE))
            return new Character((char) 0);
        else if (cls.equals(Double.TYPE))
            return new Double((double) 0);
        else if (cls.equals(Float.TYPE))
            return new Float((float) 0);
        else if (cls.equals(Integer.TYPE))
            return new Integer((int) 0);
        else if (cls.equals(Long.TYPE))
            return new Long((long) 0);
        else if (cls.equals(Short.TYPE))
            return new Short((short) 0);
        else
            return null;
    } else
        return null;
}

From source file:com.examples.with.different.packagename.testcarver.NumberConverter.java

/**
 * Default String to Number conversion./*from w w w.java 2  s  .c o m*/
 * <p>
 * This method handles conversion from a String to the following types:
 * <ul>
 *     <li><code>java.lang.Byte</code></li>
 *     <li><code>java.lang.Short</code></li>
 *     <li><code>java.lang.Integer</code></li>
 *     <li><code>java.lang.Long</code></li>
 *     <li><code>java.lang.Float</code></li>
 *     <li><code>java.lang.Double</code></li>
 *     <li><code>java.math.BigDecimal</code></li>
 *     <li><code>java.math.BigInteger</code></li>
 * </ul>
 * @param sourceType The type being converted from
 * @param targetType The Number type to convert to
 * @param value The String value to convert.
 *
 * @return The converted Number value.
 */
private Number toNumber(Class sourceType, Class targetType, String value) {

    // Byte
    if (targetType.equals(Byte.class)) {
        return new Byte(value);
    }

    // Short
    if (targetType.equals(Short.class)) {
        return new Short(value);
    }

    // Integer
    if (targetType.equals(Integer.class)) {
        return new Integer(value);
    }

    // Long
    if (targetType.equals(Long.class)) {
        return new Long(value);
    }

    // Float
    if (targetType.equals(Float.class)) {
        return new Float(value);
    }

    // Double
    if (targetType.equals(Double.class)) {
        return new Double(value);
    }

    // BigDecimal
    if (targetType.equals(BigDecimal.class)) {
        return new BigDecimal(value);
    }

    // BigInteger
    if (targetType.equals(BigInteger.class)) {
        return new BigInteger(value);
    }

    String msg = toString(getClass()) + " cannot handle conversion from '" + toString(sourceType) + "' to '"
            + toString(targetType) + "'";
    throw new ConversionException(msg);
}

From source file:org.openmrs.module.sync.SyncUtil.java

public static Object valForField(String fieldName, String fieldVal, ArrayList<Field> allFields, Node n) {
    Object o = null;/*from   w  ww. ja v  a  2 s  .c om*/

    // the String value on the node specifying the "type"
    String nodeDefinedClassName = null;
    if (n != null) {
        Node tmpNode = n.getAttributes().getNamedItem("type");
        if (tmpNode != null)
            nodeDefinedClassName = tmpNode.getTextContent();
    }

    // TODO: Speed up sync by passing in a Map of String fieldNames instead of list of Fields ? 
    // TODO: Speed up sync by returning after "o" is first set?  Or are we doing "last field wins" ?
    for (Field f : allFields) {
        //log.debug("field is " + f.getName());
        if (f.getName().equals(fieldName)) {
            Class classType = null;
            String className = f.getGenericType().toString(); // the string class name for the actual field

            // if its a collection, set, list, etc
            if (ParameterizedType.class.isAssignableFrom(f.getGenericType().getClass())) {
                ParameterizedType pType = (ParameterizedType) f.getGenericType();
                classType = (Class) pType.getRawType(); // can this be anything but Class at this point?!
            }

            if (className.startsWith("class ")) {
                className = className.substring("class ".length());
                classType = (Class) f.getGenericType();
            } else {
                log.trace("Abnormal className for " + f.getGenericType());
            }

            if (classType == null) {
                if ("int".equals(className)) {
                    return new Integer(fieldVal);
                } else if ("long".equals(className)) {
                    return new Long(fieldVal);
                } else if ("double".equals(className)) {
                    return new Double(fieldVal);
                } else if ("float".equals(className)) {
                    return new Float(fieldVal);
                } else if ("boolean".equals(className)) {
                    return new Boolean(fieldVal);
                } else if ("byte".equals(className)) {
                    return new Byte(fieldVal);
                } else if ("short".equals(className)) {
                    return new Short(fieldVal);
                }
            }

            // we have to explicitly create a new value object here because all we have is a string - won't know how to convert
            if (OpenmrsObject.class.isAssignableFrom(classType)) {
                o = getOpenmrsObj(className, fieldVal);
            } else if ("java.lang.Integer".equals(className) && !("integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName))) {
                // if we're dealing with a field like PersonAttributeType.foreignKey, the actual value was changed from
                // an integer to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still an integer because thats what the db stores.  we need to convert the uuid to the pk integer and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                o = obj.getId();
            } else if ("java.lang.String".equals(className) && !("text".equals(nodeDefinedClassName)
                    || "string".equals(nodeDefinedClassName) || "java.lang.String".equals(nodeDefinedClassName)
                    || "integer".equals(nodeDefinedClassName)
                    || "java.lang.Integer".equals(nodeDefinedClassName) || fieldVal.isEmpty())) {
                // if we're dealing with a field like PersonAttribute.value, the actual value was changed from
                // a string to a uuid by the HibernateSyncInterceptor.  The nodeDefinedClassName is the node.type which is the 
                // actual classname as defined by the PersonAttributeType.format.  However, the field.getClassName is 
                // still String because thats what the db stores.  we need to convert the uuid to the pk integer/string and return it
                OpenmrsObject obj = getOpenmrsObj(nodeDefinedClassName, fieldVal);
                if (obj == null) {
                    if (StringUtils.hasText(fieldVal)) {
                        // If we make it here, and we are dealing with person attribute values, then just return the string value as-is
                        if (PersonAttribute.class.isAssignableFrom(f.getDeclaringClass())
                                && "value".equals(f.getName())) {
                            o = fieldVal;
                        } else {
                            // throw a warning if we're having trouble converting what should be a valid value
                            log.error("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                            throw new SyncException("Unable to convert value '" + fieldVal + "' into a "
                                    + nodeDefinedClassName);
                        }
                    } else {
                        // if fieldVal is empty, just save an empty string here too
                        o = "";
                    }
                } else {
                    o = obj.getId().toString(); // call toString so the class types match when looking up the setter
                }
            } else if (Collection.class.isAssignableFrom(classType)) {
                // this is a collection of items. this is intentionally not in the convertStringToObject method

                Collection tmpCollection = null;
                if (Set.class.isAssignableFrom(classType))
                    tmpCollection = new LinkedHashSet();
                else
                    tmpCollection = new Vector();

                // get the type of class held in the collection
                String collectionTypeClassName = null;
                java.lang.reflect.Type collectionType = ((java.lang.reflect.ParameterizedType) f
                        .getGenericType()).getActualTypeArguments()[0];
                if (collectionType.toString().startsWith("class "))
                    collectionTypeClassName = collectionType.toString().substring("class ".length());

                // get the type of class defined in the text node
                // if it is different, we could be dealing with something like Cohort.memberIds
                // node type comes through as java.util.Set<classname>
                String nodeDefinedCollectionType = null;
                int indexOfLT = nodeDefinedClassName.indexOf("<");
                if (indexOfLT > 0)
                    nodeDefinedCollectionType = nodeDefinedClassName.substring(indexOfLT + 1,
                            nodeDefinedClassName.length() - 1);

                // change the string to just a comma delimited list
                fieldVal = fieldVal.replaceFirst("\\[", "").replaceFirst("\\]", "");

                for (String eachFieldVal : fieldVal.split(",")) {
                    eachFieldVal = eachFieldVal.trim(); // take out whitespace
                    if (!StringUtils.hasText(eachFieldVal))
                        continue;
                    // try to convert to a simple object
                    Object tmpObject = convertStringToObject(eachFieldVal, (Class) collectionType);

                    // convert to an openmrs object
                    if (tmpObject == null && nodeDefinedCollectionType != null)
                        tmpObject = getOpenmrsObj(nodeDefinedCollectionType, eachFieldVal).getId();

                    if (tmpObject == null)
                        log.error("Unable to convert: " + eachFieldVal + " to a " + collectionTypeClassName);
                    else
                        tmpCollection.add(tmpObject);
                }

                o = tmpCollection;
            } else if (Map.class.isAssignableFrom(classType) || Properties.class.isAssignableFrom(classType)) {
                Object tmpMap = SyncUtil.getNormalizer(classType).fromString(classType, fieldVal);

                //if we were able to convert and got anything at all back, assign it
                if (tmpMap != null) {
                    o = tmpMap;
                }
            } else if ((o = convertStringToObject(fieldVal, classType)) != null) {
                log.trace("Converted " + fieldVal + " into " + classType.getName());
            } else {
                log.debug("Don't know how to deserialize class: " + className);
            }
        }
    }

    if (o == null)
        log.debug("Never found a property named: " + fieldName + " for this class");

    return o;
}

From source file:eionet.util.Util.java

/**
 * A method for creating a unique digest of a String message.
 *
 * @param src// ww  w  .j  ava  2  s  .c o m
 *            String to be digested.
 * @param algorithm
 *            Digesting algorithm (please see Java documentation for allowable values).
 * @return A unique String-typed digest of the input message.
 */
public static String digest(String src, String algorithm) throws GeneralSecurityException {

    byte[] srcBytes = src.getBytes();
    byte[] dstBytes = new byte[16];

    MessageDigest md = MessageDigest.getInstance(algorithm);
    md.update(srcBytes);
    dstBytes = md.digest();
    md.reset();

    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < dstBytes.length; i++) {
        Byte byteWrapper = new Byte(dstBytes[i]);
        buf.append(String.valueOf(byteWrapper.intValue()));
    }

    return buf.toString();
}

From source file:org.apache.nutch.crawl.MapWritable.java

private Class getClass(final byte id) throws IOException {
    Class clazz = ID_CLASS_MAP.get(new Byte(id));
    if (clazz == null) {
        ClassIdEntry entry = fIdFirst;/*from w  w w . jav a2s .  c o  m*/
        while (entry != null) {
            if (entry.fId == id) {
                return entry.fclazz;
            }

            entry = entry.fNextIdEntry;
        }
    } else {
        return clazz;
    }
    throw new IOException("unable to load class for id: " + id);
}

From source file:com.tc.object.ApplicatorDNAEncodingTest.java

public void testBasic() throws Exception {
    final TCByteBufferOutputStream output = new TCByteBufferOutputStream();

    final List<Object> data = new ArrayList<Object>();
    data.add(new ObjectID(1));
    data.add("one");
    data.add(new Boolean(true));
    data.add("two");
    data.add(new Byte((byte) 42));
    data.add("three");
    data.add(new Character('\t'));
    data.add("four");
    data.add(new Double(Math.PI));
    data.add("five");
    data.add(new Float(Math.E));
    data.add("six");
    data.add(new Integer(Integer.MAX_VALUE));
    data.add("seven");
    data.add(new Long(System.currentTimeMillis() % 17));
    data.add("eight");
    data.add(new Short((short) -1));

    final DNAEncoding encoding = getApplicatorEncoding();
    for (Object d : data) {
        encoding.encode(d, output);//from  w w  w .ja  va  2 s.  c  o  m
    }

    final TCByteBufferInputStream input = new TCByteBufferInputStream(output.toArray());
    for (Object orig : data) {
        final Object decoded = encoding.decode(input);

        assertEquals(orig, decoded);
    }

    assertEquals(0, input.available());
}