001/****************************************************************
002 * Licensed to the Apache Software Foundation (ASF) under one   *
003 * or more contributor license agreements.  See the NOTICE file *
004 * distributed with this work for additional information        *
005 * regarding copyright ownership.  The ASF licenses this file   *
006 * to you under the Apache License, Version 2.0 (the            *
007 * "License"); you may not use this file except in compliance   *
008 * with the License.  You may obtain a copy of the License at   *
009 *                                                              *
010 *   http://www.apache.org/licenses/LICENSE-2.0                 *
011 *                                                              *
012 * Unless required by applicable law or agreed to in writing,   *
013 * software distributed under the License is distributed on an  *
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
015 * KIND, either express or implied.  See the License for the    *
016 * specific language governing permissions and limitations      *
017 * under the License.                                           *
018 ****************************************************************/
019
020package org.apache.james.mailbox.indexer.registrations;
021
022import com.google.common.base.Optional;
023import org.apache.james.mailbox.MailboxListener;
024import org.apache.james.mailbox.model.MailboxPath;
025
026import java.util.concurrent.ConcurrentHashMap;
027
028public class GlobalRegistration implements MailboxListener {
029
030    private final ConcurrentHashMap<MailboxPath, Boolean> isPathDeleted;
031    private final ConcurrentHashMap<MailboxPath, MailboxPath> nameCorrespondence;
032
033    public GlobalRegistration() {
034        this.isPathDeleted = new ConcurrentHashMap<MailboxPath, Boolean>();
035        this.nameCorrespondence = new ConcurrentHashMap<MailboxPath, MailboxPath>();
036    }
037
038    public Optional<MailboxPath> getPathToIndex(MailboxPath mailboxPath) {
039        if (isPathDeleted.get(mailboxPath) != null) {
040            return Optional.absent();
041        }
042        return Optional.of(
043            Optional.fromNullable(nameCorrespondence.get(mailboxPath)).or(mailboxPath));
044    }
045
046    @Override
047    public ListenerType getType() {
048        return ListenerType.EACH_NODE;
049    }
050
051    @Override
052    public ExecutionMode getExecutionMode() {
053        return ExecutionMode.SYNCHRONOUS;
054    }
055
056    @Override
057    public void event(Event event) {
058        if (event instanceof MailboxDeletion) {
059            isPathDeleted.put(event.getMailboxPath(), true);
060        } else if (event instanceof MailboxRenamed) {
061            nameCorrespondence.put(event.getMailboxPath(), ((MailboxRenamed) event).getNewPath());
062        }
063    }
064}