MxSwiftMessage.java 18.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
/*
 * Copyright 2006-2021 Prowide
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.prowidesoftware.swift.model;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.prowidesoftware.swift.model.mx.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;

import javax.persistence.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Objects;
import java.util.Optional;

/**
 * MX (ISO 20022) messages entity for JPA persistence.
 *
 * <p>The class holds the full xml content plus message identification metadata gathered from the application header.
 *
 * <p>Notice, the scope of Prowide MX model is the message payload (the actual message or body data) which is the fundamental
 * purpose of the transmission. The transmission wrappers (overhead data) are excluded and intentionally ignored if found.
 *
 * <p>MX messages are uniquely identify by their business process, message functionality, variant and version.<br>
 * Consider the following example: trea.001.001.02
 * <ul>
 * <li>trea refers to 'Treasury'</li>
 * <li>001 refers to 'NDF opening (notification)'</li>
 * <li>001 refers to the variant</li>
 * <li>02 refers to the version message format, in this case version 2 of 'NDF opening' type.</li>
 * </ul>
 *
 * <p>
 * <em>businessProcess</em>: Alphabetic code in four positions (fixed length) identifying the Business Process
 * <br>
 * <em>functionality</em>: Alphanumeric code in three positions (fixed length) identifying the Message Functionality
 * <br>
 * <em>variant</em>: Numeric code in three positions (fixed length) identifying a particular flavor (variant) of Message Functionality
 * <br>
 * <em>version</em>: Numeric code in two positions (fixed length) identifying the version.
 *
 * @since 7.0
 */
@Entity(name = "mx")
@DiscriminatorValue("mx")
public class MxSwiftMessage extends AbstractSwiftMessage {
    private static final long serialVersionUID = -4394356007627575831L;
    private static final transient java.util.logging.Logger log = java.util.logging.Logger.getLogger(MxSwiftMessage.class.getName());

    @Enumerated(EnumType.STRING)
    @Column(length = 4, name = "business_process")
    private MxBusinessProcess businessProcess;

    @Column(length = 3)
    private String functionality;

    @Column(length = 3)
    private String variant;

    @Column(length = 2)
    private String version;

    public MxSwiftMessage() {
        super();
    }

    /**
     * Calls {@link #MxSwiftMessage(String, MessageMetadataStrategy)} with the {@link DefaultMxMetadataStrategy}
     */
    public MxSwiftMessage(final String xml) {
        this(xml, new DefaultMxMetadataStrategy());
    }

    /**
     * Creates a new message reading the message the content from a string.
     *
     * <p>Performs a fast parsing of the header to identify the message.
     * <p>
     * If the string contains several messages, the whole passed content will be save in the message attribute but
     * identification and metadata will be parser from the first one found only.
     *
     * @param xml              the plain ISO 20022 XML content, with or without the optional header
     * @param metadataStrategy a strategy for metadata extraction
     * @since 9.1.6
     */
    public MxSwiftMessage(final String xml, final MessageMetadataStrategy metadataStrategy) {
        super(xml, FileFormat.MX, metadataStrategy);
    }

    /**
     * Calls {@link #MxSwiftMessage(InputStream, MessageMetadataStrategy)} with the {@link DefaultMxMetadataStrategy}
     *
     * @since 7.7
     */
    public MxSwiftMessage(final InputStream stream) throws IOException {
        this(stream, new DefaultMxMetadataStrategy());
    }

    /**
     * Creates a new message reading the message the content from an input stream.
     *
     * @param stream           a stream containing the XML message
     * @param metadataStrategy a strategy for metadata extraction
     * @since 9.1.6
     */
    public MxSwiftMessage(final InputStream stream, final MessageMetadataStrategy metadataStrategy) throws IOException {
        super(stream, FileFormat.MX, metadataStrategy);
    }

    /**
     * Calls {@link #MxSwiftMessage(File, MessageMetadataStrategy)} with the {@link DefaultMxMetadataStrategy}
     *
     * @since 7.7
     */
    public MxSwiftMessage(final File file) throws IOException {
        this(file, new DefaultMxMetadataStrategy());
    }

    /**
     * Creates a new message reading the message the content from a file.
     *
     * @param file             an existing file containing the XML
     * @param metadataStrategy a strategy for metadata extraction
     * @since 9.1.6
     */
    public MxSwiftMessage(final File file, final MessageMetadataStrategy metadataStrategy) throws IOException {
        super(file, FileFormat.MX, metadataStrategy);
    }

    /**
     * Calls {@link #MxSwiftMessage(AbstractMX, MessageMetadataStrategy)} with the {@link DefaultMxMetadataStrategy}
     *
     * @param mx a message object
     */
    public MxSwiftMessage(final AbstractMX mx) {
        this(mx, new DefaultMxMetadataStrategy());
    }

    /**
     * Creates a new message serializing to xml the parameter message object.
     *
     * <p>If the business header is present, the sender and receiver attributes will be set with content from the
     * header; also the internal raw XML will include both 'AppHdr' and 'Document' under a default root element tag
     * as returned by {@link AbstractMX#message()}
     *
     * <br>If the header is not present, sender and receiver will be left null and the raw internal XML will include
     * just the 'Document' element.
     *
     * @param mx               a message object
     * @param metadataStrategy a strategy for metadata extraction
     * @since 9.1.6
     */
    public MxSwiftMessage(final AbstractMX mx, final MessageMetadataStrategy metadataStrategy) {
        // instead of reusing the constructor from XML with mx.message() as parameter
        // we set the message and run the update directly to avoid an unnecessary message type detection
        Validate.notNull(mx, "the message model cannot be null");
        Validate.notNull(metadataStrategy, "the strategy for metadata extraction cannot be null");
        setMessage(mx.message());
        _updateFromMessage(mx.getMxId(), metadataStrategy);
    }

    /**
     * Creates a new message reading the message the content from a string.
     * This is a static version of the constructor {@link #MxSwiftMessage(String)}
     *
     * @since 7.7
     */
    public static MxSwiftMessage parse(final String xml) {
        return new MxSwiftMessage(xml);
    }

    /**
     * Creates a new message reading the message the content from an input stream.
     * This is a static version of the constructor {@link #MxSwiftMessage(InputStream)}
     *
     * @since 7.7
     */
    public static MxSwiftMessage parse(final InputStream stream) throws IOException {
        return new MxSwiftMessage(stream);
    }

    /**
     * Creates a new message reading the message the content from a file.
     * This is a static version of the constructor {@link #MxSwiftMessage(File)}
     *
     * @since 7.7
     */
    public static MxSwiftMessage parse(final File file) throws IOException {
        return new MxSwiftMessage(file);
    }

    /**
     * This method deserializes the JSON data into an MX message object.
     *
     * @see #toJson()
     * @since 7.10.3
     */
    public static MxSwiftMessage fromJson(String json) {
        final Gson gson = new GsonBuilder().create();
        return gson.fromJson(json, MxSwiftMessage.class);
    }

    /**
     * Calls {@link #updateFromMessage(MessageMetadataStrategy)} with {@link DefaultMxMetadataStrategy}
     *
     * @since 7.7
     */
    @Override
    protected void updateFromMessage() {
        _updateFromMessage(null, new DefaultMxMetadataStrategy());
    }

    /**
     * Updates the object attributes with metadata parsed from the message raw content using the provided strategy
     * implementation for several of the metadata fields. The method is called during message creation or update.
     *
     * @since 9.1.6
     */
    @Override
    protected void updateFromMessage(final MessageMetadataStrategy metadataStrategy) {
        Validate.notNull(metadataStrategy, "the strategy for metadata extraction cannot be null");
        _updateFromMessage(null, metadataStrategy);
    }

    private void _updateFromMessage(final MxId id, final MessageMetadataStrategy metadataStrategy) {
        if (message() != null && message().length() > 0) {
            MxId identifier = id != null ? id : MxParseUtils.identifyMessage(this.message()).orElse(null);
            extractMetadata(identifier, getAppHdr(), metadataStrategy);
        }
    }

    /**
     * Updates the the attributes with the raw message and its metadata from the given raw (XML) message content.
     *
     * @param mx the new message content
     * @see #updateFromMessage()
     * @since 7.8.4
     */
    public void updateFromModel(final AbstractMX mx) {
        updateFromModel(mx, new DefaultMxMetadataStrategy());
    }

    public void updateFromModel(final AbstractMX mx, final MessageMetadataStrategy metadataStrategy) {
        Validate.notNull(mx, "the mx parameter cannot be null");
        Validate.notNull(metadataStrategy, "the strategy for metadata extraction cannot be null");
        setMessage(mx.message());
        setFileFormat(FileFormat.MX);
        extractMetadata(mx.getMxId(), mx.getAppHdr(), metadataStrategy);
    }

    private void extractMetadata(MxId identifier, AppHdr headerModel, MessageMetadataStrategy metadataStrategy) {
        MxNode parsedMessage = MxNode.parse(this.message());
        if (headerModel == null || !extractMetadata(headerModel)) {
            extractMetadata(parsedMessage);
        }

        if (identifier != null) {
            this.identifier = identifier.id();
            this.businessProcess = identifier.getBusinessProcess();
            this.functionality = identifier.getFunctionality();
            this.variant = identifier.getVariant();
            this.version = identifier.getVersion();
        }

        applyStrategy(getMessage(), metadataStrategy);
    }

    /**
     * Updates sender, receiver and reference from parameter header
     *
     * @return true if at least some property was updated
     */
    private boolean extractMetadata(AppHdr h) {
        boolean updated = false;
        if (h != null) {
            final String from = h.from();
            if (from != null) {
                super.sender = bic11(from);
                updated = true;
            }

            final String to = h.to();
            if (to != null) {
                super.receiver = bic11(to);
                updated = true;
            }
        }
        return updated;
    }

    /**
     * Updates sender and receiver from the group header element (only present in a subset of Mx messages)
     *
     * @return true if at least some property was updated
     */
    private boolean extractMetadata(MxNode n) {
        boolean updated = false;
        final MxNode groupHeader = n != null ? n.findFirstByName("GrpHdr") : null;
        if (groupHeader != null) {
            MxNode senderBic = groupHeader.findFirst("./InstgAgt/FinInstnId/BIC");
            if (senderBic != null) {
                sender = bic11(senderBic.getValue());
                updated = true;
            }
            MxNode receiverBic = groupHeader.findFirst("./InstdAgt/FinInstnId/BIC");
            if (receiverBic != null) {
                receiver = bic11(receiverBic.getValue());
                updated = true;
            }
        }
        return updated;
    }

    /**
     * Calls {@link #updateFromXML(String, MxId, MessageMetadataStrategy)} with {@link DefaultMxMetadataStrategy}
     *
     * @since 7.8.4
     */
    public void updateFromXML(final String xml) {
        updateFromXML(xml, null);
    }

    /**
     * Calls {@link #updateFromXML(String, MxId, MessageMetadataStrategy)} with {@link DefaultMxMetadataStrategy}
     *
     * @since 7.8.4
     */
    public void updateFromXML(final String xml, final MxId id) {
        updateFromXML(xml, id, new DefaultMxMetadataStrategy());
    }

    /**
     * Updates the the attributes with the raw message and its metadata from the given raw (XML) message content.
     * Wrapper around AppHdr/Document, if present, are preserved and ignored.
     *
     * @param xml              the XML content of an MX message containing the Document and optional AppHdr elements
     * @param id               the specific Mx type identification or null if message is unknown
     * @param metadataStrategy the strategy implementation to use for metadata extraction
     * @since 9.1.6
     */
    public void updateFromXML(final String xml, final MxId id, final MessageMetadataStrategy metadataStrategy) {
        Validate.notNull(xml, "the xml message parameter cannot be null");
        Validate.notNull(metadataStrategy, "the strategy for metadata extraction cannot be null");
        setMessage(xml);
        setFileFormat(FileFormat.MX);
        _updateFromMessage(id, metadataStrategy);
    }

    public MxBusinessProcess getBusinessProcess() {
        return businessProcess;
    }

    public void setBusinessProcess(MxBusinessProcess businessProcess) {
        this.businessProcess = businessProcess;
    }

    public String getFunctionality() {
        return functionality;
    }

    public void setFunctionality(String functionality) {
        this.functionality = functionality;
    }

    public String getVariant() {
        return variant;
    }

    public void setVariant(String variant) {
        this.variant = variant;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;
        MxSwiftMessage that = (MxSwiftMessage) o;
        return businessProcess == that.businessProcess &&
                Objects.equals(functionality, that.functionality) &&
                Objects.equals(variant, that.variant) &&
                Objects.equals(version, that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(super.hashCode(), businessProcess, functionality, variant, version);
    }

    /**
     * If present in the message content, returns the business header (SWIFT or ISO version)
     * Notice this header is optional and may not be present.
     *
     * @return found header or null if not present or cannot be parsed into a header object
     * @see AppHdrParser#parse(String)
     * @since 9.0.1
     */
    public AppHdr getAppHdr() {
        return AppHdrParser.parse(this.message()).orElse(null);
    }

    /**
     * Creates a full copy of the current message object into another message.
     *
     * @param msg target message
     * @see AbstractSwiftMessage#copyTo(AbstractSwiftMessage)
     * @since 7.7
     */
    public void copyTo(MxSwiftMessage msg) {
        super.copyTo(msg);
        msg.setBusinessProcess(getBusinessProcess());
        msg.setFunctionality(getFunctionality());
        msg.setVariant(getVariant());
        msg.setVersion(getVersion());
    }

    /**
     * @since 7.8.6
     */
    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("MxSwiftMessage id=").append(getId()).append(" message=").append(getMessage());
        return sb.toString();
    }

    /**
     * Returns this message MX identification
     *
     * @return the identification object for this message
     * @since 7.10.4
     */
    public MxId getMxId() {
        return new MxId(this.businessProcess, this.functionality, this.variant, this.version);
    }

    /**
     * For MT messages returns the category number and for MX messages return the business process.
     * For example for MT103 returns 1 and for pacs.004.001.06 returns pacs
     *
     * @return a string with the category or empty if the identifier is invalid or not present
     * @since 7.10.4
     */
    @Override
    public String getCategory() {
        if (!StringUtils.isBlank(this.identifier)) {
            MxBusinessProcess proc = (new MxId(this.identifier)).getBusinessProcess();
            if (proc != null) {
                return proc.name();
            }
        }
        return "";
    }

    /**
     * Enables injecting your own implementation for the entity metadata extraction, to set the generic properties
     * shared by all message types: main reference, main amount and currency, value date, trade date.
     *
     * @since 9.1.6
     */
    public void updateMetadata(MessageMetadataStrategy strategy) {
        Validate.notNull(strategy, "the strategy for metadata extraction cannot be null");
        applyStrategy(getMessage(), strategy);
    }

    private void applyStrategy(String xml, MessageMetadataStrategy strategy) {
        boolean isKnownType = this.businessProcess != null && this.functionality != null && this.variant != null && this.version != null;
        AbstractMX mx = isKnownType ? AbstractMX.parse(xml, getMxId()) : AbstractMX.parse(xml);

        if (mx == null) {
            // could not parse the XML into a message model
            return;
        }

        String reference = strategy.reference(mx).orElse(null);
        if (StringUtils.isNotBlank(reference)) {
            setReference(reference);
        }

        Optional<Money> money = strategy.amount(mx);
        if (money.isPresent()) {
            setCurrency(money.get().getCurrency());
            setAmount(money.get().getAmount());
        }

        Calendar valueDate = strategy.valueDate(mx).orElse(null);
        if (valueDate != null) {
            setValueDate(valueDate);
        }

        Calendar tradeDate = strategy.tradeDate(mx).orElse(null);
        if (tradeDate != null) {
            setTradeDate(tradeDate);
        }
    }

}