001/**
002 *
003 * Copyright 2019-2020 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.smack.packet;
018
019import org.jivesoftware.smack.packet.id.StanzaIdSource;
020import org.jivesoftware.smack.util.ToStringUtil;
021
022public abstract class AbstractIqBuilder<IB extends AbstractIqBuilder<IB>> extends StanzaBuilder<IB> implements IqView {
023
024    protected IQ.Type type = IQ.Type.get;
025
026    AbstractIqBuilder(IQ other, String stanzaId) {
027        super(other, stanzaId);
028    }
029
030    AbstractIqBuilder(AbstractIqBuilder<?> other) {
031        super(other);
032        type = other.type;
033    }
034
035    AbstractIqBuilder(StanzaIdSource stanzaIdSource) {
036        super(stanzaIdSource);
037    }
038
039    AbstractIqBuilder(String stanzaId) {
040        super(stanzaId);
041    }
042
043    public static IqData createResponse(IqView request) {
044        return createResponse(request, IQ.ResponseType.result);
045    }
046
047    public static IqData createErrorResponse(IqView request) {
048        return createResponse(request, IQ.ResponseType.error);
049    }
050
051    protected static IqData createResponse(IqView request, IQ.ResponseType responseType) {
052        if (!(request.getType() == IQ.Type.get || request.getType() == IQ.Type.set)) {
053            throw new IllegalArgumentException("IQ request must be of type 'set' or 'get'. Original IQ: " + request);
054        }
055
056        IqData commonResponseIqData = buildResponse(request, s -> {
057            return StanzaBuilder.buildIqData(s);
058        });
059        commonResponseIqData.ofType(responseType.getType());
060
061        return commonResponseIqData;
062    }
063
064    @Override
065    protected final void addStanzaSpecificAttributes(ToStringUtil.Builder builder) {
066        builder.addValue("type", getType());
067    }
068
069    @Override
070    public final IQ.Type getType() {
071        return type;
072    }
073}