001/** 002 * 003 * Copyright © 2014-2023 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 java.util.Objects; 020 021import javax.xml.namespace.QName; 022 023/** 024 * An XMPP error IQ. 025 * <p> 026 * According to RFC 6120 § 8.3.1 "4. An error stanza MUST contain an <error/> child element.", so this class can 027 * only be constructed if a stanza error is provided. 028 */ 029public final class ErrorIQ extends IQ { 030 031 public static final String ELEMENT = StanzaError.ERROR; 032 033 private final IQ request; 034 035 private ErrorIQ(Builder builder, QName childElementQName) { 036 super(builder, childElementQName); 037 Objects.requireNonNull(builder.getError(), "Must provide an stanza error when building error IQs"); 038 this.request = builder.request; 039 } 040 041 public static ErrorIQ createErrorResponse(final IQ request, final StanzaError error) { 042 Builder builder = new Builder(error, request); 043 builder.setError(error); 044 return builder.build(); 045 } 046 047 @Override 048 protected IQChildElementXmlStringBuilder getIQChildElementBuilder(IQChildElementXmlStringBuilder xml) { 049 if (request == null) { 050 return null; 051 } 052 053 return request.getIQChildElementBuilder(xml); 054 } 055 056 public static Builder builder(StanzaError error) { 057 return new Builder(error, IqData.EMPTY.ofType(IQ.Type.error)); 058 } 059 060 public static Builder builder(StanzaError error, IqData iqData) { 061 return new Builder(error, iqData); 062 } 063 064 public static final class Builder extends IqBuilder<Builder, ErrorIQ> { 065 066 private IQ request; 067 068 Builder(StanzaError error, IqData iqData) { 069 super(iqData); 070 if (iqData.getType() != IQ.Type.error) { 071 throw new IllegalArgumentException("Error IQs must be of type 'error'"); 072 } 073 Objects.requireNonNull(error, "Must provide an stanza error when building error IQs"); 074 setError(error); 075 } 076 077 Builder(StanzaError error, IQ request) { 078 this(error, AbstractIqBuilder.createErrorResponse(request)); 079 this.request = request; 080 } 081 082 @Override 083 public Builder getThis() { 084 return this; 085 } 086 087 @Override 088 public ErrorIQ build() { 089 QName childElementQname = null; 090 if (request != null) { 091 childElementQname = request.getChildElementQName(); 092 } 093 return new ErrorIQ(this, childElementQname); 094 } 095 096 } 097}