Example usage for org.apache.commons.codec.binary Hex encodeHex

List of usage examples for org.apache.commons.codec.binary Hex encodeHex

Introduction

In this page you can find the example usage for org.apache.commons.codec.binary Hex encodeHex.

Prototype

public static char[] encodeHex(byte[] data) 

Source Link

Document

Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.

Usage

From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.dta.DTAFileReaderSpi.java

@Override
public boolean canDecodeInput(BufferedInputStream stream) throws IOException {
    if (stream == null) {
        throw new IllegalArgumentException("stream == null!");
    }//from  w w w  .j av a  2s.  c om

    dbgLog.fine("applying the dta test\n");

    byte[] b = new byte[DTA_HEADER_SIZE];

    if (stream.markSupported()) {
        stream.mark(0);
    }
    int nbytes = stream.read(b, 0, DTA_HEADER_SIZE);

    if (nbytes == 0) {
        throw new IOException();
    }
    //printHexDump(b, "hex dump of the byte-array");

    if (stream.markSupported()) {
        stream.reset();
    }

    boolean DEBUG = false;

    dbgLog.info("hex dump: 1st 4bytes =>" + new String(Hex.encodeHex(b)) + "<-");

    if (b[2] != 1) {
        dbgLog.fine("3rd byte is not 1: given file is not stata-dta type");
        return false;
    } else if ((b[1] != 1) && (b[1] != 2)) {
        dbgLog.fine("2nd byte is neither 0 nor 1: this file is not stata-dta type");
        return false;
    } else if (!DTAFileReaderSpi.stataReleaseNumber.containsKey(b[0])) {
        dbgLog.fine("1st byte (" + b[0] + ") is not within the ingestable range [rel. 3-10]:"
                + "this file is NOT stata-dta type");
        return false;
    } else {
        dbgLog.fine("this file is stata-dta type: " + DTAFileReaderSpi.stataReleaseNumber.get(b[0])
                + "(No in HEX=" + b[0] + ")");
        return true;
    }

}

From source file:at.diamonddogs.net.WebClient.java

private void saveData(InputStream i) throws IOException {
    if (i == null) {
        return;//from ww w  . ja v  a2  s . co m
    }
    TempFile tmp = webRequest.getTmpFile().second;
    FileOutputStream fos = null;
    try {

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(i, md);

        File file = new File(tmp.getPath());
        Log.d(TAG, file.getAbsolutePath() + "can write: " + file.canWrite());
        if (file.exists() && !tmp.isAppend()) {
            file.delete();
        }
        byte buffer[] = new byte[READ_BUFFER_SIZE];
        fos = new FileOutputStream(file, tmp.isAppend());
        int bytesRead = 0;
        while ((bytesRead = dis.read(buffer)) != -1) {
            if (!webRequest.isCancelled()) {
                fos.write(buffer, 0, bytesRead);
                publishDownloadProgress(bytesRead);
            } else {
                Log.i(TAG, "Cancelled Download");
                break;
            }
        }
        fos.flush();
        fos.close();

        if (webRequest.isCancelled()) {
            Log.i(TAG, "delete file due to canclled download: " + file.getName());
            file.delete();
        } else {

            if (tmp.isUseChecksum()) {
                String md5 = new String(Hex.encodeHex(md.digest()));

                Log.d(TAG, "md5 check, original: " + tmp.getChecksum() + " file: " + md5);

                if (!md5.equalsIgnoreCase(tmp.getChecksum())) {
                    throw new IOException("Error while downloading File.\nOriginal Checksum: "
                            + tmp.getChecksum() + "\nChecksum: " + md5);
                }
            }
        }

    } catch (Exception e) {
        if (fos != null && tmp.isAppend()) {
            fos.flush();
            fos.close();
        }
        Log.e(TAG, "Failed download", e);
        // Please do not do that - that hides the original error!
        throw new IOException(e.getMessage());

        // Who ever changed this... new IOException(e) is API level 9!!! and
        // gives a nice NoSuchMethodException :)
        // throw new IOException(e);
    }
}

From source file:com.persistent.cloudninja.scheduler.TenantCreationTask.java

/**
 * This method returns the SHA-1 encoded HexPassword
 * //from  w w w . java  2 s  . c  o  m
 * @param password
 *            the plain text password
 * @return hexpassword The SHA-1 encoded Hex password.
 */
private String getSHA1hexPassword(String password) {

    String hexPassword = "";

    if (password != null && password.length() > 0) {

        try {
            MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
            sha1Digest.update(password.getBytes());
            hexPassword = new String(Hex.encodeHex(sha1Digest.digest())).toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }
    return hexPassword;
}

From source file:edu.psu.citeseerx.utility.FileDigest.java

/**
 * Informs if the MD5 file digest is equals to a given digest
 * @param digest    digest  a <code>byte[]</code> that represents a file digest
 * @param filePath   Parent abstract pathname
 * @param fileName   Child path name//from   w w  w  .j a  va2  s  . c  o m
 * @return true if the MD5 file digest is equals to digest
 */
public static boolean validateMD5(byte[] digest, String filePath, String fileName) {
    String fileDigest = new String(Hex.encodeHex(digest));
    return validateMD5(fileDigest, new File(filePath, fileName));
}

From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java

@Override
protected boolean execute() {

    log.debug("SocketTextSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    /* Get a connection to the instrument */
    SocketChannel socket = getSocketConnection();
    if (socket == null)
        return false;

    // while data are being sent, read them into the buffer
    try {/*  w  ww. j  a v a  2  s.com*/
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // while there are bytes to read from the socket ...
        while (socket.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();

                // log the byte stream
                String character = new String(new byte[] { byteOne });
                if (log.isDebugEnabled()) {
                    List<Byte> whitespaceBytes = new ArrayList<Byte>();
                    whitespaceBytes.add(new Byte((byte) 0x0A));
                    whitespaceBytes.add(new Byte((byte) 0x0D));
                    if (whitespaceBytes.contains(new Byte(byteOne))) {
                        character = new String(Hex.encodeHex((new byte[] { byteOne })));

                    }
                }
                log.debug("char: " + character + "\t" + "b1: "
                        + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state);

                // evaluate each byte to find the record delimiter(s), and when found, validate and
                // send the sample to the DataTurbine.
                int numberOfChannelsFlushed = 0;

                if (getRecordDelimiters().length == 2) {
                    // have we hit the delimiters in the stream yet?
                    if (byteTwo == getFirstDelimiterByte() && byteOne == getSecondDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        log.debug("Sample byte count: " + sampleByteCount);
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } else if (getRecordDelimiters().length == 1) {
                    // have we hit the delimiter in the stream yet?
                    if (byteOne == getFirstDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } // end getRecordDelimiters().length

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more socket bytes to read)
        socket.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        log.error("There was a communication error in sending the data sample. The message was: "
                + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        return !failed;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        failed = true;
        log.error("There was an RBNB error while sending the data sample. The message was: "
                + sapie.getMessage());
        if (log.isDebugEnabled()) {
            sapie.printStackTrace();
        }
        return !failed;
    }

    return !failed;

}

From source file:net.padlocksoftware.padlock.license.LicenseImpl.java

private String convertInterfaceBytesToString(byte[] interfaceBytes) {
    return new String(Hex.encodeHex(interfaceBytes));
}

From source file:edu.utsa.sifter.IndexResource.java

@Path("index")
@POST//from  w  ww  . ja  va  2s.c o  m
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public IndexInfo openIndex(IndexInfo idx) {
    if (idx.Id == null) {
        idx.Id = new String(Hex.encodeHex(Hasher.digest(idx.Path.getBytes())));
    }
    idx.Id = idx.Id.toLowerCase();

    IndexReader rdr = State.Indices.get(idx.Id);
    if (rdr == null) {
        try {
            final File evPath = new File(idx.Path);
            final File primaryIdx = new File(evPath, "primary-idx");
            final File somIdx = new File(evPath, "som-idx");
            DirectoryReader parallel[] = new DirectoryReader[2];
            parallel[0] = DirectoryReader.open(FSDirectory.open(primaryIdx));
            parallel[1] = DirectoryReader.open(FSDirectory.open(somIdx));

            rdr = new ParallelCompositeReader(parallel);
        } catch (IOException ex) {
            HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    if (rdr != null) {
        idx.NumDocs = rdr.numDocs();

        State.Indices.put(idx.Id, rdr);
        State.IndexLocations.put(idx.Id, idx);
    }
    return idx;
}

From source file:com.cyclopsgroup.waterview.utils.TagSupportBase.java

/**
 * Get internal tag id/*from  ww w.  j a  v  a  2s  .c o m*/
 *
 * @return Tag id
 * @throws Exception
 */
public synchronized String getUniqueTagId() throws Exception {
    if (StringUtils.isNotEmpty(uniqueTagId)) {
        return uniqueTagId;
    }
    if (StringUtils.isEmpty(getTagId())) {
        throw new IllegalArgumentException("tagId attribute is required for " + this + " to get unique ID");
    }
    StringBuffer s = new StringBuffer(getTagId()).append('@');
    URL[] scriptResources = getScriptResources();
    for (int i = 0; i < scriptResources.length; i++) {
        URL resource = scriptResources[i];
        s.append("->").append(resource);
    }
    MessageDigest digest = MessageDigest.getInstance(DIGEST_ALGORITHM);
    String d = new String(Hex.encodeHex(digest.digest(s.toString().getBytes())));
    uniqueTagId = getTagId() + d;
    return uniqueTagId;
}

From source file:com.jpeterson.util.etag.FileETagTest.java

/**
 * Test the calculate method when using both file last modified and file
 * size values./*from w  w w .  j  av a2s.c o  m*/
 */
public void test_calculateLastModifiedAndSize() {
    File file;
    String content = "Hello, world!";
    String expected;
    FileETag etag;

    try {
        // create temporary file
        file = File.createTempFile("temp", "txt");

        // make sure that it gets cleaned up
        file.deleteOnExit();

        // put some date in the file
        FileOutputStream out = new FileOutputStream(file);
        out.write(content.getBytes());
        out.flush();
        out.close();

        // manipulate the last modified value to a "known" value
        SimpleDateFormat date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        long lastModified = date.parse("06/21/2007 11:19:36").getTime();
        file.setLastModified(lastModified);

        // determined expected
        StringBuffer buffer = new StringBuffer();
        buffer.append(lastModified);
        buffer.append(content.length());
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        expected = new String(Hex.encodeHex(messageDigest.digest(buffer.toString().getBytes())));

        etag = new FileETag();
        etag.setFlags(FileETag.FLAG_MTIME | FileETag.FLAG_SIZE);
        String value = etag.calculate(file);

        assertEquals("Unexpected value", expected, value);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        fail("Unexpected exception");
    }
}

From source file:ca.sqlpower.wabit.swingui.enterprise.UserPanel.java

public UserPanel(User baseUser) {
    final MessageDigest digester;
    try {/*w  ww . ja v a 2  s . co m*/
        digester = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e1) {
        throw new RuntimeException(e1);
    }
    this.user = baseUser;
    this.workspace = (WabitWorkspace) this.user.getParent();

    this.loginTextField = new JTextField();
    this.loginTextField.setText(user.getName());
    this.loginLabel = new JLabel("User name");
    this.loginTextField.getDocument().addDocumentListener(new DocumentListener() {

        public void textChanged(DocumentEvent e) {
            user.setName(loginTextField.getText());
        }

        public void changedUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void insertUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void removeUpdate(DocumentEvent e) {
            textChanged(e);
        }
    });

    this.passwordTextField = new JPasswordField();
    this.passwordLabel = new JLabel("Password");
    this.passwordTextField.getDocument().addDocumentListener(new DocumentListener() {
        public void textChanged(DocumentEvent e) {
            try {
                String pass = new String(passwordTextField.getPassword());
                String encoded = new String(Hex.encodeHex(digester.digest(pass.getBytes("UTF-8"))));
                user.setPassword(encoded);
            } catch (UnsupportedEncodingException e1) {
                throw new RuntimeException(e1);
            }
        }

        public void changedUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void insertUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void removeUpdate(DocumentEvent e) {
            textChanged(e);
        }
    });

    this.fullNameTextField = new JTextField();
    this.fullNameTextField.setText(user.getFullName());
    this.fullNameLabel = new JLabel("Full name");
    this.fullNameTextField.getDocument().addDocumentListener(new DocumentListener() {

        public void textChanged(DocumentEvent e) {
            user.setFullName(fullNameTextField.getText());
        }

        public void changedUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void insertUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void removeUpdate(DocumentEvent e) {
            textChanged(e);
        }
    });

    this.emailTextField = new JTextField();
    this.emailTextField.setText(user.getEmail());
    this.emailLabel = new JLabel("Email");
    this.emailTextField.getDocument().addDocumentListener(new DocumentListener() {

        public void textChanged(DocumentEvent e) {
            user.setEmail(emailTextField.getText());
        }

        public void changedUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void insertUpdate(DocumentEvent e) {
            textChanged(e);
        }

        public void removeUpdate(DocumentEvent e) {
            textChanged(e);
        }
    });

    this.availableGroupsLabel = new JLabel("Available Groups");
    this.availableGroupsListModel = new GroupsListModel(user, workspace, false);
    this.availableGroupsList = new JList(this.availableGroupsListModel);
    this.availableGroupsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.availableGroupsList.setCellRenderer(new DefaultListCellRenderer() {
        final JTree dummyTree = new JTree();
        final WorkspaceTreeCellRenderer delegate = new WorkspaceTreeCellRenderer();

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            return delegate.getTreeCellRendererComponent(dummyTree, value, isSelected, false, true, 0,
                    cellHasFocus);
        }
    });
    this.availableGroupsScrollPane = new JScrollPane(this.availableGroupsList);

    this.currentGroupsLabel = new JLabel("Current Memberships");
    this.currentGroupsListModel = new GroupsListModel(user, workspace, true);
    this.currentGroupsList = new JList(this.currentGroupsListModel);
    this.currentGroupsList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.currentGroupsList.setCellRenderer(new DefaultListCellRenderer() {
        final JTree dummyTree = new JTree();
        final WorkspaceTreeCellRenderer delegate = new WorkspaceTreeCellRenderer();

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            return delegate.getTreeCellRendererComponent(dummyTree, value, isSelected, false, true, 0,
                    cellHasFocus);
        }
    });
    this.groupsLabel = new JLabel("Edit user memberships");
    this.currentGroupsScrollPane = new JScrollPane(this.currentGroupsList);

    this.addButton = new JButton(">");
    this.addButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object[] selection = availableGroupsList.getSelectedValues();
            if (selection.length == 0) {
                return;
            }
            try {
                workspace.begin("Add user to groups");
                for (Object object : selection) {
                    ((Group) object).addMember(new GroupMember(user));
                }
            } finally {
                workspace.commit();
            }
        }
    });

    this.removeButton = new JButton("<");
    this.removeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object[] selection = currentGroupsList.getSelectedValues();
            if (selection.length == 0) {
                return;
            }
            try {
                workspace.begin("Remove user from groups");
                Map<Group, GroupMember> toRemove = new ArrayMap<Group, GroupMember>();
                for (Object object : selection) {
                    for (GroupMember membership : ((Group) object).getChildren(GroupMember.class)) {
                        if (membership.getUser().getUUID().equals(user.getUUID())) {
                            toRemove.put((Group) object, membership);
                        }
                    }
                }
                for (Entry<Group, GroupMember> entry : toRemove.entrySet()) {
                    entry.getKey().removeMember(entry.getValue());
                }
            } finally {
                workspace.commit();
            }
        }
    });

    Action deleteAction = new DeleteFromTreeAction(this.workspace, this.user, this.panel,
            this.workspace.getSession().getContext());
    this.toolbarBuilder.add(deleteAction, "Delete this user", WabitIcons.DELETE_ICON_32);

    // Panel building time
    JPanel namePassPanel = new JPanel(new MigLayout());
    namePassPanel.add(this.loginLabel, "align right, gaptop 20");
    namePassPanel.add(this.loginTextField, "span, wrap, wmin 600");
    namePassPanel.add(this.passwordLabel, "align right");
    namePassPanel.add(this.passwordTextField, "span, wrap, wmin 600");
    namePassPanel.add(this.fullNameLabel, "align right, gaptop 20");
    namePassPanel.add(this.fullNameTextField, "span, wrap, wmin 600");
    namePassPanel.add(this.emailLabel, "align right");
    namePassPanel.add(this.emailTextField, "span, wrap, wmin 600");
    this.panel.add(namePassPanel, "north");

    this.panel.add(this.groupsLabel, "span, wrap, gaptop 20, align center");

    JPanel buttonsPanel = new JPanel(new MigLayout());
    buttonsPanel.add(this.addButton, "wrap");
    buttonsPanel.add(this.removeButton);
    JPanel availablePanel = new JPanel(new MigLayout());
    availablePanel.add(this.availableGroupsLabel, "wrap, align center");
    availablePanel.add(this.availableGroupsScrollPane, "wmin 300");
    JPanel currentPanel = new JPanel(new MigLayout());
    currentPanel.add(this.currentGroupsLabel, "wrap, align center");
    currentPanel.add(this.currentGroupsScrollPane, "wmin 300");
    this.panel.add(availablePanel);
    this.panel.add(buttonsPanel, "shrink, span 1 2");
    this.panel.add(currentPanel);
}