Example usage for javax.xml.bind DatatypeConverter printHexBinary

List of usage examples for javax.xml.bind DatatypeConverter printHexBinary

Introduction

In this page you can find the example usage for javax.xml.bind DatatypeConverter printHexBinary.

Prototype

public static String printHexBinary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:org.jupyterkernel.kernel.MessageObject.java

public void send() {
    msg.header.msg_id = UUID.newID();
    JSONObject jsonMsg = msg.toJSON();/*from   www .ja  v a 2  s  .  c o m*/
    ZMsg newZmsg = new ZMsg();
    newZmsg.add(uuid);
    newZmsg.add(bDelimiter);
    byte[] header = jsonMsg.getJSONObject("header").toString().getBytes();
    byte[] parent = jsonMsg.getJSONObject("parent_header").toString().getBytes();
    byte[] meta = jsonMsg.getJSONObject("metadata").toString().getBytes();
    byte[] content = jsonMsg.getJSONObject("content").toString().getBytes();
    byte[] digest = computeSignature(header, parent, meta, content);
    digest = DatatypeConverter.printHexBinary(digest).toLowerCase().getBytes();
    newZmsg.add(digest);
    newZmsg.add(header);
    newZmsg.add(parent);
    newZmsg.add(meta);
    newZmsg.add(content);
    newZmsg.send(socket);
}

From source file:org.kaaproject.kaa.sandbox.AbstractSandboxBuilder.java

private boolean compareChecksum(File targetFile, String downloadedCheckSum) {
    String checkSum = "";
    try (FileInputStream fileInput = new FileInputStream(targetFile)) {
        MessageDigest messageDigest = MessageDigest.getInstance(MD5);
        byte[] dataBytes = new byte[1024 * 100];
        int bytesRead = 0;
        while ((bytesRead = fileInput.read(dataBytes)) != -1) {
            messageDigest.update(dataBytes, 0, bytesRead);
        }/*from  ww  w . j a v  a  2s  . c  om*/
        byte[] digestBytes = messageDigest.digest();
        checkSum = DatatypeConverter.printHexBinary(digestBytes);
        LOG.debug("Calculated checksum for filer[{}]: [{}], downloaded is [{}]", targetFile.getAbsolutePath(),
                checkSum, downloadedCheckSum);
    } catch (IOException | NoSuchAlgorithmException e) {
        LOG.debug("Can't calculate checksum for file [{}]", targetFile.getAbsolutePath());
    }
    return checkSum.equalsIgnoreCase(downloadedCheckSum);
}

From source file:org.kalypso.service.wps.client.simulation.SimulationDelegate.java

/**
 * This function creates the inputs for the server. It will also copy the data to the right place, if needed and
 * ajdust the references according to it.
 *
 * @param description/* w w w.j ava 2  s  .  co m*/
 *          The process description type.
 * @param monitor
 *          A progress monitor.
 * @return The inputs.
 */
public Map<String, Object> createInputs(final ProcessDescriptionType description, IProgressMonitor monitor)
        throws CoreException {
    /* Monitor. */
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }

    try {
        /* Monitor. */
        monitor.beginTask(Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.7"), //$NON-NLS-1$
                500);
        KalypsoServiceWPSDebug.DEBUG.printf("Collecting data ...\n"); //$NON-NLS-1$

        /* Need the filesystem manager. */
        final FileSystemManager fsManager = m_fsManager;

        /* Get the list with the input. */
        final Map<String, Object> wpsInputs = new HashMap<>();

        /* Get the input list. */
        final DataInputs dataInputs = description.getDataInputs();
        final List<InputDescriptionType> inputDescriptions = dataInputs.getInput();

        /* Create a resource visitor. */
        final CollectFilesVisitor visitor = new CollectFilesVisitor();

        /* Get the inputs. */
        final List<Input> inputList = m_data.getInput();

        /* Iterate over all inputs and build the data inputs for the execute request. */
        for (final InputDescriptionType inputDescription : inputDescriptions) {
            final CodeType identifier = inputDescription.getIdentifier();

            /* Check if the input is in our model data, too. */
            final Input input = SimulationUtilities.findInput(identifier.getValue(), inputList);
            if (input == null) {
                /* Check, if it is an optional one. */
                if (inputDescription.getMinimumOccurs().intValue() == 1) {
                    /* Ooops, it is a mandatory one, but it is missing in our model data. */
                    final IStatus status = StatusUtilities.createStatus(IStatus.ERROR,
                            Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.8", //$NON-NLS-1$
                                    identifier.getValue()),
                            null);
                    throw new CoreException(status);
                }

                continue;
            }

            /* Input is here. */
            final String inputPath = input.getPath();

            /* Supported complex data type. */
            final SupportedComplexDataType complexData = inputDescription.getComplexData();
            if (complexData != null) {
                /* Get the protocol if it is one. */
                final String protocol = SimulationUtilities.getProtocol(inputPath);

                /* If the protocol is null, it is a local file resource, otherwise it is a remote resource, */
                /* which is not allowed to be copied or it is a complex value type (file-protocol). */
                if ("file".equals(protocol)) //$NON-NLS-1$
                {
                    // TODO: Why do we need this?
                    final URL localFileUrl = new URL(inputPath);
                    final byte[] bytes = UrlUtilities.toByteArray(localFileUrl);
                    final String hexString = DatatypeConverter.printHexBinary(bytes);
                    wpsInputs.put(identifier.getValue(), hexString);
                    continue;
                } else if (protocol == null || protocol.equals("project") || protocol.equals("platform")) //$NON-NLS-1$ //$NON-NLS-2$
                {
                    /* If protocol is null or protocol is "project", it is a local file resource. */
                    /*
                     * If protocol is "platform", it is a resource from another project, but the same platform (i.e. same
                     * eclipse workspace).
                     */
                    if (m_calcCaseFolder == null) {
                        throw new WPSException(Messages
                                .getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.9")); //$NON-NLS-1$
                    }

                    final IProject project = m_calcCaseFolder.getProject();
                    final IResource inputResource;
                    if (protocol != null && protocol.equals(PlatformURLHandler.PROTOCOL)) {
                        final IContainer baseresource = project.getWorkspace().getRoot();
                        final String path = ResourceUtilities.findPathFromURL(new URL(inputPath))
                                .toPortableString();
                        inputResource = baseresource.findMember(path);
                    } else {
                        final IContainer baseresource = input.isRelativeToCalcCase() ? m_calcCaseFolder
                                : project;
                        inputResource = baseresource.findMember(inputPath);
                    }

                    if (inputResource == null) {
                        if (inputDescription.getMinimumOccurs().intValue() == 0) {
                            continue;
                        }

                        throw new CoreException(StatusUtilities.createErrorStatus(Messages.getString(
                                "org.kalypso.service.wps.client.simulation.SimulationDelegate.10", inputPath))); //$NON-NLS-1$
                    }

                    /* Collect all files. */
                    inputResource.accept(visitor);

                    /* Initialize the temporary directory. */
                    initServerTmpDirectory();

                    /* Build the URL for this input. */
                    /* Resource will be copied to server later (for example see SimulationDelegate.copyInputFiles). */
                    final String relativePathTo = inputResource.getFullPath().makeRelative().toString();

                    /**
                     * just put the existing resource to the inputs and DO NOT copy it in case of local calculation!! also
                     * prevent the creation of redundant data in base project folder
                     */
                    FileObject destination = fsManager.toFileObject(inputResource.getLocation().toFile());
                    if (!SERVER_INPUT_LOCAL.equals(m_input)) {
                        destination = fsManager.resolveFile(m_serverTmpDirectory, relativePathTo);
                    }

                    final String serverUrl = WPSUtilities
                            .convertInternalToServer(destination.getURL().toExternalForm(), m_input);
                    wpsInputs.put(identifier.getValue(), new URI(URIUtil.encodePath(serverUrl)));
                } else
                // maybe check the protocols?
                {
                    // Remote resource, will be passed to the service as reference
                    final URL clientUrl = new URL(inputPath);
                    final String serverUrl = WPSUtilities.convertInternalToServer(clientUrl.toExternalForm(),
                            m_input);
                    wpsInputs.put(identifier.getValue(), new URI(serverUrl));
                }
            }

            /* Literal input type */
            final LiteralInputType literalInput = inputDescription.getLiteralData();
            if (literalInput != null) {
                /* Add the input. */
                // TODO: normally we should marshall the string to the requested type
                // (the WPS-Client will unmarshall it again).
                // For the moment this works, as the WPS-Client just forwards any strings.
                wpsInputs.put(identifier.getValue(), inputPath);

                continue;
            }

            /* Supported CRSs type. */
            final SupportedCRSsType supportedCRSsType = inputDescription.getBoundingBoxData();
            if (supportedCRSsType != null) {
                // TODO Add supported CRSs type (bounding boxes).
                continue;
            }
        }

        /* Monitor. */
        monitor.worked(200);
        monitor.setTaskName(
                Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.11")); //$NON-NLS-1$
        KalypsoServiceWPSDebug.DEBUG.printf("Copy to the server ...\n"); //$NON-NLS-1$

        /* Copy all collected files. */
        final IFile[] files = visitor.getFiles();
        if (files.length > 0)
            copyInputFiles(files);

        /* Monitor. */
        monitor.worked(300);

        return wpsInputs;
    } catch (final CoreException ex) {
        throw ex;
    } catch (final Exception ex) {
        throw new CoreException(StatusUtilities.createStatus(IStatus.ERROR,
                Messages.getString("org.kalypso.service.wps.client.simulation.SimulationDelegate.12"), ex)); //$NON-NLS-1$
    } finally {
        /* Monitor. */
        monitor.done();
    }
}

From source file:org.mycore.common.MCRUtils.java

public static String toHexString(byte[] data) {
    return DatatypeConverter.printHexBinary(data).toLowerCase(Locale.ROOT);
}

From source file:org.openhab.binding.onkyo.internal.eiscp.Eiscp.java

/**
 * Sends to command to the receiver./*from ww w  .j ava  2s.c o m*/
 * 
 * @param eiscpCmd the eISCP command to send.
 * @param closeSocket flag to close the connection when done or leave it open.
 * @param retry retry count.
 **/
private void sendCommand(StringBuilder eiscpCmd, boolean closeSocket, int retry) {

    if (connectSocket()) {
        try {

            if (logger.isTraceEnabled()) {
                logger.trace("Sending {} bytes: {}", eiscpCmd.length(),
                        DatatypeConverter.printHexBinary(eiscpCmd.toString().getBytes()));
            }

            outStream.writeBytes(eiscpCmd.toString());
            outStream.flush();
        } catch (IOException ioException) {
            logger.error("Error occured when sending command", ioException);

            if (retry > 0) {
                logger.debug("Retry {}...", retry);
                closeSocket();
                sendCommand(eiscpCmd, closeSocket, retry--);
            }
        }
    }

    // finally close the socket if required ...
    if (closeSocket) {
        closeSocket();
    }
}

From source file:org.openhab.binding.onkyo.internal.eiscp.Eiscp.java

/**
 * This method wait any state messages form receiver.
 * //from w ww  . ja  v  a2 s . c om
 * @throws IOException 
 * @throws InterruptedException 
 * @throws EiscpException 
 **/
private void waitStateMessages()
        throws NumberFormatException, IOException, InterruptedException, EiscpException {

    if (connected) {

        OnkyoStatusUpdateEvent event = new OnkyoStatusUpdateEvent(this);

        logger.trace("Waiting status messages");

        while (true) {

            // 1st 4 chars are the leadIn

            if (inStream.readByte() != 'I')
                continue;
            if (inStream.readByte() != 'S')
                continue;
            if (inStream.readByte() != 'C')
                continue;
            if (inStream.readByte() != 'P')
                continue;

            // header size
            final int headerSize = (inStream.readByte() & 0xFF) << 24 | (inStream.readByte() & 0xFF) << 16
                    | (inStream.readByte() & 0xFF) << 8 | (inStream.readByte() & 0xFF);

            logger.trace("Header size: {}", headerSize);

            if (headerSize != 16) {
                throw new EiscpException("Unsupported header size: " + headerSize);
            }

            // header size
            final int dataSize = (inStream.readByte() & 0xFF) << 24 | (inStream.readByte() & 0xFF) << 16
                    | (inStream.readByte() & 0xFF) << 8 | (inStream.readByte() & 0xFF);

            logger.trace("Data size: {}", dataSize);

            // version
            final byte versionChar = inStream.readByte();
            if (versionChar != 1) {
                throw new EiscpException("Unsupported version " + String.valueOf(versionChar));
            }

            // skip 3 reserved bytes
            inStream.readByte();
            inStream.readByte();
            inStream.readByte();

            byte[] data = new byte[dataSize];

            final int bytesReceived = inStream.read(data, 0, data.length);

            if (logger.isTraceEnabled()) {
                logger.trace("Received {} bytes: {}", bytesReceived, DatatypeConverter.printHexBinary(data));
            }

            if (bytesReceived != dataSize) {
                throw new EiscpException("Data missing: " + (dataSize - bytesReceived));
            }

            // start char
            final byte startChar = data[0];

            if (startChar != '!') {
                throw new EiscpException("Illegal start char " + startChar);
            }

            // unit type
            @SuppressWarnings("unused")
            final byte unitType = data[1];

            // data should be end to "[EOF]" or "[EOF][CR]" or
            // "[EOF][CR][LF]" characters depend on model
            // [EOF] End of File ASCII Code 0x1A
            // [CR] Carriage Return ASCII Code 0x0D (\r)
            // [LF] Line Feed ASCII Code 0x0A (\n)

            int endBytes = 0;

            if (data[dataSize - 4] == (byte) 0x1A && data[dataSize - 3] == '\r' && data[dataSize - 2] == '\n'
                    && data[dataSize - 1] == 0x00) {

                // skip "[EOF][CR][LF][NULL]"
                endBytes = 4;

            } else if (data[dataSize - 3] == (byte) 0x1A && data[dataSize - 2] == '\r'
                    && data[dataSize - 1] == '\n') {

                // skip "[EOF][CR][LF]"
                endBytes = 3;

            } else if (data[dataSize - 2] == (byte) 0x1A && data[dataSize - 1] == '\r') {

                // "[EOF][CR]"
                endBytes = 2;

            } else if (data[dataSize - 1] == (byte) 0x1A) {

                // "[EOF]"
                endBytes = 1;

            } else {
                throw new EiscpException("Illegal end of message");
            }

            int bytesToCopy = dataSize - 2 - endBytes;

            byte[] message = new byte[bytesToCopy];

            // skip 2 first bytes and copy all bytes before end bytes 
            System.arraycopy(data, 2, message, 0, bytesToCopy);

            // send message to event listeners
            try {
                Iterator<OnkyoEventListener> iterator = _listeners.iterator();

                while (iterator.hasNext()) {
                    ((OnkyoEventListener) iterator.next()).statusUpdateReceived(event, receiverIP,
                            new String(message));
                }

            } catch (Exception e) {
                logger.error("Event listener invoking error", e);
            }
        }

    } else {
        throw new IOException("Not Connected to Receiver");
    }
}

From source file:org.openhab.binding.onkyo.internal.OnkyoConnection.java

/**
 * Sends to command to the receiver.//from  w  ww.ja v  a  2s .com
 *
 * @param eiscpCmd the eISCP command to send.
 * @param retry retry count when connection fails.
 **/
private void sendCommand(EiscpMessage msg, int retry) {

    if (connectSocket()) {
        try {

            String data = EiscpProtocol.createEiscpPdu(msg);
            if (logger.isTraceEnabled()) {
                logger.trace("Sending {} bytes: {}", data.length(),
                        DatatypeConverter.printHexBinary(data.toString().getBytes()));
            }

            outStream.writeBytes(data);
            outStream.flush();
        } catch (IOException ioException) {
            logger.error("Error occurred when sending command: {}", ioException.getMessage());

            if (retry > 0) {
                logger.debug("Retry {}...", retry);
                closeSocket();
                sendCommand(msg, retry--);
            } else {
                sendConnectionErrorEvent();
            }
        }
    }
}

From source file:org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControl.java

/**
 * Sends to command to the receiver.// w  w  w.j  a  v  a 2s. c  om
 * 
 * @param ipCmd the Pioneer IP command to send.
 * @param closeSocket flag to close the connection when done or leave it open.
 * @param retry retry count.
 **/
private void sendCommand(StringBuilder ipCmd, boolean closeSocket, int retry) {

    if (connectSocket()) {
        try {

            if (logger.isTraceEnabled()) {
                logger.trace("Sending {} bytes: {}", ipCmd.length(),
                        DatatypeConverter.printHexBinary(ipCmd.toString().getBytes()));
            }
            outStream.writeBytes(ipCmd.toString());
            outStream.flush();

        } catch (IOException ioException) {
            logger.error("Error occured when sending command", ioException);

            if (retry > 0) {
                logger.debug("Retry {}...", retry);
                closeSocket();
                sendCommand(ipCmd, closeSocket, retry--);
            }
        }
    }

    // finally close the socket if required ...
    if (closeSocket) {
        closeSocket();
    }
}

From source file:org.openhab.binding.pioneeravr.internal.ipcontrolprotocol.IpControl.java

/**
 * This method wait any state messages form receiver.
 * // w  ww  .  jav  a  2 s .c  o m
 * @throws IOException 
 * @throws InterruptedException 
 * @throws IpcontrolException 
 **/
private void waitStateMessages()
        throws NumberFormatException, IOException, InterruptedException, IpcontrolException {

    if (connected) {

        PioneerAvrStatusUpdateEvent event = new PioneerAvrStatusUpdateEvent(this);

        logger.trace("Waiting status messages");

        while (true) {

            String receivedData = inBufferedReader.readLine();

            if (logger.isTraceEnabled()) {
                logger.trace("Received {} bytes: {}", receivedData.length(),
                        DatatypeConverter.printHexBinary(receivedData.getBytes()));
            }

            // send message to event listeners
            try {
                Iterator<PioneerAvrEventListener> iterator = _listeners.iterator();

                while (iterator.hasNext()) {
                    ((PioneerAvrEventListener) iterator.next()).statusUpdateReceived(event, receiverIP,
                            receivedData);
                }

            } catch (Exception e) {
                logger.error("Event listener invoking error", e);
            }
        }

    } else {
        throw new IOException("Not Connected to Receiver");
    }
}

From source file:org.openhab.binding.powermax.internal.message.PowerMaxCommDriver.java

/**
 * Send an ACK for a received message/*from   ww  w . j a  v a  2 s.  c  om*/
 *
 * @param msg
 *            the received message object
 * @param ackType
 *            the type of ACK to be sent
 *
 * @return true if the ACK was sent or false if not
 */
public synchronized boolean sendAck(PowerMaxBaseMessage msg, byte ackType) {
    int code = msg.getCode();
    byte[] rawData = msg.getRawData();
    byte[] ackData;
    if ((code >= 0x80) || ((code < 0x10) && (rawData[rawData.length - 3] == 0x43))) {
        ackData = new byte[] { 0x0D, ackType, 0x43, 0x00, 0x0A };
    } else {
        ackData = new byte[] { 0x0D, ackType, 0x00, 0x0A };
    }

    if (logger.isDebugEnabled()) {
        logger.debug("sendAck(): sending message {}", DatatypeConverter.printHexBinary(ackData));
    }
    boolean done = sendMessage(ackData);
    if (!done) {
        logger.debug("sendAck(): failed");
    }
    return done;
}