001/**
002 *
003 * Copyright 2019 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.dox.element;
018
019import java.io.IOException;
020import java.nio.ByteBuffer;
021
022import org.jivesoftware.smack.packet.IQ;
023import org.jivesoftware.smack.util.stringencoder.Base64;
024
025import org.jxmpp.jid.Jid;
026import org.minidns.dnsmessage.DnsMessage;
027
028public class DnsIq extends IQ {
029
030    public static final String ELEMENT = "dns";
031    public static final String NAMESPACE = "urn:xmpp:dox:0";
032
033    private final DnsMessage dnsMessage;
034
035    private String base64DnsMessage;
036
037    public DnsIq(String base64DnsMessage) throws IOException {
038        this(Base64.decode(base64DnsMessage));
039        this.base64DnsMessage = base64DnsMessage;
040    }
041
042    public DnsIq(byte[] dnsMessage) throws IOException {
043        this(new DnsMessage(dnsMessage));
044    }
045
046    public DnsIq(DnsMessage dnsQuery, Jid to) {
047        this(dnsQuery);
048        setTo(to);
049        setType(Type.get);
050    }
051
052    public DnsIq(DnsMessage dnsMessage) {
053        super(ELEMENT, NAMESPACE);
054        this.dnsMessage = dnsMessage;
055    }
056
057    public DnsMessage getDnsMessage() {
058        return dnsMessage;
059    }
060
061    @SuppressWarnings("ByteBufferBackingArray")
062    public String getDnsMessageBase64Encoded() {
063        if (base64DnsMessage == null) {
064            ByteBuffer byteBuffer = dnsMessage.getInByteBuffer();
065            byte[] bytes = byteBuffer.array();
066            base64DnsMessage = Base64.encodeToStringWithoutPadding(bytes);
067        }
068        return base64DnsMessage;
069    }
070
071    @Override
072    protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) {
073        xml.rightAngleBracket();
074
075        xml.escape(getDnsMessageBase64Encoded());
076
077        return xml;
078    }
079
080}