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:Main.java

/**
 * <p>Converts an array of primitive bytes to objects.</p>
 *
 * <p>This method returns <code>null</code> for a <code>null</code> input array.</p>
 *
 * @param array  a <code>byte</code> array
 * @return a <code>Byte</code> array, <code>null</code> if null array input
 *//*from   w w w.j  ava2 s.  c  o m*/
public static Byte[] toObject(byte[] array) {
    if (array == null) {
        return null;
    } else if (array.length == 0) {
        return EMPTY_BYTE_OBJECT_ARRAY;
    }
    final Byte[] result = new Byte[array.length];
    for (int i = 0; i < array.length; i++) {
        result[i] = new Byte(array[i]);
    }
    return result;
}

From source file:cienciaCelularMR.FernetMapper.java

@Override
public void map(KeyMcell key, Text value, Context output) throws IOException, InterruptedException {
    try {/*from ww w  .  ja  v a 2  s. c o  m*/

        System.out.println("Entro al Map");
        System.out.println("Key del map fernet: " + key.toString());

        System.out.println("Fernet empezo a leer y guardar archivo .dat");
        try (FSDataInputStream fis = FileSystem.get(output.getConfiguration())
                .open(new Path(value.toString()))) {
            File archivo = new File("entradaFernet.dat");
            try (FileOutputStream fos = new FileOutputStream(archivo)) {
                byte[] buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = fis.read(buf)) > 0) {
                    fos.write(buf, 0, bytesRead);
                    fos.flush();
                    output.progress();
                }
                fos.close();
                fis.close();
            }
        }

        System.out.println("Fernet termino de leer y guardar archivo .dat");
        Process process = new ProcessBuilder("fernet.exe", "--mode=" + key.getModoFernet().toString(),
                "--config=fernet.cfg", "entradaFernet.dat").start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        System.out.println("Fernet is running");
        System.out.println("La key de mapper fernet es: " + key);
        String res = "";
        while ((line = br.readLine()) != null) {
            res = res.concat(line);
            output.progress();
        }

        if ("point".equals(key.getModoFernet().toString())) {
            System.out.println("Fernet es point");
            String salidaName = "salidaFernet-" + key.getIdUsuario() + "." + key.getSubIdUsuario() + ".txt";
            FSDataOutputStream fs = FileSystem.get(output.getConfiguration()).create(new Path(salidaName));

            File salidaFile = new File("out_point.txt");
            if (salidaFile.exists()) {

                byte[] buffer = readFileToByteArray(new File("out_point.txt"));
                FernetOutput salida = new FernetOutput();
                salida.setFileName(new Text("out_point.txt"));
                salida.setSubId(key.getIdUsuario());
                salida.setValue(new BytesWritable(buffer));
                output.write(key, salida);
            }
        } else {
            File dir = new File(".");
            FileFilter fileFilter = new WildcardFileFilter("multi_*.txt");
            File[] files = dir.listFiles(fileFilter);
            for (File file : files) {
                byte[] buffer = readFileToByteArray(new File(file.getName()));
                FernetOutput salida = new FernetOutput();
                salida.setFileName(new Text(file.getName()));
                salida.setSubId(key.getIdUsuario());
                salida.setValue(new BytesWritable(buffer));
                output.write(key, salida);
            }
        }

    } catch (Exception ex) {
        String salidaName = "errorMapper-" + key.getIdUsuario() + "." + key.getSubIdUsuario() + ".txt";
        FSDataOutputStream fs = FileSystem.get(output.getConfiguration()).create(new Path(salidaName));
        fs.write(new Byte("Error en Mapper FERnet"));
        fs.write(new Byte("\n"));
        fs.flush();
        fs.close();

        Logger.getLogger(FernetMapper.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }
}

From source file:org.opendaylight.openflowplugin.outputtest.OutputTestCommandProvider.java

public void _sendPacketOutputMsg(CommandInterpreter ci) {
    /* Sending package OUT with action */
    LOG.debug("SendOutMsgWithAction");
    if (sessionInitiated) {
        String inNodeKey = ci.nextArgument();
        String inPort = ci.nextArgument();
        String outPort = "0xfffffffd";

        ArrayList<Byte> _arrayList = new ArrayList<Byte>(40);
        ArrayList<Byte> list = _arrayList;
        String _string = new String("sendOutputMsg_TEST");
        byte[] msg = _string.getBytes();
        int index = 0;
        for (final byte b : msg) {
            {//from  w  w  w  .jav a  2 s  .  com
                list.add(Byte.valueOf(b));
                boolean _lessThan = (index < 7);
                if (_lessThan) {
                    int _plus = (index + 1);
                    index = _plus;
                } else {
                    index = 0;
                }
            }
        }
        boolean _lessThan = (index < 8);
        boolean _while = _lessThan;
        while (_while) {
            {
                Byte _byte = new Byte("0");
                list.add(_byte);
                int _plus = (index + 1);
                index = _plus;
            }
            boolean _lessThan_1 = (index < 8);
            _while = _lessThan_1;
        }
        NodeRef ref = OutputTestUtil.createNodeRef(inNodeKey);

        TransmitPacketInputBuilder packet_out = new TransmitPacketInputBuilder();

        NodeConnectorRef _createNodeConnRef_1 = OutputTestUtil.createNodeConnRef(inNodeKey, inPort);
        NodeConnectorRef _nodeConnectorRef_1 = new NodeConnectorRef(_createNodeConnRef_1);
        NodeConnectorRef nIngressConRef = _nodeConnectorRef_1;

        NodeConnectorRef _createNodeConnRef_2 = OutputTestUtil.createNodeConnRef(inNodeKey, outPort);
        NodeConnectorRef _nodeConnectorRef_2 = new NodeConnectorRef(_createNodeConnRef_2);
        NodeConnectorRef nEngressConRef = _nodeConnectorRef_2;

        final ArrayList<Byte> _converted_list = list;
        byte[] _primitive = ArrayUtils
                .toPrimitive(((Byte[]) Conversions.unwrapArray(_converted_list, Byte.class)));

        List<Action> actionList = new ArrayList<Action>();
        ActionBuilder ab = new ActionBuilder();

        OutputActionBuilder output = new OutputActionBuilder();
        output.setMaxLength(new Integer(0xffff));
        Uri value = new Uri(OutputPortValues.CONTROLLER.toString());
        output.setOutputNodeConnector(value);
        ab.setAction(new OutputActionCaseBuilder().setOutputAction(output.build()).build());
        ab.setOrder(0);
        ab.setKey(new ActionKey(0));
        actionList.add(ab.build());

        packet_out.setCookie(null);
        packet_out.setAction(actionList);
        packet_out.setPayload(_primitive);
        packet_out.setNode(ref);
        packet_out.setIngress(nIngressConRef);
        packet_out.setEgress(nEngressConRef);
        packet_out.setBufferId(new Long(0xffffffffL));

        packetProcessingService.transmitPacket(packet_out.build());
    } else {
        ci.println("Session not initiated, try again in a few seconds");
    }
}

From source file:pl.exsio.frameset.vaadin.module.util.usergen.UserGenModule.java

private void generateUsers(Form form) {

    OptionGroup groups = (OptionGroup) form.getField("groups");
    Set<Group> groupsSet = getGroupsSet(groups);
    Set<Role> rolesSet = getRolesSet(form);
    String usernamePrefix = (String) form.getField("usernamePrefix").getValue();
    String usernameSuffix = (String) form.getField("usernameSuffix").getValue();
    Long from = Long.parseLong((String) form.getField("from").getValue());
    Long to = Long.parseLong((String) form.getField("to").getValue());

    Table csvTable = createCsvTable();/*from   w ww . j  a v a 2s.co m*/

    for (int i = from.intValue(); i < to.intValue(); i++) {
        String username = usernamePrefix + i + "@" + usernameSuffix;
        byte[] byteArray = KeyGenerators.secureRandom(2).generateKey();
        String passwordSuffix = "";
        for (byte b : byteArray) {
            passwordSuffix += new Byte(b).toString();
        }
        String password = usernamePrefix + passwordSuffix;
        User user = this.securityEntities.newUser();
        user.setUsername(username);
        user.setPassword(this.encoder.encode(password));
        user.setEmail(username);
        user.setEnabled(true);
        user.setGroups(groupsSet);
        user.setRoles(rolesSet);

        Item item = csvTable.addItem(username);
        item.getItemProperty("username").setValue(username);
        try {
            this.securityRepositories.getUserRepository().save(user);
            item.getItemProperty("password").setValue(password);
        } catch (DataIntegrityViolationException ex) {
            item.getItemProperty("password").setValue(t("username_exists"));
        }
    }

    CSVExporter exporter = createCsvExporter(csvTable);
    this.addComponent(exporter);
    Notification.show(t("generation_completed"));
}

From source file:org.springframework.jdbc.core.AbstractBeanPropertyRowMapper.java

protected Object doMapRow(ResultSet rs, int rowNumber) throws SQLException {
    if (getMappedClass() == null)
        throw new InvalidDataAccessApiUsageException("Target class was not specified - it is mandatory");
    Object result;//w w  w.j a v  a2  s .co  m
    try {
        result = this.defaultConstruct.newInstance((Object[]) null);
    } catch (IllegalAccessException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InvocationTargetException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    } catch (InstantiationException e) {
        throw new DataAccessResourceFailureException("Failed to load class " + this.mappedClass.getName(), e);
    }
    ResultSetMetaData rsmd = rs.getMetaData();
    int columns = rsmd.getColumnCount();
    for (int i = 1; i <= columns; i++) {
        String column = JdbcUtils.lookupColumnName(rsmd, i).toLowerCase();
        PersistentField fieldMeta = (PersistentField) this.mappedFields.get(column);
        if (fieldMeta != null) {
            BeanWrapper bw = new BeanWrapperImpl(mappedClass);
            bw.setWrappedInstance(result);
            fieldMeta.setSqlType(rsmd.getColumnType(i));
            Object value = null;
            Class fieldType = fieldMeta.getJavaType();
            if (fieldType.equals(String.class)) {
                value = rs.getString(column);
            } else if (fieldType.equals(byte.class) || fieldType.equals(Byte.class)) {
                value = new Byte(rs.getByte(column));
            } else if (fieldType.equals(short.class) || fieldType.equals(Short.class)) {
                value = new Short(rs.getShort(column));
            } else if (fieldType.equals(int.class) || fieldType.equals(Integer.class)) {
                value = new Integer(rs.getInt(column));
            } else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) {
                value = new Long(rs.getLong(column));
            } else if (fieldType.equals(float.class) || fieldType.equals(Float.class)) {
                value = new Float(rs.getFloat(column));
            } else if (fieldType.equals(double.class) || fieldType.equals(Double.class)) {
                value = new Double(rs.getDouble(column));
            } else if (fieldType.equals(BigDecimal.class)) {
                value = rs.getBigDecimal(column);
            } else if (fieldType.equals(boolean.class) || fieldType.equals(Boolean.class)) {
                value = (rs.getBoolean(column)) ? Boolean.TRUE : Boolean.FALSE;
            } else if (fieldType.equals(java.util.Date.class) || fieldType.equals(java.sql.Timestamp.class)
                    || fieldType.equals(java.sql.Time.class) || fieldType.equals(Number.class)) {
                value = JdbcUtils.getResultSetValue(rs, rs.findColumn(column));
            }
            if (value != null) {
                if (bw.isWritableProperty(fieldMeta.getFieldName())) {
                    try {
                        if (logger.isDebugEnabled() && rowNumber == 0) {
                            logger.debug("Mapping column named \"" + column + "\""
                                    + " containing values of SQL type " + fieldMeta.getSqlType()
                                    + " to property \"" + fieldMeta.getFieldName() + "\"" + " of type "
                                    + fieldMeta.getJavaType());
                        }
                        bw.setPropertyValue(fieldMeta.getFieldName(), value);
                    } catch (NotWritablePropertyException ex) {
                        throw new DataRetrievalFailureException(
                                "Unable to map column " + column + " to property " + fieldMeta.getFieldName(),
                                ex);
                    }
                } else {
                    if (rowNumber == 0) {
                        logger.warn("Unable to access the setter for " + fieldMeta.getFieldName()
                                + ".  Check that " + "set" + StringUtils.capitalize(fieldMeta.getFieldName())
                                + " is declared and has public access.");
                    }
                }
            }
        }
    }
    return result;
}

From source file:mx.edu.um.mateo.general.web.EmpresaControllerTest.java

@Test
public void debieraCrearEmpresa() throws Exception {
    Organizacion organizacion = new Organizacion("TEST01", "TEST01", "TEST01");
    currentSession().save(organizacion);
    EjercicioPK ejercicioPK = new EjercicioPK("TEST", organizacion);
    Byte x = new Byte("0");
    Ejercicio ejercicio = new Ejercicio(ejercicioPK, "TEST", "A", StringUtils.EMPTY, StringUtils.EMPTY,
            StringUtils.EMPTY, StringUtils.EMPTY, x, x);
    currentSession().save(ejercicio);/*from   w ww. j a  v a 2  s .  co  m*/
    Empresa otraEmpresa = new Empresa("tst-01", "test-01", "test-01", "000000000001", organizacion);
    currentSession().save(otraEmpresa);
    Almacen almacen = new Almacen("TST", "TEST01", otraEmpresa);
    currentSession().save(almacen);
    Rol rol = new Rol("ROLE_TEST");
    currentSession().save(rol);
    Set<Rol> roles = new HashSet<>();
    roles.add(rol);
    Usuario usuario = new Usuario("bugs@um.edu.mx", "apPaterno", "apMaterno", "TEST-01", "TEST-01");
    usuario.setEmpresa(otraEmpresa);
    usuario.setAlmacen(almacen);
    usuario.setRoles(roles);
    usuario.setEjercicio(ejercicio);
    currentSession().save(usuario);

    this.authenticate(usuario, usuario.getPassword(), new ArrayList<>(usuario.getAuthorities()));

    this.mockMvc
            .perform(post("/admin/empresa/crea").param("codigo", "tst-02").param("nombre", "TEST--02")
                    .param("nombreCompleto", "TEST--02").param("rfc", "000000000001"))
            .andExpect(status().isOk()).andExpect(flash().attributeExists("message"))
            .andExpect(flash().attribute("message", "empresa.creada.message"));
}

From source file:com.igorbaiborodine.example.mybatis.customer.TestCustomerService.java

private Customer createCustomer(int random_) {

    Customer customer = new Customer();
    String firstName = "FIRST_NAME_ANT_" + random_;
    String lastName = "LAST_NAME_ANT_" + random_;

    customer.setFirstName(firstName);/*w  ww . ja  va  2s . c o m*/
    customer.setLastName(lastName);
    customer.setEmail(random_ + "_test.service@sakilacustomer.org");
    customer.setStoreId(new Byte("1"));
    customer.setActive(true);
    customer.setCreateDate(new Date());

    return customer;
}

From source file:com.judoscript.jamaica.MyUtils.java

public static Object value2object(Object val, String typeHint) {
    if (typeHint == null)
        return val;

    if (typeHint.equals("boolean") || val instanceof Boolean)
        return val; // leave type check to caller.

    double v;//  w  ww.  j av a 2 s. co m
    if (val instanceof Character)
        v = ((Character) val).charValue();
    else if (val instanceof Number)
        v = ((Number) val).doubleValue();
    else
        return val; // leave type check to caller.

    if (typeHint.equals("int"))
        return new Integer((int) v);
    if (typeHint.equals("long"))
        return new Long((long) v);
    if (typeHint.equals("short"))
        return new Short((short) v);
    if (typeHint.equals("char"))
        return new Character((char) v);
    if (typeHint.equals("byte"))
        return new Byte((byte) v);
    if (typeHint.equals("float"))
        return new Float((float) v);
    //  if (typeHint.equals("double"))
    return new Double(v);
}

From source file:org.jboss.dashboard.factory.PropertyChangeProcessingInstruction.java

protected Object getNewInstanceForClass(Class expectedClass) {
    log.debug("Creating 'empty' class of type " + expectedClass);
    Object object = null;//from w  w  w . j  av  a 2  s  .  com
    if (expectedClass.isArray()) {
        Class componentClass = expectedClass.getComponentType();
        if (componentClass.isPrimitive()) {
            if (componentClass.equals(int.class))
                object = new int[0];
            else if (componentClass.equals(boolean.class))
                object = new boolean[0];
            else if (componentClass.equals(long.class))
                object = new long[0];
            else if (componentClass.equals(char.class))
                object = new char[0];
            else if (componentClass.equals(double.class))
                object = new double[0];
            else if (componentClass.equals(float.class))
                object = new float[0];
            else if (componentClass.equals(byte.class))
                object = new byte[0];
            else if (componentClass.equals(short.class))
                object = new short[0];
        } else if (String.class.equals(componentClass)) //Array of Strings
            object = new String[0];
        else if (componentClass.equals(Integer.class))
            object = new Integer[0];
        else if (componentClass.equals(Boolean.class))
            object = new Boolean[0];
        else if (componentClass.equals(Long.class))
            object = new Long[0];
        else if (componentClass.equals(Character.class))
            object = new Character[0];
        else if (componentClass.equals(Double.class))
            object = new Double[0];
        else if (componentClass.equals(Float.class))
            object = new Float[0];
        else if (componentClass.equals(Byte.class))
            object = new Byte[0];
        else if (componentClass.equals(Short.class))
            object = new Short[0];
        else { //It will be an array of components
            object = Array.newInstance(componentClass, 0);
        }
    } else {
        if (String.class.equals(expectedClass))
            object = "";
        else if (expectedClass.equals(int.class))
            object = new Integer(0);
        else if (expectedClass.equals(boolean.class))
            object = new Boolean(false);
        else if (expectedClass.equals(long.class))
            object = new Long(0);
        else if (expectedClass.equals(char.class))
            object = new Character((char) 0);
        else if (expectedClass.equals(double.class))
            object = new Double(0);
        else if (expectedClass.equals(float.class))
            object = new Float(0);
        else if (expectedClass.equals(byte.class))
            object = new Byte((byte) 0);
        else if (expectedClass.equals(short.class))
            object = new Short((short) 0);
        else if (expectedClass.equals(Integer.class))
            object = new Integer(0);
        else if (expectedClass.equals(Boolean.class))
            object = new Boolean(false);
        else if (expectedClass.equals(Long.class))
            object = new Long(0);
        else if (expectedClass.equals(Character.class))
            object = new Character((char) 0);
        else if (expectedClass.equals(Double.class))
            object = new Double(0);
        else if (expectedClass.equals(Float.class))
            object = new Float(0);
        else if (expectedClass.equals(Byte.class))
            object = new Byte((byte) 0);
        else if (expectedClass.equals(Short.class))
            object = new Short((short) 0);
        else { //It will be a component
            object = null;
        }
    }
    return object;
}

From source file:com.google.gsa.valve.saml.SAMLArtifactProcessor.java

/**
 * Generate a random Hex for creating the artifact
 * //from   w  ww.  java  2  s.  co  m
 * @param size artifact size
 * 
 * @return random number
 */
public static String createRandomHexString(int size) {
    byte[] bytes = new byte[size];
    randomGenerator.nextBytes(bytes);
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (int i = 0; i < bytes.length; i++) {
        Byte aByte = new Byte(bytes[i]);
        int intVal = Math.abs(aByte.intValue());
        sb.append(Integer.toHexString(intVal));
    }
    return sb.toString();
}