001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.messageboards.util.comparator;
016    
017    import com.liferay.portal.kernel.util.DateUtil;
018    import com.liferay.portlet.messageboards.model.MBMessage;
019    
020    import java.io.Serializable;
021    
022    import java.util.Comparator;
023    
024    /**
025     * @author Brian Wing Shun Chan
026     */
027    public class MessageThreadComparator
028            implements Comparator<MBMessage>, Serializable {
029    
030            public MessageThreadComparator() {
031                    this(true);
032            }
033    
034            public MessageThreadComparator(boolean ascending) {
035                    _ascending = ascending;
036            }
037    
038            @Override
039            public int compare(MBMessage msg1, MBMessage msg2) {
040                    Long parentMessageId1 = Long.valueOf(msg1.getParentMessageId());
041                    Long parentMessageId2 = Long.valueOf(msg2.getParentMessageId());
042    
043                    int value = parentMessageId1.compareTo(parentMessageId2);
044    
045                    if (value == 0) {
046                            value = DateUtil.compareTo(
047                                    msg1.getCreateDate(), msg2.getCreateDate());
048                    }
049    
050                    if (value == 0) {
051                            Long messageId1 = Long.valueOf(msg1.getMessageId());
052                            Long messageId2 = Long.valueOf(msg2.getMessageId());
053    
054                            value = messageId1.compareTo(messageId2);
055                    }
056    
057                    if (_ascending) {
058                            return value;
059                    }
060                    else {
061                            return -value;
062                    }
063            }
064    
065            private final boolean _ascending;
066    
067    }