Example usage for java.lang Long equals

List of usage examples for java.lang Long equals

Introduction

In this page you can find the example usage for java.lang Long equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:org.kuali.mobility.maps.service.LocationServiceImpl.java

@Transactional
public void removeMapsGroupFromLocation(Long groupId, Long locationId) {
    Location location = this.getLocationById(locationId);
    Set<MapsGroup> mapsGroups = location.getMapsGroups();
    MapsGroup mapsGroupRemove = null;//ww w  .  j  a va  2s  .c om
    for (MapsGroup mapsGroup : mapsGroups) {
        if (groupId.equals(mapsGroup.getGroupId())) {
            mapsGroupRemove = mapsGroup;
            break;
        }
    }
    if (mapsGroupRemove != null) {
        location.getMapsGroups().remove(mapsGroupRemove);
        this.saveLocation(location);
    }
}

From source file:com.moss.appkeep.server.AppkeepServiceImpl.java

private StoredComponent resolve(ComponentSelector selector) {
    final StoredComponent result;

    final List<StoredComponent> matches = selector
            .accept(new ComponentSelectorVisitor<List<StoredComponent>>() {
                public List<StoredComponent> visit(ComponentHandlesSelector handles) {
                    final ComponentHandlesMatchJoiner joiner = new ComponentHandlesMatchJoiner(handles);

                    for (ComponentHandle handle : handles.handles()) {
                        handle.accept(new ComponentHandleVisitor<Void>() {

                            public Void visit(final CRC32ComponentHandle h) {

                                data.componentsByCrc32.keySearchForward(h.value(),
                                        new SearchVisitor<Long, StoredComponent>() {
                                            public boolean next(Long key, StoredComponent value) {
                                                if (key.equals(h.value())) {

                                                    joiner.addMatch(h, value);

                                                    return true;
                                                } else {
                                                    return false;
                                                }
                                            }
                                        }, null);

                                return null;
                            }//w  w  w.ja va2  s.  c o m

                            public Void visit(final MavenCoordinatesHandle m) {
                                final MavenKey k = new MavenKey(m.coordinates());

                                data.componentsByMavenId.keySearchForward(k,
                                        new SearchVisitor<MavenKey, StoredComponent>() {
                                            public boolean next(MavenKey key, StoredComponent value) {
                                                if (key.equals(k)) {
                                                    joiner.addMatch(m, value);
                                                    return true;
                                                } else {
                                                    return false;
                                                }
                                            }
                                        }, null);

                                return null;
                            }

                            public Void visit(final Md5ComponentHandle h) {
                                final byte[] hash = h.hash();

                                data.componentsByMd5.keySearchForward(hash,
                                        new SearchVisitor<byte[], StoredComponent>() {
                                            public boolean next(byte[] key, StoredComponent value) {
                                                if (AppkeepServiceImpl.equals(hash, key)) {
                                                    joiner.addMatch(h, value);
                                                    return true;
                                                } else {
                                                    return false;
                                                }
                                            }
                                        }, null);
                                return null;
                            }

                            public Void visit(final BuildTimestampComponentHandle h) {

                                data.componentsByWhenBuilt.keySearchForward(h.getWhenBuilt(),
                                        new SearchVisitor<Instant, StoredComponent>() {
                                            public boolean next(Instant key, StoredComponent value) {
                                                if (key.equals(h.getWhenBuilt())) {
                                                    joiner.addMatch(h, value);
                                                    return true;
                                                } else {
                                                    return false;
                                                }
                                            }
                                        }, null);

                                return null;
                            }

                        });
                    }
                    return joiner.fullMatches();
                }

                public List<StoredComponent> visit(DirectComponentSelector directSelector) {
                    return Collections.singletonList(
                            data.components.get(directSelector.id(), null, LockMode.READ_COMMITTED));
                }
            });

    // HANDLE MULTIPLE MATCHES
    if (matches.size() == 0) {
        result = null;
    } else if (matches.size() == 1) {
        result = matches.get(0);
    } else {
        StoredComponent latest = null;
        for (StoredComponent next : matches) {
            if (latest == null || next.whenAdded().isAfter(latest.whenAdded())) {
                latest = next;
            }
        }
        result = latest;
    }
    return result;
}

From source file:jp.co.opentone.bsol.linkbinder.service.admin.impl.UserServiceImpl.java

private CorresponGroup checkDefaultCorresponGroup(String userId, String projectId, Long corresponGroupId)
        throws ServiceAbortException {
    List<CorresponGroupUser> corresponGroupUserList = findCorresponGroupUserList(userId, projectId);
    for (CorresponGroupUser corresponGroupUser : corresponGroupUserList) {
        if (corresponGroupId.equals(corresponGroupUser.getCorresponGroup().getId())) {
            return corresponGroupUser.getCorresponGroup();
        }/*from   w w  w . ja  v  a  2  s .  co m*/
    }

    //?
    throw new ServiceAbortException(
            ApplicationMessageCode.CANNOT_PERFORM_BECAUSE_CORRESPON_GROUP_NOT_RELATED_WITH_USER);
}

From source file:com.evolveum.midpoint.prism.PrismContainer.java

public PrismContainerValue<C> getValue(Long id) {
    for (PrismContainerValue<C> pval : getValues()) {
        if ((id == null && pval.getId() == null) || id.equals(pval.getId())) {
            return pval;
        }/*from   w  ww .  ja  v a2 s .  c  om*/
    }
    return null;
}

From source file:io.plaidapp.ui.DesignerNewsStory.java

private boolean isOP(Long userId) {
    return userId.equals(story.user_id);
}

From source file:de.micromata.genome.chronos.spi.ram.RamJobStore.java

/**
 * Gets the job result count.//from   w w  w .  j  a v  a2s.  c  om
 *
 * @param schedulerName the scheduler name
 * @param state the state
 * @return the job result count
 */
public synchronized long getJobResultCount(String schedulerName, State state) {
    Long schedPk = findSchedulerPkByName(schedulerName);
    long result = 0;
    for (List<JobResultDO> lr : jobResults.values()) {
        for (JobResultDO jr : lr) {
            if (state != null && jr.getState() != state) {
                continue;
            }
            if (schedulerName != null) {
                TriggerJobDO jb = getJobByPk(jr.getJobPk());
                if (jb == null) {
                    continue;
                }
                if (schedPk != null && schedPk.equals(jb.getScheduler()) == false) {
                    continue;
                }
            }
            ++result;
        }
    }
    return result;
}

From source file:com.ushahidi.swiftriver.core.api.service.AccountService.java

/**
 * Adds the {@link Account} with the specified <code>accountId</code> to the
 * list of followers for the {@link Account} specified in <code>id</code>
 * /*from  www.  jav  a2s  .  co m*/
 * @param id
 * @param accountId
 */
@Transactional
public void addFollower(Long id, Long accountId) {
    if (id.equals(accountId)) {
        throw new BadRequestException("An account cannot follow itself");
    }

    Account account = getAccount(id);

    if (accountDao.getFollower(account, accountId) != null) {
        throw new BadRequestException(
                String.format("Account %d is already following account %d", accountId, id));
    }

    Account follower = getAccount(accountId);
    accountDao.addFollower(account, follower);

    logActivity(follower, ActivityType.FOLLOW, account);
}

From source file:lineage2.gameserver.network.clientpackets.EnterWorld.java

/**
 * Method runImpl./*from  w  w  w .  j ava  2s  .  c o m*/
 */
@Override
protected void runImpl() {
    GameClient client = getClient();
    Player activeChar = client.getActiveChar();
    if (activeChar == null) {
        client.closeNow(false);
        return;
    }
    int MyObjectId = activeChar.getObjectId();
    Long MyStoreId = activeChar.getStoredId();
    for (Castle castle : ResidenceHolder.getInstance().getResidenceList(Castle.class)) {
        activeChar.sendPacket(new ExCastleState(castle));
    }
    synchronized (_lock) {

        for (Player cha : GameObjectsStorage.getAllPlayersForIterate()) {
            if (MyStoreId.equals(cha.getStoredId())) {
                continue;
            }
            try {
                if (cha.getObjectId() == MyObjectId) {
                    _log.warn("Double EnterWorld for char: " + activeChar.getName());
                    cha.kick();
                }
            } catch (Exception e) {
                _log.error("", e);
            }
        }
    }
    GameStats.incrementPlayerEnterGame();
    boolean first = activeChar.entering;
    if (first) {
        activeChar.setOnlineStatus(true);
        if (activeChar.getPlayerAccess().GodMode && !Config.SHOW_GM_LOGIN) {
            activeChar.setInvisibleType(InvisibleType.NORMAL);
        }
        activeChar.setNonAggroTime(Long.MAX_VALUE);
        activeChar.spawnMe();
        if (activeChar.isInStoreMode()) {
            if (!TradeHelper.checksIfCanOpenStore(activeChar, activeChar.getPrivateStoreType())) {
                activeChar.setPrivateStoreType(Player.STORE_PRIVATE_NONE);
                activeChar.standUp();
                activeChar.broadcastCharInfo();
            }
        }
        activeChar.setRunning();
        activeChar.standUp();
        activeChar.startTimers();
    }
    activeChar.sendPacket(new ExBR_PremiumState(activeChar, activeChar.hasBonus()));

    activeChar.getMacroses().sendUpdate(0x01, 0, true);
    activeChar.sendPacket(new SSQInfo(), new HennaInfo(activeChar));
    activeChar.sendItemList(false);
    activeChar.sendPacket(new ShortCutInit(activeChar));
    activeChar.sendPacket(new ShortCutInit(activeChar), new SkillList(activeChar),
            new SkillCoolTime(activeChar));
    activeChar.sendPacket(new SkillCoolTime(activeChar));
    //activeChar.sendPacket(new ExCastleState(_castle));
    activeChar.sendPacket(new ExVitalityEffectInfo(activeChar));
    for (Castle castle : ResidenceHolder.getInstance().getResidenceList(Castle.class)) {
        activeChar.sendPacket(new ExCastleState(castle));
    }
    activeChar.sendPacket(SystemMsg.WELCOME_TO_THE_WORLD_OF_LINEAGE_II);
    Announcements.getInstance().showAnnouncements(activeChar);
    if (first) {
        activeChar.getListeners().onEnter();
    }
    if (first && (activeChar.getCreateTime() > 0)) {
        Calendar create = Calendar.getInstance();
        create.setTimeInMillis(activeChar.getCreateTime());
        Calendar now = Calendar.getInstance();
        int day = create.get(Calendar.DAY_OF_MONTH);
        if ((create.get(Calendar.MONTH) == Calendar.FEBRUARY) && (day == 29)) {
            day = 28;
        }
        int myBirthdayReceiveYear = activeChar.getVarInt(Player.MY_BIRTHDAY_RECEIVE_YEAR, 0);
        if ((create.get(Calendar.MONTH) == now.get(Calendar.MONTH))
                && (create.get(Calendar.DAY_OF_MONTH) == day)) {
            if (((myBirthdayReceiveYear == 0) && (create.get(Calendar.YEAR) != now.get(Calendar.YEAR)))
                    || ((myBirthdayReceiveYear > 0) && (myBirthdayReceiveYear != now.get(Calendar.YEAR)))) {
                Mail mail = new Mail();
                mail.setSenderId(1);
                mail.setSenderName(StringHolder.getInstance().getNotNull(activeChar, "birthday.npc"));
                mail.setReceiverId(activeChar.getObjectId());
                mail.setReceiverName(activeChar.getName());
                mail.setTopic(StringHolder.getInstance().getNotNull(activeChar, "birthday.title"));
                mail.setBody(StringHolder.getInstance().getNotNull(activeChar, "birthday.text"));
                ItemInstance item = ItemFunctions.createItem(21169);
                item.setLocation(ItemInstance.ItemLocation.MAIL);
                item.setCount(1L);
                item.save();
                mail.addAttachment(item);
                mail.setUnread(true);
                mail.setType(Mail.SenderType.BIRTHDAY);
                mail.setExpireTime((720 * 3600) + (int) (System.currentTimeMillis() / 1000L));
                mail.save();
                activeChar.setVar(Player.MY_BIRTHDAY_RECEIVE_YEAR, String.valueOf(now.get(Calendar.YEAR)), -1);
            }
        }
    }
    if (activeChar.getClan() != null) {
        notifyClanMembers(activeChar);
        activeChar.sendPacket(activeChar.getClan().listAll());
        activeChar.sendPacket(new PledgeShowInfoUpdate(activeChar.getClan()),
                new PledgeSkillList(activeChar.getClan()));
    }
    if (first && Config.ALLOW_WEDDING) {
        CoupleManager.getInstance().engage(activeChar);
        CoupleManager.getInstance().notifyPartner(activeChar);
    }
    if (first) {
        activeChar.getFriendList().notifyFriends(true);
        loadTutorial(activeChar);
        activeChar.restoreDisableSkills();
        activeChar.mentoringLoginConditions();
    }
    sendPacket(new L2FriendList(activeChar), new ExStorageMaxCount(activeChar), new QuestList(activeChar),
            new ExBasicActionList(activeChar), new EtcStatusUpdate(activeChar));
    activeChar.checkHpMessages(activeChar.getMaxHp(), activeChar.getCurrentHp());
    activeChar.checkDayNightMessages();
    if (Config.PETITIONING_ALLOWED) {
        PetitionManager.getInstance().checkPetitionMessages(activeChar);
    }
    if (!first) {
        if (activeChar.isCastingNow()) {
            Creature castingTarget = activeChar.getCastingTarget();
            Skill castingSkill = activeChar.getCastingSkill();
            long animationEndTime = activeChar.getAnimationEndTime();
            if ((castingSkill != null) && (castingTarget != null) && castingTarget.isCreature()
                    && (activeChar.getAnimationEndTime() > 0)) {
                sendPacket(new MagicSkillUse(activeChar, castingTarget, castingSkill.getId(),
                        castingSkill.getLevel(), (int) (animationEndTime - System.currentTimeMillis()), 0));
            }
        }
        if (activeChar.isInBoat()) {
            activeChar.sendPacket(activeChar.getBoat().getOnPacket(activeChar, activeChar.getInBoatPosition()));
        }
        if (activeChar.isMoving || activeChar.isFollow) {
            sendPacket(activeChar.movePacket());
        }
        if (activeChar.getMountNpcId() != 0) {
            sendPacket(new Ride(activeChar));
        }
        if (activeChar.isFishing()) {
            activeChar.stopFishing();
        }
    }
    activeChar.entering = false;
    activeChar.sendUserInfo();
    if (activeChar.isSitting()) {
        activeChar.sendPacket(new ChangeWaitType(activeChar, ChangeWaitType.WT_SITTING));
    }
    if (activeChar.getPrivateStoreType() != Player.STORE_PRIVATE_NONE) {
        if (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_BUY) {
            sendPacket(new PrivateStoreMsgBuy(activeChar));
        } else if ((activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_SELL)
                || (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_SELL_PACKAGE)) {
            sendPacket(new PrivateStoreMsgSell(activeChar));
        } else if (activeChar.getPrivateStoreType() == Player.STORE_PRIVATE_MANUFACTURE) {
            sendPacket(new RecipeShopMsg(activeChar));
        }
    }
    if (activeChar.isDead()) {
        sendPacket(new Die(activeChar));
    }
    activeChar.unsetVar("offline");
    activeChar.sendActionFailed();
    if (first && activeChar.isGM() && Config.SAVE_GM_EFFECTS && activeChar.getPlayerAccess().CanUseGMCommand) {
        if (activeChar.getVarB("gm_silence")) {
            activeChar.setMessageRefusal(true);
            activeChar.sendPacket(SystemMsg.MESSAGE_REFUSAL_MODE);
        }
        if (activeChar.getVarB("gm_invul")) {
            activeChar.setIsInvul(true);
            activeChar.startAbnormalEffect(AbnormalEffect.S_INVINCIBLE);
            activeChar.sendMessage(activeChar.getName() + " is now immortal.");
        }
        try {
            int var_gmspeed = Integer.parseInt(activeChar.getVar("gm_gmspeed"));
            if ((var_gmspeed >= 1) && (var_gmspeed <= 4)) {
                activeChar.doCast(SkillTable.getInstance().getInfo(7029, var_gmspeed), activeChar, true);
            }
        } catch (Exception E) {
        }
    }
    PlayerMessageStack.getInstance().CheckMessages(activeChar);
    sendPacket(ClientSetTime.STATIC, new ExSetCompassZoneCode(activeChar));
    Pair<Integer, OnAnswerListener> entry = activeChar.getAskListener(false);
    if ((entry != null) && (entry.getValue() instanceof ReviveAnswerListener)) {
        sendPacket(new ConfirmDlg(
                SystemMsg.C1_IS_MAKING_AN_ATTEMPT_TO_RESURRECT_YOU_IF_YOU_CHOOSE_THIS_PATH_S2_EXPERIENCE_WILL_BE_RETURNED_FOR_YOU,
                0).addString("Other player").addString("some"));
    }
    if (activeChar.isCursedWeaponEquipped()) {
        CursedWeaponsManager.getInstance().showUsageTime(activeChar, activeChar.getCursedWeaponEquippedId());
    }
    if (!first) {
        if (activeChar.isInObserverMode()) {
            if (activeChar.getObserverMode() == Player.OBSERVER_LEAVING) {
                activeChar.returnFromObserverMode();
            } else if (activeChar.getOlympiadObserveGame() != null) {
                activeChar.leaveOlympiadObserverMode(true);
            } else {
                activeChar.leaveObserverMode();
            }
        } else if (activeChar.isVisible()) {
            World.showObjectsToPlayer(activeChar);
        }
        for (Summon summon : activeChar.getSummonList()) {
            sendPacket(new PetInfo(summon));
        }
        if (activeChar.isInParty()) {
            sendPacket(new PartySmallWindowAll(activeChar.getParty(), activeChar));
            for (Player member : activeChar.getParty().getPartyMembers()) {
                if (member != activeChar) {
                    sendPacket(new PartySpelled(member, true));
                    for (Summon memberPet : member.getSummonList()) {
                        sendPacket(new PartySpelled(memberPet, true));
                    }
                    sendPacket(RelationChanged.update(activeChar, member, activeChar));
                }
            }
            if (activeChar.getParty().isInCommandChannel()) {
                sendPacket(ExMPCCOpen.STATIC);
            }
        }
        for (int shotId : activeChar.getAutoSoulShot()) {
            sendPacket(new ExAutoSoulShot(shotId, true));
        }
        for (Effect e : activeChar.getEffectList().getAllFirstEffects()) {
            if (e.getSkill().isToggle()) {
                sendPacket(new MagicSkillLaunched(activeChar.getObjectId(), e.getSkill().getId(),
                        e.getSkill().getLevel(), activeChar));
            }
        }
        activeChar.broadcastCharInfo();
    } else {
        activeChar.sendUserInfo();
    }
    activeChar.updateEffectIcons();
    activeChar.setCurrentHpMp(activeChar.getActiveSubClass().getlogOnHp(),
            activeChar.getActiveSubClass().getlogOnMp());
    activeChar.setCurrentCp(activeChar.getActiveSubClass().getlogOnCp());
    activeChar.updateStats();
    if (Config.ALT_PCBANG_POINTS_ENABLED) {
        activeChar.sendPacket(new ExPCCafePointInfo(activeChar, 0, 1, 2, 12));
    }
    if (!activeChar.getPremiumItemList().isEmpty()) {
        activeChar.sendPacket(Config.GOODS_INVENTORY_ENABLED ? ExGoodsInventoryChangedNotify.STATIC
                : ExNotifyPremiumItem.STATIC);
    }
    if (activeChar.getVarB("HeroPeriod") && Config.SERVICES_HERO_SELL_ENABLED) {
        activeChar.setHero(activeChar);
    }
    activeChar.sendVoteSystemInfo();
    activeChar.sendPacket(new ExReceiveShowPostFriend(activeChar));
    activeChar.sendPacket(new ExSubjobInfo(activeChar.getPlayer(), false));
    activeChar.sendPacket(new ExVitalityEffectInfo(activeChar));
    activeChar.sendPacket(new ExTutorialList());
    activeChar.sendPacket(new ExWaitWaitingSubStituteInfo(true));
    for (Effect effect : activeChar.getEffectList().getAllEffects()) {
        if (effect.isInUse()) {
            if (effect.getSkill().getId() == 10022) {
                activeChar.setIsIgnoringDeath(true);
            }
        }
    }
    if (Config.ALT_GAME_REMOVE_PREVIOUS_CERTIFICATES) {
        Skill[] allSkill = activeChar.getAllSkillsArray();
        int totalCertificates = 0;
        for (Skill skl : allSkill) {
            if (skl.getId() >= 1573 && skl.getId() <= 1581) {
                totalCertificates += skl.getLevel();
                activeChar.removeSkill(skl, true);
            }
        }
        if (totalCertificates > 0) {
            activeChar.getInventory().addItem(10280, totalCertificates);
            _log.info("EnterWorld: Player - " + activeChar.getName() + " - Has received " + totalCertificates
                    + " by previous skill certificate deletion.");
            for (SubClass sc : activeChar.getSubClassList().values()) {
                sc.setCertification(0);
                activeChar.store(true);
            }
        }
    }
    activeChar.sendPacket(new ExAcquirableSkillListByClass(activeChar));
    activeChar.setPartySearchStatus(true);
    activeChar.sendPacket(new ExWaitWaitingSubStituteInfo(true));
    checkNewMail(activeChar);
    activeChar.sendPacket(new ExChangeMPCost(1, -3));
    activeChar.sendPacket(new ExChangeMPCost(1, -5));
    activeChar.sendPacket(new ExChangeMPCost(0, 20));
    activeChar.sendPacket(new ExChangeMPCost(1, -10));
    activeChar.sendPacket(new ExChangeMPCost(3, -20));
    activeChar.sendPacket(new ExChangeMPCost(22, -20));
    if (activeChar.getVar("startMovie") == null) {
        activeChar.setVar("startMovie", "1", -1);
        activeChar.sendPacket(new ExShowUsmVideo(ExShowUsmVideo.GD1_INTRO));
    }
    if ((activeChar.getLevel() > 84) && !activeChar.isAwaking()) {
        AwakingManager.getInstance().SendReqToStartQuest(activeChar);
    }
    if (activeChar.isAwaking()) //If the characters returns to Main, or dual Subclass and Delete Skills prof are active, do check of Correct skills
    {
        if (Config.ALT_CHECK_SKILLS_AWAKENING) {
            AwakingManager.getInstance().checkAwakenPlayerSkills(activeChar);
        }
    }
}

From source file:com.mobileman.projecth.business.UserServiceTest.java

/**
 * /*from w  w  w. jav  a 2s.  com*/
 * @throws Exception
 */
@Test
public void acceptInvitation() throws Exception {

    UserConnectionService userConnectionBo = (UserConnectionService) applicationContext
            .getBean(ComponentNames.USER_CONNECTION_SERVICE);
    assertNotNull(userConnectionBo);

    User owner = userService.login("sysuser1", "12345");
    assertNotNull(owner);
    assertTrue(Patient.class.isInstance(owner));

    User user = userService.login("sysuser1", "12345");
    assertNotNull(user);
    assertTrue(Patient.class.isInstance(user));

    try {
        userConnectionBo.acceptInvitation(user.getId(), null);
        fail();
    } catch (IllegalArgumentException e) {
        assertTrue(e.getMessage().equals("Owner id must not be null"));
    }

    try {
        userConnectionBo.acceptInvitation(null, owner.getId());
        fail();
    } catch (IllegalArgumentException e) {
        assertTrue(e.getMessage().equals("User id must not be null"));
    }

    try {
        userConnectionBo.acceptInvitation(user.getId(), owner.getId());
        fail();
    } catch (IllegalStateException e) {
        assertTrue(e.getMessage().equals("Connection not exists"));
    }

    List<UserConnection> connections = userConnectionBo.findAll();
    int oldSize = connections.size();

    UserConnection userConnection = new UserConnection();
    userConnection.setState(UserConnectionState.P);
    userConnection.setOwner(owner);
    userConnection.setUser(user);
    userConnection.setCreated(new Date());
    Long userConnectionId = userConnectionBo.save(userConnection);
    assertTrue(!userConnectionId.equals(0L));
    assertNotNull(userConnectionId);

    connections = userConnectionBo.findAll();
    assertTrue(connections.size() == oldSize + 1);

    userConnectionBo.acceptInvitation(user.getId(), owner.getId());

    UserConnection connection = userConnectionBo.findById(userConnectionId);
    assertTrue(connection.getState().equals(UserConnectionState.A));

    try {
        userConnectionBo.acceptInvitation(user.getId(), owner.getId());
        fail();
    } catch (IllegalStateException e) {
        assertTrue(e.getMessage().equals("Connection wrong state, it isn't pending"));
    }
}

From source file:org.energyos.espi.datacustodian.web.filter.ResourceValidationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    System.out.println("ResourceValidationFilter: start of pooFilter");

    Boolean invalid = true;/*w w  w  .  j ava  2  s. com*/
    Boolean hasBearer = false;
    Boolean hasValidOAuthAccessToken = false;
    Boolean resourceRequest = false;

    Authorization authorizationFromToken = null;
    Subscription subscription = null;
    String resourceUri = null;
    String authorizationUri = null;
    Set<String> roles = null;

    // Get the URI for later tests
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String uri = request.getRequestURI();
    String service = request.getMethod();

    // See if any authentication has happened
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

    } else {
        System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
        throw new AccessDeniedException(String.format("Access Not Authorized"));

    }

    System.out.printf("ResourceValidationFilter: role = %s, HttpRequest Method: %s, uri: %s\n", roles, service,
            uri);

    // Only process resource API request

    if ((uri.indexOf("/espi/1_1/resource/") != -1)) {
        resourceRequest = true;
    }

    // /////////////////////////////////////////////////////////////////////
    // find the access token if present and validate we have a good one
    // /////////////////////////////////////////////////////////////////////
    String token = request.getHeader("authorization");

    if (token != null) {
        if (token.contains("Bearer")) {
            // has Authorization header with Bearer type
            hasBearer = true;
            token = token.replace("Bearer ", "");

            // ensure length is >12 characters (48 bits in hex at least)
            if (token.length() >= 12) {
                // lookup the authorization -- we must have one to
                // correspond to an access token
                try {
                    authorizationFromToken = authorizationService.findByAccessToken(token);

                    hasValidOAuthAccessToken = true;
                    resourceUri = authorizationFromToken.getResourceURI();
                    authorizationUri = authorizationFromToken.getAuthorizationURI();
                    subscription = authorizationFromToken.getSubscription();

                } catch (Exception e) {
                    System.out.printf("ResourceValidationFilter: doFilter - No Authorization Found - %s\n",
                            e.toString());
                    throw new AccessDeniedException(String.format("No Authorization Found"));
                }
            }
        }
    }

    // /////////////////////////////////////////////////////////////////////
    // If this is a resource request ensure it has a Bearer token
    // /////////////////////////////////////////////////////////////////////
    if ((hasBearer == false) & !(resourceRequest == true)) {
        // no Bearer token and it passed the OAuth filter - so it must be
        // good2go not RESTAPI request
        // make sure the role is not an ANONYMOUS request for /manage ...
        if (!((roles.contains("ROLE_ANONYMOUS")) & (uri.indexOf("/management") != -1))) {
            invalid = false;
        }

    }
    // /////////////////////////////////////////////////////////////////////
    // if this is RESTful request, process based on ROLE
    // /////////////////////////////////////////////////////////////////////
    else if (hasValidOAuthAccessToken == true) {
        // if it has a valid access token
        // then we know it is REST request
        // Dispatch on authentication type

        // first, escape out of this if it is the special
        // "manage?command=foo" form
        int i = uri.indexOf("/management");
        if (i > 0) {
            if (roles.contains("ROLE_DC_ADMIN")) {
                invalid = false;
            } else {
                System.out.printf("ResourceValidationFilter: doFilter - not valid for this token %s\n", uri);
                throw new AccessDeniedException(String.format("Access Not Authorized"));
            }
        } else {
            // lets check the uri
            i = uri.indexOf("espi/1_1/resource/");
            if (i > 0) {
                // lets shorten it by stripping off up to resource
                uri = uri.substring(uri.indexOf("/resource/"));
            } else {
                // cant be a resource
                System.out.printf("ResourceValidationFilter: doFilter - Uri not well formed %s\n", uri);
                throw new AccessDeniedException(String.format("Access Not Authorized"));
            }
        }

        // strip off uri up to /resource/ since that is how we go here
        resourceUri = resourceUri.substring(resourceUri.indexOf("/resource/"));
        authorizationUri = authorizationUri.substring(authorizationUri.indexOf("/resource/"));

        // /////////////////////////////////////////////////////////////////////
        // ROLE_USER
        //
        // GET /resource/LocalTimeParameters
        // GET /resource/LocalTimeParameters/{localTimeParametersId}
        // GET /resource/ReadingType
        // GET /resource/ReadingType/{readingTypeId}
        // GET /resource/Batch/Subscription/{subscriptionId}
        // GET
        // /resource/Batch/Subscription/{subscriptionId}/UsagePoint/{usagePointId}
        // GET /resource/Subscription/{subscriptionId}/UsagePoint
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerQualitySummary
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerQualitySummary/{electricPowerQualitySummaryId}
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerUsageSumary
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/ElectricPowerUsageSumary/{electricPowerUsageSummaryId}
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId}
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId}/IntervalBlock
        // GET
        // /resource/Subscription/{subscriptionId}/UsagePoint/{usagePointId}/MeterReading/{meterReadingId}/IntervalBlock/{intervalBlockId}
        //
        // /////////////////////////////////////////////////////////////////////
        if (invalid && roles.contains("ROLE_USER")) {

            // break uri into tokens
            String[] tokens = uri.split("/");

            // only GET for this ROLE permitted
            if (!service.equals("GET")) {
                System.out.printf(
                        "ResourceValidationFilter: doFilter - ROLE_USER attempted a RESTful %s Request -- Only GET Request are allowed\n",
                        service);
                throw new AccessDeniedException(String.format("Access Not Authorized"));
            }

            // look for the root forms of LocalTimeParameters and
            // ReadingType
            if (invalid && ((uri.contains("resource/LocalTimeParameters"))
                    || (uri.contains("resource/ReadingType")))) {
                invalid = false;
            }

            // must be either /resource/Batch/Subscription/{subscriptionId}
            if (invalid && uri.contains("/resource/Batch/Subscription")) {
                if (uri.startsWith(resourceUri)) {
                    invalid = false;
                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }
            }

            // or /resource/Batch/Subscription/{subscriptionId}/**
            if (invalid && uri.contains("/resource/Subscription")) {
                if (authorizationFromToken.getSubscription().getId()
                        .compareTo(Long.parseLong(tokens[3], 10)) == 0) {
                    invalid = false;
                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }
            }

        } else if (invalid && roles.contains("ROLE_DC_ADMIN")) {
            // /////////////////////////////////////////////////////////////////////
            // ROLE_DC_ADMIN
            // Access to all services and APIs
            // /////////////////////////////////////////////////////////////////////
            //
            invalid = false;

        } else if (invalid && roles.contains("ROLE_TP_ADMIN")) {
            // /////////////////////////////////////////////////////////////////////
            // ROLE_TP_ADMIN
            //
            // GET /resource/Authorization
            // GET /resource/Authorization/{authorizationId}
            // PUT /resource/Authorization/{authorizationId}
            // DELETE /resource/Authorization/{authorizationId}
            // GET /resource/Batch/Bulk/{bulkId}
            // GET /resource/ReadServiceStatus
            // GETALL
            // sftp://services.greenbuttondata.org/DataCustodian/espi/1_1/resource/Batch/Bulk/{bulkId}
            // /////////////////////////////////////////////////////////////////////

            // the Bulk Authorizations
            if (invalid && uri.contains("/resource/Batch/Bulk")) {
                invalid = false;
            }

            // Authorizations GET/PUT/DELETE on individual, GET on
            // collection
            if (invalid && (uri.contains("/resource/Authorization"))) {
                // this is retrieving the authorization related to the token
                // the TP has access to AuthorizationIds he is tp for
                // which is authorization looked by access token, or,
                // any authorization that points to same
                // applicationInformationId

                if (service.equals("GET") || service.equals("PUT") || service.equals("DELETE")) {
                    if (authorizationUri.equals(uri)) {
                        invalid = false;
                    } else {
                        // get authorizationID if present
                        String[] tokens = uri.split("/");
                        Long authorizationId = -1l;
                        if (tokens.length > 3) {
                            authorizationId = Long.parseLong(tokens[3], 10);
                        }

                        // check if its a collection
                        if (authorizationId != -1l) {
                            // it is specific ID, see if it authorization
                            // for this third party
                            Authorization requestedAuthorization = authorizationService
                                    .findById(authorizationId);
                            if ((requestedAuthorization.getApplicationInformation().getId())
                                    .equals(authorizationFromToken.getApplicationInformation().getId())) {
                                invalid = false;
                            } else {
                                // not authorized for this resource
                                System.out
                                        .printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                                throw new AccessDeniedException(String.format("Access Not Authorized"));
                            }
                        } else {
                            // this is collection request and controller
                            // will limit to valid authorizations
                            if (service.equals("GET")) {
                                invalid = false;
                            } else {
                                // not authorized for this resource
                                System.out
                                        .printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                                throw new AccessDeniedException(String.format("Access Not Authorized"));
                            }
                        }
                    }
                }
            }

            if (invalid && uri.contains("/resource/ReadServiceStatus")) {
                if (service.equals("GET")) {
                    invalid = false;
                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }
            }

            // sftp
            // TODO:

        } else if (invalid && roles.contains("ROLE_UL_ADMIN")) {
            // /////////////////////////////////////////////////////////////////////
            // ROLE_UL_ADMIN
            //
            // GET
            // /resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint
            // POST
            // /resource/Batch/RetailCustomer/{retailCustomerId}/UsagePoint
            // GET /resource/Authorization/{authorizationId}
            //
            // /////////////////////////////////////////////////////////////////////

            // he can get his own AuthorizationUri
            // check if it is this authorization request
            if (uri.contains("/resource/Authorization")) {
                if (authorizationUri.equals(uri)) {
                    invalid = false;
                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }
            }

            if (invalid && uri.contains("/resource/Batch/RetailCustomer")) {
                invalid = false;
            }

            if (invalid && uri.contains("/resource/ReadServiceStatus")) {
                if (service.equals("GET")) {
                    invalid = false;
                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }
            }
        } else if (invalid && roles.contains("ROLE_TP_REGISTRATION")) {
            // /////////////////////////////////////////////////////////////////////
            // ROLE_TP_REGISTRATION
            //
            // GET
            // /resource/ApplicationInformation/{applicationInformationId}
            // PUT
            // /resource/ApplicationInformation/{applicationInformationId}
            // DELETE
            // /resource/ApplicationInformation/{applicationInformationId}
            // /////////////////////////////////////////////////////////////////////

            if (service.equals("GET") || service.equals("PUT") || service.equals("DELETE")) {
                if (uri.contains("/resource/ApplicationInformation")) {
                    String[] tokens = uri.split("/");

                    if (tokens.length > 3) {
                        Long applicationInformationIdFromUri = Long.parseLong(tokens[3], 10);
                        Long applicationInformationId = authorizationFromToken.getApplicationInformation()
                                .getId();

                        // only gets access to his
                        if (applicationInformationIdFromUri.equals(applicationInformationId)) {
                            invalid = false;
                        }

                    } else {
                        // not authorized for this resource
                        System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                        throw new AccessDeniedException(String.format("Access Not Authorized"));
                    }

                } else {
                    // not authorized for this resource
                    System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                    throw new AccessDeniedException(String.format("Access Not Authorized"));
                }

            } else {
                // not authorized for this resource
                System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
                throw new AccessDeniedException(String.format("Access Not Authorized"));
            }
        }
    }

    System.out.printf("ResourceValidationFilter: normal exit doFilter: invalid=%s\n", invalid);

    if (invalid) {
        // not authorized for this resource
        System.out.printf("ResourceValidationFilter: doFilter - Access Not Authorized\n");
        throw new AccessDeniedException(String.format("Access Not Authorized"));
    }

    // TODO -- Verify contents of query parameters are properly formatted

    chain.doFilter(req, res);

}