Example usage for javax.xml.bind DatatypeConverter parseBase64Binary

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

Introduction

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

Prototype

public static byte[] parseBase64Binary(String lexicalXSDBase64Binary) 

Source Link

Document

Converts the string argument into an array of bytes.

Usage

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

@Override
public void onMessage(Message msg) {
    log.trace("Received packet forwarding request.");

    // TODO: Check, how we can send an error message to the requester if something goes wrong.

    // Parse JSON

    if (!(msg instanceof TextMessage)) {
        log.error("Received invalid message type (not a text message).");
        return;/*from  w w  w  .  j av  a  2  s  . c o m*/
    }

    JSONObject json = null;
    try {
        json = new JSONObject(((TextMessage) msg).getText());
    } catch (JSONException e) {
        log.error("Could not parse JSON message: " + e.getMessage());
        return;
    } catch (JMSException e) {
        log.error(e.getMessage());
        return;
    }
    assert (json != null);
    log.trace(json.toString());

    // Get node information

    String nodeId = null;
    String nodeType = null;
    try {
        JSONObject nodeJson = json.getJSONObject(PacketForwarderRequestAttributes.Keys.NODE.toJSON());
        nodeId = nodeJson.getString(NodeAttributes.Keys.ID.toJSON());
        nodeType = nodeJson.getString(NodeAttributes.Keys.TYPE.toJSON());
    } catch (JSONException e) {
        log.error("Node attributes not specified: " + e.getMessage());
        return;
    }

    // Outgoing port

    String outPort = null;
    try {
        outPort = json.getString(PacketForwarderRequestAttributes.Keys.EGRESS_PORT.toJSON());
    } catch (JSONException e) {
        log.error("Outport not specified: " + e.getMessage());
        return;
    }

    // The raw packet to be sent.

    byte[] packetData = null;
    try {
        packetData = DatatypeConverter
                .parseBase64Binary(json.getString(PacketForwarderRequestAttributes.Keys.PACKET.toJSON()));
    } catch (JSONException e) {
        log.error("Packet data not specified: " + e.getMessage());
        return;
    }

    assert (nodeId != null);
    assert (nodeType != null);
    assert (packetData != null);
    assert (outPort != null);

    // Try to find node and node connector

    Node node = Node.fromString(nodeType, nodeId);
    if (node == null) {
        log.error("Invalid node id: " + nodeId);
        return;
    }

    if (!switchManager.getNodes().contains(node)) {
        log.error("Node '" + node.getID() + "' not found");
        return;
    }

    NodeConnector connector = NodeConnector.fromStringNoNode(outPort, node);
    if (!switchManager.doesNodeConnectorExist(connector)) {
        log.error("Port '" + outPort + "' does not exist on node '" + node.getID() + "'");
        return;
    }

    // Construct packet 

    RawPacket pkt;
    try {
        pkt = new RawPacket(packetData);
    } catch (ConstructionException e) {
        log.error("Invalid packet data: " + e.getMessage());
        return;
    }

    // Send packet via Data Packet Service

    dataPacketService.transmitDataPacket(pkt);
}

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

public static void main(String[] args) {
    // Standard JMS setup.
    try {//from  w  ww  . ja  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 = (TopicConnectionFactory) ctx.lookup("TopicConnectionFactory");
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

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

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

    try {
        packetinTopic = (Topic) ctx.lookup(PACKETIN_TOPIC_NAME);
    } catch (NameNotFoundException e) {
        System.err.println(e.getMessage());
        die(-1);
    } catch (NamingException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

    try {
        subscriber = session.createSubscriber(packetinTopic);
    } catch (JMSException e) {
        System.err.println(e.getMessage());
        die(-1);
    }

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

    // Wait for packet-in events.

    while (true) {
        try {
            // Block until a packet-in event is received.
            // Another alternative is to define a callback function
            // (cf. example FilteringPacketInSubscriber).
            Message msg = subscriber.receive();
            if (msg instanceof TextMessage) {
                String messageStr = ((TextMessage) (msg)).getText();

                // Parse JSON message payload

                JSONObject json = null;
                try {
                    json = new JSONObject(messageStr);
                    // Print the JSON message to show how it looks like.
                    System.out.println(json.toString());
                    System.out.println();
                } catch (JSONException e) {
                    System.err.println(e.getMessage());
                    continue;
                }

                // Search for some packet attributes (for a list of all possible keys, see class PacketInAttributes).

                try {
                    int ethertype = json.getInt(PacketInAttributes.Keys.ETHERTYPE.toJSON());
                    System.out.println("Ethertype: " + ethertype);
                    String macSrcAddr = json.getString(PacketInAttributes.Keys.DL_SRC.toJSON());
                    System.out.println("Source MAC address: " + macSrcAddr);
                    if (json.has(PacketInAttributes.Keys.NW_SRC.toJSON())) {
                        InetAddress nwSrcAddr;
                        try {
                            nwSrcAddr = InetAddress.getByName(PacketInAttributes.Keys.NW_SRC.toJSON());
                            System.out.println(nwSrcAddr);
                        } catch (UnknownHostException e) {
                            System.err.println("Invalid source IP address: " + e.getMessage());
                        }
                    }
                    JSONObject nodeJson = json.getJSONObject(PacketInAttributes.Keys.NODE.toJSON());
                    String nodeId = nodeJson.getString(NodeAttributes.Keys.ID.toJSON());
                    System.out.println("Node (switch): " + nodeId);
                    String inport = json.getString(PacketInAttributes.Keys.INGRESS_PORT.toJSON());
                    System.out.println("Ingress port: " + inport);
                } catch (JSONException e) {
                    System.err.println(e.getMessage());
                }

                // If you want to use your own packet parser, you can also get
                // the raw packet data.

                String packetDataBase64 = json.getString(PacketInAttributes.Keys.PACKET.toJSON());
                byte[] packetData = DatatypeConverter.parseBase64Binary(packetDataBase64);
                // Add your own custom packet parsing here ... we just print the raw data here.
                for (int i = 0; i < packetData.length; i++) {
                    if (i % 16 == 0) {
                        System.out.println();
                    }
                    System.out.print(String.format("%02X ", packetData[i]) + " ");
                }
                System.out.println();
            }
        } catch (JMSException e) {
            System.err.println(e.getMessage());
        }
    }
}

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

public static void main(String[] args) {
    // Standard JMS setup.
    try {// ww  w  .jav a 2s .co 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 Object deserializeFromString(String x) {
    try {/*from  w  w  w  . ja  v a  2s  .com*/
        byte[] A = DatatypeConverter.parseBase64Binary(x);
        ByteArrayInputStream bin = new ByteArrayInputStream(A);
        ObjectInputStream in = new ObjectInputStream(bin);
        return in.readObject();
    } catch (Exception t) {
        throw new RuntimeException(t);
    }
}

From source file:org.wso2.analytics.esb.siddhi.extension.CompressedEventProcessor.java

@SuppressWarnings("unchecked")
@Override// w w w .  ja  v a2  s  .com
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
        StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
    ComplexEventChunk<StreamEvent> decompressedStreamEventChunk = new ComplexEventChunk<StreamEvent>(false);
    while (streamEventChunk.hasNext()) {
        StreamEvent compressedEvent = streamEventChunk.next();
        String eventString = (String) compressedEvent.getAttribute(this.dataColumnIndex);
        if (!eventString.isEmpty()) {
            ByteArrayInputStream unzippedByteArray;
            if ((Boolean) compressedEvent.getAttribute(this.metaCompressedIndex)) {
                unzippedByteArray = CompressedEventAnalyticsUtils.decompress(eventString);
            } else {
                unzippedByteArray = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(eventString));
            }
            Input input = new Input(unzippedByteArray);
            Map<String, Object> aggregatedEvent = kryoTL.get().readObjectOrNull(input, HashMap.class);

            ArrayList<List<Object>> eventsList = (ArrayList<List<Object>>) aggregatedEvent
                    .get(AnalyticsConstants.EVENTS_ATTRIBUTE);
            ArrayList<PublishingPayload> payloadsList = (ArrayList<PublishingPayload>) aggregatedEvent
                    .get(AnalyticsConstants.PAYLOADS_ATTRIBUTE);

            String host = (String) aggregatedEvent.get(AnalyticsConstants.HOST_ATTRIBUTE);
            int metaTenantId = (int) compressedEvent.getAttribute(this.metaTenantIdIndex);
            // Iterate over the array of events
            for (int i = 0; i < eventsList.size(); i++) {
                StreamEvent decompressedEvent = streamEventCloner.copyStreamEvent(compressedEvent);
                // Create a new event with decompressed fields
                Object[] decompressedFields = CompressedEventUtils.getFieldValues(
                        new ArrayList<String>(this.fields.keySet()), eventsList.get(i), payloadsList, i,
                        compressedEvent.getTimestamp(), metaTenantId, host);
                complexEventPopulater.populateComplexEvent(decompressedEvent, decompressedFields);
                decompressedStreamEventChunk.add(decompressedEvent);
            }
        } else {
            throw new ExecutionPlanRuntimeException(
                    "Error occured while decompressing events. No compressed" + " data found.");
        }
    }
    nextProcessor.process(decompressedStreamEventChunk);
}

From source file:org.wso2.carbon.analytics.esb.siddhi.extension.CompressedEventProcessor.java

@SuppressWarnings("unchecked")
@Override/*from w ww  .j  a v a  2 s  . co  m*/
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
        StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
    ComplexEventChunk<StreamEvent> decompressedStreamEventChunk = new ComplexEventChunk<StreamEvent>(false);
    while (streamEventChunk.hasNext()) {
        StreamEvent compressedEvent = streamEventChunk.next();
        String eventString = (String) compressedEvent.getAttribute(this.dataColumnIndex);
        if (!eventString.isEmpty()) {
            ByteArrayInputStream unzippedByteArray;
            if ((Boolean) compressedEvent.getAttribute(this.meta_compressedIndex)) {
                unzippedByteArray = CompressedEventAnalyticsUtils.decompress(eventString);
            } else {
                unzippedByteArray = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(eventString));
            }
            Input input = new Input(unzippedByteArray);
            Map<String, Object> aggregatedEvent = kryoTL.get().readObjectOrNull(input, HashMap.class);

            ArrayList<Map<String, Object>> eventsList = (ArrayList<Map<String, Object>>) aggregatedEvent
                    .get(AnalyticsConstants.EVENTS_ATTRIBUTE);
            ArrayList<PublishingPayload> payloadsList = (ArrayList<PublishingPayload>) aggregatedEvent
                    .get(AnalyticsConstants.PAYLOADS_ATTRIBUTE);
            Map<Integer, Map<String, String>> payloadsMap = null;
            if (payloadsList != null) {
                payloadsMap = CompressedEventAnalyticsUtils.getPayloadsAsMap(payloadsList);
            }

            String host = (String) aggregatedEvent.get(AnalyticsConstants.HOST_ATTRIBUTE);
            String messageFlowId = (String) aggregatedEvent.get(AnalyticsConstants.MESSAGE_FLOW_ID_ATTRIBUTE);
            // Iterate over the array of events
            for (int i = 0; i < eventsList.size(); i++) {
                StreamEvent decompressedEvent = streamEventCloner.copyStreamEvent(compressedEvent);
                // Create a new event with decompressed fields
                Set<String> outputColumns = this.fields.keySet();
                Object[] decompressedFields = CompressedEventAnalyticsUtils.getFieldValues(eventsList.get(i),
                        outputColumns.toArray(new String[outputColumns.size()]), payloadsMap, i,
                        compressedEvent.getTimestamp(), host, messageFlowId);
                complexEventPopulater.populateComplexEvent(decompressedEvent, decompressedFields);
                decompressedStreamEventChunk.add(decompressedEvent);
            }
        } else {
            throw new ExecutionPlanRuntimeException(
                    "Error occured while decompressing events. No compressed" + " data found.");
        }
    }
    nextProcessor.process(decompressedStreamEventChunk);
}

From source file:org.wso2.carbon.analytics.spark.core.util.CompressedEventAnalyticsUtils.java

/**
 * Decompress a compressed event string.
 * //from w  w  w . jav a2 s.c om
 * @param str   Compressed string
 * @return      Decompressed string
 */
public static ByteArrayInputStream decompress(String str) {
    ByteArrayInputStream byteInputStream = null;
    GZIPInputStream gzipInputStream = null;
    try {
        byteInputStream = new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(str));
        gzipInputStream = new GZIPInputStream(byteInputStream);
        byte[] unzippedBytes = IOUtils.toByteArray(gzipInputStream);
        return new ByteArrayInputStream(unzippedBytes);
    } catch (IOException e) {
        throw new RuntimeException("Error occured while decompressing events string: " + e.getMessage(), e);
    } finally {
        try {
            if (byteInputStream != null) {
                byteInputStream.close();
            }
            if (gzipInputStream != null) {
                gzipInputStream.close();
            }
        } catch (IOException e) {
            log.error("Error occured while closing streams: " + e.getMessage(), e);
        }
    }
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

/**
 * This method is used to retrieve signed certificate from certificate signing request.
 *
 * @param binarySecurityToken CSR that comes from the client as a String value.It is base 64 encoded request
 *                            security token.
 * @return Return signed certificate in X508Certificate type object.
 * @throws KeystoreException/*from  w w  w.j ava2 s .c  o m*/
 */
public X509Certificate getSignedCertificateFromCSR(String binarySecurityToken) throws KeystoreException {
    byte[] byteArrayBst = DatatypeConverter.parseBase64Binary(binarySecurityToken);
    PKCS10CertificationRequest certificationRequest;
    KeyStoreReader keyStoreReader = new KeyStoreReader();
    PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey();
    X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate();

    try {
        certificationRequest = new PKCS10CertificationRequest(byteArrayBst);
    } catch (IOException e) {
        throw new KeystoreException("CSR cannot be recovered.", e);
    }
    return generateCertificateFromCSR(privateKeyCA, certificationRequest,
            certCA.getIssuerX500Principal().getName());
}

From source file:org.wso2.carbon.repository.core.ResourceStorer.java

private void restoreRecursively(String path, XMLStreamReader xmlReader, DumpReader dumpReader,
        long currentVersion, boolean resourceExists) throws RepositoryException, XMLStreamException {
    while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
        xmlReader.next();/*from   ww w.j  a  v  a2  s  . c  o  m*/
    }

    if (!xmlReader.hasNext()) {
        return;
    }

    if (!xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        String msg = "Invalid dump to restore at " + path;
        log.error(msg);
        throw new RepositoryException(msg);
    }

    String incomingParentPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);

    String resourceName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
    String ignoreConflictsStrValue = xmlReader.getAttributeValue(null, DumpConstants.IGNORE_CONFLICTS);

    boolean ignoreConflicts = true;

    if (ignoreConflictsStrValue != null && Boolean.toString(false).equals(ignoreConflictsStrValue)) {
        ignoreConflicts = false;
    }

    String isCollectionString = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_IS_COLLECTION);
    boolean isCollection = isCollectionString.equals(DumpConstants.RESOURCE_IS_COLLECTION_TRUE);

    if (path.equals(RepositoryConstants.ROOT_PATH) && !isCollection) {
        String msg = "Illegal to restore a non-collection in place of root collection.";
        log.error(msg);
        throw new RepositoryException(msg);
    }

    String status = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_STATUS);

    if (DumpConstants.RESOURCE_DELETED.equals(status) && resourceExists) {
        delete(path);
        return;
    }

    ResourceImpl resourceImpl;
    byte[] contentBytes = new byte[0];

    if (isCollection) {
        resourceImpl = new CollectionImpl();
    } else {
        resourceImpl = new ResourceImpl();
    }

    boolean isCreatorExisting = false;
    boolean isCreatedTimeExisting = false;
    boolean isUpdaterExisting = false;
    boolean isUpdatedTimeExisting = false;
    long dumpingResourceVersion = -1;

    do {
        xmlReader.next();
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    while (xmlReader.hasNext()) {
        String localName = xmlReader.getLocalName();

        // setMediaType
        if (localName.equals(DumpConstants.MEDIA_TYPE)) {
            String text = xmlReader.getElementText();
            if (text.indexOf('/') < 0) {
                text = MediaTypesUtils.getMediaType("dummy." + text);
            }
            if (text != null) {
                resourceImpl.setMediaType(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        } else if (localName.equals(DumpConstants.CREATOR)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setAuthorUserName(text);
                isCreatorExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // version: just to keep track of the server changes
        else if (localName.equals(DumpConstants.VERSION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                dumpingResourceVersion = Long.parseLong(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // uuid: just to keep track of the server changes
        else if (localName.equals(DumpConstants.UUID)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setUUID(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // createdTime
        else if (localName.equals(DumpConstants.CREATED_TIME)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setCreatedTime(new Date(date));
                isCreatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // setLastUpdater
        else if (localName.equals(DumpConstants.LAST_UPDATER)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setLastUpdaterUserName(text);
                isUpdaterExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // LastModified
        else if (localName.equals(DumpConstants.LAST_MODIFIED)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                long date = Long.parseLong(text);
                resourceImpl.setLastModified(new Date(date));
                isUpdatedTimeExisting = true;
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get description
        else if (localName.equals(DumpConstants.DESCRIPTION)) {
            String text = xmlReader.getElementText();
            if (text != null) {
                resourceImpl.setDescription(text);
            }
            // now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
        // get properties
        else if (localName.equals(DumpConstants.PROPERTIES)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.PROPERTY_ENTRY)) {
                String key = xmlReader.getAttributeValue(null, DumpConstants.PROPERTY_ENTRY_KEY);
                String text = xmlReader.getElementText();
                if (text.equals("")) {
                    text = null;
                }
                if (text != null) {
                    resourceImpl.addPropertyWithNoUpdate(key, text);
                }
                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            }
        }
        // get content
        else if (localName.equals(DumpConstants.CONTENT)) {
            String text = xmlReader.getElementText();
            // we keep content as base64 encoded
            if (text != null) {
                contentBytes = DatatypeConverter.parseBase64Binary(text);
            }
            do {
                xmlReader.next();
            } while ((!xmlReader.isStartElement() && xmlReader.hasNext())
                    && !(xmlReader.isEndElement() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
        }

        // getting rating information
        else if (localName.equals(DumpConstants.ASSOCIATIONS)) {
            // iterating trying to find the children..
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
            while (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.ASSOCIATION_ENTRY)) {
                String source = null;
                String destination = null;
                String type = null;

                do {
                    xmlReader.next();
                } while (!xmlReader.isStartElement() && xmlReader.hasNext());

                localName = xmlReader.getLocalName();
                while (xmlReader.hasNext() && (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)
                        || localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE))) {
                    if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_SOURCE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            source = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_DESTINATION)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            destination = text;
                        }
                    } else if (localName.equals(DumpConstants.ASSOCIATION_ENTRY_TYPE)) {
                        String text = xmlReader.getElementText();
                        if (text != null) {
                            type = text;
                        }
                    }
                    do {
                        xmlReader.next();
                    } while (!xmlReader.isStartElement() && xmlReader.hasNext());
                    if (xmlReader.hasNext()) {
                        localName = xmlReader.getLocalName();
                    }
                }
                // get the source and destination as absolute paths
                source = RepositoryUtils.getAbsoluteAssociationPath(source, path);
                if (destination.startsWith(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX)) {
                    destination = destination
                            .substring(DumpConstants.EXTERNAL_ASSOCIATION_DESTINATION_PREFIX.length());
                } else {
                    destination = RepositoryUtils.getAbsoluteAssociationPath(destination, path);
                }
                //                    associationList.add(new Association(source, destination, type));
            }
        }

        // getting children, just storing in array list now, will used at the end
        // we are keeping old name to keep backward compatibility.
        else if (localName.equals(DumpConstants.CHILDREN) || localName.equals(DumpConstants.CHILDS)) {
            // we keep the stream to call this function recursively
            break;
        } else if (localName.equals(DumpConstants.RESOURCE)) {
            // we keep the stream to call this function recursively
            break;
        } else {
            // we don't mind having unwanted elements, now go to the next element
            do {
                xmlReader.next();
            } while (!xmlReader.isStartElement() && xmlReader.hasNext());
        }
    }

    if (!ignoreConflicts) {
        // so we handling the conflicts.
        if (dumpingResourceVersion > 0) {
            if (currentVersion == -1) {
                // the current version == -1 means the resource is deleted in the server
                // but since the client is sending a version number, it has a previously checkout
                // resource
                String msg = "Resource is deleted in the server, resource path: " + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }
            // we should check whether our dump is up-to-date
            if (currentVersion > dumpingResourceVersion) {
                // that mean the current resource is updated before the current version
                // so we have to notify user to get an update
                String msg = "Resource is in a newer version than the restoring version. " + "resource path: "
                        + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }
        }
    }

    // completing the empty fields
    if (!isCreatorExisting) {
        String creator = CurrentContext.getUser();
        resourceImpl.setAuthorUserName(creator);
    }

    if (!isCreatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setCreatedTime(new Date(now));
    }

    if (!isUpdaterExisting) {
        String updater = CurrentContext.getUser();
        resourceImpl.setLastUpdaterUserName(updater);
    }

    if (!isUpdatedTimeExisting) {
        long now = System.currentTimeMillis();
        resourceImpl.setLastModified(new Date(now));
    }

    if (resourceImpl.getUUID() == null) {
        setUUIDForResource(resourceImpl);
    }

    // create sym links
    String linkRestoration = resourceImpl.getPropertyValue(InternalConstants.REGISTRY_LINK_RESTORATION);
    if (linkRestoration != null) {
        String[] parts = linkRestoration.split(RepositoryConstants.URL_SEPARATOR);

        if (parts.length == 4) {
            if (parts[2] != null && parts[2].length() == 0) {
                parts[2] = null;
            }
            if (parts[0] != null && parts[1] != null && parts[3] != null) {
                InternalUtils.registerHandlerForRemoteLinks(RepositoryContext.getBaseInstance(), parts[0],
                        parts[1], parts[2], parts[3]);
            }
        } else if (parts.length == 3) {
            // here parts[0] the current path, path[1] is the target path.
            if (parts[0] != null && parts[1] != null) {
                // first we are calculating the relative path of path[1] to path[0]
                String relativeTargetPath = RepositoryUtils.getRelativeAssociationPath(parts[1], parts[0]);
                // then we derive the absolute path with reference to the current path.
                String absoluteTargetPath = RepositoryUtils.getAbsoluteAssociationPath(relativeTargetPath,
                        path);
                InternalUtils.registerHandlerForSymbolicLinks(RepositoryContext.getBaseInstance(), path,
                        absoluteTargetPath, parts[2]);
            }
        }
    }

    synchronized (this) {
        ResourceIDImpl resourceID = null;
        ResourceDO resourceDO = null;

        if (resourceDAO.resourceExists(path)) {
            resourceID = resourceDAO.getResourceID(path);
            resourceDO = resourceDAO.getResourceDO(resourceID);

            if (resourceDO == null) {
                if (isCollection) {
                    resourceID = resourceDAO.getResourceID(path, isCollection);

                    if (resourceID != null) {
                        resourceDO = resourceDAO.getResourceDO(resourceID);
                    }
                }

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

        if (DumpConstants.RESOURCE_UPDATED.equals(status) || DumpConstants.RESOURCE_ADDED.equals(status)
                || DumpConstants.RESOURCE_DUMP.equals(status)) {
            if (resourceDAO.resourceExists(path)) {
                if (DumpConstants.RESOURCE_DUMP.equals(status)) {
                    delete(path);
                } else {
                    deleteNode(resourceID, resourceDO, true);
                }
            }

            if (resourceID == null) {
                // need to create a resourceID
                String parentPath = RepositoryUtils.getParentPath(path);

                ResourceIDImpl parentResourceID = resourceDAO.getResourceID(parentPath, true);
                if (parentResourceID == null || !resourceDAO.resourceExists(parentResourceID)) {
                    addEmptyCollection(parentPath);
                    if (parentResourceID == null) {
                        parentResourceID = resourceDAO.getResourceID(parentPath, true);
                    }
                }
                resourceDAO.createAndApplyResourceID(path, parentResourceID, resourceImpl);
            } else {
                resourceImpl.setPathID(resourceID.getPathID());
                resourceImpl.setName(resourceID.getName());
                resourceImpl.setPath(path);
            }

            // adding resource followed by content (for nonCollection)
            if (!isCollection) {
                int contentId = 0;

                if (contentBytes.length > 0) {
                    contentId = resourceDAO.addContentBytes(new ByteArrayInputStream(contentBytes));
                }

                resourceImpl.setDbBasedContentID(contentId);
            }

            resourceDO = resourceImpl.getResourceDO();
            resourceDAO.addResourceDO(resourceDO);
            resourceImpl.setVersionNumber(resourceDO.getVersion());

            // adding the properties.
            resourceDAO.addProperties(resourceImpl);
        }
    }

    if (!xmlReader.hasNext() || !(xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
            || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
        // finished the recursion
        return;
    }

    do {
        xmlReader.next();
        if (xmlReader.isEndElement() && (xmlReader.getLocalName().equals(DumpConstants.CHILDREN)
                || xmlReader.getLocalName().equals(DumpConstants.CHILDS))) {
            // this means empty children, just quit from here
            // before that we have to set the cursor to the start of the next element
            if (xmlReader.hasNext()) {
                do {
                    xmlReader.next();
                } while ((!xmlReader.isStartElement() && xmlReader.hasNext()) && !(xmlReader.isEndElement()
                        && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)));
            }
            Resource resource = get(path);

            if (resource instanceof Collection) {
                String[] existingChildren = ((Collection) resource).getChildPaths();
                for (String existingChild : existingChildren) {
                    delete(existingChild);
                }
            }

            return;
        }
    } while (!xmlReader.isStartElement() && xmlReader.hasNext());

    int i = 0;

    if (xmlReader.hasNext() && xmlReader.getLocalName().equals(DumpConstants.RESOURCE)) {
        Set<String> childPathSet = new HashSet<String>();

        while (true) {
            if (i != 0) {
                dumpReader.setReadingChildResourceIndex(i);

                // otherwise we will set the stuff for the next resource
                // get an xlm reader in the checking child by parent mode.
                xmlReader = XMLInputFactory.newInstance().createXMLStreamReader(dumpReader);

                while (!xmlReader.isStartElement() && xmlReader.hasNext()) {
                    xmlReader.next();
                }
            }

            String absoluteChildPath;

            if (incomingParentPath != null) {
                // the code to support backward compatibility.
                // prepare the children absolute path
                String incomingChildPath = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_PATH);
                /*                    if (!incomingChildPath.startsWith(incomingParentPath)) {
                //break;
                                    }*/

                String relativeChildPath;

                if (incomingParentPath.equals(RepositoryConstants.ROOT_PATH)) {
                    relativeChildPath = incomingChildPath;
                } else {
                    if (incomingParentPath.contains(incomingChildPath)) {
                        relativeChildPath = incomingChildPath.substring(incomingParentPath.length());
                    } else {
                        // this happens only at some custom editing of dump.xml
                        relativeChildPath = null;
                    }
                }
                if (relativeChildPath != null) {
                    if (path.equals(RepositoryConstants.ROOT_PATH)) {
                        absoluteChildPath = relativeChildPath;
                    } else {
                        absoluteChildPath = path + relativeChildPath;
                    }
                } else {
                    String checkoutRoot = path.substring(0, path.length() - incomingParentPath.length());
                    absoluteChildPath = checkoutRoot + incomingChildPath;
                }
            } else if (resourceName != null) {
                String childName = xmlReader.getAttributeValue(null, DumpConstants.RESOURCE_NAME);
                absoluteChildPath = path
                        + (path.equals(RepositoryConstants.ROOT_PATH) ? "" : RepositoryConstants.PATH_SEPARATOR)
                        + childName;
            } else {
                String msg = "Error in deriving the child paths for collection. path: " + path + ".";
                log.error(msg);
                throw new RepositoryException(msg);
            }

            // we give the control back to the child.
            dumpReader.setCheckingChildByParent(false);

            dumpReader.setReadingChildResourceIndex(i);
            // call the check in method recursively

            recursionRepository.restoreRecursively(absoluteChildPath, dumpReader);
            childPathSet.add(absoluteChildPath);

            dumpReader.setCheckingChildByParent(true);

            try {
                if (dumpReader.isLastResource(i)) {
                    dumpReader.setCheckingChildByParent(false);
                    break;
                }
            } catch (IOException e) {
                String msg = "Error in checking the last resource exists.";
                log.error(msg, e);
                throw new RepositoryException(msg + e.getMessage(), e);
            }
            // by this time i ++ child resource should exist
            i++;
        }

        Collection parent = (Collection) get(path);
        String[] existingChildren = parent.getChildPaths();

        for (String existingChild : existingChildren) {
            if (!childPathSet.contains(existingChild)) {
                delete(existingChild);
            }
        }
    }
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

private static byte[] parseDERFromPEM(byte[] pem, String beginDelimiter, String endDelimiter) {
    String data = new String(pem);
    String[] tokens = data.split(beginDelimiter);
    tokens = tokens[1].split(endDelimiter);
    return DatatypeConverter.parseBase64Binary(tokens[0]);
}