Example usage for javax.xml.bind DatatypeConverter printBase64Binary

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

Introduction

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

Prototype

public static String printBase64Binary(byte[] val) 

Source Link

Document

Converts an array of bytes into a string.

Usage

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

private static void addHTTPBasicAuthProperty(HttpsURLConnection conn) {
    String userpass = username + ":" + password;
    String basicAuth = "Basic " + new String(DatatypeConverter.printBase64Binary(userpass.getBytes()));
    conn.setRequestProperty("Authorization", basicAuth);
}

From source file:org.raml.parser.visitor.SchemaCompiler.java

public static String encodeIncludePath(ScalarNode node) {
    String schema = node.getValue();
    String includePath = "";
    if (node instanceof IncludeResolver.IncludeScalarNode) {
        includePath = ((IncludeResolver.IncludeScalarNode) node).getIncludeName();
    }/*from ww w .  j av  a  2  s.  c om*/
    String includeEncoded = DatatypeConverter.printBase64Binary(includePath.getBytes());

    return includeEncoded + SEPARATOR + schema;
}

From source file:org.sdnmq.jms.PacketHandler.java

/**
 * Converts a packet to JSON representation.
 * // ww w  .  j a  v  a  2s.co  m
 * @param pkt the packet to be converted
 * @return JSON representation.
 */
private JSONObject pktToJSON(RawPacket rawPkt) {
    log.trace("Received packet-in event.");

    JSONObject json = new JSONObject();

    // Add incoming node

    // The connector, the packet came from ("port")
    NodeConnector ingressConnector = rawPkt.getIncomingNodeConnector();
    // The node that received the packet ("switch")
    Node node = ingressConnector.getNode();

    JSONObject nodeJson = new JSONObject();
    nodeJson.put(NodeAttributes.Keys.ID.toJSON(), node.getNodeIDString());
    nodeJson.put(NodeAttributes.Keys.TYPE.toJSON(), node.getType());
    json.put(PacketInAttributes.Keys.NODE.toJSON(), nodeJson);

    // Add inport

    json.put(PacketInAttributes.Keys.INGRESS_PORT.toJSON(), ingressConnector.getNodeConnectorIDString());

    // Add raw packet data

    // Use DataPacketService to decode the packet.
    Packet pkt = dataPacketService.decodeDataPacket(rawPkt);

    while (pkt != null) {
        if (pkt instanceof Ethernet) {
            Ethernet ethernet = (Ethernet) pkt;
            ethernetToJSON(ethernet, json);
        } else if (pkt instanceof IEEE8021Q) {
            IEEE8021Q ieee802q = (IEEE8021Q) pkt;
            ieee8021qToJSON(ieee802q, json);
        } else if (pkt instanceof IPv4) {
            IPv4 ipv4 = (IPv4) pkt;
            ipv4ToJSON(ipv4, json);
        } else if (pkt instanceof TCP) {
            TCP tcp = (TCP) pkt;
            tcpToJSON(tcp, json);
        } else if (pkt instanceof UDP) {
            UDP udp = (UDP) pkt;
            udpToJSON(udp, json);
        }

        pkt = pkt.getPayload();
    }

    json.put(PacketInAttributes.Keys.PACKET.toJSON(),
            DatatypeConverter.printBase64Binary(rawPkt.getPacketData()));

    return json;
}

From source file:org.sdnmq.jms_demoapps.SimplePacketSender.java

public static void main(String[] args) {
    // Standard JMS setup.
    try {/*  w ww. j a v a2 s. c o m*/
        // Uses settings from file jndi.properties if file is in CLASSPATH.
        ctx = new InitialContext();
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        queueFactory = (QueueConnectionFactory) ctx.lookup("QueueConnectionFactory");
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection = queueFactory.createQueueConnection();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        packetForwarderQueue = (Queue) ctx.lookup(PACKETFORWARDER_QUEUE_NAME);
    } catch (NameNotFoundException e) {
        System.err.println(e.getMessage());
        die(-1);
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        sender = session.createSender(packetForwarderQueue);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        connection.start();
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    // Create packet using OpenDaylight packet classes (or any other packet parser/constructor you like most)
    // In most use cases, you will not create the complete packet yourself from scratch
    // but rather use a packet received from a packet-in event as basis. Let's assume that
    // the received packet-in event looks like this (in JSON representation as delivered by
    // the packet-in handler):
    //
    // {"node":{"id":"00:00:00:00:00:00:00:01","type":"OF"},"ingressPort":"1","protocol":1,"etherType":2048,"nwDst":"10.0.0.2","packet":"Io6q62g3mn66JKnjCABFAABUAABAAEABJqcKAAABCgAAAggAGFlGXgABELmmUwAAAAAVaA4AAAAAABAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc=","dlDst":"22:8E:AA:EB:68:37","nwSrc":"10.0.0.1","dlSrc":"9A:7E:BA:24:A9:E3"}
    //
    // Thus, we can use the "packet" field to re-construct the raw packet data from Base64-encoding:
    String packetInBase64 = "Io6q62g3mn66JKnjCABFAABUAABAAEABJqcKAAABCgAAAggAGFlGXgABELmmUwAAAAAVaA4AAAAAABAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc=";
    byte[] packetData = DatatypeConverter.parseBase64Binary(packetInBase64);
    // Now we can use the OpenDaylight classes to get Java objects for this packet:
    Ethernet ethPkt = new Ethernet();
    try {
        ethPkt.deserialize(packetData, 0, packetData.length * 8);
    } catch (Exception e) {
        System.err.println("Failed to decode packet");
        die(-1);
    }
    if (ethPkt.getEtherType() == 0x800) {
        IPv4 ipv4Pkt = (IPv4) ethPkt.getPayload();
        // We could go on parsing layer by layer ... but you got the idea already I think.
        // So let's make some change to the packet to make it more interesting:
        InetAddress newDst = null;
        try {
            newDst = InetAddress.getByName("10.0.0.2");
        } catch (UnknownHostException e) {
            die(-1);
        }
        assert (newDst != null);
        ipv4Pkt.setDestinationAddress(newDst);
    }
    // Now we can get the binary data of the new packet to be forwarded.
    byte[] pktBinary = null;
    try {
        pktBinary = ethPkt.serialize();
    } catch (PacketException e1) {
        System.err.println("Failed to serialize packet");
        die(-1);
    }
    assert (pktBinary != null);

    // Encode packet to Base64 textual representation to be sent in JSON.
    String pktBase64 = DatatypeConverter.printBase64Binary(pktBinary);

    // We need to tell the packet forwarder, which node should forward the packet.
    // In OpenDaylight, a node is identified by node id and node type (like "OF" for OpenFlow).
    // For a list of all node attributes, cf. class NodeAttributes.
    // For a list of possible node types, cf. class NodeAttributes.TypeValues.
    JSONObject nodeJson = new JSONObject();
    String nodeId = "00:00:00:00:00:00:00:01";
    nodeJson.put(NodeAttributes.Keys.ID.toJSON(), nodeId);
    nodeJson.put(NodeAttributes.Keys.TYPE.toJSON(), NodeAttributes.TypeValues.OF.toJSON());

    // Create a packet forwarding request in JSON representation.
    // All attributes are described in class PacketForwarderRequestAttributes.
    JSONObject packetFwdRequestJson = new JSONObject();
    packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.NODE.toJSON(), nodeJson);
    packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.EGRESS_PORT.toJSON(), 1);
    packetFwdRequestJson.put(PacketForwarderRequestAttributes.Keys.PACKET.toJSON(), pktBase64);

    // Send the request by posting it to the packet forwarder queue.

    System.out.println("Sending packet forwarding request: ");
    System.out.println(packetFwdRequestJson.toString());

    try {
        TextMessage msg = session.createTextMessage();
        msg.setText(packetFwdRequestJson.toString());
        sender.send(msg);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    die(0);
}

From source file:org.sharegov.cirm.utils.GenUtils.java

public static String serializeAsString(Object x) {
    try {/*from   w  w w  .  j  av a 2  s. com*/
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(bos);
        out.writeObject(x);
        out.close();
        return DatatypeConverter.printBase64Binary(bos.toByteArray());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.silverpeas.core.util.WebEncodeHelper.java

/**
 * Encode an UTF-8 filename in Base64 for the content-disposition header according to
 * <a href="http://www.ietf.org/rfc/rfc2047.txt">RFC2047</a>.
 *
 * @param filename the UTF-8 filename to be encoded.
 * @return the filename to be inserted in the content-disposition header.
 *///  ww  w .  j  a  v a2  s. c om
public static String encodeFilename(String filename) {
    return "=?UTF-8?B?" + DatatypeConverter.printBase64Binary(filename.getBytes(Charsets.UTF_8)) + "?=";
}

From source file:org.springframework.integration.splunk.support.SplunkServiceFactory.java

private Callable<Service> buildServiceCallable(SplunkServer splunkServer) {
    final Map<String, Object> args = new HashMap<String, Object>();
    if (splunkServer.getHost() != null) {
        args.put("host", splunkServer.getHost());
    }// ww  w  .j  a  v a2s.  c o m
    if (splunkServer.getPort() != 0) {
        args.put("port", splunkServer.getPort());
    }
    if (splunkServer.getScheme() != null) {
        args.put("scheme", splunkServer.getScheme());
    }
    if (splunkServer.getApp() != null) {
        args.put("app", splunkServer.getApp());
    }
    if (splunkServer.getOwner() != null) {
        args.put("owner", splunkServer.getOwner());
    }

    args.put("username", splunkServer.getUsername());
    args.put("password", splunkServer.getPassword());

    String auth = splunkServer.getUsername() + ":" + splunkServer.getPassword();
    String authToken = "Basic " + DatatypeConverter.printBase64Binary(auth.getBytes());
    args.put("token", authToken);

    return new Callable<Service>() {
        public Service call() throws Exception {
            return Service.connect(args);
        }
    };
}

From source file:org.springframework.web.socket.server.DefaultHandshakeHandler.java

private String getWebSocketKeyHash(String key) throws HandshakeFailureException {
    try {/*w ww  .j a  v a2  s .  c  om*/
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        byte[] bytes = digest.digest((key + GUID).getBytes(Charset.forName("ISO-8859-1")));
        return DatatypeConverter.printBase64Binary(bytes);
    } catch (NoSuchAlgorithmException ex) {
        throw new HandshakeFailureException("Failed to generate value for Sec-WebSocket-Key header", ex);
    }
}

From source file:org.takes.facets.auth.PsBasicTest.java

/**
 * Generate the string used on the request that store information about
 * authentication./*from ww w .j av a2 s  . c o m*/
 * @param user Username
 * @param pass Password
 * @return Header string.
 */
private static String header(final String user, final String pass) {
    final String auth = String.format("%s:%s", user, pass);
    final String encoded = DatatypeConverter.printBase64Binary(auth.getBytes());
    return String.format(PsBasicTest.AUTH_BASIC, encoded);
}

From source file:org.vpac.web.controller.DataController.java

@RequestMapping(value = "/PreviewQuery", method = RequestMethod.POST)
public void previewQuery(@RequestParam(required = false) String query,
        @RequestParam(required = false) String threads, @RequestParam(required = false) Double minX,
        @RequestParam(required = false) Double minY, @RequestParam(required = false) Double maxX,
        @RequestParam(required = false) Double maxY, @RequestParam(required = false) String startDate,
        @RequestParam(required = false) String endDate, @RequestParam(required = false) String netcdfVersion,
        ModelMap model, HttpServletResponse response) throws Exception {

    // FIXME: this should only be done once!
    ProviderRegistry.getInstance().clearProivders();
    ProviderRegistry.getInstance().addProivder(rsaDatasetProvider);
    ProviderRegistry.getInstance().addProivder(previewDatasetProvider);

    final QueryDefinition qd = QueryDefinition.fromString(query);
    if (minX != null)
        qd.output.grid.bounds = String.format("%f %f %f %f", minX, minY, maxX, maxY);

    if (startDate != null) {
        qd.output.grid.timeMin = startDate;
        qd.output.grid.timeMax = endDate;
    }/*from w w  w.ja v  a2 s  .  co m*/

    Version version;
    if (netcdfVersion != null) {
        if (netcdfVersion.equals("nc3")) {
            version = Version.netcdf3;
        } else if (netcdfVersion.equals("nc4")) {
            version = Version.netcdf4;
        } else {
            throw new IllegalArgumentException(String.format("Unrecognised NetCDF version %s", netcdfVersion));
        }
    } else {
        version = Version.netcdf4;
    }
    final Version ver = version;

    final QueryProgress qp = new QueryProgress(jobProgressDao);
    String taskId = qp.getTaskId();
    final Integer t = threads == null ? null : Integer.parseInt(threads);
    Path outputDir = FileUtils.getTargetLocation(taskId);
    final Path queryPath = outputDir.resolve("query_output.nc");
    if (!Files.exists(outputDir))
        Files.createDirectories(outputDir);

    try {
        executeQuery(qd, qp, t, queryPath, ver);

        if (!Files.exists(queryPath)) {
            throw new ResourceNotFoundException("Query output file not found: " + queryPath);
        }

        Path previewPath = queryPath.getParent().resolve("preview.png");

        ImageTranslator converter = new ImageTranslator();
        // mandatory
        converter.setFormat(GdalFormat.PNG);
        converter.setLayerIndex(1);
        converter.setSrcFile(queryPath);
        converter.setDstFile(previewPath);
        converter.initialise();
        converter.execute();

        try {
            // get your file as InputStream
            InputStream is = new FileInputStream(previewPath.toString());
            String result = DatatypeConverter.printBase64Binary(IOUtils.toByteArray(is));
            response.setContentType("application/json");
            response.setContentLength(result.getBytes().length);
            response.getOutputStream().write(result.getBytes());
            response.flushBuffer();
        } catch (IOException ex) {
            throw new RuntimeException("IOError writing file to output stream: " + ex);
        }
    } catch (Exception e) {
        qp.setErrorMessage(e.getMessage());
        log.error("Task exited abnormally: ", e);
        throw e;
    }
}