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    // TODO: Deprecate and use corresponding method in IqData instead.
044    public static IqData createResponse(IqView request) {
045        return createResponse(request, IQ.ResponseType.result);
046    }
047
048    // TODO: Deprecate and use corresponding method in IqData instead.
049    public static IqData createErrorResponse(IqView request) {
050        return createResponse(request, IQ.ResponseType.error);
051    }
052
053    protected static IqData createResponse(IqView request, IQ.ResponseType responseType) {
054        if (!request.isRequestIQ()) {
055            throw new IllegalArgumentException("IQ request must be of type 'set' or 'get'. Original IQ: " + request);
056        }
057
058        IqData commonResponseIqData = buildResponse(request, s -> {
059            return StanzaBuilder.buildIqData(s);
060        });
061        commonResponseIqData.ofType(responseType.getType());
062
063        return commonResponseIqData;
064    }
065
066    @Override
067    protected final void addStanzaSpecificAttributes(ToStringUtil.Builder builder) {
068        builder.addValue("type", getType());
069    }
070
071    @Override
072    public final IQ.Type getType() {
073        return type;
074    }
075}