target
stringlengths
20
113k
src_fm
stringlengths
11
86.3k
src_fm_fc
stringlengths
21
86.4k
src_fm_fc_co
stringlengths
30
86.4k
src_fm_fc_ms
stringlengths
42
86.8k
src_fm_fc_ms_ff
stringlengths
43
86.8k
@Test public void testGetActor() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getActor(); assertEquals(tomAccount.getActor().getId(), db.getTom().getInternalAccount().getActor().getId()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getActor(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getActor(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); }
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } }
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); }
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }
Account extends Identifiable<T> { public final Actor<?> getActor() throws UnauthorizedOperationException { tryAccess(new RgtAccount.Actor(), Action.READ); return getActorUnprotected(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }
@Test public void testGetCreationDate() { final InternalAccount tomAccount = InternalAccount.create(db.getTom().getInternalAccount()); try { AuthToken.unAuthenticate(); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); tomAccount.getCreationDate(); assertEquals(tomAccount.getCreationDate(), db.getTom().getInternalAccount().getCreationDate()); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(loser); tomAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } final InternalAccount publicGroupAccount = InternalAccount.create(db.getPublicGroup().getInternalAccount()); try { AuthToken.unAuthenticate(); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(memberTom); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memberYo); publicGroupAccount.getCreationDate(); } catch (final UnauthorizedOperationException e) { fail(); } try { AuthToken.authenticate(memeberFred); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } try { AuthToken.authenticate(loser); publicGroupAccount.getCreationDate(); fail(); } catch (final UnauthorizedOperationException e) { assertTrue(true); } }
public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); }
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } }
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); }
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }
Account extends Identifiable<T> { public final Date getCreationDate() throws UnauthorizedOperationException { tryAccess(new RgtAccount.CreationDate(), Action.READ); return getDao().getCreationDate(); } protected Account(final T id); final boolean canAccessTransaction(); final boolean canAccessAmount(); final boolean canAccessActor(); final boolean canAccessCreationDate(); final boolean canAccessLastModificationDate(); final Date getLastModificationDate(); final BigDecimal getAmount(); final PageIterable<Transaction> getTransactions(); final Actor<?> getActor(); final Date getCreationDate(); }
@Test public void testGetAuthor() { assertEquals(yo, feature.getMember()); }
public DaoActor getAuthor() { return asTeam == null ? member : asTeam; }
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } }
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); }
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); DaoMember getMember(); DaoActor getAuthor(); Date getCreationDate(); DaoTeam getAsTeam(); PageIterable<DaoFileMetadata> getFiles(); boolean isDeleted(); void setIsDeleted(final Boolean isDeleted); void addFile(final DaoFileMetadata daoFileMetadata); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoUserContent extends DaoIdentifiable { public DaoActor getAuthor() { return asTeam == null ? member : asTeam; } protected DaoUserContent(final DaoMember member, final DaoTeam team); protected DaoUserContent(); DaoMember getMember(); DaoActor getAuthor(); Date getCreationDate(); DaoTeam getAsTeam(); PageIterable<DaoFileMetadata> getFiles(); boolean isDeleted(); void setIsDeleted(final Boolean isDeleted); void addFile(final DaoFileMetadata daoFileMetadata); @Override int hashCode(); @Override boolean equals(final Object obj); }
@Test public void testGetKarma() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memeberFred); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memberTom); assertEquals(0, yo.getKarma()); }
public int getKarma() { return getDao().getKarma(); }
Member extends Actor<DaoMember> implements User { public int getKarma() { return getDao().getKarma(); } }
Member extends Actor<DaoMember> implements User { public int getKarma() { return getDao().getKarma(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public int getKarma() { return getDao().getKarma(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public int getKarma() { return getDao().getKarma(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testSetFullName() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memeberFred); assertEquals(0, yo.getKarma()); AuthToken.authenticate(memberTom); assertEquals(0, yo.getKarma()); }
public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testGetFullname() { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); assertEquals("Yoann Plénet", yo.getFullname()); AuthToken.authenticate(memeberFred); assertEquals("Yoann Plénet", yo.getFullname()); AuthToken.authenticate(memberTom); assertEquals("Yoann Plénet", yo.getFullname()); }
public String getFullname() { return getDao().getFullname(); }
Member extends Actor<DaoMember> implements User { public String getFullname() { return getDao().getFullname(); } }
Member extends Actor<DaoMember> implements User { public String getFullname() { return getDao().getFullname(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public String getFullname() { return getDao().getFullname(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public String getFullname() { return getDao().getFullname(); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testSetFullname() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); yo.setFullname("Plénet Yoann"); try { AuthToken.authenticate(memeberFred); yo.setFullname("plop"); fail(); } catch (final Exception e) { assertTrue(true); } assertEquals("Plénet Yoann", yo.getFullname()); }
public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public void setFullname(final String fullname) throws UnauthorizedPublicAccessException { tryAccess(new RgtMember.FullName(), Action.WRITE); getDao().setFullname(fullname); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testSetPassword() throws UnauthorizedOperationException { final Member yo = MemberManager.getMemberByLogin("Yoann"); AuthToken.authenticate(memberYo); yo.setPassword("Coucou"); try { AuthToken.authenticate("Yoann", "Coucou"); } catch (final ElementNotFoundException e) { fail(); } }
public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); }
Member extends Actor<DaoMember> implements User { public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); } }
Member extends Actor<DaoMember> implements User { public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public void setPassword(final String password) throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Password(), Action.WRITE); getDao().setPassword(Hash.calculateHash(password, getDao().getSalt())); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testGetFeatures() { final Member yo = MemberManager.getMemberByLogin("Yoann"); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); AuthToken.authenticate(memberYo); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); AuthToken.authenticate(memeberFred); assertEquals("Mon titre", yo.getFeatures(false).iterator().next().getDescription().getTranslationOrDefault(Language.EN).getTitle()); }
public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); }
Member extends Actor<DaoMember> implements User { public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); } }
Member extends Actor<DaoMember> implements User { public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public PageIterable<Feature> getFeatures(final boolean asMemberOnly) { return new FeatureList(getDao().getFeatures(asMemberOnly)); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testGetKudos() { final Member yo = MemberManager.getMemberByLogin("Yoann"); try { assertEquals(1, yo.getKudos().size()); fail(); } catch (final UnauthorizedPrivateAccessException e) { assertTrue(true); } try { AuthToken.authenticate(memberYo); assertEquals(1, yo.getKudos().size()); } catch (final UnauthorizedPrivateAccessException e) { fail(); } try { AuthToken.authenticate(memeberFred); assertEquals(1, yo.getKudos().size()); fail(); } catch (final UnauthorizedPrivateAccessException e) { assertTrue(true); } }
public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); }
Member extends Actor<DaoMember> implements User { public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); } }
Member extends Actor<DaoMember> implements User { public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); }
Member extends Actor<DaoMember> implements User { public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
Member extends Actor<DaoMember> implements User { public PageIterable<Kudos> getKudos() throws UnauthorizedPrivateAccessException { tryAccess(new RgtMember.Kudos(), Action.READ); return new KudosList(getDao().getKudos()); } Member(final String login, final String password, final String email, final Locale locale); Member(final String login, final String password, final String email, final String fullname, final Locale locale); private Member(final DaoMember dao); @SuppressWarnings("synthetic-access") static Member create(final DaoMember dao); void sendInvitation(final Member member, final Team team); boolean acceptInvitation(final JoinTeamInvitation invitation); void refuseInvitation(final JoinTeamInvitation invitation); void kickFromTeam(final Team aTeam, final Member actor); void addToPublicTeam(final Team team); void setPassword(final String password); boolean checkPassword(final String password); void setFullname(final String fullname); void setAvatar(final FileMetadata fileImage); void setDescription(final String userDescription); void setEmail(final String email); void setLocal(final Locale loacle); boolean isActive(); boolean activate(final String activationKey); boolean hasEmailToActivate(); boolean activateEmail(final String activationKey); void setEmailToActivate(final String email); void acceptNewsLetter(final boolean newsletter); FollowFeature followOrGetFeature(final Feature f); boolean isFollowing(final Feature feature); boolean isFollowing(final Software software); boolean isFollowing(final Actor<?> actor); void unfollowFeature(final Feature f); FollowSoftware followOrGetSoftware(final Software s); void unfollowSoftware(final Software s); FollowActor followOrGetActor(final Actor<?> f); void unfollowActor(final Actor<?> a); void setLastWatchedEvents(final Date lastWatchedEvents); void setEmailStrategy(final EmailStrategy emailStrategy); void setGlobalFollow(final boolean globalFollow); void setGlobalFollowWithMail(final boolean globalFollow); Date getLastWatchedEvents(); @Override ActivationState getActivationState(); String getDescription(); EmailStrategy getEmailStrategy(); FollowFeature getFollowFeature(final Feature feature); boolean isGlobalFollow(); boolean isGlobalFollowWithMail(); String getActivationKey(); String getEmailActivationKey(); PageIterable<JoinTeamInvitation> getReceivedInvitation(final State state); PageIterable<JoinTeamInvitation> getSentInvitation(final State state); PageIterable<Team> getTeams(); int getKarma(); PageIterable<Milestone> getMilestoneToInvoice(); PageIterable<Milestone> getMilestoneInvoiced(); PageIterable<Milestone> getMilestones(); PageIterable<UserContent<? extends DaoUserContent>> getHistory(); @Override String getDisplayName(); String getEmail(); String getEmailToActivate(); String getEmailUnprotected(); boolean getNewsletterAccept(); Locale getLocaleUnprotected(); @Override Locale getLocale(); String getFullname(); @Override Image getAvatar(); long getInvitationCount(); PageIterable<Feature> getFeatures(final boolean asMemberOnly); PageIterable<Kudos> getKudos(); @Override PageIterable<Contribution> doGetContributions(); @Override PageIterable<MoneyWithdrawal> doGetMoneyWithdrawals(); PageIterable<Contribution> getContributions(final boolean asMemberOnly); PageIterable<Comment> getComments(final boolean asMemberOnly); PageIterable<Offer> getOffers(final boolean asMemberOnly); PageIterable<Translation> getTranslations(final boolean asMemberOnly); void addToKarma(final int value); Role getRole(); String getResetKey(); PageIterable<ExternalServiceMembership> getExternalServices(); PageIterable<FollowFeature> getFollowedFeatures(); PageIterable<FollowActor> getFollowedActors(); PageIterable<FollowSoftware> getFollowedSoftware(); void addAuthorizedExternalService(final String clientId, final String token, final EnumSet<RightLevel> rights); final boolean canAccessAvatar(final Action action); boolean canGetTeams(); boolean canSetPassword(); boolean canAccessEmail(final Action action); boolean canAccessUserInformations(final Action action); boolean canBeKickFromTeam(final Team aTeam, final Member actor); boolean hasTeamRight(final Team aTeam, final UserTeamRight aRight); Set<UserTeamRight> getTeamRights(final Team g); boolean hasConsultTeamRight(final Team aTeam); boolean hasTalkTeamRight(final Team aTeam); boolean hasInviteTeamRight(final Team aTeam); boolean hasModifyTeamRight(final Team aTeam); boolean hasPromoteTeamRight(final Team aTeam); boolean hasBankTeamRight(final Team aTeam); boolean isInTeam(final Team team); @Override ReturnType accept(final ModelClassVisitor<ReturnType> visitor); }
@Test public void testCreateFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, yo.getFeatures(false).iterator().next()); }
public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }
@Test public void testRetrieveFeature() { final DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); assertEquals(feature, DBRequests.getAll(DaoFeature.class).iterator().next()); assertEquals(yo, feature.getMember()); }
public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoFeature extends DaoKudosable implements DaoCommentable { public static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software) { final Session session = SessionManager.getSessionFactory().getCurrentSession(); final DaoFeature feature = new DaoFeature(member, team, description, software); try { session.save(feature); } catch (final HibernateException e) { session.getTransaction().rollback(); SessionManager.getSessionFactory().getCurrentSession().beginTransaction(); throw e; } DaoEvent.createFeatureEvent(feature, EventType.CREATE_FEATURE); return feature; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }
@Test public void testAddContribution() throws Throwable { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); fred.getInternalAccount().setAmount(new BigDecimal("100")); yo.getInternalAccount().setAmount(new BigDecimal("100")); feature.addContribution(fred, null, new BigDecimal("25.00"), "Contribution"); feature.addContribution(yo, null, new BigDecimal("18.00"), "I'm so generous"); feature = DBRequests.getById(DaoFeature.class, feature.getId()); assertEquals(2, feature.getContributions().size()); assertEquals(0, fred.getInternalAccount().getBlocked().compareTo(new BigDecimal("25"))); assertEquals(0, fred.getInternalAccount().getAmount().compareTo(new BigDecimal("75"))); assertEquals(0, yo.getInternalAccount().getBlocked().compareTo(new BigDecimal("18"))); assertEquals(0, yo.getInternalAccount().getAmount().compareTo(new BigDecimal("82"))); super.closeDB(); super.createDB(); }
public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; }
DaoFeature extends DaoKudosable implements DaoCommentable { public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; } }
DaoFeature extends DaoKudosable implements DaoCommentable { public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); }
DaoFeature extends DaoKudosable implements DaoCommentable { public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoFeature extends DaoKudosable implements DaoCommentable { public DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment) throws NotEnoughMoneyException { if (amount == null) { throw new NonOptionalParameterException(); } if (amount.compareTo(BigDecimal.ZERO) <= 0) { Log.data().fatal("Cannot create a contribution with this amount " + amount.toEngineeringString() + " by member " + member.getId()); throw new BadProgrammerException("The amount of a contribution cannot be <= 0.", null); } if (comment != null && comment.length() > DaoContribution.COMMENT_MAX_LENGTH) { Log.data().fatal("The comment of a contribution must be <= 140 chars long."); throw new BadProgrammerException("Comments length of Contribution must be < 140.", null); } if (team != null && !team.getUserTeamRight(member).contains(UserTeamRight.BANK)) { throw new BadProgrammerException("This member cannot contribute as a team."); } final DaoContribution newContribution = new DaoContribution(member, team, this, amount, comment); this.contributions.add(newContribution); this.contribution = this.contribution.add(amount); return newContribution; } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }
@Test public void testAddOffer() { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature = DBRequests.getById(DaoFeature.class, feature.getId()); feature.addOffer(createOffer(feature)); assertEquals(1, feature.getOffers().size()); }
public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); }
DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } }
DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); }
DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoFeature extends DaoKudosable implements DaoCommentable { public void addOffer(final DaoOffer offer) { this.offers.add(offer); DaoEvent.createOfferEvent(this, EventType.ADD_OFFER, offer); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }
@Test public void testAddComment() throws Throwable { DaoFeature feature = DaoFeature.createAndPersist(yo, null, DaoDescription.createAndPersist(yo, null, Language.FR, "Ma super demande !", "Ceci est la descption de ma demande :) "), project); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "4")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "3")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "2")); feature.addComment(DaoComment.createAndPersist(feature, null, yo, "1")); feature = DBRequests.getById(DaoFeature.class, feature.getId()); assertEquals(4, feature.getComments().size()); }
@Override public void addComment(final DaoComment comment) { this.comments.add(comment); }
DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } }
DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); }
DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); }
DaoFeature extends DaoKudosable implements DaoCommentable { @Override public void addComment(final DaoComment comment) { this.comments.add(comment); } private DaoFeature(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); protected DaoFeature(); static DaoFeature createAndPersist(final DaoMember member, final DaoTeam team, final DaoDescription description, final DaoSoftware software); void setSoftware(final DaoSoftware soft); @Override void addComment(final DaoComment comment); DaoContribution addContribution(final DaoMember member, final DaoTeam team, final BigDecimal amount, final String comment); void addOffer(final DaoOffer offer); void removeOffer(final DaoOffer offer); DaoOffer computeSelectedOffer(); void setSelectedOffer(final DaoOffer selectedOffer); void setValidationDate(final Date validationDate); void setFeatureState(final FeatureState featureState); void setDescription(final String newDescription, final Language language); void setTitle(final String title, final Language language); @Field(store = Store.YES, index = Index.UN_TOKENIZED) float getProgress(); List<DaoFollowFeature> getFollowers(); DaoDescription getDescription(); PageIterable<DaoOffer> getOffers(); FeatureState getFeatureState(); PageIterable<DaoContribution> getContributions(); PageIterable<DaoContribution> getContributions(final boolean isCanceled); Long getCommentsCount(); @Override PageIterable<DaoComment> getComments(); @Override DaoComment getLastComment(); DaoOffer getSelectedOffer(); BigDecimal getContribution(); BigDecimal getContributionMin(); BigDecimal getContributionMax(); BigDecimal getContributionAvg(); BigDecimal getContributionOf(final DaoMember member); Date getValidationDate(); DaoSoftware getSoftware(); int countOpenBugs(); PageIterable<DaoBug> getOpenBugs(); PageIterable<DaoBug> getClosedBugs(); static PageIterable<DaoFeature> getAllByCreationDate(); @Override ReturnType accept(final DataClassVisitor<ReturnType> visitor); @Override int hashCode(); @Override boolean equals(final Object obj); static final int PROGRESSION_PERCENT; }
@Test public void testMinimal() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("\n[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); }
public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); }
@Test public void testExtractAttributesMultiline() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("bar jim", doc.getAttribute("foo")); }
public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } }
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } }
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } }
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } static JsDoc parse(String moduleId, String content); }
JsDocParser { public static JsDoc parse(String moduleId, String content) { if (content == null) { return EMPTY_JSDOC; } if (content.startsWith("/**")) { final String noStars = stripStars(content); Iterable<String> tokens = filter(asList(noStars.split("(?:^|[\\r\\n])\\s*@")), new Predicate<String>() { public boolean apply(String input) { return input.trim().length() > 0; } }); ListMultimap<String,String> tags = ArrayListMultimap.create(); int x = 0; for (String token : tokens) { if (x++ == 0 && !noStars.startsWith("@")) { tags.put(DESCRIPTION, token.trim()); } else { int spacePos = token.indexOf(' '); if (spacePos > -1) { String value = token.substring(spacePos + 1); StringBuilder sb = new StringBuilder(); for (String line : value.split("(?:\\r\\n)|\\r|\\n")) { sb.append(line.trim()).append(" "); } tags.put(token.substring(0, spacePos).toLowerCase(), sb.toString().trim()); } else { tags.put(token.toLowerCase(), token.toLowerCase()); } } } Map<String,Collection<String>> attributes = tags.asMap(); Collection<String> descriptions = attributes.remove(DESCRIPTION); return new JsDoc(descriptions != null ? descriptions.iterator().next() : null, attributes); } else { log.debug("Module '{}' doesn't start with /** so not parsed as a jsdoc comment", moduleId); return EMPTY_JSDOC; } } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void testMinimalNoComment() { List<Element> list = jsonToElementParser.createWebItems(new ByteArrayInputStream("[{\"section\":\"foo\",\"weight\":40}\n]".getBytes())); assertNotNull(list); assertEquals(1, list.size()); assertEquals("foo", list.get(0).attributeValue("section")); }
public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); }
JsonToElementParser { public List<Element> createWebItems(InputStream in) { List<Element> items = newArrayList(); DocumentFactory factory = DocumentFactory.getInstance(); try { if (in == null) { return emptyList(); } final String content = StringUtils.join(IOUtils.readLines(in), "\n"); JSONArray root = new JSONArray(stripComments(content)); for (int x=0; x<root.length(); x++) { Element element = factory.createElement("scoped-web-item"); element.addAttribute("key", "item-" + x); JSONObject item = root.getJSONObject(x); if (!item.isNull("section")) { element.addAttribute("section", item.getString("section")); } if (!item.isNull("label")) { element.addElement("label").setText(item.getString("label")); } if (hasLink(item)) { Element link = element.addElement("link"); link.setText(getLink(item)); if (!item.isNull("cssId")) { link.addAttribute("linkId", item.getString("cssId")); } } if (!item.isNull("cssName")) { element.addElement("styleClass").setText(item.getString("cssName")); } if (!item.isNull("weight")) { element.addAttribute("weight", item.getString("weight")); } if (!item.isNull("tooltip")) { element.addElement("tooltip").setText(item.getString("tooltip")); } if (!item.isNull("icon")) { JSONObject iconJson = item.getJSONObject("icon"); Element iconE = element.addElement("icon"); if (!iconJson.isNull("width")) { iconE.addAttribute("width", iconJson.getString("width")); } if (!iconJson.isNull("height")) { iconE.addAttribute("height", iconJson.getString("height")); } if (hasLink(iconJson)) { iconE.addElement("link").setText(getLink(iconJson)); } } items.add(element); } } catch (IOException e) { throw new PluginOperationFailedException("Unable to read ui/web-items.json", e, null); } catch (JSONException e) { throw new PluginOperationFailedException("Unable to parse ui/web-items.json: " + e.getMessage(), e, null); } finally { IOUtils.closeQuietly(in); } return items; } List<Element> createWebItems(InputStream in); }
@Test public void testKeyFromFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo.jar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1-bar-2.zip")); assertEquals("foo", KeyExtractor.extractFromFilename("foo-1.0.zip")); assertEquals("foo-bar", KeyExtractor.extractFromFilename("foo-bar.zip")); }
public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); static final String SPEAKEASY_KEY_SEPARATOR; }
@Test public void testKeyFromTempFilename() { assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar")); assertEquals("foo", KeyExtractor.extractFromFilename("foo----speakeasy-bar.zip")); assertEquals("foo-1", KeyExtractor.extractFromFilename("foo-1----speakeasy-jim.jar")); }
public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); }
KeyExtractor { public static String extractFromFilename(String fileName) { String name = stripExtension(fileName); Matcher m = TEMP_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } else { m = UPLOADED_FILENAME_WITH_VERSION.matcher(name); if (m.matches()) { return m.group(1); } } return name; } static String extractFromFilename(String fileName); static File createExtractableTempFile(String key, String suffix); static final String SPEAKEASY_KEY_SEPARATOR; }
@Test public void testGetEntries() throws IOException { final File dir = tmp.newFolder("names"); new File(dir, "foo.txt").createNewFile(); new File(dir, "a/b").mkdirs(); new File(dir, "a/bar.txt").createNewFile(); new File(dir, "c").mkdirs(); assertEquals(newArrayList("a/", "a/b/", "a/bar.txt", "c/", "foo.txt"), RepositoryDirectoryUtil.getEntries(dir)); }
public static List<String> getEntries(File root) { return walk(root.toURI(), root); }
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } }
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } }
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } static List<String> getEntries(File root); static List<String> walk(URI root, File dir); }
RepositoryDirectoryUtil { public static List<String> getEntries(File root) { return walk(root.toURI(), root); } static List<String> getEntries(File root); static List<String> walk(URI root, File dir); }
@Test public void testStripStarsJsDocMultilineComment() { assertEquals("foo", JsDocParser.stripStars("")); }
static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void testStripStarsJsDocMultilineCommentWithStars() { assertEquals("foo", JsDocParser.stripStars("")); }
static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void testStripStarsJsDocMultilineCommentWithSpaceStars() { assertEquals("foo", JsDocParser.stripStars("")); }
static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void testStripStarsJsDocOneLineComment() { assertEquals("foo", JsDocParser.stripStars("")); }
static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); }
JsDocParser { static String stripStars(String jsDoc) { String noStartOrEndStars = jsDoc != null ? jsDoc.replaceAll("^\\/\\*\\*|\\*\\/$", "") : ""; String result = Pattern.compile("^\\s*\\* ?", Pattern.MULTILINE).matcher(noStartOrEndStars).replaceAll(""); return result.trim(); } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void testExtractAttributes() { JsDoc doc = JsDocParser.parse("foo", ""); assertEquals("Desc", doc.getDescription()); assertEquals("bar", doc.getAttribute("foo")); assertEquals("jim bob", doc.getAttribute("baz")); }
static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; }
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } }
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } }
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } static JsDoc parse(String moduleId, String content); }
JsDocParser { static Map<String,String> extractAttributes(String jsDocWithNoStars) { return null; } static JsDoc parse(String moduleId, String content); static final JsDoc EMPTY_JSDOC; }
@Test public void test() { Optional<SentinelVersion> version = VersionUtils.parseVersion("1.2.3"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(0, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3."); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3.4"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(0, version.get().getMinorVersion()); assertEquals(0, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("1.2.3-"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertNull(version.get().getPostfix()); version = VersionUtils.parseVersion("-"); assertFalse(version.isPresent()); version = VersionUtils.parseVersion("-t"); assertFalse(version.isPresent()); version = VersionUtils.parseVersion(""); assertFalse(version.isPresent()); version = VersionUtils.parseVersion(null); assertFalse(version.isPresent()); version = VersionUtils.parseVersion("1.2.3-SNAPSHOTS"); assertTrue(version.isPresent()); assertEquals(1, version.get().getMajorVersion()); assertEquals(2, version.get().getMinorVersion()); assertEquals(3, version.get().getFixVersion()); assertEquals("SNAPSHOTS", version.get().getPostfix()); }
public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } }
VersionUtils { public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } } }
VersionUtils { public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } } private VersionUtils(); }
VersionUtils { public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } } private VersionUtils(); static Optional<SentinelVersion> parseVersion(String s); }
VersionUtils { public static Optional<SentinelVersion> parseVersion(String s) { if (StringUtil.isBlank(s)) { return Optional.empty(); } try { String versionFull = s; SentinelVersion version = new SentinelVersion(); int index = versionFull.indexOf("-"); if (index == 0) { return Optional.empty(); } if (index == versionFull.length() - 1) { } else if (index > 0) { version.setPostfix(versionFull.substring(index + 1)); } if (index >= 0) { versionFull = versionFull.substring(0, index); } int segment = 0; int[] ver = new int[3]; while (segment < ver.length) { index = versionFull.indexOf('.'); if (index < 0) { if (versionFull.length() > 0) { ver[segment] = Integer.valueOf(versionFull); } break; } ver[segment] = Integer.valueOf(versionFull.substring(0, index)); versionFull = versionFull.substring(index + 1); segment ++; } if (ver[0] < 1) { return Optional.empty(); } else { return Optional.of(version .setMajorVersion(ver[0]) .setMinorVersion(ver[1]) .setFixVersion(ver[2])); } } catch (Exception ex) { return Optional.empty(); } } private VersionUtils(); static Optional<SentinelVersion> parseVersion(String s); }
@Test public void testGetConfigInt() { DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(1, DashboardConfig.getConfigInt("t", 1, 10)); System.setProperty("t", "asdf"); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); System.setProperty("t", ""); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); System.setProperty("t", "2"); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, 1)); DashboardConfig.clearCache(); assertEquals(10, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, -1)); environmentVariables.set("t", "20"); DashboardConfig.clearCache(); assertEquals(20, DashboardConfig.getConfigInt("t", 0, 10)); environmentVariables.set("t", "20dddd"); DashboardConfig.clearCache(); assertEquals(0, DashboardConfig.getConfigInt("t", 0, 10)); environmentVariables.set("t", ""); DashboardConfig.clearCache(); assertEquals(10, DashboardConfig.getConfigInt("t", 0, 10)); DashboardConfig.clearCache(); assertEquals(2, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "666"); DashboardConfig.clearCache(); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "777"); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); System.setProperty("t", "555"); assertEquals(666, DashboardConfig.getConfigInt("t", 0, 1)); }
protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; }
DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; } }
DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; } }
DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); }
DashboardConfig { protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS; static final String CONFIG_AUTH_USERNAME; static final String CONFIG_AUTH_PASSWORD; static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS; static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS; static final String CONFIG_UNHEALTHY_MACHINE_MILLIS; static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS; }
@Test public void testSave() { MetricEntity entry = new MetricEntity(); entry.setApp("testSave"); entry.setResource("testResource"); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); inMemoryMetricsRepository.save(entry); List<String> resources = inMemoryMetricsRepository.listResourcesOfApp("testSave"); Assert.assertTrue(resources.size() == 1 && "testResource".equals(resources.get(0))); }
@Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void save(MetricEntity entity) { if (entity == null || StringUtil.isBlank(entity.getApp())) { return; } readWriteLock.writeLock().lock(); try { allMetrics.computeIfAbsent(entity.getApp(), e -> new HashMap<>(16)) .computeIfAbsent(entity.getResource(), e -> new LinkedHashMap<Long, MetricEntity>() { @Override protected boolean removeEldestEntry(Entry<Long, MetricEntity> eldest) { return eldest.getKey() < TimeUtil.currentTimeMillis() - MAX_METRIC_LIVE_TIME_MS; } }).put(entity.getTimestamp().getTime(), entity); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
@Test public void testSaveAll() { List<MetricEntity> entities = new ArrayList<>(10000); for (int i = 0; i < 10000; i++) { MetricEntity entry = new MetricEntity(); entry.setApp("testSaveAll"); entry.setResource("testResource" + i); entry.setTimestamp(new Date(System.currentTimeMillis())); entry.setPassQps(1L); entry.setExceptionQps(1L); entry.setBlockQps(0L); entry.setSuccessQps(1L); entities.add(entry); } inMemoryMetricsRepository.saveAll(entities); List<String> result = inMemoryMetricsRepository.listResourcesOfApp("testSaveAll"); Assert.assertTrue(result.size() == entities.size()); }
@Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public void saveAll(Iterable<MetricEntity> metrics) { if (metrics == null) { return; } readWriteLock.writeLock().lock(); try { metrics.forEach(this::save); } finally { readWriteLock.writeLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
@Test public void testConcurrentPutAndGet() { List<CompletableFuture> futures = new ArrayList<>(10000); final CyclicBarrier cyclicBarrier = new CyclicBarrier(8); for (int j = 0; j < 10000; j++) { final int finalJ = j; futures.add(CompletableFuture.runAsync(() -> { try { cyclicBarrier.await(); if (finalJ % 2 == 0) { batchSave(); } else { inMemoryMetricsRepository.listResourcesOfApp(DEFAULT_APP); } } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } }, executorService) ); } CompletableFuture all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); try { all.get(10, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.getCause().printStackTrace(); if (e.getCause() instanceof ConcurrentModificationException) { fail("concurrent error occurred"); } else { fail("unexpected exception"); } } catch (TimeoutException e) { fail("allOf future timeout"); } }
@Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
InMemoryMetricsRepository implements MetricsRepository<MetricEntity> { @Override public List<String> listResourcesOfApp(String app) { List<String> results = new ArrayList<>(); if (StringUtil.isBlank(app)) { return results; } Map<String, LinkedHashMap<Long, MetricEntity>> resourceMap = allMetrics.get(app); if (resourceMap == null) { return results; } final long minTimeMs = System.currentTimeMillis() - 1000 * 60; Map<String, MetricEntity> resourceCount = new ConcurrentHashMap<>(32); readWriteLock.readLock().lock(); try { for (Entry<String, LinkedHashMap<Long, MetricEntity>> resourceMetrics : resourceMap.entrySet()) { for (Entry<Long, MetricEntity> metrics : resourceMetrics.getValue().entrySet()) { if (metrics.getKey() < minTimeMs) { continue; } MetricEntity newEntity = metrics.getValue(); if (resourceCount.containsKey(resourceMetrics.getKey())) { MetricEntity oldEntity = resourceCount.get(resourceMetrics.getKey()); oldEntity.addPassQps(newEntity.getPassQps()); oldEntity.addRtAndSuccessQps(newEntity.getRt(), newEntity.getSuccessQps()); oldEntity.addBlockQps(newEntity.getBlockQps()); oldEntity.addExceptionQps(newEntity.getExceptionQps()); oldEntity.addCount(1); } else { resourceCount.put(resourceMetrics.getKey(), MetricEntity.copyOf(newEntity)); } } } return resourceCount.entrySet() .stream() .sorted((o1, o2) -> { MetricEntity e1 = o1.getValue(); MetricEntity e2 = o2.getValue(); int t = e2.getBlockQps().compareTo(e1.getBlockQps()); if (t != 0) { return t; } return e2.getPassQps().compareTo(e1.getPassQps()); }) .map(Entry::getKey) .collect(Collectors.toList()); } finally { readWriteLock.readLock().unlock(); } } @Override void save(MetricEntity entity); @Override void saveAll(Iterable<MetricEntity> metrics); @Override List<MetricEntity> queryByAppAndResourceBetween(String app, String resource, long startTime, long endTime); @Override List<String> listResourcesOfApp(String app); }
@Test public void postRequest() throws HttpException, IOException { RequestContent processor = new RequestContent(); Map<String, String> params = new HashMap<String, String>(); params.put("a", "1"); params.put("b", "2+"); params.put("c", "3 "); HttpUriRequest request; request = SentinelApiClient.postRequest("/test", params, false); assertNotNull(request); processor.process(request, null); assertNotNull(request.getFirstHeader("Content-Type")); assertEquals("application/x-www-form-urlencoded", request.getFirstHeader("Content-Type").getValue()); request = SentinelApiClient.postRequest("/test", params, true); assertNotNull(request); processor.process(request, null); assertNotNull(request.getFirstHeader("Content-Type")); assertEquals("application/x-www-form-urlencoded; charset=UTF-8", request.getFirstHeader("Content-Type").getValue()); }
protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; }
SentinelApiClient { protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; } }
SentinelApiClient { protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; } SentinelApiClient(); }
SentinelApiClient { protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; } SentinelApiClient(); void close(); List<NodeVo> fetchResourceOfMachine(String ip, int port, String type); List<NodeVo> fetchClusterNodeOfMachine(String ip, int port, boolean includeZero); List<FlowRuleEntity> fetchFlowRuleOfMachine(String app, String ip, int port); List<DegradeRuleEntity> fetchDegradeRuleOfMachine(String app, String ip, int port); List<SystemRuleEntity> fetchSystemRuleOfMachine(String app, String ip, int port); CompletableFuture<List<ParamFlowRuleEntity>> fetchParamFlowRulesOfMachine(String app, String ip, int port); List<AuthorityRuleEntity> fetchAuthorityRulesOfMachine(String app, String ip, int port); boolean setFlowRuleOfMachine(String app, String ip, int port, List<FlowRuleEntity> rules); CompletableFuture<Void> setFlowRuleOfMachineAsync(String app, String ip, int port, List<FlowRuleEntity> rules); boolean setDegradeRuleOfMachine(String app, String ip, int port, List<DegradeRuleEntity> rules); boolean setSystemRuleOfMachine(String app, String ip, int port, List<SystemRuleEntity> rules); boolean setAuthorityRuleOfMachine(String app, String ip, int port, List<AuthorityRuleEntity> rules); CompletableFuture<Void> setParamFlowRuleOfMachine(String app, String ip, int port, List<ParamFlowRuleEntity> rules); CompletableFuture<ClusterStateSimpleEntity> fetchClusterMode(String ip, int port); CompletableFuture<Void> modifyClusterMode(String ip, int port, int mode); CompletableFuture<ClusterClientInfoVO> fetchClusterClientInfoAndConfig(String ip, int port); CompletableFuture<Void> modifyClusterClientConfig(String app, String ip, int port, ClusterClientConfig config); CompletableFuture<Void> modifyClusterServerFlowConfig(String app, String ip, int port, ServerFlowConfig config); CompletableFuture<Void> modifyClusterServerTransportConfig(String app, String ip, int port, ServerTransportConfig config); CompletableFuture<Void> modifyClusterServerNamespaceSet(String app, String ip, int port, Set<String> set); CompletableFuture<ClusterServerStateVO> fetchClusterServerBasicInfo(String ip, int port); CompletableFuture<List<ApiDefinitionEntity>> fetchApis(String app, String ip, int port); boolean modifyApis(String app, String ip, int port, List<ApiDefinitionEntity> apis); CompletableFuture<List<GatewayFlowRuleEntity>> fetchGatewayFlowRules(String app, String ip, int port); boolean modifyGatewayFlowRules(String app, String ip, int port, List<GatewayFlowRuleEntity> rules); }
SentinelApiClient { protected static HttpUriRequest postRequest(String url, Map<String, String> params, boolean supportEnhancedContentType) { HttpPost httpPost = new HttpPost(url); if (params != null && params.size() > 0) { List<NameValuePair> list = new ArrayList<>(params.size()); for (Entry<String, String> entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } httpPost.setEntity(new UrlEncodedFormEntity(list, Consts.UTF_8)); if (!supportEnhancedContentType) { httpPost.setHeader(HTTP_HEADER_CONTENT_TYPE, HTTP_HEADER_CONTENT_TYPE_URLENCODED); } } return httpPost; } SentinelApiClient(); void close(); List<NodeVo> fetchResourceOfMachine(String ip, int port, String type); List<NodeVo> fetchClusterNodeOfMachine(String ip, int port, boolean includeZero); List<FlowRuleEntity> fetchFlowRuleOfMachine(String app, String ip, int port); List<DegradeRuleEntity> fetchDegradeRuleOfMachine(String app, String ip, int port); List<SystemRuleEntity> fetchSystemRuleOfMachine(String app, String ip, int port); CompletableFuture<List<ParamFlowRuleEntity>> fetchParamFlowRulesOfMachine(String app, String ip, int port); List<AuthorityRuleEntity> fetchAuthorityRulesOfMachine(String app, String ip, int port); boolean setFlowRuleOfMachine(String app, String ip, int port, List<FlowRuleEntity> rules); CompletableFuture<Void> setFlowRuleOfMachineAsync(String app, String ip, int port, List<FlowRuleEntity> rules); boolean setDegradeRuleOfMachine(String app, String ip, int port, List<DegradeRuleEntity> rules); boolean setSystemRuleOfMachine(String app, String ip, int port, List<SystemRuleEntity> rules); boolean setAuthorityRuleOfMachine(String app, String ip, int port, List<AuthorityRuleEntity> rules); CompletableFuture<Void> setParamFlowRuleOfMachine(String app, String ip, int port, List<ParamFlowRuleEntity> rules); CompletableFuture<ClusterStateSimpleEntity> fetchClusterMode(String ip, int port); CompletableFuture<Void> modifyClusterMode(String ip, int port, int mode); CompletableFuture<ClusterClientInfoVO> fetchClusterClientInfoAndConfig(String ip, int port); CompletableFuture<Void> modifyClusterClientConfig(String app, String ip, int port, ClusterClientConfig config); CompletableFuture<Void> modifyClusterServerFlowConfig(String app, String ip, int port, ServerFlowConfig config); CompletableFuture<Void> modifyClusterServerTransportConfig(String app, String ip, int port, ServerTransportConfig config); CompletableFuture<Void> modifyClusterServerNamespaceSet(String app, String ip, int port, Set<String> set); CompletableFuture<ClusterServerStateVO> fetchClusterServerBasicInfo(String ip, int port); CompletableFuture<List<ApiDefinitionEntity>> fetchApis(String app, String ip, int port); boolean modifyApis(String app, String ip, int port, List<ApiDefinitionEntity> apis); CompletableFuture<List<GatewayFlowRuleEntity>> fetchGatewayFlowRules(String app, String ip, int port); boolean modifyGatewayFlowRules(String app, String ip, int port, List<GatewayFlowRuleEntity> rules); }
@Test public void testGreater() { assertTrue(new SentinelVersion(2, 0, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 1, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 0))); assertTrue(new SentinelVersion(1, 1, 4).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 0, 0).greaterThan(new SentinelVersion(1, 0, 0))); assertFalse(new SentinelVersion(1, 0, 0).greaterThan(new SentinelVersion(1, 1, 0))); assertFalse(new SentinelVersion(1, 1, 3).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 1, 2).greaterThan(new SentinelVersion(1, 1, 3))); assertFalse(new SentinelVersion(1, 0, 0, "").greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 0, 1).greaterThan(new SentinelVersion(1, 0, 0))); assertTrue(new SentinelVersion(1, 0, 1, "a").greaterThan(new SentinelVersion(1, 0, 0, "b"))); assertFalse(new SentinelVersion(1, 0, 0, "b").greaterThan(new SentinelVersion(1, 0, 0, "a"))); }
public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); }
SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } }
SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } SentinelVersion(); SentinelVersion(int major, int minor, int fix); SentinelVersion(int major, int minor, int fix, String postfix); }
SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } SentinelVersion(); SentinelVersion(int major, int minor, int fix); SentinelVersion(int major, int minor, int fix, String postfix); int getFullVersion(); int getMajorVersion(); SentinelVersion setMajorVersion(int majorVersion); int getMinorVersion(); SentinelVersion setMinorVersion(int minorVersion); int getFixVersion(); SentinelVersion setFixVersion(int fixVersion); String getPostfix(); SentinelVersion setPostfix(String postfix); boolean greaterThan(SentinelVersion version); boolean greaterOrEqual(SentinelVersion version); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
SentinelVersion { public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } SentinelVersion(); SentinelVersion(int major, int minor, int fix); SentinelVersion(int major, int minor, int fix, String postfix); int getFullVersion(); int getMajorVersion(); SentinelVersion setMajorVersion(int majorVersion); int getMinorVersion(); SentinelVersion setMinorVersion(int minorVersion); int getFixVersion(); SentinelVersion setFixVersion(int fixVersion); String getPostfix(); SentinelVersion setPostfix(String postfix); boolean greaterThan(SentinelVersion version); boolean greaterOrEqual(SentinelVersion version); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testGetApplicationContext() { ApplicationContext context = SpringContextHolder.getApplicationContext(); PersonMapper personMapper = SpringContextHolder.getBean(PersonMapper.class); personMapper.findAll(); personMapper.findAll(); logger.info(personMapper.getClass().getName()); }
public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; }
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } }
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } }
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } @Override void setApplicationContext(ApplicationContext applicationContext); static ApplicationContext getApplicationContext(); static T getBean(String name); static T getBean(Class<T> clazz); }
SpringContextHolder implements ApplicationContextAware { public static ApplicationContext getApplicationContext() { checkApplicationContext(); return context; } @Override void setApplicationContext(ApplicationContext applicationContext); static ApplicationContext getApplicationContext(); static T getBean(String name); static T getBean(Class<T> clazz); }
@Test public void testQueryApis() throws Exception { String path = "/gateway/api/list.json"; List<ApiDefinitionEntity> entities = new ArrayList<>(); ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setId(1L); entity.setApp(TEST_APP); entity.setIp(TEST_IP); entity.setPort(TEST_PORT); entity.setApiName("foo"); Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); Set<ApiPredicateItemEntity> itemEntities = new LinkedHashSet<>(); entity.setPredicateItems(itemEntities); ApiPredicateItemEntity itemEntity = new ApiPredicateItemEntity(); itemEntity.setPattern("/aaa"); itemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); itemEntities.add(itemEntity); entities.add(entity); ApiDefinitionEntity entity2 = new ApiDefinitionEntity(); entity2.setId(2L); entity2.setApp(TEST_APP); entity2.setIp(TEST_IP); entity2.setPort(TEST_PORT); entity2.setApiName("biz"); entity.setGmtCreate(date); entity.setGmtModified(date); Set<ApiPredicateItemEntity> itemEntities2 = new LinkedHashSet<>(); entity2.setPredicateItems(itemEntities2); ApiPredicateItemEntity itemEntity2 = new ApiPredicateItemEntity(); itemEntity2.setPattern("/bbb"); itemEntity2.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX); itemEntities2.add(itemEntity2); entities.add(entity2); CompletableFuture<List<ApiDefinitionEntity>> completableFuture = mock(CompletableFuture.class); given(completableFuture.get()).willReturn(entities); given(sentinelApiClient.fetchApis(TEST_APP, TEST_IP, TEST_PORT)).willReturn(completableFuture); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(path); requestBuilder.param("app", TEST_APP); requestBuilder.param("ip", TEST_IP); requestBuilder.param("port", String.valueOf(TEST_PORT)); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).fetchApis(TEST_APP, TEST_IP, TEST_PORT); Result<List<ApiDefinitionEntity>> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<List<ApiDefinitionEntity>>>(){}); assertTrue(result.isSuccess()); List<ApiDefinitionEntity> data = result.getData(); assertEquals(2, data.size()); assertEquals(entities, data); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(2, entitiesInMem.size()); assertEquals(entities, entitiesInMem); }
@GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } }
GatewayApiController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } }
GatewayApiController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } }
GatewayApiController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
GatewayApiController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<ApiDefinitionEntity> apis = sentinelApiClient.fetchApis(app, ip, port).get(); repository.saveAll(apis); return Result.ofSuccess(apis); } catch (Throwable throwable) { logger.error("queryApis error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testAddApi() throws Exception { String path = "/gateway/api/new.json"; AddApiReqVo reqVo = new AddApiReqVo(); reqVo.setApp(TEST_APP); reqVo.setIp(TEST_IP); reqVo.setPort(TEST_PORT); reqVo.setApiName("customized_api"); List<ApiPredicateItemVo> itemVos = new ArrayList<>(); ApiPredicateItemVo itemVo = new ApiPredicateItemVo(); itemVo.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); itemVo.setPattern("/product"); itemVos.add(itemVo); reqVo.setPredicateItems(itemVos); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {}); assertTrue(result.isSuccess()); ApiDefinitionEntity entity = result.getData(); assertNotNull(entity); assertEquals(TEST_APP, entity.getApp()); assertEquals(TEST_IP, entity.getIp()); assertEquals(TEST_PORT, entity.getPort()); assertEquals("customized_api", entity.getApiName()); assertNotNull(entity.getId()); assertNotNull(entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems(); assertEquals(1, predicateItemEntities.size()); ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next(); assertEquals(URL_MATCH_STRATEGY_EXACT, predicateItemEntity.getMatchStrategy().intValue()); assertEquals("/product", predicateItemEntity.getPattern()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
@PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); }
GatewayApiController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } }
GatewayApiController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } }
GatewayApiController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
GatewayApiController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } ApiDefinitionEntity entity = new ApiDefinitionEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); String apiName = reqVo.getApiName(); if (StringUtil.isBlank(apiName)) { return Result.ofFail(-1, "apiName can't be null or empty"); } entity.setApiName(apiName.trim()); List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); Integer matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port)); if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) { return Result.ofFail(-1, "apiName exists: " + apiName); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, ip, port)) { logger.warn("publish gateway apis fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testUpdateApi() throws Exception { String path = "/gateway/api/save.json"; ApiDefinitionEntity addEntity = new ApiDefinitionEntity(); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setApiName("bbb"); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>(); addEntity.setPredicateItems(addRedicateItemEntities); ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity(); addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); addPredicateItemEntity.setPattern("/order"); addEntity = repository.save(addEntity); UpdateApiReqVo reqVo = new UpdateApiReqVo(); reqVo.setId(addEntity.getId()); reqVo.setApp(TEST_APP); List<ApiPredicateItemVo> itemVos = new ArrayList<>(); ApiPredicateItemVo itemVo = new ApiPredicateItemVo(); itemVo.setMatchStrategy(URL_MATCH_STRATEGY_PREFIX); itemVo.setPattern("/my_order"); itemVos.add(itemVo); reqVo.setPredicateItems(itemVos); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<ApiDefinitionEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<ApiDefinitionEntity>>() {}); assertTrue(result.isSuccess()); ApiDefinitionEntity entity = result.getData(); assertNotNull(entity); assertEquals("bbb", entity.getApiName()); assertEquals(date, entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); assertNotEquals(entity.getGmtCreate(), entity.getGmtModified()); Set<ApiPredicateItemEntity> predicateItemEntities = entity.getPredicateItems(); assertEquals(1, predicateItemEntities.size()); ApiPredicateItemEntity predicateItemEntity = predicateItemEntities.iterator().next(); assertEquals(URL_MATCH_STRATEGY_PREFIX, predicateItemEntity.getMatchStrategy().intValue()); assertEquals("/my_order", predicateItemEntity.getPattern()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
@PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); }
GatewayApiController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } }
GatewayApiController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } }
GatewayApiController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
GatewayApiController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "api does not exist, id=" + id); } List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems(); if (CollectionUtils.isEmpty(predicateItems)) { return Result.ofFail(-1, "predicateItems can't empty"); } List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>(); for (ApiPredicateItemVo predicateItem : predicateItems) { ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity(); int matchStrategy = predicateItem.getMatchStrategy(); if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "Invalid matchStrategy: " + matchStrategy); } predicateItemEntity.setMatchStrategy(matchStrategy); String pattern = predicateItem.getPattern(); if (StringUtil.isBlank(pattern)) { return Result.ofFail(-1, "pattern can't be null or empty"); } predicateItemEntity.setPattern(pattern); predicateItemEntities.add(predicateItemEntity); } entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities)); Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway apis fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testDeleteApi() throws Exception { String path = "/gateway/api/delete.json"; ApiDefinitionEntity addEntity = new ApiDefinitionEntity(); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setApiName("ccc"); Date date = new Date(); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); Set<ApiPredicateItemEntity> addRedicateItemEntities = new HashSet<>(); addEntity.setPredicateItems(addRedicateItemEntities); ApiPredicateItemEntity addPredicateItemEntity = new ApiPredicateItemEntity(); addPredicateItemEntity.setMatchStrategy(URL_MATCH_STRATEGY_EXACT); addPredicateItemEntity.setPattern("/user/add"); addEntity = repository.save(addEntity); given(sentinelApiClient.modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.param("id", String.valueOf(addEntity.getId())); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyApis(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {}); assertTrue(result.isSuccess()); assertEquals(addEntity.getId(), result.getData()); List<ApiDefinitionEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(0, entitiesInMem.size()); }
@PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); }
GatewayApiController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } }
GatewayApiController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } }
GatewayApiController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
GatewayApiController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteApi(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } ApiDefinitionEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway api error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishApis(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway apis fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<ApiDefinitionEntity>> queryApis(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<ApiDefinitionEntity> updateApi(@RequestBody UpdateApiReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteApi(Long id); }
@Test public void testQueryFlowRules() throws Exception { String path = "/gateway/flow/list.json"; List<GatewayFlowRuleEntity> entities = new ArrayList<>(); GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setId(1L); entity.setApp(TEST_APP); entity.setIp(TEST_IP); entity.setPort(TEST_PORT); entity.setResource("httpbin_route"); entity.setResourceMode(RESOURCE_MODE_ROUTE_ID); entity.setGrade(FLOW_GRADE_QPS); entity.setCount(5D); entity.setInterval(30L); entity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); entity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); entity.setBurst(0); entity.setMaxQueueingTimeoutMs(0); GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); itemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); entities.add(entity); GatewayFlowRuleEntity entity2 = new GatewayFlowRuleEntity(); entity2.setId(2L); entity2.setApp(TEST_APP); entity2.setIp(TEST_IP); entity2.setPort(TEST_PORT); entity2.setResource("some_customized_api"); entity2.setResourceMode(RESOURCE_MODE_CUSTOM_API_NAME); entity2.setCount(30D); entity2.setInterval(2L); entity2.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE); entity2.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); entity2.setBurst(0); entity2.setMaxQueueingTimeoutMs(0); GatewayParamFlowItemEntity itemEntity2 = new GatewayParamFlowItemEntity(); entity2.setParamItem(itemEntity2); itemEntity2.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); entities.add(entity2); CompletableFuture<List<GatewayFlowRuleEntity>> completableFuture = mock(CompletableFuture.class); given(completableFuture.get()).willReturn(entities); given(sentinelApiClient.fetchGatewayFlowRules(TEST_APP, TEST_IP, TEST_PORT)).willReturn(completableFuture); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get(path); requestBuilder.param("app", TEST_APP); requestBuilder.param("ip", TEST_IP); requestBuilder.param("port", String.valueOf(TEST_PORT)); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).fetchGatewayFlowRules(TEST_APP, TEST_IP, TEST_PORT); Result<List<GatewayFlowRuleEntity>> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<List<GatewayFlowRuleEntity>>>(){}); assertTrue(result.isSuccess()); List<GatewayFlowRuleEntity> data = result.getData(); assertEquals(2, data.size()); assertEquals(entities, data); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(2, entitiesInMem.size()); assertEquals(entities, entitiesInMem); }
@GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } }
GatewayFlowRuleController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } }
GatewayFlowRuleController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } }
GatewayFlowRuleController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
GatewayFlowRuleController { @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) public Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port) { if (StringUtil.isEmpty(app)) { return Result.ofFail(-1, "app can't be null or empty"); } if (StringUtil.isEmpty(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } if (port == null) { return Result.ofFail(-1, "port can't be null"); } try { List<GatewayFlowRuleEntity> rules = sentinelApiClient.fetchGatewayFlowRules(app, ip, port).get(); repository.saveAll(rules); return Result.ofSuccess(rules); } catch (Throwable throwable) { logger.error("query gateway flow rules error:", throwable); return Result.ofThrowable(-1, throwable); } } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testAddFlowRule() throws Exception { String path = "/gateway/flow/new.json"; AddFlowRuleReqVo reqVo = new AddFlowRuleReqVo(); reqVo.setApp(TEST_APP); reqVo.setIp(TEST_IP); reqVo.setPort(TEST_PORT); reqVo.setResourceMode(RESOURCE_MODE_ROUTE_ID); reqVo.setResource("httpbin_route"); reqVo.setGrade(FLOW_GRADE_QPS); reqVo.setCount(5D); reqVo.setInterval(30L); reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); reqVo.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); reqVo.setBurst(0); reqVo.setMaxQueueingTimeoutMs(0); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() {}); assertTrue(result.isSuccess()); GatewayFlowRuleEntity entity = result.getData(); assertNotNull(entity); assertEquals(TEST_APP, entity.getApp()); assertEquals(TEST_IP, entity.getIp()); assertEquals(TEST_PORT, entity.getPort()); assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue()); assertEquals("httpbin_route", entity.getResource()); assertNotNull(entity.getId()); assertNotNull(entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(1, entitiesInMem.size()); assertEquals(entity, entitiesInMem.get(0)); }
@PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); }
GatewayFlowRuleController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } }
GatewayFlowRuleController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } }
GatewayFlowRuleController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
GatewayFlowRuleController { @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } GatewayFlowRuleEntity entity = new GatewayFlowRuleEntity(); entity.setApp(app.trim()); String ip = reqVo.getIp(); if (StringUtil.isBlank(ip)) { return Result.ofFail(-1, "ip can't be null or empty"); } entity.setIp(ip.trim()); Integer port = reqVo.getPort(); if (port == null) { return Result.ofFail(-1, "port can't be null"); } entity.setPort(port); Integer resourceMode = reqVo.getResourceMode(); if (resourceMode == null) { return Result.ofFail(-1, "resourceMode can't be null"); } if (!Arrays.asList(RESOURCE_MODE_ROUTE_ID, RESOURCE_MODE_CUSTOM_API_NAME).contains(resourceMode)) { return Result.ofFail(-1, "invalid resourceMode: " + resourceMode); } entity.setResourceMode(resourceMode); String resource = reqVo.getResource(); if (StringUtil.isBlank(resource)) { return Result.ofFail(-1, "resource can't be null or empty"); } entity.setResource(resource.trim()); GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtCreate(date); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("add gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, ip, port)) { logger.warn("publish gateway flow rules fail after add"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testUpdateFlowRule() throws Exception { String path = "/gateway/flow/save.json"; GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity(); addEntity.setId(1L); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setResource("httpbin_route"); addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID); addEntity.setGrade(FLOW_GRADE_QPS); addEntity.setCount(5D); addEntity.setInterval(30L); addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); addEntity.setBurst(0); addEntity.setMaxQueueingTimeoutMs(0); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity(); addEntity.setParamItem(addItemEntity); addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); repository.save(addEntity); UpdateFlowRuleReqVo reqVo = new UpdateFlowRuleReqVo(); reqVo.setId(addEntity.getId()); reqVo.setApp(TEST_APP); reqVo.setGrade(FLOW_GRADE_QPS); reqVo.setCount(6D); reqVo.setInterval(2L); reqVo.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE); reqVo.setControlBehavior(CONTROL_BEHAVIOR_RATE_LIMITER); reqVo.setMaxQueueingTimeoutMs(500); GatewayParamFlowItemVo itemVo = new GatewayParamFlowItemVo(); reqVo.setParamItem(itemVo); itemVo.setParseStrategy(PARAM_PARSE_STRATEGY_URL_PARAM); itemVo.setFieldName("pa"); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.content(JSON.toJSONString(reqVo)).contentType(MediaType.APPLICATION_JSON); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<GatewayFlowRuleEntity> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<GatewayFlowRuleEntity>>() { }); assertTrue(result.isSuccess()); GatewayFlowRuleEntity entity = result.getData(); assertNotNull(entity); assertEquals(RESOURCE_MODE_ROUTE_ID, entity.getResourceMode().intValue()); assertEquals("httpbin_route", entity.getResource()); assertEquals(6D, entity.getCount().doubleValue(), 0); assertEquals(2L, entity.getInterval().longValue()); assertEquals(GatewayFlowRuleEntity.INTERVAL_UNIT_MINUTE, entity.getIntervalUnit().intValue()); assertEquals(CONTROL_BEHAVIOR_RATE_LIMITER, entity.getControlBehavior().intValue()); assertEquals(0, entity.getBurst().intValue()); assertEquals(500, entity.getMaxQueueingTimeoutMs().intValue()); assertEquals(date, entity.getGmtCreate()); assertNotNull(entity.getGmtModified()); assertNotEquals(entity.getGmtCreate(), entity.getGmtModified()); GatewayParamFlowItemEntity itemEntity = entity.getParamItem(); assertEquals(PARAM_PARSE_STRATEGY_URL_PARAM, itemEntity.getParseStrategy().intValue()); assertEquals("pa", itemEntity.getFieldName()); }
@PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); }
GatewayFlowRuleController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } }
GatewayFlowRuleController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } }
GatewayFlowRuleController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
GatewayFlowRuleController { @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) public Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo) { String app = reqVo.getApp(); if (StringUtil.isBlank(app)) { return Result.ofFail(-1, "app can't be null or empty"); } Long id = reqVo.getId(); if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "gateway flow rule does not exist, id=" + id); } GatewayParamFlowItemVo paramItem = reqVo.getParamItem(); if (paramItem != null) { GatewayParamFlowItemEntity itemEntity = new GatewayParamFlowItemEntity(); entity.setParamItem(itemEntity); Integer parseStrategy = paramItem.getParseStrategy(); if (!Arrays.asList(PARAM_PARSE_STRATEGY_CLIENT_IP, PARAM_PARSE_STRATEGY_HOST, PARAM_PARSE_STRATEGY_HEADER , PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { return Result.ofFail(-1, "invalid parseStrategy: " + parseStrategy); } itemEntity.setParseStrategy(paramItem.getParseStrategy()); if (Arrays.asList(PARAM_PARSE_STRATEGY_HEADER, PARAM_PARSE_STRATEGY_URL_PARAM, PARAM_PARSE_STRATEGY_COOKIE).contains(parseStrategy)) { String fieldName = paramItem.getFieldName(); if (StringUtil.isBlank(fieldName)) { return Result.ofFail(-1, "fieldName can't be null or empty"); } itemEntity.setFieldName(paramItem.getFieldName()); } String pattern = paramItem.getPattern(); if (StringUtil.isNotEmpty(pattern)) { itemEntity.setPattern(pattern); Integer matchStrategy = paramItem.getMatchStrategy(); if (!Arrays.asList(PARAM_MATCH_STRATEGY_EXACT, PARAM_MATCH_STRATEGY_CONTAINS, PARAM_MATCH_STRATEGY_REGEX).contains(matchStrategy)) { return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy); } itemEntity.setMatchStrategy(matchStrategy); } } else { entity.setParamItem(null); } Integer grade = reqVo.getGrade(); if (grade == null) { return Result.ofFail(-1, "grade can't be null"); } if (!Arrays.asList(FLOW_GRADE_THREAD, FLOW_GRADE_QPS).contains(grade)) { return Result.ofFail(-1, "invalid grade: " + grade); } entity.setGrade(grade); Double count = reqVo.getCount(); if (count == null) { return Result.ofFail(-1, "count can't be null"); } if (count < 0) { return Result.ofFail(-1, "count should be at lease zero"); } entity.setCount(count); Long interval = reqVo.getInterval(); if (interval == null) { return Result.ofFail(-1, "interval can't be null"); } if (interval <= 0) { return Result.ofFail(-1, "interval should be greater than zero"); } entity.setInterval(interval); Integer intervalUnit = reqVo.getIntervalUnit(); if (intervalUnit == null) { return Result.ofFail(-1, "intervalUnit can't be null"); } if (!Arrays.asList(INTERVAL_UNIT_SECOND, INTERVAL_UNIT_MINUTE, INTERVAL_UNIT_HOUR, INTERVAL_UNIT_DAY).contains(intervalUnit)) { return Result.ofFail(-1, "Invalid intervalUnit: " + intervalUnit); } entity.setIntervalUnit(intervalUnit); Integer controlBehavior = reqVo.getControlBehavior(); if (controlBehavior == null) { return Result.ofFail(-1, "controlBehavior can't be null"); } if (!Arrays.asList(CONTROL_BEHAVIOR_DEFAULT, CONTROL_BEHAVIOR_RATE_LIMITER).contains(controlBehavior)) { return Result.ofFail(-1, "invalid controlBehavior: " + controlBehavior); } entity.setControlBehavior(controlBehavior); if (CONTROL_BEHAVIOR_DEFAULT == controlBehavior) { Integer burst = reqVo.getBurst(); if (burst == null) { return Result.ofFail(-1, "burst can't be null"); } if (burst < 0) { return Result.ofFail(-1, "invalid burst: " + burst); } entity.setBurst(burst); } else if (CONTROL_BEHAVIOR_RATE_LIMITER == controlBehavior) { Integer maxQueueingTimeoutMs = reqVo.getMaxQueueingTimeoutMs(); if (maxQueueingTimeoutMs == null) { return Result.ofFail(-1, "maxQueueingTimeoutMs can't be null"); } if (maxQueueingTimeoutMs < 0) { return Result.ofFail(-1, "invalid maxQueueingTimeoutMs: " + maxQueueingTimeoutMs); } entity.setMaxQueueingTimeoutMs(maxQueueingTimeoutMs); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); } catch (Throwable throwable) { logger.error("update gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(app, entity.getIp(), entity.getPort())) { logger.warn("publish gateway flow rules fail after update"); } return Result.ofSuccess(entity); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testDeleteFlowRule() throws Exception { String path = "/gateway/flow/delete.json"; GatewayFlowRuleEntity addEntity = new GatewayFlowRuleEntity(); addEntity.setId(1L); addEntity.setApp(TEST_APP); addEntity.setIp(TEST_IP); addEntity.setPort(TEST_PORT); addEntity.setResource("httpbin_route"); addEntity.setResourceMode(RESOURCE_MODE_ROUTE_ID); addEntity.setGrade(FLOW_GRADE_QPS); addEntity.setCount(5D); addEntity.setInterval(30L); addEntity.setIntervalUnit(GatewayFlowRuleEntity.INTERVAL_UNIT_SECOND); addEntity.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT); addEntity.setBurst(0); addEntity.setMaxQueueingTimeoutMs(0); Date date = new Date(); date = DateUtils.addSeconds(date, -1); addEntity.setGmtCreate(date); addEntity.setGmtModified(date); GatewayParamFlowItemEntity addItemEntity = new GatewayParamFlowItemEntity(); addEntity.setParamItem(addItemEntity); addItemEntity.setParseStrategy(PARAM_PARSE_STRATEGY_CLIENT_IP); repository.save(addEntity); given(sentinelApiClient.modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any())).willReturn(true); MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(path); requestBuilder.param("id", String.valueOf(addEntity.getId())); MvcResult mvcResult = mockMvc.perform(requestBuilder) .andExpect(MockMvcResultMatchers.status().isOk()).andDo(MockMvcResultHandlers.print()).andReturn(); verify(sentinelApiClient).modifyGatewayFlowRules(eq(TEST_APP), eq(TEST_IP), eq(TEST_PORT), any()); Result<Long> result = JSONObject.parseObject(mvcResult.getResponse().getContentAsString(), new TypeReference<Result<Long>>() {}); assertTrue(result.isSuccess()); assertEquals(addEntity.getId(), result.getData()); List<GatewayFlowRuleEntity> entitiesInMem = repository.findAllByApp(TEST_APP); assertEquals(0, entitiesInMem.size()); }
@PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); }
GatewayFlowRuleController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } }
GatewayFlowRuleController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } }
GatewayFlowRuleController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
GatewayFlowRuleController { @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) public Result<Long> deleteFlowRule(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } GatewayFlowRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); } catch (Throwable throwable) { logger.error("delete gateway flow rule error:", throwable); return Result.ofThrowable(-1, throwable); } if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) { logger.warn("publish gateway flow rules fail after delete"); } return Result.ofSuccess(id); } @GetMapping("/list.json") @AuthAction(AuthService.PrivilegeType.READ_RULE) Result<List<GatewayFlowRuleEntity>> queryFlowRules(String app, String ip, Integer port); @PostMapping("/new.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> addFlowRule(@RequestBody AddFlowRuleReqVo reqVo); @PostMapping("/save.json") @AuthAction(AuthService.PrivilegeType.WRITE_RULE) Result<GatewayFlowRuleEntity> updateFlowRule(@RequestBody UpdateFlowRuleReqVo reqVo); @PostMapping("/delete.json") @AuthAction(AuthService.PrivilegeType.DELETE_RULE) Result<Long> deleteFlowRule(Long id); }
@Test public void testGetConfigStr() { DashboardConfig.clearCache(); assertEquals(null, DashboardConfig.getConfigStr("a")); System.setProperty("a", "111"); assertEquals("111", DashboardConfig.getConfigStr("a")); environmentVariables.set("a", "222"); assertEquals("111", DashboardConfig.getConfigStr("a")); DashboardConfig.clearCache(); assertEquals("222", DashboardConfig.getConfigStr("a")); }
protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; }
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } }
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } }
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); }
DashboardConfig { protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } static String getAuthUsername(); static String getAuthPassword(); static int getHideAppNoMachineMillis(); static int getRemoveAppNoMachineMillis(); static int getAutoRemoveMachineMillis(); static int getUnhealthyMachineMillis(); static void clearCache(); static final int DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS; static final String CONFIG_AUTH_USERNAME; static final String CONFIG_AUTH_PASSWORD; static final String CONFIG_HIDE_APP_NO_MACHINE_MILLIS; static final String CONFIG_REMOVE_APP_NO_MACHINE_MILLIS; static final String CONFIG_UNHEALTHY_MACHINE_MILLIS; static final String CONFIG_AUTO_REMOVE_MACHINE_MILLIS; }
@Test public void RGB_to_3ByteBGR() { new ImageConversion().RGB_to_3ByteBGR(); }
@Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; }
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } }
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } }
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
ImageConversion { @Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_3BYTE_BGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void RGBA_to_4ByteABGR() { new ImageConversion().RGBA_to_4ByteABGR(); }
@Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; }
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } }
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } }
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
ImageConversion { @Benchmark public BufferedImage RGBA_to_4ByteABGR() { DataBuffer buffer = new DataBufferByte(RGBA_SRC, RGBA_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 4, WIDTH * 4, new int[]{0, 1, 2, 3}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); Raster raster = Raster.createRaster(sampleModel, buffer, null); image.setData(raster); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void ABGR_to_4ByteABGR() { new ImageConversion().ABGR_to_4ByteABGR_arraycopy(); }
@Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_arraycopy() { BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_4BYTE_ABGR); DataBufferByte buffer = (DataBufferByte)(image.getRaster().getDataBuffer()); byte[] data = buffer.getData(); System.arraycopy(ABGR_SRC, 0, data, 0, ABGR_SRC.length); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void ABGR_to_4ByteABGR_instantiate() { new ImageConversion().ABGR_to_4ByteABGR_instantiate(); }
@Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
ImageConversion { @Benchmark public BufferedImage ABGR_to_4ByteABGR_instantiate() { ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB); ColorModel colorModel; WritableRaster raster; int[] nBits = {8, 8, 8, 8}; int[] bOffs = {3, 2, 1, 0}; colorModel = new ComponentColorModel(cs, nBits, true, false, Transparency.TRANSLUCENT, DataBuffer.TYPE_BYTE); DataBufferByte buffer = new DataBufferByte(ABGR_SRC, ABGR_SRC.length); raster = Raster.createInterleavedRaster(buffer, WIDTH, HEIGHT, WIDTH*4, 4, bOffs, null); BufferedImage image = new BufferedImage(colorModel, raster, false, null); return image; } @Benchmark BufferedImage RGB_to_3ByteBGR(); @Benchmark BufferedImage RGBA_to_4ByteABGR(); @Benchmark BufferedImage ABGR_to_4ByteABGR_arraycopy(); @Benchmark BufferedImage ABGR_to_4ByteABGR_instantiate(); @Benchmark BufferedImage BGR_to_3ByteBGR_instantiate(); static void main(String[] args); }
@Test public void displayText() throws Exception { new TextDisplay(senseHat).displayText("Hallo Welt!"); }
public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); }
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } }
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } }
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } void displayText(String text); void setForeground(SenseHatColor foreground); void setBackground(SenseHatColor background); }
TextDisplay { public void displayText(String text) throws IOException { BufferedImage image = new BufferedImage(8, 8, BufferedImage.TYPE_USHORT_565_RGB); Graphics2D graphics = image.createGraphics(); if (big) { text = text.toUpperCase(); } Font sansSerif = new Font("SansSerif", Font.PLAIN, big ? 10 : 8); graphics.setFont(sansSerif); int i = graphics.getFontMetrics().stringWidth(text) - 8; if (i <= 0) { i = 1; } long durationInMillis = duration.toMillis(); for (int j = 0; j <= i; j++) { long start = System.currentTimeMillis(); graphics.setColor(background); graphics.setPaint(background); graphics.fillRect(0, 0, 8, 8); graphics.setColor(foreground); graphics.setPaint(foreground); graphics.drawString(text, -j, big ? 8 : 7); senseHat.fadeTo(image, duration.dividedBy(2)); long timeToSleep = durationInMillis - (System.currentTimeMillis() - start); if(timeToSleep > 0) { try { Thread.sleep(timeToSleep); } catch (InterruptedException e) { log.error(e.getLocalizedMessage(), e); } } } graphics.dispose(); } void displayText(String text); void setForeground(SenseHatColor foreground); void setBackground(SenseHatColor background); }
@Test public void testInt_red() { assertThat(SenseHatColor.fromRGB(0xFF, 0x00, 0x00).getSenseHatColor()).isEqualTo(0xF800); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testDouble_red() { assertThat(SenseHatColor.fromRGB(1f ,0f, 0f).getSenseHatColor()).isEqualTo(0xF800); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testString_red() { assertThat(SenseHatColor.fromString("red").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("F00").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("#F00").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("FF0000").getSenseHatColor()).isEqualTo(0xF800); assertThat(SenseHatColor.fromString("#FF0000").getSenseHatColor()).isEqualTo(0xF800); }
public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testInt_blue() { assertThat(SenseHatColor.fromRGB(0x00, 0x00, 0xFF).getSenseHatColor()).isEqualTo(0x001F); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testDouble_blue() { assertThat(SenseHatColor.fromRGB(0f ,0f, 1f).getSenseHatColor()).isEqualTo(0x001F); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testString_blue() { assertThat(SenseHatColor.fromString("blue").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("00F").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("#00F").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("0000FF").getSenseHatColor()).isEqualTo(0x001F); assertThat(SenseHatColor.fromString("#0000FF").getSenseHatColor()).isEqualTo(0x001F); }
public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testPlus() { SenseHatColor white = SenseHatColor.fromString("FFF"); SenseHatColor black = SenseHatColor.fromString("000"); assertThat(white.plus(black)).isEqualTo(white); assertThat(white.plus(white)).isEqualTo(white); assertThat(black.plus(black)).isEqualTo(black); assertThat(SenseHatColor.fromString("F00").plus(SenseHatColor.fromString("00F"))) .isEqualTo(SenseHatColor.fromString("F0F")); }
public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); }
SenseHatColor { public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); } }
SenseHatColor { public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public SenseHatColor plus(SenseHatColor other) { int newRed = getRedRaw() + other.getRedRaw(); int newGreen = getGreenRaw() + other.getGreenRaw(); int newBlue = getBlueRaw() + other.getBlueRaw(); if (newRed > 31) { newRed = 31; } if (newGreen > 63) { newGreen = 63; } if (newBlue > 31) { newBlue = 31; } return new SenseHatColor(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testMix() { SenseHatColor white = SenseHatColor.fromString("FFF"); SenseHatColor black = SenseHatColor.fromString("000"); assertThat(white.mix(black)).isEqualTo(white.divide(2)); assertThat(white.mix(white)).isEqualTo(white); assertThat(black.mix(black)).isEqualTo(black); assertThat(SenseHatColor.fromString("F00").mix(SenseHatColor.fromString("00F"))) .isEqualTo(SenseHatColor.fromRGB(0.5f, 0f, 0.5f)); }
public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); }
SenseHatColor { public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); } }
SenseHatColor { public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public SenseHatColor mix(SenseHatColor other) { if (this.equals(other)) { return this; } float newRed = (getRed() + other.getRed()) / 2f; float newGreen = (getGreen() + other.getGreen()) / 2f; float newBlue = (getBlue() + other.getBlue()) / 2f; return fromRGB(newRed, newGreen, newBlue); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testGetRed() throws Exception { assertThat(new SenseHatColor(0xFFFF).getRed()).isEqualTo(1); assertThat(new SenseHatColor(0xF800).getRed()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getRed()).isEqualTo(0); }
public float getRed() { return getRedRaw() / 31f; }
SenseHatColor { public float getRed() { return getRedRaw() / 31f; } }
SenseHatColor { public float getRed() { return getRedRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public float getRed() { return getRedRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public float getRed() { return getRedRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void getGreen() throws Exception { assertThat(new SenseHatColor(0xFFFF).getGreen()).isEqualTo(1); assertThat(new SenseHatColor(0x07E0).getGreen()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getGreen()).isEqualTo(0); }
public float getGreen() { return getGreenRaw() / 63f; }
SenseHatColor { public float getGreen() { return getGreenRaw() / 63f; } }
SenseHatColor { public float getGreen() { return getGreenRaw() / 63f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public float getGreen() { return getGreenRaw() / 63f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public float getGreen() { return getGreenRaw() / 63f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void getBlue() throws Exception { assertThat(new SenseHatColor(0xFFFF).getBlue()).isEqualTo(1); assertThat(new SenseHatColor(0x003F).getBlue()).isEqualTo(1); assertThat(new SenseHatColor(0x0000).getBlue()).isEqualTo(0); }
public float getBlue() { return getBlueRaw() / 31f; }
SenseHatColor { public float getBlue() { return getBlueRaw() / 31f; } }
SenseHatColor { public float getBlue() { return getBlueRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public float getBlue() { return getBlueRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public float getBlue() { return getBlueRaw() / 31f; } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testInt_white() { assertThat(SenseHatColor.fromRGB(0xFF, 0xFF, 0xFF).getSenseHatColor()).isEqualTo(0xFFFF); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testDouble_white() { assertThat(SenseHatColor.fromRGB(1f ,1f, 1f).getSenseHatColor()).isEqualTo(0xFFFF); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testString_white() { assertThat(SenseHatColor.fromString("white").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("FFF").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("fff").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("#FFF").getSenseHatColor()).isEqualTo(0xFFFF); assertThat(SenseHatColor.fromString("#FFFFFF").getSenseHatColor()).isEqualTo(0xFFFF); }
public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testInt_black() { assertThat(SenseHatColor.fromRGB(0x00, 0x00, 0x00).getSenseHatColor()).isEqualTo(0x0000); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testDouble_black() { assertThat(SenseHatColor.fromRGB(0f ,0f, 0f).getSenseHatColor()).isEqualTo(0x0000); }
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testString_black() { assertThat(SenseHatColor.fromString("black").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("#000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("000000").getSenseHatColor()).isEqualTo(0x0000); assertThat(SenseHatColor.fromString("#000000").getSenseHatColor()).isEqualTo(0x0000); }
public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); }
SenseHatColor { public static SenseHatColor fromString(String color) { switch (color.toLowerCase()) { case "red": return RED; case "green": return GREEN; case "blue": return BLUE; case "yellow": return YELLOW; case "pink": case "magenta": return MAGENTA; case "cyan": return CYAN; case "white": return WHITE; case "black": return BLACK; case "grey": return fromRGB(0.5f, 0.5f, 0.5f); } Matcher smallMatcher = SMALL_COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (smallMatcher.matches()) { int red = Integer.parseInt(smallMatcher.group(1), 16); int green = Integer.parseInt(smallMatcher.group(2), 16); int blue = Integer.parseInt(smallMatcher.group(3), 16); return fromRGB(red / 15f, green / 15f, blue / 15f); } Matcher matcher = COLOR_HEX_PATTERN.matcher(color.toUpperCase()); if (matcher.matches()) { int red = Integer.parseInt(matcher.group(1), 16); int green = Integer.parseInt(matcher.group(2), 16); int blue = Integer.parseInt(matcher.group(3), 16); return fromRGB(red, green, blue); } throw new IllegalArgumentException(); } SenseHatColor(int senseHatColor); SenseHatColor(int r, int g, int b); short getRedRaw(); float getRed(); SenseHatColor withRedRaw(short red); SenseHatColor withRed(float red); short getGreenRaw(); float getGreen(); SenseHatColor withGreenRaw(short green); SenseHatColor withGreen(float green); short getBlueRaw(); float getBlue(); SenseHatColor withBlueRaw(short blue); SenseHatColor withBlue(float blue); SenseHatColor plus(SenseHatColor other); SenseHatColor minus(SenseHatColor other); SenseHatColor multiply(float factor); SenseHatColor divide(float divisor); SenseHatColor mix(SenseHatColor other); SenseHatColor mix(SenseHatColor other, float factor); static SenseHatColor fromRGB(int red, int green, int blue); static SenseHatColor fromRGB(float red, float green, float blue); static SenseHatColor fromColor(Color color); Color toColor(); static SenseHatColor fromRGB(int rgb); static SenseHatColor fromString(String color); @Override String toString(); static final SenseHatColor BLACK; static final SenseHatColor WHITE; static final SenseHatColor GREY; static final SenseHatColor RED; static final SenseHatColor GREEN; static final SenseHatColor BLUE; static final SenseHatColor CYAN; static final SenseHatColor MAGENTA; static final SenseHatColor YELLOW; static final Pattern SMALL_COLOR_HEX_PATTERN; static final Pattern COLOR_HEX_PATTERN; }
@Test public void testRoute_ReturnFalse() { Router router = new ConditionRouterFactory().getRouter(getRouteUrl("host = " + NetUtils.getLocalHost() + " => false")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); List<Invoker<String>> fileredInvokers = router.route(invokers, URL.valueOf("consumer: Assert.assertEquals(0, fileredInvokers.size()); }
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; }
ConditionRouter implements Router, Comparable<Router> { public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; } }
ConditionRouter implements Router, Comparable<Router> { public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; } ConditionRouter(URL url); }
ConditionRouter implements Router, Comparable<Router> { public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; } ConditionRouter(URL url); List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation); URL getUrl(); int compareTo(Router o); boolean matchWhen(URL url); boolean matchThen(URL url, URL param); }
ConditionRouter implements Router, Comparable<Router> { public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { if (invokers == null || invokers.size() == 0) { return invokers; } try { if (!matchWhen(url)) { return invokers; } List<Invoker<T>> result = new ArrayList<Invoker<T>>(); if (thenCondition == null) { logger.warn("The current consumer in the service blacklist. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey()); return result; } for (Invoker<T> invoker : invokers) { if (matchThen(invoker.getUrl(), url)) { result.add(invoker); } } if (result.size() > 0) { return result; } else if (force) { logger.warn("The route result is empty and force execute. consumer: " + NetUtils.getLocalHost() + ", service: " + url.getServiceKey() + ", router: " + url.getParameterAndDecoded(Constants.RULE_KEY)); return result; } } catch (Throwable t) { logger.error("Failed to execute condition router rule: " + getUrl() + ", invokers: " + invokers + ", cause: " + t.getMessage(), t); } return invokers; } ConditionRouter(URL url); List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation); URL getUrl(); int compareTo(Router o); boolean matchWhen(URL url); boolean matchThen(URL url, URL param); }
@Test public void testDoRetry_subscribe() throws Exception { final CountDownLatch latch = new CountDownLatch(1); registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.register(serviceUrl); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); }
@Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } }
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } }
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } FailbackRegistry(URL url); }
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
FailbackRegistry extends AbstractRegistry { @Override public void register(URL url) { super.register(url); failedRegistered.remove(url); failedUnregistered.remove(url); try { doRegister(url); } catch (Exception e) { Throwable t = e; boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true) && !Constants.CONSUMER_PROTOCOL.equals(url.getProtocol()); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to register " + url + " to registry " + getUrl().getAddress() + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to register " + url + ", waiting for retry, cause: " + t.getMessage(), t); } failedRegistered.add(url); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
@Test public void testDoRetry_register() throws Exception { final AtomicReference<Boolean> notified = new AtomicReference<Boolean>(false); final CountDownLatch latch = new CountDownLatch(1); NotifyListener listner = new NotifyListener() { public void notify(List<URL> urls) { notified.set(Boolean.TRUE); } }; registry = new MockRegistry(registryUrl, latch); registry.setBad(true); registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); assertEquals(false, notified.get()); assertEquals(1, latch.getCount()); registry.setBad(false); for (int i = 0; i < trytimes; i++) { System.out.println("failback registry retry ,times:" + i); if (latch.getCount() == 0) break; Thread.sleep(sleeptime); } assertEquals(0, latch.getCount()); assertEquals(true, notified.get()); }
@Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
@Test public void testDoRetry_nofify() throws Exception { final AtomicInteger count = new AtomicInteger(0); NotifyListener listner = new NotifyListener() { public void notify(List<URL> urls) { count.incrementAndGet(); if (count.get() == 1l) { throw new RuntimeException("test exception please ignore"); } } }; registry = new MockRegistry(registryUrl, new CountDownLatch(0)); registry.subscribe(serviceUrl.setProtocol(Constants.CONSUMER_PROTOCOL).addParameters(CollectionUtils.toStringMap("check", "false")), listner); assertEquals(1, count.get()); for (int i = 0; i < trytimes; i++) { System.out.println("failback notify retry ,times:" + i); if (count.get() == 2) break; Thread.sleep(sleeptime); } assertEquals(2, count.get()); }
@Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
FailbackRegistry extends AbstractRegistry { @Override public void subscribe(URL url, NotifyListener listener) { super.subscribe(url, listener); removeFailedSubscribed(url, listener); try { doSubscribe(url, listener); } catch (Exception e) { Throwable t = e; List<URL> urls = getCacheUrls(url); if (urls != null && urls.size() > 0) { notify(url, listener, urls); logger.error("Failed to subscribe " + url + ", Using cached list: " + urls + " from cache file: " + getUrl().getParameter(Constants.FILE_KEY, System.getProperty("user.home") + "/dubbo-registry-" + url.getHost() + ".cache") + ", cause: " + t.getMessage(), t); } else { boolean check = getUrl().getParameter(Constants.CHECK_KEY, true) && url.getParameter(Constants.CHECK_KEY, true); boolean skipFailback = t instanceof SkipFailbackWrapperException; if (check || skipFailback) { if (skipFailback) { t = t.getCause(); } throw new IllegalStateException("Failed to subscribe " + url + ", cause: " + t.getMessage(), t); } else { logger.error("Failed to subscribe " + url + ", waiting for retry, cause: " + t.getMessage(), t); } } addFailedSubscribed(url, listener); } } FailbackRegistry(URL url); Future<?> getRetryFuture(); Set<URL> getFailedRegistered(); Set<URL> getFailedUnregistered(); Map<URL, Set<NotifyListener>> getFailedSubscribed(); Map<URL, Set<NotifyListener>> getFailedUnsubscribed(); Map<URL, Map<NotifyListener, List<URL>>> getFailedNotified(); @Override void register(URL url); @Override void unregister(URL url); @Override void subscribe(URL url, NotifyListener listener); @Override void unsubscribe(URL url, NotifyListener listener); @Override void destroy(); }
@Test public void test_makeEmptyClass() throws Exception { Wrapper.getWrapper(EmptyServiceImpl.class); }
public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; }
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } }
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } }
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } static Wrapper getWrapper(Class<?> c); abstract String[] getPropertyNames(); abstract Class<?> getPropertyType(String pn); abstract boolean hasProperty(String name); abstract Object getPropertyValue(Object instance, String pn); abstract void setPropertyValue(Object instance, String pn, Object pv); Object[] getPropertyValues(Object instance, String[] pns); void setPropertyValues(Object instance, String[] pns, Object[] pvs); abstract String[] getMethodNames(); abstract String[] getDeclaredMethodNames(); boolean hasMethod(String name); abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args); }
Wrapper { public static Wrapper getWrapper(Class<?> c) { while (ClassGenerator.isDynamicClass(c)) c = c.getSuperclass(); if (c == Object.class) return OBJECT_WRAPPER; Wrapper ret = WRAPPER_MAP.get(c); if (ret == null) { ret = makeWrapper(c); WRAPPER_MAP.put(c, ret); } return ret; } static Wrapper getWrapper(Class<?> c); abstract String[] getPropertyNames(); abstract Class<?> getPropertyType(String pn); abstract boolean hasProperty(String name); abstract Object getPropertyValue(Object instance, String pn); abstract void setPropertyValue(Object instance, String pn, Object pv); Object[] getPropertyValues(Object instance, String[] pns); void setPropertyValues(Object instance, String[] pns, Object[] pvs); abstract String[] getMethodNames(); abstract String[] getDeclaredMethodNames(); boolean hasMethod(String name); abstract Object invokeMethod(Object instance, String mn, Class<?>[] types, Object[] args); }
@Test public void test_valueOf_Exception_noProtocol() throws Exception { try { URL.valueOf(": fail(); } catch (IllegalStateException expected) { assertEquals("url missing protocol: \": } }
public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); static URL valueOf(String url); String getProtocol(); String getUsername(); String getPassword(); String getAuthority(); String getHost(); String getIp(); int getPort(); int getPort(int defaultPort); String getAddress(); String getBackupAddress(); String getBackupAddress(int defaultPort); List<URL> getBackupUrls(); String getPath(); String getAbsolutePath(); URL setProtocol(String protocol); URL setUsername(String username); URL setPassword(String password); URL setAddress(String address); URL setHost(String host); URL setPort(int port); URL setPath(String path); Map<String, String> getParameters(); String getParameterAndDecoded(String key); String getParameterAndDecoded(String key, String defaultValue); String getParameter(String key); String getParameter(String key, String defaultValue); String[] getParameter(String key, String[] defaultValue); URL getUrlParameter(String key); double getParameter(String key, double defaultValue); float getParameter(String key, float defaultValue); long getParameter(String key, long defaultValue); int getParameter(String key, int defaultValue); short getParameter(String key, short defaultValue); byte getParameter(String key, byte defaultValue); float getPositiveParameter(String key, float defaultValue); double getPositiveParameter(String key, double defaultValue); long getPositiveParameter(String key, long defaultValue); int getPositiveParameter(String key, int defaultValue); short getPositiveParameter(String key, short defaultValue); byte getPositiveParameter(String key, byte defaultValue); char getParameter(String key, char defaultValue); boolean getParameter(String key, boolean defaultValue); boolean hasParameter(String key); String getMethodParameterAndDecoded(String method, String key); String getMethodParameterAndDecoded(String method, String key, String defaultValue); String getMethodParameter(String method, String key); String getMethodParameter(String method, String key, String defaultValue); double getMethodParameter(String method, String key, double defaultValue); float getMethodParameter(String method, String key, float defaultValue); long getMethodParameter(String method, String key, long defaultValue); int getMethodParameter(String method, String key, int defaultValue); short getMethodParameter(String method, String key, short defaultValue); byte getMethodParameter(String method, String key, byte defaultValue); double getMethodPositiveParameter(String method, String key, double defaultValue); float getMethodPositiveParameter(String method, String key, float defaultValue); long getMethodPositiveParameter(String method, String key, long defaultValue); int getMethodPositiveParameter(String method, String key, int defaultValue); short getMethodPositiveParameter(String method, String key, short defaultValue); byte getMethodPositiveParameter(String method, String key, byte defaultValue); char getMethodParameter(String method, String key, char defaultValue); boolean getMethodParameter(String method, String key, boolean defaultValue); boolean hasMethodParameter(String method, String key); boolean isLocalHost(); boolean isAnyHost(); URL addParameterAndEncoded(String key, String value); URL addParameter(String key, boolean value); URL addParameter(String key, char value); URL addParameter(String key, byte value); URL addParameter(String key, short value); URL addParameter(String key, int value); URL addParameter(String key, long value); URL addParameter(String key, float value); URL addParameter(String key, double value); URL addParameter(String key, Enum<?> value); URL addParameter(String key, Number value); URL addParameter(String key, CharSequence value); URL addParameter(String key, String value); URL addParameterIfAbsent(String key, String value); URL addParameters(Map<String, String> parameters); URL addParametersIfAbsent(Map<String, String> parameters); URL addParameters(String... pairs); URL addParameterString(String query); URL removeParameter(String key); URL removeParameters(Collection<String> keys); URL removeParameters(String... keys); URL clearParameters(); String getRawParameter(String key); Map<String, String> toMap(); String toString(); String toString(String... parameters); String toIdentityString(); String toIdentityString(String... parameters); String toFullString(); String toFullString(String... parameters); String toParameterString(); String toParameterString(String... parameters); java.net.URL toJavaURL(); InetSocketAddress toInetSocketAddress(); String getServiceKey(); String toServiceString(); @Deprecated String getServiceName(); String getServiceInterface(); URL setServiceInterface(String service); @Deprecated int getIntParameter(String key); @Deprecated int getIntParameter(String key, int defaultValue); @Deprecated int getPositiveIntParameter(String key, int defaultValue); @Deprecated boolean getBooleanParameter(String key); @Deprecated boolean getBooleanParameter(String key, boolean defaultValue); @Deprecated int getMethodIntParameter(String method, String key); @Deprecated int getMethodIntParameter(String method, String key, int defaultValue); @Deprecated int getMethodPositiveIntParameter(String method, String key, int defaultValue); @Deprecated boolean getMethodBooleanParameter(String method, String key); @Deprecated boolean getMethodBooleanParameter(String method, String key, boolean defaultValue); static String encode(String value); static String decode(String value); @Override int hashCode(); @Override boolean equals(Object obj); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); static URL valueOf(String url); String getProtocol(); String getUsername(); String getPassword(); String getAuthority(); String getHost(); String getIp(); int getPort(); int getPort(int defaultPort); String getAddress(); String getBackupAddress(); String getBackupAddress(int defaultPort); List<URL> getBackupUrls(); String getPath(); String getAbsolutePath(); URL setProtocol(String protocol); URL setUsername(String username); URL setPassword(String password); URL setAddress(String address); URL setHost(String host); URL setPort(int port); URL setPath(String path); Map<String, String> getParameters(); String getParameterAndDecoded(String key); String getParameterAndDecoded(String key, String defaultValue); String getParameter(String key); String getParameter(String key, String defaultValue); String[] getParameter(String key, String[] defaultValue); URL getUrlParameter(String key); double getParameter(String key, double defaultValue); float getParameter(String key, float defaultValue); long getParameter(String key, long defaultValue); int getParameter(String key, int defaultValue); short getParameter(String key, short defaultValue); byte getParameter(String key, byte defaultValue); float getPositiveParameter(String key, float defaultValue); double getPositiveParameter(String key, double defaultValue); long getPositiveParameter(String key, long defaultValue); int getPositiveParameter(String key, int defaultValue); short getPositiveParameter(String key, short defaultValue); byte getPositiveParameter(String key, byte defaultValue); char getParameter(String key, char defaultValue); boolean getParameter(String key, boolean defaultValue); boolean hasParameter(String key); String getMethodParameterAndDecoded(String method, String key); String getMethodParameterAndDecoded(String method, String key, String defaultValue); String getMethodParameter(String method, String key); String getMethodParameter(String method, String key, String defaultValue); double getMethodParameter(String method, String key, double defaultValue); float getMethodParameter(String method, String key, float defaultValue); long getMethodParameter(String method, String key, long defaultValue); int getMethodParameter(String method, String key, int defaultValue); short getMethodParameter(String method, String key, short defaultValue); byte getMethodParameter(String method, String key, byte defaultValue); double getMethodPositiveParameter(String method, String key, double defaultValue); float getMethodPositiveParameter(String method, String key, float defaultValue); long getMethodPositiveParameter(String method, String key, long defaultValue); int getMethodPositiveParameter(String method, String key, int defaultValue); short getMethodPositiveParameter(String method, String key, short defaultValue); byte getMethodPositiveParameter(String method, String key, byte defaultValue); char getMethodParameter(String method, String key, char defaultValue); boolean getMethodParameter(String method, String key, boolean defaultValue); boolean hasMethodParameter(String method, String key); boolean isLocalHost(); boolean isAnyHost(); URL addParameterAndEncoded(String key, String value); URL addParameter(String key, boolean value); URL addParameter(String key, char value); URL addParameter(String key, byte value); URL addParameter(String key, short value); URL addParameter(String key, int value); URL addParameter(String key, long value); URL addParameter(String key, float value); URL addParameter(String key, double value); URL addParameter(String key, Enum<?> value); URL addParameter(String key, Number value); URL addParameter(String key, CharSequence value); URL addParameter(String key, String value); URL addParameterIfAbsent(String key, String value); URL addParameters(Map<String, String> parameters); URL addParametersIfAbsent(Map<String, String> parameters); URL addParameters(String... pairs); URL addParameterString(String query); URL removeParameter(String key); URL removeParameters(Collection<String> keys); URL removeParameters(String... keys); URL clearParameters(); String getRawParameter(String key); Map<String, String> toMap(); String toString(); String toString(String... parameters); String toIdentityString(); String toIdentityString(String... parameters); String toFullString(); String toFullString(String... parameters); String toParameterString(); String toParameterString(String... parameters); java.net.URL toJavaURL(); InetSocketAddress toInetSocketAddress(); String getServiceKey(); String toServiceString(); @Deprecated String getServiceName(); String getServiceInterface(); URL setServiceInterface(String service); @Deprecated int getIntParameter(String key); @Deprecated int getIntParameter(String key, int defaultValue); @Deprecated int getPositiveIntParameter(String key, int defaultValue); @Deprecated boolean getBooleanParameter(String key); @Deprecated boolean getBooleanParameter(String key, boolean defaultValue); @Deprecated int getMethodIntParameter(String method, String key); @Deprecated int getMethodIntParameter(String method, String key, int defaultValue); @Deprecated int getMethodPositiveIntParameter(String method, String key, int defaultValue); @Deprecated boolean getMethodBooleanParameter(String method, String key); @Deprecated boolean getMethodBooleanParameter(String method, String key, boolean defaultValue); static String encode(String value); static String decode(String value); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void test_equals() throws Exception { URL url1 = URL.valueOf("dubbo: Map<String, String> params = new HashMap<String, String>(); params.put("version", "1.0.0"); params.put("application", "morgan"); URL url2 = new URL("dubbo", "admin", "hello1234", "10.20.130.230", 20880, "context/path", params); assertEquals(url1, url2); }
public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); static URL valueOf(String url); String getProtocol(); String getUsername(); String getPassword(); String getAuthority(); String getHost(); String getIp(); int getPort(); int getPort(int defaultPort); String getAddress(); String getBackupAddress(); String getBackupAddress(int defaultPort); List<URL> getBackupUrls(); String getPath(); String getAbsolutePath(); URL setProtocol(String protocol); URL setUsername(String username); URL setPassword(String password); URL setAddress(String address); URL setHost(String host); URL setPort(int port); URL setPath(String path); Map<String, String> getParameters(); String getParameterAndDecoded(String key); String getParameterAndDecoded(String key, String defaultValue); String getParameter(String key); String getParameter(String key, String defaultValue); String[] getParameter(String key, String[] defaultValue); URL getUrlParameter(String key); double getParameter(String key, double defaultValue); float getParameter(String key, float defaultValue); long getParameter(String key, long defaultValue); int getParameter(String key, int defaultValue); short getParameter(String key, short defaultValue); byte getParameter(String key, byte defaultValue); float getPositiveParameter(String key, float defaultValue); double getPositiveParameter(String key, double defaultValue); long getPositiveParameter(String key, long defaultValue); int getPositiveParameter(String key, int defaultValue); short getPositiveParameter(String key, short defaultValue); byte getPositiveParameter(String key, byte defaultValue); char getParameter(String key, char defaultValue); boolean getParameter(String key, boolean defaultValue); boolean hasParameter(String key); String getMethodParameterAndDecoded(String method, String key); String getMethodParameterAndDecoded(String method, String key, String defaultValue); String getMethodParameter(String method, String key); String getMethodParameter(String method, String key, String defaultValue); double getMethodParameter(String method, String key, double defaultValue); float getMethodParameter(String method, String key, float defaultValue); long getMethodParameter(String method, String key, long defaultValue); int getMethodParameter(String method, String key, int defaultValue); short getMethodParameter(String method, String key, short defaultValue); byte getMethodParameter(String method, String key, byte defaultValue); double getMethodPositiveParameter(String method, String key, double defaultValue); float getMethodPositiveParameter(String method, String key, float defaultValue); long getMethodPositiveParameter(String method, String key, long defaultValue); int getMethodPositiveParameter(String method, String key, int defaultValue); short getMethodPositiveParameter(String method, String key, short defaultValue); byte getMethodPositiveParameter(String method, String key, byte defaultValue); char getMethodParameter(String method, String key, char defaultValue); boolean getMethodParameter(String method, String key, boolean defaultValue); boolean hasMethodParameter(String method, String key); boolean isLocalHost(); boolean isAnyHost(); URL addParameterAndEncoded(String key, String value); URL addParameter(String key, boolean value); URL addParameter(String key, char value); URL addParameter(String key, byte value); URL addParameter(String key, short value); URL addParameter(String key, int value); URL addParameter(String key, long value); URL addParameter(String key, float value); URL addParameter(String key, double value); URL addParameter(String key, Enum<?> value); URL addParameter(String key, Number value); URL addParameter(String key, CharSequence value); URL addParameter(String key, String value); URL addParameterIfAbsent(String key, String value); URL addParameters(Map<String, String> parameters); URL addParametersIfAbsent(Map<String, String> parameters); URL addParameters(String... pairs); URL addParameterString(String query); URL removeParameter(String key); URL removeParameters(Collection<String> keys); URL removeParameters(String... keys); URL clearParameters(); String getRawParameter(String key); Map<String, String> toMap(); String toString(); String toString(String... parameters); String toIdentityString(); String toIdentityString(String... parameters); String toFullString(); String toFullString(String... parameters); String toParameterString(); String toParameterString(String... parameters); java.net.URL toJavaURL(); InetSocketAddress toInetSocketAddress(); String getServiceKey(); String toServiceString(); @Deprecated String getServiceName(); String getServiceInterface(); URL setServiceInterface(String service); @Deprecated int getIntParameter(String key); @Deprecated int getIntParameter(String key, int defaultValue); @Deprecated int getPositiveIntParameter(String key, int defaultValue); @Deprecated boolean getBooleanParameter(String key); @Deprecated boolean getBooleanParameter(String key, boolean defaultValue); @Deprecated int getMethodIntParameter(String method, String key); @Deprecated int getMethodIntParameter(String method, String key, int defaultValue); @Deprecated int getMethodPositiveIntParameter(String method, String key, int defaultValue); @Deprecated boolean getMethodBooleanParameter(String method, String key); @Deprecated boolean getMethodBooleanParameter(String method, String key, boolean defaultValue); static String encode(String value); static String decode(String value); @Override int hashCode(); @Override boolean equals(Object obj); }
URL implements Serializable { public static URL valueOf(String url) { if (url == null || (url = url.trim()).length() == 0) { throw new IllegalArgumentException("url == null"); } String protocol = null; String username = null; String password = null; String host = null; int port = 0; String path = null; Map<String, String> parameters = null; int i = url.indexOf("?"); if (i >= 0) { String[] parts = url.substring(i + 1).split("\\&"); parameters = new HashMap<String, String>(); for (String part : parts) { part = part.trim(); if (part.length() > 0) { int j = part.indexOf('='); if (j >= 0) { parameters.put(part.substring(0, j), part.substring(j + 1)); } else { parameters.put(part, part); } } } url = url.substring(0, i); } i = url.indexOf(": if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 3); } else { i = url.indexOf(":/"); if (i >= 0) { if (i == 0) throw new IllegalStateException("url missing protocol: \"" + url + "\""); protocol = url.substring(0, i); url = url.substring(i + 1); } } i = url.indexOf("/"); if (i >= 0) { path = url.substring(i + 1); url = url.substring(0, i); } i = url.indexOf("@"); if (i >= 0) { username = url.substring(0, i); int j = username.indexOf(":"); if (j >= 0) { password = username.substring(j + 1); username = username.substring(0, j); } url = url.substring(i + 1); } i = url.indexOf(":"); if (i >= 0 && i < url.length() - 1) { port = Integer.parseInt(url.substring(i + 1)); url = url.substring(0, i); } if (url.length() > 0) host = url; return new URL(protocol, username, password, host, port, path, parameters); } protected URL(); URL(String protocol, String host, int port); URL(String protocol, String host, int port, String[] pairs); URL(String protocol, String host, int port, Map<String, String> parameters); URL(String protocol, String host, int port, String path); URL(String protocol, String host, int port, String path, String... pairs); URL(String protocol, String host, int port, String path, Map<String, String> parameters); URL(String protocol, String username, String password, String host, int port, String path); URL(String protocol, String username, String password, String host, int port, String path, String... pairs); URL(String protocol, String username, String password, String host, int port, String path, Map<String, String> parameters); static URL valueOf(String url); String getProtocol(); String getUsername(); String getPassword(); String getAuthority(); String getHost(); String getIp(); int getPort(); int getPort(int defaultPort); String getAddress(); String getBackupAddress(); String getBackupAddress(int defaultPort); List<URL> getBackupUrls(); String getPath(); String getAbsolutePath(); URL setProtocol(String protocol); URL setUsername(String username); URL setPassword(String password); URL setAddress(String address); URL setHost(String host); URL setPort(int port); URL setPath(String path); Map<String, String> getParameters(); String getParameterAndDecoded(String key); String getParameterAndDecoded(String key, String defaultValue); String getParameter(String key); String getParameter(String key, String defaultValue); String[] getParameter(String key, String[] defaultValue); URL getUrlParameter(String key); double getParameter(String key, double defaultValue); float getParameter(String key, float defaultValue); long getParameter(String key, long defaultValue); int getParameter(String key, int defaultValue); short getParameter(String key, short defaultValue); byte getParameter(String key, byte defaultValue); float getPositiveParameter(String key, float defaultValue); double getPositiveParameter(String key, double defaultValue); long getPositiveParameter(String key, long defaultValue); int getPositiveParameter(String key, int defaultValue); short getPositiveParameter(String key, short defaultValue); byte getPositiveParameter(String key, byte defaultValue); char getParameter(String key, char defaultValue); boolean getParameter(String key, boolean defaultValue); boolean hasParameter(String key); String getMethodParameterAndDecoded(String method, String key); String getMethodParameterAndDecoded(String method, String key, String defaultValue); String getMethodParameter(String method, String key); String getMethodParameter(String method, String key, String defaultValue); double getMethodParameter(String method, String key, double defaultValue); float getMethodParameter(String method, String key, float defaultValue); long getMethodParameter(String method, String key, long defaultValue); int getMethodParameter(String method, String key, int defaultValue); short getMethodParameter(String method, String key, short defaultValue); byte getMethodParameter(String method, String key, byte defaultValue); double getMethodPositiveParameter(String method, String key, double defaultValue); float getMethodPositiveParameter(String method, String key, float defaultValue); long getMethodPositiveParameter(String method, String key, long defaultValue); int getMethodPositiveParameter(String method, String key, int defaultValue); short getMethodPositiveParameter(String method, String key, short defaultValue); byte getMethodPositiveParameter(String method, String key, byte defaultValue); char getMethodParameter(String method, String key, char defaultValue); boolean getMethodParameter(String method, String key, boolean defaultValue); boolean hasMethodParameter(String method, String key); boolean isLocalHost(); boolean isAnyHost(); URL addParameterAndEncoded(String key, String value); URL addParameter(String key, boolean value); URL addParameter(String key, char value); URL addParameter(String key, byte value); URL addParameter(String key, short value); URL addParameter(String key, int value); URL addParameter(String key, long value); URL addParameter(String key, float value); URL addParameter(String key, double value); URL addParameter(String key, Enum<?> value); URL addParameter(String key, Number value); URL addParameter(String key, CharSequence value); URL addParameter(String key, String value); URL addParameterIfAbsent(String key, String value); URL addParameters(Map<String, String> parameters); URL addParametersIfAbsent(Map<String, String> parameters); URL addParameters(String... pairs); URL addParameterString(String query); URL removeParameter(String key); URL removeParameters(Collection<String> keys); URL removeParameters(String... keys); URL clearParameters(); String getRawParameter(String key); Map<String, String> toMap(); String toString(); String toString(String... parameters); String toIdentityString(); String toIdentityString(String... parameters); String toFullString(); String toFullString(String... parameters); String toParameterString(); String toParameterString(String... parameters); java.net.URL toJavaURL(); InetSocketAddress toInetSocketAddress(); String getServiceKey(); String toServiceString(); @Deprecated String getServiceName(); String getServiceInterface(); URL setServiceInterface(String service); @Deprecated int getIntParameter(String key); @Deprecated int getIntParameter(String key, int defaultValue); @Deprecated int getPositiveIntParameter(String key, int defaultValue); @Deprecated boolean getBooleanParameter(String key); @Deprecated boolean getBooleanParameter(String key, boolean defaultValue); @Deprecated int getMethodIntParameter(String method, String key); @Deprecated int getMethodIntParameter(String method, String key, int defaultValue); @Deprecated int getMethodPositiveIntParameter(String method, String key, int defaultValue); @Deprecated boolean getMethodBooleanParameter(String method, String key); @Deprecated boolean getMethodBooleanParameter(String method, String key, boolean defaultValue); static String encode(String value); static String decode(String value); @Override int hashCode(); @Override boolean equals(Object obj); }
@Test public void testMergeValues() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default.cunstom", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("dubbo", "json", "aaa", "bbb", "default.cunstom"), merged); }
public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testMergeValues_addDefault() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "aaa,bbb,default,zzz", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("aaa", "bbb", "dubbo", "json", "zzz"), merged); }
public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testMergeValuesDeleteDefault() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-default", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray(), merged); }
public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testMergeValuesDeleteDefault_2() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-default,aaa", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("aaa"), merged); }
public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testMergeValuesDelete() { List<String> merged = ConfigUtils.mergeValues(Serialization.class, "-dubbo,aaa", toArray("dubbo", "default.hessian2", "json")); Assert.assertEquals(toArray("json", "aaa"), merged); }
public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static List<String> mergeValues(Class<?> type, String cfg, List<String> def) { List<String> defaults = new ArrayList<String>(); if (def != null) { for (String name : def) { if (ExtensionLoader.getExtensionLoader(type).hasExtension(name)) { defaults.add(name); } } } List<String> names = new ArrayList<String>(); String[] configs = (cfg == null || cfg.trim().length() == 0) ? new String[0] : Constants.COMMA_SPLIT_PATTERN.split(cfg); for (String config : configs) { if (config != null && config.trim().length() > 0) { names.add(config); } } if (!names.contains(Constants.REMOVE_VALUE_PREFIX + Constants.DEFAULT_KEY)) { int i = names.indexOf(Constants.DEFAULT_KEY); if (i > 0) { names.addAll(i, defaults); } else { names.addAll(0, defaults); } names.remove(Constants.DEFAULT_KEY); } else { names.remove(Constants.DEFAULT_KEY); } for (String name : new ArrayList<String>(names)) { if (name.startsWith(Constants.REMOVE_VALUE_PREFIX)) { names.remove(name); names.remove(name.substring(1)); } } return names; } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_loadProperties_noFile() throws Exception { Properties p = ConfigUtils.loadProperties("notExisted", true); Properties expected = new Properties(); Assert.assertEquals(expected, p); p = ConfigUtils.loadProperties("notExisted", false); Assert.assertEquals(expected, p); }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void testSelect_Invokersize0() throws Exception { { Invoker invoker = cluster.select(null, null, null, null); Assert.assertEquals(null, invoker); } { invokers.clear(); selectedInvokers.clear(); Invoker invoker = cluster.select(null, null, invokers, null); Assert.assertEquals(null, invoker); } }
protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test public void test_loadProperties_oneFile() throws Exception { Properties p = ConfigUtils.loadProperties("properties.load", false); Properties expected = new Properties(); expected.put("a", "12"); expected.put("b", "34"); expected.put("c", "56"); Assert.assertEquals(expected, p); }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_loadProperties_oneFile_allowMulti() throws Exception { Properties p = ConfigUtils.loadProperties("properties.load", true); Properties expected = new Properties(); expected.put("a", "12"); expected.put("b", "34"); expected.put("c", "56"); Assert.assertEquals(expected, p); }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_loadProperties_oneFile_notRootPath() throws Exception { Properties p = ConfigUtils.loadProperties("META-INF/dubbo/internal/com.alibaba.dubbo.common.threadpool.ThreadPool", false); Properties expected = new Properties(); expected.put("fixed", "com.alibaba.dubbo.common.threadpool.support.fixed.FixedThreadPool"); expected.put("cached", "com.alibaba.dubbo.common.threadpool.support.cached.CachedThreadPool"); expected.put("limited", "com.alibaba.dubbo.common.threadpool.support.limited.LimitedThreadPool"); Assert.assertEquals(expected, p); }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Ignore("see http: @Test public void test_loadProperties_multiFile_notRootPath_Exception() throws Exception { try { ConfigUtils.loadProperties("META-INF/services/com.alibaba.dubbo.common.status.StatusChecker", false); Assert.fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString("only 1 META-INF/services/com.alibaba.dubbo.common.status.StatusChecker file is expected, but 2 dubbo.properties files found on class path:")); } }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_loadProperties_multiFile_notRootPath() throws Exception { Properties p = ConfigUtils.loadProperties("META-INF/dubbo/internal/com.alibaba.dubbo.common.status.StatusChecker", true); Properties expected = new Properties(); expected.put("memory", "com.alibaba.dubbo.common.status.support.MemoryStatusChecker"); expected.put("load", "com.alibaba.dubbo.common.status.support.LoadStatusChecker"); expected.put("aa", "12"); Assert.assertEquals(expected, p); }
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
ConfigUtils { public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); } private ConfigUtils(); static boolean isNotEmpty(String value); static boolean isEmpty(String value); static boolean isDefault(String value); static List<String> mergeValues(Class<?> type, String cfg, List<String> def); static String replaceProperty(String expression, Map<String, String> params); static Properties getProperties(); static void addProperties(Properties properties); static void setProperties(Properties properties); static String getProperty(String key); @SuppressWarnings({"unchecked", "rawtypes"}) static String getProperty(String key, String defaultValue); static Properties loadProperties(String fileName); static Properties loadProperties(String fileName, boolean allowMultiFile); static Properties loadProperties(String fileName, boolean allowMultiFile, boolean optional); static int getPid(); }
@Test public void test_realize_LongPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setLong", long.class); assertNotNull(method); Object value = PojoUtils.realize("563439743927993", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); }
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
@Test public void test_realize_IntPararmter_IllegalArgumentException() throws Exception { Method method = PojoUtilsTest.class.getMethod("setInt", int.class); assertNotNull(method); Object value = PojoUtils.realize("123", method.getParameterTypes()[0], method.getGenericParameterTypes()[0]); method.invoke(new PojoUtilsTest(), value); }
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
@Test public void testRealize() throws Exception { Map<String, String> inputMap = new LinkedHashMap<String, String>(); inputMap.put("key", "value"); Object obj = PojoUtils.generalize(inputMap); Assert.assertTrue(obj instanceof LinkedHashMap); Object outputObject = PojoUtils.realize(inputMap, LinkedHashMap.class); System.out.println(outputObject.getClass().getName()); Assert.assertTrue(outputObject instanceof LinkedHashMap); }
public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
PojoUtils { public static Object[] realize(Object[] objs, Class<?>[] types) { if (objs.length != types.length) throw new IllegalArgumentException("args.length != types.length"); Object[] dests = new Object[objs.length]; for (int i = 0; i < objs.length; i++) { dests[i] = realize(objs[i], types[i]); } return dests; } static Object[] generalize(Object[] objs); static Object[] realize(Object[] objs, Class<?>[] types); static Object[] realize(Object[] objs, Class<?>[] types, Type[] gtypes); static Object generalize(Object pojo); static Object realize(Object pojo, Class<?> type); static Object realize(Object pojo, Class<?> type, Type genericType); static boolean isPojo(Class<?> cls); }
@SuppressWarnings("unchecked") @Test public void testCompatibleTypeConvert() throws Exception { Object result; { Object input = new Object(); result = CompatibleTypeUtils.compatibleTypeConvert(input, Date.class); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(input, null); assertSame(input, result); result = CompatibleTypeUtils.compatibleTypeConvert(null, Date.class); assertNull(result); } { result = CompatibleTypeUtils.compatibleTypeConvert("a", char.class); assertEquals(Character.valueOf('a'), (Character) result); result = CompatibleTypeUtils.compatibleTypeConvert("A", MyEnum.class); assertEquals(MyEnum.A, (MyEnum) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigInteger.class); assertEquals(new BigInteger("3"), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert("3", BigDecimal.class); assertEquals(new BigDecimal("3"), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert("2011-12-11 12:24:12", Date.class); assertEquals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2011-12-11 12:24:12"), (Date) result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3, byte.class); assertEquals(Byte.valueOf((byte) 3), (Byte) result); result = CompatibleTypeUtils.compatibleTypeConvert((byte) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, short.class); assertEquals(Short.valueOf((short) 3), (Short) result); result = CompatibleTypeUtils.compatibleTypeConvert((short) 3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3, long.class); assertEquals(Long.valueOf(3), (Long) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, int.class); assertEquals(Integer.valueOf(3), (Integer) result); result = CompatibleTypeUtils.compatibleTypeConvert(3L, BigInteger.class); assertEquals(BigInteger.valueOf(3L), (BigInteger) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigInteger.valueOf(3L), int.class); assertEquals(Integer.valueOf(3), (Integer) result); } { result = CompatibleTypeUtils.compatibleTypeConvert(3D, float.class); assertEquals(Float.valueOf(3), (Float) result); result = CompatibleTypeUtils.compatibleTypeConvert(3F, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, double.class); assertEquals(Double.valueOf(3), (Double) result); result = CompatibleTypeUtils.compatibleTypeConvert(3D, BigDecimal.class); assertEquals(BigDecimal.valueOf(3D), (BigDecimal) result); result = CompatibleTypeUtils.compatibleTypeConvert(BigDecimal.valueOf(3D), double.class); assertEquals(Double.valueOf(3), (Double) result); } { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); Set<String> set = new HashSet<String>(); set.add("a"); set.add("b"); String[] array = new String[]{"a", "b"}; result = CompatibleTypeUtils.compatibleTypeConvert(array, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, List.class); assertEquals(ArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, CopyOnWriteArrayList.class); assertEquals(CopyOnWriteArrayList.class, result.getClass()); assertEquals(2, ((List<String>) result).size()); assertTrue(((List<String>) result).contains("a")); assertTrue(((List<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(set, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a") || ((String[]) result)[0].equals("b")); assertTrue(((String[]) result)[1].equals("a") || ((String[]) result)[1].equals("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, Set.class); assertEquals(HashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(array, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, ConcurrentHashSet.class); assertEquals(ConcurrentHashSet.class, result.getClass()); assertEquals(2, ((Set<String>) result).size()); assertTrue(((Set<String>) result).contains("a")); assertTrue(((Set<String>) result).contains("b")); result = CompatibleTypeUtils.compatibleTypeConvert(list, String[].class); assertEquals(String[].class, result.getClass()); assertEquals(2, ((String[]) result).length); assertTrue(((String[]) result)[0].equals("a")); assertTrue(((String[]) result)[1].equals("b")); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; }
CompatibleTypeUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } }
CompatibleTypeUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } private CompatibleTypeUtils(); }
CompatibleTypeUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } private CompatibleTypeUtils(); @SuppressWarnings({"unchecked", "rawtypes"}) static Object compatibleTypeConvert(Object value, Class<?> type); }
CompatibleTypeUtils { @SuppressWarnings({"unchecked", "rawtypes"}) public static Object compatibleTypeConvert(Object value, Class<?> type) { if (value == null || type == null || type.isAssignableFrom(value.getClass())) { return value; } if (value instanceof String) { String string = (String) value; if (char.class.equals(type) || Character.class.equals(type)) { if (string.length() != 1) { throw new IllegalArgumentException(String.format("CAN NOT convert String(%s) to char!" + " when convert String to char, the String MUST only 1 char.", string)); } return string.charAt(0); } else if (type.isEnum()) { return Enum.valueOf((Class<Enum>) type, string); } else if (type == BigInteger.class) { return new BigInteger(string); } else if (type == BigDecimal.class) { return new BigDecimal(string); } else if (type == Short.class || type == short.class) { return new Short(string); } else if (type == Integer.class || type == int.class) { return new Integer(string); } else if (type == Long.class || type == long.class) { return new Long(string); } else if (type == Double.class || type == double.class) { return new Double(string); } else if (type == Float.class || type == float.class) { return new Float(string); } else if (type == Byte.class || type == byte.class) { return new Byte(string); } else if (type == Boolean.class || type == boolean.class) { return new Boolean(string); } else if (type == Date.class) { try { return new SimpleDateFormat(DATE_FORMAT).parse((String) value); } catch (ParseException e) { throw new IllegalStateException("Failed to parse date " + value + " by format " + DATE_FORMAT + ", cause: " + e.getMessage(), e); } } else if (type == Class.class) { try { return ReflectUtils.name2class((String) value); } catch (ClassNotFoundException e) { throw new RuntimeException(e.getMessage(), e); } } } else if (value instanceof Number) { Number number = (Number) value; if (type == byte.class || type == Byte.class) { return number.byteValue(); } else if (type == short.class || type == Short.class) { return number.shortValue(); } else if (type == int.class || type == Integer.class) { return number.intValue(); } else if (type == long.class || type == Long.class) { return number.longValue(); } else if (type == float.class || type == Float.class) { return number.floatValue(); } else if (type == double.class || type == Double.class) { return number.doubleValue(); } else if (type == BigInteger.class) { return BigInteger.valueOf(number.longValue()); } else if (type == BigDecimal.class) { return BigDecimal.valueOf(number.doubleValue()); } else if (type == Date.class) { return new Date(number.longValue()); } } else if (value instanceof Collection) { Collection collection = (Collection) value; if (type.isArray()) { int length = collection.size(); Object array = Array.newInstance(type.getComponentType(), length); int i = 0; for (Object item : collection) { Array.set(array, i++, item); } return array; } else if (!type.isInterface()) { try { Collection result = (Collection) type.newInstance(); result.addAll(collection); return result; } catch (Throwable e) { } } else if (type == List.class) { return new ArrayList<Object>(collection); } else if (type == Set.class) { return new HashSet<Object>(collection); } } else if (value.getClass().isArray() && Collection.class.isAssignableFrom(type)) { Collection collection; if (!type.isInterface()) { try { collection = (Collection) type.newInstance(); } catch (Throwable e) { collection = new ArrayList<Object>(); } } else if (type == Set.class) { collection = new HashSet<Object>(); } else { collection = new ArrayList<Object>(); } int length = Array.getLength(value); for (int i = 0; i < length; i++) { collection.add(Array.get(value, i)); } return collection; } return value; } private CompatibleTypeUtils(); @SuppressWarnings({"unchecked", "rawtypes"}) static Object compatibleTypeConvert(Object value, Class<?> type); }
@Test public void test_findMethodByMethodSignature_override_Morethan1() throws Exception { try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "overrideMethod", null); fail(); } catch (IllegalStateException expected) { assertThat(expected.getMessage(), containsString( "Not unique method for method name(")); } }
public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; static final Class<?>[] EMPTY_CLASS_ARRAY; static final String JAVA_IDENT_REGEX; static final String JAVA_NAME_REGEX; static final String CLASS_DESC; static final String ARRAY_DESC; static final String DESC_REGEX; static final Pattern DESC_PATTERN; static final String METHOD_DESC_REGEX; static final Pattern METHOD_DESC_PATTERN; static final Pattern GETTER_METHOD_DESC_PATTERN; static final Pattern SETTER_METHOD_DESC_PATTERN; static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN; }
@Test public void testSelect_Invokersize1() throws Exception { invokers.clear(); invokers.add(invoker1); Invoker invoker = cluster.select(null, null, invokers, null); Assert.assertEquals(invoker1, invoker); }
protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test public void test_findMethodByMethodSignature_notFound() throws Exception { try { ReflectUtils.findMethodByMethodSignature(TestedClass.class, "notExsited", null); fail(); } catch (NoSuchMethodException expected) { assertThat(expected.getMessage(), containsString("No such method ")); assertThat(expected.getMessage(), containsString("in class")); } }
public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); }
ReflectUtils { public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes) throws NoSuchMethodException, ClassNotFoundException { String signature = methodName; if (parameterTypes != null && parameterTypes.length > 0) { signature = methodName + StringUtils.join(parameterTypes); } Method method = Signature_METHODS_CACHE.get(signature); if (method != null) { return method; } if (parameterTypes == null) { List<Method> finded = new ArrayList<Method>(); for (Method m : clazz.getMethods()) { if (m.getName().equals(methodName)) { finded.add(m); } } if (finded.isEmpty()) { throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz); } if (finded.size() > 1) { String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.", methodName, clazz.getName(), finded.size()); throw new IllegalStateException(msg); } method = finded.get(0); } else { Class<?>[] types = new Class<?>[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { types[i] = ReflectUtils.name2class(parameterTypes[i]); } method = clazz.getMethod(methodName, types); } Signature_METHODS_CACHE.put(signature, method); return method; } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; static final Class<?>[] EMPTY_CLASS_ARRAY; static final String JAVA_IDENT_REGEX; static final String JAVA_NAME_REGEX; static final String CLASS_DESC; static final String ARRAY_DESC; static final String DESC_REGEX; static final Pattern DESC_PATTERN; static final String METHOD_DESC_REGEX; static final Pattern METHOD_DESC_PATTERN; static final Pattern GETTER_METHOD_DESC_PATTERN; static final Pattern SETTER_METHOD_DESC_PATTERN; static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN; }
@Test public void test_getEmptyObject() throws Exception { assertTrue(ReflectUtils.getEmptyObject(Collection.class) instanceof Collection); assertTrue(ReflectUtils.getEmptyObject(List.class) instanceof List); assertTrue(ReflectUtils.getEmptyObject(Set.class) instanceof Set); assertTrue(ReflectUtils.getEmptyObject(Map.class) instanceof Map); assertTrue(ReflectUtils.getEmptyObject(Object[].class) instanceof Object[]); assertEquals(ReflectUtils.getEmptyObject(String.class), ""); assertEquals(ReflectUtils.getEmptyObject(short.class), Short.valueOf((short) 0)); assertEquals(ReflectUtils.getEmptyObject(byte.class), Byte.valueOf((byte) 0)); assertEquals(ReflectUtils.getEmptyObject(int.class), Integer.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(long.class), Long.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(float.class), Float.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(double.class), Double.valueOf(0)); assertEquals(ReflectUtils.getEmptyObject(char.class), Character.valueOf('\0')); assertEquals(ReflectUtils.getEmptyObject(boolean.class), Boolean.FALSE); EmptyClass object = (EmptyClass) ReflectUtils.getEmptyObject(EmptyClass.class); assertNotNull(object); assertNotNull(object.getProperty()); }
public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); }
ReflectUtils { public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); } }
ReflectUtils { public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); } private ReflectUtils(); }
ReflectUtils { public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); }
ReflectUtils { public static Object getEmptyObject(Class<?> returnType) { return getEmptyObject(returnType, new HashMap<Class<?>, Object>(), 0); } private ReflectUtils(); static boolean isPrimitives(Class<?> cls); static boolean isPrimitive(Class<?> cls); static Class<?> getBoxedClass(Class<?> c); static boolean isCompatible(Class<?> c, Object o); static boolean isCompatible(Class<?>[] cs, Object[] os); static String getCodeBase(Class<?> cls); static String getName(Class<?> c); static Class<?> getGenericClass(Class<?> cls); static Class<?> getGenericClass(Class<?> cls, int i); static String getName(final Method m); static String getSignature(String methodName, Class<?>[] parameterTypes); static String getName(final Constructor<?> c); static String getDesc(Class<?> c); static String getDesc(final Class<?>[] cs); static String getDesc(final Method m); static String getDesc(final Constructor<?> c); static String getDescWithoutMethodName(Method m); static String getDesc(final CtClass c); static String getDesc(final CtMethod m); static String getDesc(final CtConstructor c); static String getDescWithoutMethodName(final CtMethod m); static String name2desc(String name); static String desc2name(String desc); static Class<?> forName(String name); static Class<?> name2class(String name); static Class<?> desc2class(String desc); static Class<?>[] desc2classArray(String desc); static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes); static Method findMethodByMethodName(Class<?> clazz, String methodName); static Constructor<?> findConstructor(Class<?> clazz, Class<?> paramType); static boolean isInstance(Object obj, String interfaceClazzName); static Object getEmptyObject(Class<?> returnType); static boolean isBeanPropertyReadMethod(Method method); static String getPropertyNameFromBeanReadMethod(Method method); static boolean isBeanPropertyWriteMethod(Method method); static String getPropertyNameFromBeanWriteMethod(Method method); static boolean isPublicInstanceField(Field field); static final char JVM_VOID; static final char JVM_BOOLEAN; static final char JVM_BYTE; static final char JVM_CHAR; static final char JVM_DOUBLE; static final char JVM_FLOAT; static final char JVM_INT; static final char JVM_LONG; static final char JVM_SHORT; static final Class<?>[] EMPTY_CLASS_ARRAY; static final String JAVA_IDENT_REGEX; static final String JAVA_NAME_REGEX; static final String CLASS_DESC; static final String ARRAY_DESC; static final String DESC_REGEX; static final Pattern DESC_PATTERN; static final String METHOD_DESC_REGEX; static final Pattern METHOD_DESC_PATTERN; static final Pattern GETTER_METHOD_DESC_PATTERN; static final Pattern SETTER_METHOD_DESC_PATTERN; static final Pattern IS_HAS_CAN_METHOD_DESC_PATTERN; }
@Test public void testSelect_Invokersize2AndselectNotNull() throws Exception { invokers.clear(); invokers.add(invoker1); invokers.add(invoker2); { selectedInvokers.clear(); selectedInvokers.add(invoker1); Invoker invoker = cluster.select(null, null, invokers, selectedInvokers); Assert.assertEquals(invoker2, invoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker2); Invoker invoker = cluster.select(null, null, invokers, selectedInvokers); Assert.assertEquals(invoker1, invoker); } }
protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test public void testRevertForbid() { String service = "dubbo.test.api.HelloService"; List<String> forbid = new ArrayList<String>(); forbid.add(service); Set<URL> subscribed = new HashSet<URL>(); subscribed.add(URL.valueOf("dubbo: List<String> newForbid = UrlUtils.revertForbid(forbid, subscribed); List<String> expectForbid = new ArrayList<String>(); expectForbid.add("perf/" + service + ":1.0.0"); assertEquals(expectForbid, newForbid); }
public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testDonotSelectAgainAndNoCheckAvailable() { LoadBalance lb = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension(RoundRobinLoadBalance.NAME); initlistsize5(); { selectedInvokers.clear(); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker1, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker2, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker3, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertSame(invoker5, sinvoker); } { selectedInvokers.clear(); selectedInvokers.add(invoker1); selectedInvokers.add(invoker2); selectedInvokers.add(invoker3); selectedInvokers.add(invoker4); selectedInvokers.add(invoker5); Invoker sinvoker = cluster_nocheck.select(lb, invocation, invokers, selectedInvokers); Assert.assertTrue(invokers.contains(sinvoker)); } }
protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
AbstractClusterInvoker implements Invoker<T> { protected Invoker<T> select(LoadBalance loadbalance, Invocation invocation, List<Invoker<T>> invokers, List<Invoker<T>> selected) throws RpcException { if (invokers == null || invokers.size() == 0) return null; String methodName = invocation == null ? "" : invocation.getMethodName(); boolean sticky = invokers.get(0).getUrl().getMethodParameter(methodName, Constants.CLUSTER_STICKY_KEY, Constants.DEFAULT_CLUSTER_STICKY); { if (stickyInvoker != null && !invokers.contains(stickyInvoker)) { stickyInvoker = null; } if (sticky && stickyInvoker != null && (selected == null || !selected.contains(stickyInvoker))) { if (availablecheck && stickyInvoker.isAvailable()) { return stickyInvoker; } } } Invoker<T> invoker = doselect(loadbalance, invocation, invokers, selected); if (sticky) { stickyInvoker = invoker; } return invoker; } AbstractClusterInvoker(Directory<T> directory); AbstractClusterInvoker(Directory<T> directory, URL url); Class<T> getInterface(); URL getUrl(); boolean isAvailable(); void destroy(); Result invoke(final Invocation invocation); @Override String toString(); }
@Test public void testRevertForbid2() { List<String> newForbid = UrlUtils.revertForbid(null, null); assertNull(newForbid); }
public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testRevertForbid3() { String service1 = "dubbo.test.api.HelloService:1.0.0"; String service2 = "dubbo.test.api.HelloService:2.0.0"; List<String> forbid = new ArrayList<String>(); forbid.add(service1); forbid.add(service2); List<String> newForbid = UrlUtils.revertForbid(forbid, null); assertEquals(forbid, newForbid); }
public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static List<String> revertForbid(List<String> forbid, Set<URL> subscribed) { if (forbid != null && forbid.size() > 0) { List<String> newForbid = new ArrayList<String>(); for (String serviceName : forbid) { if (!serviceName.contains(":") && !serviceName.contains("/")) { for (URL url : subscribed) { if (serviceName.equals(url.getServiceInterface())) { newForbid.add(url.getServiceKey()); break; } } } else { newForbid.add(serviceName); } } return newForbid; } return forbid; } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testIsMatch() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertTrue(UrlUtils.isMatch(consumerUrl, providerUrl)); }
public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testIsMatch2() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl)); }
public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
@Test public void testIsMatch3() { URL consumerUrl = URL.valueOf("dubbo: URL providerUrl = URL.valueOf("http: assertFalse(UrlUtils.isMatch(consumerUrl, providerUrl)); }
public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }
UrlUtils { public static boolean isMatch(URL consumerUrl, URL providerUrl) { String consumerInterface = consumerUrl.getServiceInterface(); String providerInterface = providerUrl.getServiceInterface(); if (!(Constants.ANY_VALUE.equals(consumerInterface) || StringUtils.isEquals(consumerInterface, providerInterface))) return false; if (!isMatchCategory(providerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY), consumerUrl.getParameter(Constants.CATEGORY_KEY, Constants.DEFAULT_CATEGORY))) { return false; } if (!providerUrl.getParameter(Constants.ENABLED_KEY, true) && !Constants.ANY_VALUE.equals(consumerUrl.getParameter(Constants.ENABLED_KEY))) { return false; } String consumerGroup = consumerUrl.getParameter(Constants.GROUP_KEY); String consumerVersion = consumerUrl.getParameter(Constants.VERSION_KEY); String consumerClassifier = consumerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); String providerGroup = providerUrl.getParameter(Constants.GROUP_KEY); String providerVersion = providerUrl.getParameter(Constants.VERSION_KEY); String providerClassifier = providerUrl.getParameter(Constants.CLASSIFIER_KEY, Constants.ANY_VALUE); return (Constants.ANY_VALUE.equals(consumerGroup) || StringUtils.isEquals(consumerGroup, providerGroup) || StringUtils.isContains(consumerGroup, providerGroup)) && (Constants.ANY_VALUE.equals(consumerVersion) || StringUtils.isEquals(consumerVersion, providerVersion)) && (consumerClassifier == null || Constants.ANY_VALUE.equals(consumerClassifier) || StringUtils.isEquals(consumerClassifier, providerClassifier)); } static URL parseURL(String address, Map<String, String> defaults); static List<URL> parseURLs(String address, Map<String, String> defaults); static Map<String, Map<String, String>> convertRegister(Map<String, Map<String, String>> register); static Map<String, String> convertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertRegister(Map<String, Map<String, String>> register); static Map<String, String> revertSubscribe(Map<String, String> subscribe); static Map<String, Map<String, String>> revertNotify(Map<String, Map<String, String>> notify); static List<String> revertForbid(List<String> forbid, Set<URL> subscribed); static URL getEmptyUrl(String service, String category); static boolean isMatchCategory(String category, String categories); static boolean isMatch(URL consumerUrl, URL providerUrl); static boolean isMatchGlobPattern(String pattern, String value, URL param); static boolean isMatchGlobPattern(String pattern, String value); static boolean isServiceKeyMatch(URL pattern, URL value); }