The Unified and Autonomous Development Platform
Display "changes since last visit" link in request activities page
robin shine55a6c00d7869
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketRenderBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketRenderBehavior.javaindex 64a2cadc92..945cbe231a 100644--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketRenderBehavior.java+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketRenderBehavior.java@@ -1,276 +1,276 @@-package com.pmease.commons.wicket.websocket;--import java.io.IOException;-import java.lang.reflect.Field;-import java.util.ArrayList;-import java.util.Date;-import java.util.Iterator;-import java.util.List;-import java.util.Map;-import java.util.concurrent.ConcurrentHashMap;-import java.util.concurrent.ExecutorService;--import javax.annotation.Nullable;--import org.apache.wicket.Component;-import org.apache.wicket.protocol.ws.api.IWebSocketConnection;-import org.apache.wicket.protocol.ws.api.WebSocketBehavior;-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;-import org.apache.wicket.protocol.ws.api.message.ConnectedMessage;-import org.apache.wicket.protocol.ws.api.message.TextMessage;-import org.apache.wicket.protocol.ws.api.registry.PageIdKey;-import org.apache.wicket.protocol.ws.api.registry.SimpleWebSocketConnectionRegistry;-import org.apache.wicket.request.component.IRequestablePage;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.fasterxml.jackson.core.JsonProcessingException;-import com.fasterxml.jackson.databind.ObjectMapper;-import com.google.common.collect.MapMaker;-import com.pmease.commons.loader.AppLoader;-import com.pmease.commons.util.Pair;--@SuppressWarnings("serial")-public abstract class WebSocketRenderBehavior extends WebSocketBehavior {-- private static final Logger logger = LoggerFactory.getLogger(WebSocketRenderBehavior.class);-- private static final Map<IWebSocketConnection, ConnectionData> connections =- new MapMaker().concurrencyLevel(16).weakKeys().makeMap();-- private static final Map<Integer, Date> recentRenderedPages = new ConcurrentHashMap<>();-- private static final Map<RenderData, Date> recentSentMessages = new ConcurrentHashMap<>();-- private Component component;-- @Override- public void bind(Component component) {- super.bind(component);-- component.setOutputMarkupId(true);- this.component = component;- }-- public static void onPageRender(Integer pageId) {- recentRenderedPages.put(pageId, new Date());- }-- protected Component getComponent() {- return component;- }-- public static void removePagesBefore(Date date) {- for (Iterator<Map.Entry<Integer, Date>> it = recentRenderedPages.entrySet().iterator(); it.hasNext();) {- Map.Entry<Integer, Date> entry = it.next();- if (entry.getValue().before(date))- it.remove();- }- }-- public static void removeMessagesBefore(Date date) {- for (Iterator<Map.Entry<RenderData, Date>> it = recentSentMessages.entrySet().iterator(); it.hasNext();) {- Map.Entry<RenderData, Date> entry = it.next();- if (entry.getValue().before(date))- it.remove();- }- }-- @Override- protected void onConnect(ConnectedMessage message) {- super.onConnect(message);-- IWebSocketConnection connection = new SimpleWebSocketConnectionRegistry().getConnection(- message.getApplication(), message.getSessionId(), message.getKey());-- ConnectionData data = connections.get(connection);- if (data == null) {- List<WebSocketTrait> traits = new ArrayList<>();- traits.add(getTrait());- Integer pageId;- if (message.getKey() instanceof PageIdKey) {- try {- Field field = PageIdKey.class.getDeclaredField("pageId");- field.setAccessible(true);- pageId = (Integer) field.get(message.getKey());- } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {- throw new RuntimeException(e);- }- } else {- pageId = null;- }- data = new ConnectionData(pageId, traits);- } else {- data = data.addTrait(getTrait());- }- connections.put(connection, data);-- /*- * When a new websocket connection arrives, we re-send all sent websocket messages since- * rendering of its hosting page as otherwise the host page might be missing some- * important websocket messages. For instance, when a pull request is opened, a pull- * request integration preview is calculating in the background, and the request page- * will be rendered, and then a websocket connection is established after browser renders- * the page. If integration preview calculation finishes after rendering of the request- * detail page and before websocket establishing of request detail page, the integration- * preview area of the page will not be refreshed without below code as it will miss the- * websocket message sent upon completion of integration preview.- *- */- Integer connectionPageId = data.getPageId();- List<WebSocketTrait> connectionTraits = data.getTraits();- AppLoader.getInstance(ExecutorService.class).execute(new Runnable() {-- @Override- public void run() {-- if (connectionPageId != null) {- Date renderDate = recentRenderedPages.get(connectionPageId);- if (renderDate != null) {- for (Iterator<Map.Entry<RenderData, Date>> it = recentSentMessages.entrySet().iterator(); it.hasNext();) {- Map.Entry<RenderData, Date> entry = it.next();- Integer pageId = entry.getKey().getPageId();- WebSocketTrait trait = entry.getKey().getTrait();- if ((pageId == null || !pageId.equals(connectionPageId)) && entry.getValue().after(renderDate)) {- for (WebSocketTrait each: connectionTraits) {- if (trait.is(each)) {- try {- connection.sendMessage(asMessage(trait));- } catch (IOException e) {- throw new RuntimeException(e);- }- break;- }- }- }- }- }- }- }- });- }-- /**- * Return trait object of this behavior. When method {@link #requestToRender(Object, PageId)} gets- * called, its first parameter will be compared with this trait via <tt>equals</tt> method, and if- * equals, method {@link #onRender(WebSocketRequestHandler)} will be called to render this behavior.- *- * @return- * trait of this behavior- */- protected abstract WebSocketTrait getTrait();-- protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {- handler.add(component);- }-- @Override- protected void onMessage(WebSocketRequestHandler handler, TextMessage message) {- super.onMessage(handler, message);-- ObjectMapper mapper = AppLoader.getInstance(ObjectMapper.class);- WebSocketMessage webSocketMessage;- try {- webSocketMessage = mapper.readValue(message.getText(), WebSocketMessage.class);- } catch (IOException e) {- throw new RuntimeException(e);- }-- if (webSocketMessage.getType().equals(WebSocketMessage.RENDER_CALLBACK)- && ((WebSocketTrait)webSocketMessage.getPayload()).is(getTrait())) {- onRender(handler, (WebSocketTrait) webSocketMessage.getPayload());- }- }-- private static String asMessage(WebSocketTrait trait) {- try {- ObjectMapper mapper = AppLoader.getInstance(ObjectMapper.class);- WebSocketMessage webSocketMessage = new WebSocketMessage(WebSocketMessage.RENDER_CALLBACK, trait);- return mapper.writeValueAsString(webSocketMessage);- } catch (JsonProcessingException e) {- throw new RuntimeException(e);- }- }-- public static void requestToRender(WebSocketTrait trait) {- requestToRender(trait, null);- }-- public static void requestToRender(WebSocketTrait trait, @Nullable IRequestablePage page) {- try {- String message = asMessage(trait);-- for (Iterator<Map.Entry<IWebSocketConnection, ConnectionData>> it = connections.entrySet().iterator(); it.hasNext();) {- Map.Entry<IWebSocketConnection, ConnectionData> entry = it.next();- IWebSocketConnection connection = entry.getKey();- if (connection != null && connection.isOpen()) {- synchronized (connection) {- ConnectionData data = entry.getValue();- if ((page == null || !Integer.valueOf(page.getPageId()).equals(data.getPageId()))) {- for (WebSocketTrait each: data.getTraits()) {- if (trait.is(each)) {- try {- connection.sendMessage(message);- } catch (IOException e) {- throw new RuntimeException(e);- }- break;- }- }- }- }- } else {- it.remove();- }- }-- recentSentMessages.put(new RenderData(trait, page!=null?page.getPageId():null), new Date());- } catch (Exception e) {- logger.error("Error sending websocket message", e);- }- }-- private static class RenderData extends Pair<WebSocketTrait, Integer> {-- RenderData(WebSocketTrait trait, Integer pageId) {- super(trait, pageId);- }-- public WebSocketTrait getTrait() {- return getFirst();- }-- public Integer getPageId() {- return getSecond();- }-- }-- private static class ConnectionData {-- private final Integer pageId;-- private final List<WebSocketTrait> traits;-- ConnectionData(@Nullable Integer pageId, List<WebSocketTrait> traits) {- this.pageId = pageId;- this.traits = traits;- }-- @Nullable- public Integer getPageId() {- return pageId;- }-- public List<WebSocketTrait> getTraits() {- return traits;- }-- ConnectionData addTrait(final WebSocketTrait trait) {- List<WebSocketTrait> copyOfTraits = new ArrayList<>(getTraits());- copyOfTraits.add(trait);- return new ConnectionData(getPageId(), copyOfTraits);- }- }--}+package com.pmease.commons.wicket.websocket;++import java.io.IOException;+import java.lang.reflect.Field;+import java.util.ArrayList;+import java.util.Date;+import java.util.Iterator;+import java.util.List;+import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.ExecutorService;++import javax.annotation.Nullable;++import org.apache.wicket.Component;+import org.apache.wicket.protocol.ws.api.IWebSocketConnection;+import org.apache.wicket.protocol.ws.api.WebSocketBehavior;+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;+import org.apache.wicket.protocol.ws.api.message.ConnectedMessage;+import org.apache.wicket.protocol.ws.api.message.TextMessage;+import org.apache.wicket.protocol.ws.api.registry.PageIdKey;+import org.apache.wicket.protocol.ws.api.registry.SimpleWebSocketConnectionRegistry;+import org.apache.wicket.request.component.IRequestablePage;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.fasterxml.jackson.core.JsonProcessingException;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.google.common.collect.MapMaker;+import com.pmease.commons.loader.AppLoader;+import com.pmease.commons.util.Pair;++@SuppressWarnings("serial")+public abstract class WebSocketRenderBehavior extends WebSocketBehavior {++ private static final Logger logger = LoggerFactory.getLogger(WebSocketRenderBehavior.class);++ private static final Map<IWebSocketConnection, ConnectionData> connections =+ new MapMaker().concurrencyLevel(16).weakKeys().makeMap();++ private static final Map<Integer, Date> recentRenderedPages = new ConcurrentHashMap<>();++ private static final Map<RenderData, Date> recentSentMessages = new ConcurrentHashMap<>();++ private Component component;++ @Override+ public void bind(Component component) {+ super.bind(component);++ component.setOutputMarkupId(true);+ this.component = component;+ }++ public static void onPageRender(Integer pageId) {+ recentRenderedPages.put(pageId, new Date());+ }++ protected Component getComponent() {+ return component;+ }++ public static void removePagesBefore(Date date) {+ for (Iterator<Map.Entry<Integer, Date>> it = recentRenderedPages.entrySet().iterator(); it.hasNext();) {+ Map.Entry<Integer, Date> entry = it.next();+ if (entry.getValue().before(date))+ it.remove();+ }+ }++ public static void removeMessagesBefore(Date date) {+ for (Iterator<Map.Entry<RenderData, Date>> it = recentSentMessages.entrySet().iterator(); it.hasNext();) {+ Map.Entry<RenderData, Date> entry = it.next();+ if (entry.getValue().before(date))+ it.remove();+ }+ }++ @Override+ protected void onConnect(ConnectedMessage message) {+ super.onConnect(message);++ IWebSocketConnection connection = new SimpleWebSocketConnectionRegistry().getConnection(+ message.getApplication(), message.getSessionId(), message.getKey());++ ConnectionData data = connections.get(connection);+ if (data == null) {+ List<WebSocketTrait> traits = new ArrayList<>();+ traits.add(getTrait());+ Integer pageId;+ if (message.getKey() instanceof PageIdKey) {+ try {+ Field field = PageIdKey.class.getDeclaredField("pageId");+ field.setAccessible(true);+ pageId = (Integer) field.get(message.getKey());+ } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {+ throw new RuntimeException(e);+ }+ } else {+ pageId = null;+ }+ data = new ConnectionData(pageId, traits);+ } else {+ data = data.addTrait(getTrait());+ }+ connections.put(connection, data);++ /*+ * When a new websocket connection arrives, we re-send all sent websocket messages since+ * rendering of its hosting page as otherwise the host page might be missing some+ * important websocket messages. For instance, when a pull request is opened, a pull+ * request integration preview is calculating in the background, and the request page+ * will be rendered, and then a websocket connection is established after browser renders+ * the page. If integration preview calculation finishes after rendering of the request+ * detail page and before websocket establishing of request detail page, the integration+ * preview area of the page will not be refreshed without below code as it will miss the+ * websocket message sent upon completion of integration preview.+ *+ */+ Integer connectionPageId = data.getPageId();+ List<WebSocketTrait> connectionTraits = data.getTraits();+ AppLoader.getInstance(ExecutorService.class).execute(new Runnable() {++ @Override+ public void run() {++ if (connectionPageId != null) {+ Date renderDate = recentRenderedPages.get(connectionPageId);+ if (renderDate != null) {+ for (Iterator<Map.Entry<RenderData, Date>> it = recentSentMessages.entrySet().iterator(); it.hasNext();) {+ Map.Entry<RenderData, Date> entry = it.next();+ Integer pageId = entry.getKey().getPageId();+ WebSocketTrait trait = entry.getKey().getTrait();+ if ((pageId == null || !pageId.equals(connectionPageId)) && entry.getValue().getTime()>renderDate.getTime()) {+ for (WebSocketTrait each: connectionTraits) {+ if (trait.is(each)) {+ try {+ connection.sendMessage(asMessage(trait));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ break;+ }+ }+ }+ }+ }+ }+ }+ });+ }++ /**+ * Return trait object of this behavior. When method {@link #requestToRender(Object, PageId)} gets+ * called, its first parameter will be compared with this trait via <tt>equals</tt> method, and if+ * equals, method {@link #onRender(WebSocketRequestHandler)} will be called to render this behavior.+ *+ * @return+ * trait of this behavior+ */+ protected abstract WebSocketTrait getTrait();++ protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {+ handler.add(component);+ }++ @Override+ protected void onMessage(WebSocketRequestHandler handler, TextMessage message) {+ super.onMessage(handler, message);++ ObjectMapper mapper = AppLoader.getInstance(ObjectMapper.class);+ WebSocketMessage webSocketMessage;+ try {+ webSocketMessage = mapper.readValue(message.getText(), WebSocketMessage.class);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ if (webSocketMessage.getType().equals(WebSocketMessage.RENDER_CALLBACK)+ && ((WebSocketTrait)webSocketMessage.getPayload()).is(getTrait())) {+ onRender(handler, (WebSocketTrait) webSocketMessage.getPayload());+ }+ }++ private static String asMessage(WebSocketTrait trait) {+ try {+ ObjectMapper mapper = AppLoader.getInstance(ObjectMapper.class);+ WebSocketMessage webSocketMessage = new WebSocketMessage(WebSocketMessage.RENDER_CALLBACK, trait);+ return mapper.writeValueAsString(webSocketMessage);+ } catch (JsonProcessingException e) {+ throw new RuntimeException(e);+ }+ }++ public static void requestToRender(WebSocketTrait trait) {+ requestToRender(trait, null);+ }++ public static void requestToRender(WebSocketTrait trait, @Nullable IRequestablePage page) {+ try {+ String message = asMessage(trait);++ for (Iterator<Map.Entry<IWebSocketConnection, ConnectionData>> it = connections.entrySet().iterator(); it.hasNext();) {+ Map.Entry<IWebSocketConnection, ConnectionData> entry = it.next();+ IWebSocketConnection connection = entry.getKey();+ if (connection != null && connection.isOpen()) {+ synchronized (connection) {+ ConnectionData data = entry.getValue();+ if ((page == null || !Integer.valueOf(page.getPageId()).equals(data.getPageId()))) {+ for (WebSocketTrait each: data.getTraits()) {+ if (trait.is(each)) {+ try {+ connection.sendMessage(message);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ break;+ }+ }+ }+ }+ } else {+ it.remove();+ }+ }++ recentSentMessages.put(new RenderData(trait, page!=null?page.getPageId():null), new Date());+ } catch (Exception e) {+ logger.error("Error sending websocket message", e);+ }+ }++ private static class RenderData extends Pair<WebSocketTrait, Integer> {++ RenderData(WebSocketTrait trait, Integer pageId) {+ super(trait, pageId);+ }++ public WebSocketTrait getTrait() {+ return getFirst();+ }++ public Integer getPageId() {+ return getSecond();+ }++ }++ private static class ConnectionData {++ private final Integer pageId;++ private final List<WebSocketTrait> traits;++ ConnectionData(@Nullable Integer pageId, List<WebSocketTrait> traits) {+ this.pageId = pageId;+ this.traits = traits;+ }++ @Nullable+ public Integer getPageId() {+ return pageId;+ }++ public List<WebSocketTrait> getTraits() {+ return traits;+ }++ ConnectionData addTrait(final WebSocketTrait trait) {+ List<WebSocketTrait> copyOfTraits = new ArrayList<>(getTraits());+ copyOfTraits.add(trait);+ return new ConnectionData(getPageId(), copyOfTraits);+ }+ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.javaindex 289a1c5982..a4992f02cc 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/CodeComment.java@@ -1,236 +1,236 @@-package com.pmease.gitplex.core.entity;--import java.io.Serializable;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Date;-import java.util.UUID;--import javax.annotation.Nullable;-import javax.persistence.CascadeType;-import javax.persistence.Column;-import javax.persistence.Embedded;-import javax.persistence.Entity;-import javax.persistence.FetchType;-import javax.persistence.Index;-import javax.persistence.JoinColumn;-import javax.persistence.Lob;-import javax.persistence.ManyToOne;-import javax.persistence.OneToMany;-import javax.persistence.Table;-import javax.persistence.Version;--import org.hibernate.annotations.DynamicUpdate;--import com.pmease.commons.hibernate.AbstractEntity;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.support.CommentPos;-import com.pmease.gitplex.core.entity.support.CompareContext;-import com.pmease.gitplex.core.entity.support.LastEvent;-import com.pmease.gitplex.core.manager.VisitInfoManager;-import com.pmease.gitplex.core.security.SecurityUtils;--/*- * @DynamicUpdate annotation here along with various @OptimisticLock annotations- * on certain fields tell Hibernate not to perform version check on those fields- * which can be updated from background thread.- */-@Entity-@Table(indexes={@Index(columnList="uuid"), @Index(columnList="commit"),- @Index(columnList="path"), @Index(columnList="compareCommit")})-@DynamicUpdate-public class CodeComment extends AbstractEntity {-- private static final long serialVersionUID = 1L;-- @Version- private long version;-- @ManyToOne(fetch=FetchType.LAZY)- @JoinColumn(nullable=false)- private Depot depot;-- @ManyToOne(fetch=FetchType.LAZY)- private Account user;-- @Column(nullable=false)- private String title;-- @Lob- @Column(nullable=false, length=65535)- private String content;-- @Column(nullable=false)- private Date date = new Date();-- @Embedded- private LastEvent lastEvent;-- @Embedded- private CommentPos commentPos;-- @Embedded- private CompareContext compareContext;-- private boolean resolved;-- @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)- private Collection<CodeCommentReply> replies = new ArrayList<>();-- @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)- private Collection<CodeCommentRelation> relations = new ArrayList<>();-- @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)- private Collection<CodeCommentStatusChange> statusChanges= new ArrayList<>();-- @Column(nullable=false)- private String uuid = UUID.randomUUID().toString();-- public Depot getDepot() {- return depot;- }-- public void setDepot(Depot depot) {- this.depot = depot;- }-- @Nullable- public Account getUser() {- return user;- }-- public void setUser(@Nullable Account user) {- this.user = user;- }-- public long getVersion() {- return version;- }-- public String getTitle() {- return title;- }-- public void setTitle(String title) {- this.title = title;- }-- @Nullable- public String getContent() {- return content;- }-- public void setContent(String content) {- this.content = content;- }-- public Date getDate() {- return date;- }-- public void setDate(Date date) {- this.date = date;- }-- public CommentPos getCommentPos() {- return commentPos;- }-- public void setCommentPos(CommentPos commentPos) {- this.commentPos = commentPos;- }-- public CompareContext getCompareContext() {- return compareContext;- }-- public void setCompareContext(CompareContext compareContext) {- this.compareContext = compareContext;- }-- public Collection<CodeCommentReply> getReplies() {- return replies;- }-- public void setReplies(Collection<CodeCommentReply> replies) {- this.replies = replies;- }-- public Collection<CodeCommentRelation> getRelations() {- return relations;- }-- public void setRelations(Collection<CodeCommentRelation> relations) {- this.relations = relations;- }-- public Collection<CodeCommentStatusChange> getStatusChanges() {- return statusChanges;- }-- public void setStatusChanges(Collection<CodeCommentStatusChange> statusChanges) {- this.statusChanges = statusChanges;- }-- public String getUUID() {- return uuid;- }-- public void setUUID(String uuid) {- this.uuid = uuid;- }-- public boolean isResolved() {- return resolved;- }-- public void setResolved(boolean resolved) {- this.resolved = resolved;- }-- public LastEvent getLastEvent() {- return lastEvent;- }-- public void setLastEvent(LastEvent lastEvent) {- this.lastEvent = lastEvent;- }-- public boolean isVisitedAfter(Date date) {- Account user = SecurityUtils.getAccount();- if (user != null) {- Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);- return visitDate != null && visitDate.after(date);- } else {- return true;- }- }-- public ComparingInfo getComparingInfo() {- return new ComparingInfo(commentPos.getCommit(), compareContext);- }-- public static class ComparingInfo implements Serializable {-- private static final long serialVersionUID = 1L;-- private final String commit;-- private final CompareContext compareContext;-- public ComparingInfo(String commit, CompareContext compareContext) {- this.commit = commit;- this.compareContext = compareContext;- }-- public String getCommit() {- return commit;- }-- public CompareContext getCompareContext() {- return compareContext;- }-- }--}+package com.pmease.gitplex.core.entity;++import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Date;+import java.util.UUID;++import javax.annotation.Nullable;+import javax.persistence.CascadeType;+import javax.persistence.Column;+import javax.persistence.Embedded;+import javax.persistence.Entity;+import javax.persistence.FetchType;+import javax.persistence.Index;+import javax.persistence.JoinColumn;+import javax.persistence.Lob;+import javax.persistence.ManyToOne;+import javax.persistence.OneToMany;+import javax.persistence.Table;+import javax.persistence.Version;++import org.hibernate.annotations.DynamicUpdate;++import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.support.CommentPos;+import com.pmease.gitplex.core.entity.support.CompareContext;+import com.pmease.gitplex.core.entity.support.LastEvent;+import com.pmease.gitplex.core.manager.VisitInfoManager;+import com.pmease.gitplex.core.security.SecurityUtils;++/*+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations+ * on certain fields tell Hibernate not to perform version check on those fields+ * which can be updated from background thread.+ */+@Entity+@Table(indexes={@Index(columnList="uuid"), @Index(columnList="commit"),+ @Index(columnList="path"), @Index(columnList="compareCommit")})+@DynamicUpdate+public class CodeComment extends AbstractEntity {++ private static final long serialVersionUID = 1L;++ @Version+ private long version;++ @ManyToOne(fetch=FetchType.LAZY)+ @JoinColumn(nullable=false)+ private Depot depot;++ @ManyToOne(fetch=FetchType.LAZY)+ private Account user;++ @Column(nullable=false)+ private String title;++ @Lob+ @Column(nullable=false, length=65535)+ private String content;++ @Column(nullable=false)+ private Date date = new Date();++ @Embedded+ private LastEvent lastEvent;++ @Embedded+ private CommentPos commentPos;++ @Embedded+ private CompareContext compareContext;++ private boolean resolved;++ @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)+ private Collection<CodeCommentReply> replies = new ArrayList<>();++ @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)+ private Collection<CodeCommentRelation> relations = new ArrayList<>();++ @OneToMany(mappedBy="comment", cascade=CascadeType.REMOVE)+ private Collection<CodeCommentStatusChange> statusChanges= new ArrayList<>();++ @Column(nullable=false)+ private String uuid = UUID.randomUUID().toString();++ public Depot getDepot() {+ return depot;+ }++ public void setDepot(Depot depot) {+ this.depot = depot;+ }++ @Nullable+ public Account getUser() {+ return user;+ }++ public void setUser(@Nullable Account user) {+ this.user = user;+ }++ public long getVersion() {+ return version;+ }++ public String getTitle() {+ return title;+ }++ public void setTitle(String title) {+ this.title = title;+ }++ @Nullable+ public String getContent() {+ return content;+ }++ public void setContent(String content) {+ this.content = content;+ }++ public Date getDate() {+ return date;+ }++ public void setDate(Date date) {+ this.date = date;+ }++ public CommentPos getCommentPos() {+ return commentPos;+ }++ public void setCommentPos(CommentPos commentPos) {+ this.commentPos = commentPos;+ }++ public CompareContext getCompareContext() {+ return compareContext;+ }++ public void setCompareContext(CompareContext compareContext) {+ this.compareContext = compareContext;+ }++ public Collection<CodeCommentReply> getReplies() {+ return replies;+ }++ public void setReplies(Collection<CodeCommentReply> replies) {+ this.replies = replies;+ }++ public Collection<CodeCommentRelation> getRelations() {+ return relations;+ }++ public void setRelations(Collection<CodeCommentRelation> relations) {+ this.relations = relations;+ }++ public Collection<CodeCommentStatusChange> getStatusChanges() {+ return statusChanges;+ }++ public void setStatusChanges(Collection<CodeCommentStatusChange> statusChanges) {+ this.statusChanges = statusChanges;+ }++ public String getUUID() {+ return uuid;+ }++ public void setUUID(String uuid) {+ this.uuid = uuid;+ }++ public boolean isResolved() {+ return resolved;+ }++ public void setResolved(boolean resolved) {+ this.resolved = resolved;+ }++ public LastEvent getLastEvent() {+ return lastEvent;+ }++ public void setLastEvent(LastEvent lastEvent) {+ this.lastEvent = lastEvent;+ }++ public boolean isVisitedAfter(Date date) {+ Account user = SecurityUtils.getAccount();+ if (user != null) {+ Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);+ return visitDate != null && visitDate.getTime()>date.getTime();+ } else {+ return true;+ }+ }++ public ComparingInfo getComparingInfo() {+ return new ComparingInfo(commentPos.getCommit(), compareContext);+ }++ public static class ComparingInfo implements Serializable {++ private static final long serialVersionUID = 1L;++ private final String commit;++ private final CompareContext compareContext;++ public ComparingInfo(String commit, CompareContext compareContext) {+ this.commit = commit;+ this.compareContext = compareContext;+ }++ public String getCommit() {+ return commit;+ }++ public CompareContext getCompareContext() {+ return compareContext;+ }++ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.javaindex 4e7ef965f6..bb17618d7e 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequest.java@@ -1,1015 +1,1015 @@-package com.pmease.gitplex.core.entity;--import java.io.IOException;-import java.io.Serializable;-import java.util.ArrayList;-import java.util.Collection;-import java.util.Collections;-import java.util.Date;-import java.util.HashMap;-import java.util.HashSet;-import java.util.List;-import java.util.Map;-import java.util.Set;-import java.util.UUID;-import java.util.stream.Collectors;--import javax.annotation.Nullable;-import javax.persistence.CascadeType;-import javax.persistence.Column;-import javax.persistence.Embedded;-import javax.persistence.Entity;-import javax.persistence.FetchType;-import javax.persistence.Index;-import javax.persistence.JoinColumn;-import javax.persistence.Lob;-import javax.persistence.ManyToOne;-import javax.persistence.OneToMany;-import javax.persistence.Table;-import javax.persistence.UniqueConstraint;-import javax.persistence.Version;--import org.apache.commons.lang3.StringUtils;-import org.eclipse.jgit.lib.ObjectId;-import org.eclipse.jgit.revwalk.RevCommit;-import org.eclipse.jgit.revwalk.RevWalk;-import org.hibernate.annotations.DynamicUpdate;-import org.hibernate.annotations.OptimisticLock;-import org.hibernate.criterion.Criterion;-import org.hibernate.criterion.Restrictions;--import com.fasterxml.jackson.annotation.JsonView;-import com.google.common.base.Preconditions;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.hibernate.AbstractEntity;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.jackson.ExternalView;-import com.pmease.commons.lang.diff.WhitespaceOption;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.support.CloseInfo;-import com.pmease.gitplex.core.entity.support.CompareContext;-import com.pmease.gitplex.core.entity.support.DepotAndBranch;-import com.pmease.gitplex.core.entity.support.IntegrationPreview;-import com.pmease.gitplex.core.entity.support.LastEvent;-import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;-import com.pmease.gitplex.core.manager.CodeCommentRelationManager;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.PullRequestReviewManager;-import com.pmease.gitplex.core.manager.VisitInfoManager;-import com.pmease.gitplex.core.security.ObjectPermission;-import com.pmease.gitplex.core.security.SecurityUtils;--@Entity-/*- * @DynamicUpdate annotation here along with various @OptimisticLock annotations- * on certain fields tell Hibernate not to perform version check on those fields- * which can be updated from background thread.- */-@DynamicUpdate-@Table(indexes={@Index(columnList="title"), @Index(columnList="uuid"), @Index(columnList="numberStr"), @Index(columnList="noSpaceTitle")},- uniqueConstraints={@UniqueConstraint(columnNames={"g_targetdepot_id", "number"})})-public class PullRequest extends AbstractEntity {-- private static final long serialVersionUID = 1L;-- public static final int MAX_CODE_COMMENTS = 1000;-- public enum Status {- PENDING_APPROVAL("Pending Approval"),- PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),- INTEGRATED("Integrated"), DISCARDED("Discarded");-- private final String displayName;-- Status(String displayName) {- this.displayName = displayName;- }-- @Override- public String toString() {- return displayName;- }-- }-- public enum IntegrationStrategy {- MERGE_ALWAYS("Merge always",- "Always create merge commit when integrate into target branch"),- MERGE_IF_NECESSARY("Merge if necessary",- "Create merge commit only if target branch can not be fast-forwarded to the pull request"),- MERGE_WITH_SQUASH("Merge with squash",- "Squash all commits in the pull request and then merge with target branch"),- REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",- "Rebase source branch onto target branch and then fast-forward target branch to source branch"),- REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",- "Rebase target branch onto source branch");-- private final String displayName;-- private final String description;-- IntegrationStrategy(String displayName, String description) {- this.displayName = displayName;- this.description = description;- }-- public String getDisplayName() {- return displayName;- }-- public String getDescription() {- return description;- }-- @Override- public String toString() {- return displayName;- }-- }-- @Embedded- private CloseInfo closeInfo;-- @Column(nullable=false)- private String title;-- @Lob- @Column(length=65535)- private String description;-- @ManyToOne(fetch=FetchType.LAZY)- private Account submitter;-- @ManyToOne(fetch=FetchType.LAZY)- @JoinColumn(nullable=false)- private Depot targetDepot;-- @Column(nullable=false)- private String targetBranch;-- @ManyToOne(fetch=FetchType.LAZY)- private Depot sourceDepot;-- @Column(nullable=false)- private String sourceBranch;-- @Column(nullable=false)- private String baseCommitHash;-- @ManyToOne(fetch=FetchType.LAZY)- private Account assignee;-- @Embedded- private LastEvent lastEvent;-- @Column(nullable=true)- private Date lastCodeCommentEventDate;-- // used for number search in markdown editor- @Column(nullable=false)- private String numberStr;-- // used for title search in markdown editor- @Column(nullable=false)- private String noSpaceTitle;-- @Version- private long version;-- @OptimisticLock(excluded=true)- @Embedded- private IntegrationPreview lastIntegrationPreview;-- @Column(nullable=false)- private Date submitDate = new Date();-- @Column(nullable=false)- private IntegrationStrategy integrationStrategy;-- @Column(nullable=false)- private String uuid = UUID.randomUUID().toString();-- private long number;-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestUpdate> updates = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<CodeCommentRelation> codeCommentRelations = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestReviewInvitation> reviewInvitations = new ArrayList<>();-- @OneToMany(mappedBy="referenced", cascade=CascadeType.REMOVE)- private Collection<PullRequestReference> referencedBy = new ArrayList<>();-- @OneToMany(mappedBy="referencedBy",cascade=CascadeType.REMOVE)- private Collection<PullRequestReference> referenced = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestVerification> verifications = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestComment> comments = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestStatusChange> statusChanges = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestNotification> notifications = new ArrayList<>();-- @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)- private Collection<PullRequestWatch> watches = new ArrayList<>();-- private transient CheckResult checkResult;-- private transient List<PullRequestUpdate> sortedUpdates;-- private transient List<PullRequestUpdate> effectiveUpdates;-- private transient PullRequestUpdate referentialUpdate;-- private transient Collection<RevCommit> pendingCommits;-- private transient Collection<RevCommit> mergedCommits;-- private transient List<PullRequestReview> reviews;-- private transient IntegrationPreview integrationPreview;-- private transient List<CodeComment> codeComments;-- /**- * Get title of this merge request.- *- * @return user specified title of this merge request, <tt>null</tt> for- * auto-created merge request.- */- public @Nullable String getTitle() {- return title;- }-- public void setTitle(String title) {- this.title = title;- noSpaceTitle = StringUtils.deleteWhitespace(title);- }-- public String getDescription() {- return description;- }-- public void setDescription(String description) {- this.description = description;- }-- /**- * Get the user submitting the pull request.- *- * @return- * the user submitting the pull request, or <tt>null</tt> if unknown- */- @Nullable- public Account getSubmitter() {- return submitter;- }-- public void setSubmitter(@Nullable Account submitter) {- this.submitter = submitter;- }-- /**- * Get the user responsible for integration of the pull request.- *- * @return- * the user responsible for integration of this pull request, or <tt>null</tt> to have the- * system integrate the pull request automatically- */- @Nullable- public Account getAssignee() {- return assignee;- }-- public void setAssignee(Account assignee) {- this.assignee = assignee;- }-- public Depot getTargetDepot() {- return targetDepot;- }-- public DepotAndBranch getTarget() {- return new DepotAndBranch(getTargetDepot(), getTargetBranch());- }-- public void setTarget(DepotAndBranch target) {- setTargetDepot(target.getDepot());- setTargetBranch(target.getBranch());- }-- public void setSource(DepotAndBranch source) {- setSourceDepot(source.getDepot());- setSourceBranch(source.getBranch());- }-- public void setTargetDepot(Depot targetDepot) {- this.targetDepot = targetDepot;- }-- public String getTargetBranch() {- return targetBranch;- }-- public void setTargetBranch(String targetBranch) {- this.targetBranch = targetBranch;- }-- @Nullable- public Depot getSourceDepot() {- return sourceDepot;- }-- public void setSourceDepot(Depot sourceDepot) {- this.sourceDepot = sourceDepot;- }-- public String getSourceBranch() {- return sourceBranch;- }-- public void setSourceBranch(String sourceBranch) {- this.sourceBranch = sourceBranch;- }-- public DepotAndBranch getSource() {- return new DepotAndBranch(getSourceDepot(), getSourceBranch());- }-- public String getTargetRef() {- return GitUtils.branch2ref(getTargetBranch());- }-- public String getSourceRef() {- return GitUtils.branch2ref(getSourceBranch());- }-- public String getBaseCommitHash() {- return baseCommitHash;- }-- public void setBaseCommitHash(String baseCommitHash) {- this.baseCommitHash = baseCommitHash;- }-- public RevCommit getBaseCommit() {- return getTargetDepot().getRevCommit(ObjectId.fromString(getBaseCommitHash()));- }-- /**- * Get unmodifiable collection of updates of this pull request. To add update- * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.- *- * @return- * unmodifiable collection of updates- */- public Collection<PullRequestUpdate> getUpdates() {- return Collections.unmodifiableCollection(updates);- }-- public void setUpdates(Collection<PullRequestUpdate> updates) {- this.updates = updates;- sortedUpdates = null;- effectiveUpdates = null;- }-- public void addUpdate(PullRequestUpdate update) {- updates.add(update);- sortedUpdates = null;- effectiveUpdates = null;- }-- public Collection<CodeCommentRelation> getCodeCommentRelations() {- return codeCommentRelations;- }-- public void setCodeCommentRelations(Collection<CodeCommentRelation> codeCommentRelations) {- this.codeCommentRelations = codeCommentRelations;- }-- public Collection<PullRequestReviewInvitation> getReviewInvitations() {- return reviewInvitations;- }-- public void setReviewInvitations(Collection<PullRequestReviewInvitation> reviewInvitations) {- this.reviewInvitations = reviewInvitations;- }-- public Collection<PullRequestVerification> getVerifications() {- return verifications;- }-- public void setVerifications(Collection<PullRequestVerification> verifications) {- this.verifications = verifications;- }-- public Collection<PullRequestReference> getReferencedBy() {- return referencedBy;- }-- public void setReferencedBy(Collection<PullRequestReference> referencedBy) {- this.referencedBy = referencedBy;- }-- public Collection<PullRequestReference> getReferenced() {- return referenced;- }-- public void setReferenced(Collection<PullRequestReference> referenced) {- this.referenced = referenced;- }-- public Collection<PullRequestComment> getComments() {- return comments;- }-- public void setComments(Collection<PullRequestComment> comments) {- this.comments = comments;- }-- public Collection<PullRequestStatusChange> getStatusChanges() {- return statusChanges;- }-- public void setStatusChanges(Collection<PullRequestStatusChange> statusChanges) {- this.statusChanges = statusChanges;- }-- public Collection<PullRequestNotification> getNotifications() {- return notifications;- }-- public void setNotifications(Collection<PullRequestNotification> notifications) {- this.notifications = notifications;- }-- public Collection<PullRequestWatch> getWatches() {- return watches;- }-- public void setWatches(Collection<PullRequestWatch> watches) {- this.watches = watches;- }-- public Status getStatus() {- if (closeInfo != null) {- if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)- return Status.INTEGRATED;- else- return Status.DISCARDED;- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)- return Status.PENDING_APPROVAL;- else if (getCheckResult() instanceof Failed)- return Status.PENDING_UPDATE;- else- return Status.PENDING_INTEGRATE;- }-- @Nullable- public CloseInfo getCloseInfo() {- return closeInfo;- }-- public void setCloseInfo(CloseInfo closeInfo) {- this.closeInfo = closeInfo;- }-- public boolean isOpen() {- return closeInfo == null;- }-- public PullRequestUpdate getReferentialUpdate() {- if (referentialUpdate != null)- return referentialUpdate;- else- return getEffectiveUpdates().get(0);- }-- public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {- this.referentialUpdate = referentiralUpdate;- }-- /**- * Get gate keeper check result.- *- * @return- * check result of this pull request has not been refreshed yet- */- public CheckResult getCheckResult() {- if (checkResult == null)- checkResult = getTargetDepot().getGateKeeper().checkRequest(this);- return checkResult;- }-- /**- * Get last integration preview of this pull request. Note that this method may return an- * out dated integration preview. Refer to {@link this#getIntegrationPreview()}- * if you'd like to get an update-to-date integration preview- *- * @return- * integration preview of this pull request, or <tt>null</tt> if integration- * preview has not been calculated yet.- */- @Nullable- public IntegrationPreview getLastIntegrationPreview() {- return lastIntegrationPreview;- }-- public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {- this.lastIntegrationPreview = lastIntegrationPreview;- }-- /**- * Get effective integration preview of this pull request.- *- * @return- * update to date integration preview of this pull request, or <tt>null</tt> if- * the integration preview has not been calculated or out dated. In both cases,- * it will trigger a re-calculation, and client should call this method later- * to get the calculated result- */- @JsonView(ExternalView.class)- @Nullable- public IntegrationPreview getIntegrationPreview() {- if (integrationPreview == null)- integrationPreview = GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);- return integrationPreview;- }-- /**- * Get list of sorted updates.- *- * @return- * list of sorted updates ordered by id- */- public List<PullRequestUpdate> getSortedUpdates() {- if (sortedUpdates == null) {- Preconditions.checkState(updates.size() >= 1);- sortedUpdates = new ArrayList<PullRequestUpdate>(updates);- Collections.sort(sortedUpdates);- }- return sortedUpdates;- }-- /**- * Get list of effective updates reversely sorted by id. Update is considered effective if it is- * not ancestor of target branch head.- *- * @return- * list of effective updates reversely sorted by id- */- public List<PullRequestUpdate> getEffectiveUpdates() {- Preconditions.checkState(isOpen(), "Can only be called while request is open");- if (effectiveUpdates == null) {- effectiveUpdates = new ArrayList<PullRequestUpdate>();-- for (int i=getSortedUpdates().size()-1; i>=0; i--) {- PullRequestUpdate update = getSortedUpdates().get(i);- if (!getTargetDepot().isMergedInto(update.getHeadCommitHash(), getTarget().getObjectName()))- effectiveUpdates.add(update);- else- break;- }-- Preconditions.checkState(!effectiveUpdates.isEmpty());- }- return effectiveUpdates;- }-- public IntegrationStrategy getIntegrationStrategy() {- return integrationStrategy;- }-- public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {- this.integrationStrategy = integrationStrategy;- }-- @JsonView(ExternalView.class)- public PullRequestUpdate getLatestUpdate() {- return getSortedUpdates().get(getSortedUpdates().size()-1);- }-- @JsonView(ExternalView.class)- public String getBaseRef() {- Preconditions.checkNotNull(getId());- return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/base";- }-- @JsonView(ExternalView.class)- public String getIntegrateRef() {- Preconditions.checkNotNull(getId());- return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/integrate";- }-- /**- * Delete refs of this pull request, without touching refs of its updates.- */- public void deleteRefs() {- GitUtils.deleteRef(getTargetDepot().updateRef(getBaseRef()));- GitUtils.deleteRef(getTargetDepot().updateRef(getIntegrateRef()));- }-- /**- * Invite specified number of users in candidates to review this request.- * <p>- *- * @param candidates- * a collection of users to invite users from- * @param count- * number of users to invite- */- public void pickReviewers(Collection<Account> candidates, int count) {- List<Account> pickList = new ArrayList<Account>(candidates);-- /*- * users already reviewed since base update should be excluded from- * invitation list as their reviews are still valid- */- for (PullRequestReview review: getReferentialUpdate().listReviewsOnwards())- pickList.remove(review.getUser());-- final Map<Account, Date> firstChoices = new HashMap<>();- final Map<Account, Date> secondChoices = new HashMap<>();-- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {- if (invitation.isPreferred())- firstChoices.put(invitation.getUser(), invitation.getDate());- else- secondChoices.put(invitation.getUser(), invitation.getDate());- }-- // submitter is not preferred- if (getSubmitter() != null)- secondChoices.put(getSubmitter(), new Date());-- /* Follow below rules to pick reviewers:- * 1. If user is excluded previously, it will be considered last.- * 2. If user is already a reviewer, it will be considered first.- * 3. Otherwise pick user with least reviews.- */- pickList.sort((user1, user2) -> {- if (firstChoices.containsKey(user1)) {- if (firstChoices.containsKey(user2))- return user1.getReviewEffort() - user2.getReviewEffort();- else- return -1;- } else if (firstChoices.containsKey(user2)) {- return 1;- } else if (secondChoices.containsKey(user1)) {- if (secondChoices.containsKey(user2))- return secondChoices.get(user1).compareTo(secondChoices.get(user2));- else- return 1;- } else if (secondChoices.containsKey(user2)) {- return -1;- } else {- return user1.getReviewEffort() - user2.getReviewEffort();- }- });-- List<Account> picked;- if (count <= pickList.size())- picked = pickList.subList(0, count);- else- picked = pickList;-- for (Account user: picked) {- boolean found = false;- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {- if (invitation.getUser().equals(user)) {- invitation.setDate(new Date());- invitation.setPerferred(true);- found = true;- }- }- if (!found) {- PullRequestReviewInvitation invitation = new PullRequestReviewInvitation();- invitation.setRequest(this);- invitation.setUser(user);- getReviewInvitations().add(invitation);- }- }-- }-- public static class CriterionHelper {- public static Criterion ofOpen() {- return Restrictions.isNull("closeInfo");- }-- public static Criterion ofClosed() {- return Restrictions.isNotNull("closeInfo");- }-- public static Criterion ofTarget(DepotAndBranch target) {- return Restrictions.and(- Restrictions.eq("targetDepot", target.getDepot()),- Restrictions.eq("targetBranch", target.getBranch()));- }-- public static Criterion ofTargetDepot(Depot target) {- return Restrictions.eq("targetDepot", target);- }-- public static Criterion ofSource(DepotAndBranch source) {- return Restrictions.and(- Restrictions.eq("sourceDepot", source.getDepot()),- Restrictions.eq("sourceBranch", source.getBranch()));- }-- public static Criterion ofSourceDepot(Depot source) {- return Restrictions.eq("sourceDepot", source);- }-- public static Criterion ofSubmitter(Account submitter) {- return Restrictions.eq("submitter", submitter);- }-- }-- public Date getSubmitDate() {- return submitDate;- }-- public void setSubmitDate(Date submitDate) {- this.submitDate = submitDate;- }-- /**- * Get commits pending integration.- *- * @return- * commits pending integration- */- public Collection<RevCommit> getPendingCommits() {- if (pendingCommits == null) {- pendingCommits = new HashSet<>();- Depot depot = getTargetDepot();- try (RevWalk revWalk = new RevWalk(depot.getRepository())) {- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getLatestUpdate().getHeadCommitHash())));- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));- revWalk.forEach(c->pendingCommits.add(c));- } catch (IOException e) {- throw new RuntimeException(e);- }- }- return pendingCommits;- }-- /**- * Merged commits represent commits already merged to target branch since base commit.- *- * @return- * commits already merged to target branch since base commit- */- public Collection<RevCommit> getMergedCommits() {- if (mergedCommits == null) {- mergedCommits = new HashSet<>();- Depot depot = getTargetDepot();- try (RevWalk revWalk = new RevWalk(depot.getRepository())) {- revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));- revWalk.forEach(c->mergedCommits.add(c));- } catch (IOException e) {- throw new RuntimeException(e);- }- }- return mergedCommits;- }-- public List<PullRequestReview> getReviews() {- if (reviews == null) {- if (!isNew())- reviews = GitPlex.getInstance(PullRequestReviewManager.class).findAll(this);- else- reviews = new ArrayList<>();- }- return reviews;- }-- /**- * This method is here for performance consideration. Often we need to load reviews of- * different updates in a pull request. And we optimize it to load all reviews at once- * for all updates in a pull request to reduce SQL queries.- *- * @param update- * @return- */- public List<PullRequestReview> getReviews(PullRequestUpdate update) {- List<PullRequestReview> reviews = new ArrayList<>();- for (PullRequestReview review: getReviews()) {- if (review.getUpdate().equals(update))- reviews.add(review);- }- return reviews;- }-- public boolean isReviewEffective(Account user) {- for (PullRequestReview review: getReviews()) {- if (review.getUpdate().equals(getLatestUpdate()) && review.getUser().equals(user))- return true;- }- return false;- }-- /**- * Calculate list of users can be added as reviewers of this pull request.- *- * @return- * list of potential reviewers- */- public List<Account> getPotentialReviewers() {- List<Account> reviewers = new ArrayList<>();- Set<Account> alreadyInvited = new HashSet<>();- for (PullRequestReviewInvitation invitation: getReviewInvitations()) {- if (invitation.isPreferred())- alreadyInvited.add(invitation.getUser());- }- ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());- for (Account user: GitPlex.getInstance(Dao.class).findAll(Account.class)) {- if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))- reviewers.add(user);- }- return reviewers;- }-- @Nullable- public PullRequestWatch getWatch(Account user) {- for (PullRequestWatch watch: getWatches()) {- if (watch.getUser().equals(user))- return watch;- }- return null;- }-- public String getNumberStr() {- return numberStr;- }-- public String getNoSpaceTitle() {- return noSpaceTitle;- }-- public long getVersion() {- return version;- }-- public String getUUID() {- return uuid;- }-- public void setUUID(String uuid) {- this.uuid = uuid;- }-- public long getNumber() {- return number;- }-- public void setNumber(long number) {- this.number = number;- numberStr = String.valueOf(number);- }-- public List<CodeComment> getCodeComments() {- if (codeComments == null) {- codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findAllCodeComments(this);- }- return codeComments;- }-- @Nullable- public ComparingInfo getRequestComparingInfo(CodeComment.ComparingInfo commentComparingInfo) {- List<String> commits = new ArrayList<>();- commits.add(getBaseCommitHash());- for (PullRequestUpdate update: getSortedUpdates()) {- commits.addAll(update.getCommits().stream().map(RevCommit::getName).collect(Collectors.toList()));- }- String commit = commentComparingInfo.getCommit();- CompareContext compareContext = commentComparingInfo.getCompareContext();- if (commit.equals(compareContext.getCompareCommit())) {- int index = commits.indexOf(commit);- if (index == 0) {- return null;- } else {- return new ComparingInfo(commits.get(index-1), commit,- compareContext.getWhitespaceOption(), compareContext.getPathFilter());- }- } else {- int commitIndex = commits.indexOf(commit);- int compareCommitIndex = commits.indexOf(compareContext.getCompareCommit());- if (commitIndex == -1 || compareCommitIndex == -1) {- return null;- } else if (compareContext.isLeftSide()) {- if (compareCommitIndex < commitIndex) {- return new ComparingInfo(compareContext.getCompareCommit(), commit,- compareContext.getWhitespaceOption(), compareContext.getPathFilter());- } else {- return null;- }- } else {- if (commitIndex < compareCommitIndex) {- return new ComparingInfo(commit, compareContext.getCompareCommit(),- compareContext.getWhitespaceOption(), compareContext.getPathFilter());- } else {- return null;- }- }- }- }-- public List<RevCommit> getCommits() {- List<RevCommit> commits = new ArrayList<>();- getSortedUpdates().forEach(update->commits.addAll(update.getCommits()));- return commits;- }-- public String getCommitMessage() {- String commitMessage = getTitle() + "\n\n";- if (getDescription() != null)- commitMessage += getDescription() + "\n\n";- commitMessage += "This commit is created as result of integrating pull request #" + getNumber();- return commitMessage;- }-- public LastEvent getLastEvent() {- return lastEvent;- }-- public void setLastEvent(LastEvent lastEvent) {- this.lastEvent = lastEvent;- }-- public Date getLastCodeCommentEventDate() {- return lastCodeCommentEventDate;- }-- public void setLastCodeCommentEventDate(Date lastCodeCommentEventDate) {- this.lastCodeCommentEventDate = lastCodeCommentEventDate;- }-- public boolean isVisitedAfter(Date date) {- Account user = SecurityUtils.getAccount();- if (user != null) {- Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);- return visitDate != null && visitDate.after(date);- } else {- return true;- }- }-- public boolean isMerged() {- return getTargetDepot().isMergedInto(- getLatestUpdate().getHeadCommitHash(),- getTarget().getObjectName());- }-- public static class ComparingInfo implements Serializable {-- private static final long serialVersionUID = 1L;-- private final String oldCommit;-- private final String newCommit;-- private final String pathFilter;-- private final WhitespaceOption whitespaceOption;-- public ComparingInfo(String oldCommit, String newCommit, WhitespaceOption whitespaceOption, @Nullable String pathFilter) {- this.oldCommit = oldCommit;- this.newCommit = newCommit;- this.whitespaceOption = whitespaceOption;- this.pathFilter = pathFilter;- }-- public String getOldCommit() {- return oldCommit;- }-- public String getNewCommit() {- return newCommit;- }-- public String getPathFilter() {- return pathFilter;- }-- public WhitespaceOption getWhitespaceOption() {- return whitespaceOption;- }-- }-}+package com.pmease.gitplex.core.entity;++import java.io.IOException;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.Date;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;+import java.util.Set;+import java.util.UUID;+import java.util.stream.Collectors;++import javax.annotation.Nullable;+import javax.persistence.CascadeType;+import javax.persistence.Column;+import javax.persistence.Embedded;+import javax.persistence.Entity;+import javax.persistence.FetchType;+import javax.persistence.Index;+import javax.persistence.JoinColumn;+import javax.persistence.Lob;+import javax.persistence.ManyToOne;+import javax.persistence.OneToMany;+import javax.persistence.Table;+import javax.persistence.UniqueConstraint;+import javax.persistence.Version;++import org.apache.commons.lang3.StringUtils;+import org.eclipse.jgit.lib.ObjectId;+import org.eclipse.jgit.revwalk.RevCommit;+import org.eclipse.jgit.revwalk.RevWalk;+import org.hibernate.annotations.DynamicUpdate;+import org.hibernate.annotations.OptimisticLock;+import org.hibernate.criterion.Criterion;+import org.hibernate.criterion.Restrictions;++import com.fasterxml.jackson.annotation.JsonView;+import com.google.common.base.Preconditions;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.hibernate.AbstractEntity;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.jackson.ExternalView;+import com.pmease.commons.lang.diff.WhitespaceOption;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.support.CloseInfo;+import com.pmease.gitplex.core.entity.support.CompareContext;+import com.pmease.gitplex.core.entity.support.DepotAndBranch;+import com.pmease.gitplex.core.entity.support.IntegrationPreview;+import com.pmease.gitplex.core.entity.support.LastEvent;+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;+import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;+import com.pmease.gitplex.core.manager.CodeCommentRelationManager;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.PullRequestReviewManager;+import com.pmease.gitplex.core.manager.VisitInfoManager;+import com.pmease.gitplex.core.security.ObjectPermission;+import com.pmease.gitplex.core.security.SecurityUtils;++@Entity+/*+ * @DynamicUpdate annotation here along with various @OptimisticLock annotations+ * on certain fields tell Hibernate not to perform version check on those fields+ * which can be updated from background thread.+ */+@DynamicUpdate+@Table(indexes={@Index(columnList="title"), @Index(columnList="uuid"), @Index(columnList="numberStr"), @Index(columnList="noSpaceTitle")},+ uniqueConstraints={@UniqueConstraint(columnNames={"g_targetdepot_id", "number"})})+public class PullRequest extends AbstractEntity {++ private static final long serialVersionUID = 1L;++ public static final int MAX_CODE_COMMENTS = 1000;++ public enum Status {+ PENDING_APPROVAL("Pending Approval"),+ PENDING_UPDATE("Pending Update"), PENDING_INTEGRATE("Pending Integration"),+ INTEGRATED("Integrated"), DISCARDED("Discarded");++ private final String displayName;++ Status(String displayName) {+ this.displayName = displayName;+ }++ @Override+ public String toString() {+ return displayName;+ }++ }++ public enum IntegrationStrategy {+ MERGE_ALWAYS("Merge always",+ "Always create merge commit when integrate into target branch"),+ MERGE_IF_NECESSARY("Merge if necessary",+ "Create merge commit only if target branch can not be fast-forwarded to the pull request"),+ MERGE_WITH_SQUASH("Merge with squash",+ "Squash all commits in the pull request and then merge with target branch"),+ REBASE_SOURCE_ONTO_TARGET("Rebase source onto target",+ "Rebase source branch onto target branch and then fast-forward target branch to source branch"),+ REBASE_TARGET_ONTO_SOURCE("Rebase target onto source",+ "Rebase target branch onto source branch");++ private final String displayName;++ private final String description;++ IntegrationStrategy(String displayName, String description) {+ this.displayName = displayName;+ this.description = description;+ }++ public String getDisplayName() {+ return displayName;+ }++ public String getDescription() {+ return description;+ }++ @Override+ public String toString() {+ return displayName;+ }++ }++ @Embedded+ private CloseInfo closeInfo;++ @Column(nullable=false)+ private String title;++ @Lob+ @Column(length=65535)+ private String description;++ @ManyToOne(fetch=FetchType.LAZY)+ private Account submitter;++ @ManyToOne(fetch=FetchType.LAZY)+ @JoinColumn(nullable=false)+ private Depot targetDepot;++ @Column(nullable=false)+ private String targetBranch;++ @ManyToOne(fetch=FetchType.LAZY)+ private Depot sourceDepot;++ @Column(nullable=false)+ private String sourceBranch;++ @Column(nullable=false)+ private String baseCommitHash;++ @ManyToOne(fetch=FetchType.LAZY)+ private Account assignee;++ @Embedded+ private LastEvent lastEvent;++ @Column(nullable=true)+ private Date lastCodeCommentEventDate;++ // used for number search in markdown editor+ @Column(nullable=false)+ private String numberStr;++ // used for title search in markdown editor+ @Column(nullable=false)+ private String noSpaceTitle;++ @Version+ private long version;++ @OptimisticLock(excluded=true)+ @Embedded+ private IntegrationPreview lastIntegrationPreview;++ @Column(nullable=false)+ private Date submitDate = new Date();++ @Column(nullable=false)+ private IntegrationStrategy integrationStrategy;++ @Column(nullable=false)+ private String uuid = UUID.randomUUID().toString();++ private long number;++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestUpdate> updates = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<CodeCommentRelation> codeCommentRelations = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestReviewInvitation> reviewInvitations = new ArrayList<>();++ @OneToMany(mappedBy="referenced", cascade=CascadeType.REMOVE)+ private Collection<PullRequestReference> referencedBy = new ArrayList<>();++ @OneToMany(mappedBy="referencedBy",cascade=CascadeType.REMOVE)+ private Collection<PullRequestReference> referenced = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestVerification> verifications = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestComment> comments = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestStatusChange> statusChanges = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestNotification> notifications = new ArrayList<>();++ @OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)+ private Collection<PullRequestWatch> watches = new ArrayList<>();++ private transient CheckResult checkResult;++ private transient List<PullRequestUpdate> sortedUpdates;++ private transient List<PullRequestUpdate> effectiveUpdates;++ private transient PullRequestUpdate referentialUpdate;++ private transient Collection<RevCommit> pendingCommits;++ private transient Collection<RevCommit> mergedCommits;++ private transient List<PullRequestReview> reviews;++ private transient IntegrationPreview integrationPreview;++ private transient List<CodeComment> codeComments;++ /**+ * Get title of this merge request.+ *+ * @return user specified title of this merge request, <tt>null</tt> for+ * auto-created merge request.+ */+ public @Nullable String getTitle() {+ return title;+ }++ public void setTitle(String title) {+ this.title = title;+ noSpaceTitle = StringUtils.deleteWhitespace(title);+ }++ public String getDescription() {+ return description;+ }++ public void setDescription(String description) {+ this.description = description;+ }++ /**+ * Get the user submitting the pull request.+ *+ * @return+ * the user submitting the pull request, or <tt>null</tt> if unknown+ */+ @Nullable+ public Account getSubmitter() {+ return submitter;+ }++ public void setSubmitter(@Nullable Account submitter) {+ this.submitter = submitter;+ }++ /**+ * Get the user responsible for integration of the pull request.+ *+ * @return+ * the user responsible for integration of this pull request, or <tt>null</tt> to have the+ * system integrate the pull request automatically+ */+ @Nullable+ public Account getAssignee() {+ return assignee;+ }++ public void setAssignee(Account assignee) {+ this.assignee = assignee;+ }++ public Depot getTargetDepot() {+ return targetDepot;+ }++ public DepotAndBranch getTarget() {+ return new DepotAndBranch(getTargetDepot(), getTargetBranch());+ }++ public void setTarget(DepotAndBranch target) {+ setTargetDepot(target.getDepot());+ setTargetBranch(target.getBranch());+ }++ public void setSource(DepotAndBranch source) {+ setSourceDepot(source.getDepot());+ setSourceBranch(source.getBranch());+ }++ public void setTargetDepot(Depot targetDepot) {+ this.targetDepot = targetDepot;+ }++ public String getTargetBranch() {+ return targetBranch;+ }++ public void setTargetBranch(String targetBranch) {+ this.targetBranch = targetBranch;+ }++ @Nullable+ public Depot getSourceDepot() {+ return sourceDepot;+ }++ public void setSourceDepot(Depot sourceDepot) {+ this.sourceDepot = sourceDepot;+ }++ public String getSourceBranch() {+ return sourceBranch;+ }++ public void setSourceBranch(String sourceBranch) {+ this.sourceBranch = sourceBranch;+ }++ public DepotAndBranch getSource() {+ return new DepotAndBranch(getSourceDepot(), getSourceBranch());+ }++ public String getTargetRef() {+ return GitUtils.branch2ref(getTargetBranch());+ }++ public String getSourceRef() {+ return GitUtils.branch2ref(getSourceBranch());+ }++ public String getBaseCommitHash() {+ return baseCommitHash;+ }++ public void setBaseCommitHash(String baseCommitHash) {+ this.baseCommitHash = baseCommitHash;+ }++ public RevCommit getBaseCommit() {+ return getTargetDepot().getRevCommit(ObjectId.fromString(getBaseCommitHash()));+ }++ /**+ * Get unmodifiable collection of updates of this pull request. To add update+ * to the pull request, call {@link this#addUpdate(PullRequestUpdate)} instead.+ *+ * @return+ * unmodifiable collection of updates+ */+ public Collection<PullRequestUpdate> getUpdates() {+ return Collections.unmodifiableCollection(updates);+ }++ public void setUpdates(Collection<PullRequestUpdate> updates) {+ this.updates = updates;+ sortedUpdates = null;+ effectiveUpdates = null;+ }++ public void addUpdate(PullRequestUpdate update) {+ updates.add(update);+ sortedUpdates = null;+ effectiveUpdates = null;+ }++ public Collection<CodeCommentRelation> getCodeCommentRelations() {+ return codeCommentRelations;+ }++ public void setCodeCommentRelations(Collection<CodeCommentRelation> codeCommentRelations) {+ this.codeCommentRelations = codeCommentRelations;+ }++ public Collection<PullRequestReviewInvitation> getReviewInvitations() {+ return reviewInvitations;+ }++ public void setReviewInvitations(Collection<PullRequestReviewInvitation> reviewInvitations) {+ this.reviewInvitations = reviewInvitations;+ }++ public Collection<PullRequestVerification> getVerifications() {+ return verifications;+ }++ public void setVerifications(Collection<PullRequestVerification> verifications) {+ this.verifications = verifications;+ }++ public Collection<PullRequestReference> getReferencedBy() {+ return referencedBy;+ }++ public void setReferencedBy(Collection<PullRequestReference> referencedBy) {+ this.referencedBy = referencedBy;+ }++ public Collection<PullRequestReference> getReferenced() {+ return referenced;+ }++ public void setReferenced(Collection<PullRequestReference> referenced) {+ this.referenced = referenced;+ }++ public Collection<PullRequestComment> getComments() {+ return comments;+ }++ public void setComments(Collection<PullRequestComment> comments) {+ this.comments = comments;+ }++ public Collection<PullRequestStatusChange> getStatusChanges() {+ return statusChanges;+ }++ public void setStatusChanges(Collection<PullRequestStatusChange> statusChanges) {+ this.statusChanges = statusChanges;+ }++ public Collection<PullRequestNotification> getNotifications() {+ return notifications;+ }++ public void setNotifications(Collection<PullRequestNotification> notifications) {+ this.notifications = notifications;+ }++ public Collection<PullRequestWatch> getWatches() {+ return watches;+ }++ public void setWatches(Collection<PullRequestWatch> watches) {+ this.watches = watches;+ }++ public Status getStatus() {+ if (closeInfo != null) {+ if (closeInfo.getCloseStatus() == CloseInfo.Status.INTEGRATED)+ return Status.INTEGRATED;+ else+ return Status.DISCARDED;+ } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)+ return Status.PENDING_APPROVAL;+ else if (getCheckResult() instanceof Failed)+ return Status.PENDING_UPDATE;+ else+ return Status.PENDING_INTEGRATE;+ }++ @Nullable+ public CloseInfo getCloseInfo() {+ return closeInfo;+ }++ public void setCloseInfo(CloseInfo closeInfo) {+ this.closeInfo = closeInfo;+ }++ public boolean isOpen() {+ return closeInfo == null;+ }++ public PullRequestUpdate getReferentialUpdate() {+ if (referentialUpdate != null)+ return referentialUpdate;+ else+ return getEffectiveUpdates().get(0);+ }++ public void setReferentialUpdate(PullRequestUpdate referentiralUpdate) {+ this.referentialUpdate = referentiralUpdate;+ }++ /**+ * Get gate keeper check result.+ *+ * @return+ * check result of this pull request has not been refreshed yet+ */+ public CheckResult getCheckResult() {+ if (checkResult == null)+ checkResult = getTargetDepot().getGateKeeper().checkRequest(this);+ return checkResult;+ }++ /**+ * Get last integration preview of this pull request. Note that this method may return an+ * out dated integration preview. Refer to {@link this#getIntegrationPreview()}+ * if you'd like to get an update-to-date integration preview+ *+ * @return+ * integration preview of this pull request, or <tt>null</tt> if integration+ * preview has not been calculated yet.+ */+ @Nullable+ public IntegrationPreview getLastIntegrationPreview() {+ return lastIntegrationPreview;+ }++ public void setLastIntegrationPreview(IntegrationPreview lastIntegrationPreview) {+ this.lastIntegrationPreview = lastIntegrationPreview;+ }++ /**+ * Get effective integration preview of this pull request.+ *+ * @return+ * update to date integration preview of this pull request, or <tt>null</tt> if+ * the integration preview has not been calculated or out dated. In both cases,+ * it will trigger a re-calculation, and client should call this method later+ * to get the calculated result+ */+ @JsonView(ExternalView.class)+ @Nullable+ public IntegrationPreview getIntegrationPreview() {+ if (integrationPreview == null)+ integrationPreview = GitPlex.getInstance(PullRequestManager.class).previewIntegration(this);+ return integrationPreview;+ }++ /**+ * Get list of sorted updates.+ *+ * @return+ * list of sorted updates ordered by id+ */+ public List<PullRequestUpdate> getSortedUpdates() {+ if (sortedUpdates == null) {+ Preconditions.checkState(updates.size() >= 1);+ sortedUpdates = new ArrayList<PullRequestUpdate>(updates);+ Collections.sort(sortedUpdates);+ }+ return sortedUpdates;+ }++ /**+ * Get list of effective updates reversely sorted by id. Update is considered effective if it is+ * not ancestor of target branch head.+ *+ * @return+ * list of effective updates reversely sorted by id+ */+ public List<PullRequestUpdate> getEffectiveUpdates() {+ Preconditions.checkState(isOpen(), "Can only be called while request is open");+ if (effectiveUpdates == null) {+ effectiveUpdates = new ArrayList<PullRequestUpdate>();++ for (int i=getSortedUpdates().size()-1; i>=0; i--) {+ PullRequestUpdate update = getSortedUpdates().get(i);+ if (!getTargetDepot().isMergedInto(update.getHeadCommitHash(), getTarget().getObjectName()))+ effectiveUpdates.add(update);+ else+ break;+ }++ Preconditions.checkState(!effectiveUpdates.isEmpty());+ }+ return effectiveUpdates;+ }++ public IntegrationStrategy getIntegrationStrategy() {+ return integrationStrategy;+ }++ public void setIntegrationStrategy(IntegrationStrategy integrationStrategy) {+ this.integrationStrategy = integrationStrategy;+ }++ @JsonView(ExternalView.class)+ public PullRequestUpdate getLatestUpdate() {+ return getSortedUpdates().get(getSortedUpdates().size()-1);+ }++ @JsonView(ExternalView.class)+ public String getBaseRef() {+ Preconditions.checkNotNull(getId());+ return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/base";+ }++ @JsonView(ExternalView.class)+ public String getIntegrateRef() {+ Preconditions.checkNotNull(getId());+ return Depot.REFS_GITPLEX + "pulls/" + getNumber() + "/integrate";+ }++ /**+ * Delete refs of this pull request, without touching refs of its updates.+ */+ public void deleteRefs() {+ GitUtils.deleteRef(getTargetDepot().updateRef(getBaseRef()));+ GitUtils.deleteRef(getTargetDepot().updateRef(getIntegrateRef()));+ }++ /**+ * Invite specified number of users in candidates to review this request.+ * <p>+ *+ * @param candidates+ * a collection of users to invite users from+ * @param count+ * number of users to invite+ */+ public void pickReviewers(Collection<Account> candidates, int count) {+ List<Account> pickList = new ArrayList<Account>(candidates);++ /*+ * users already reviewed since base update should be excluded from+ * invitation list as their reviews are still valid+ */+ for (PullRequestReview review: getReferentialUpdate().listReviewsOnwards())+ pickList.remove(review.getUser());++ final Map<Account, Date> firstChoices = new HashMap<>();+ final Map<Account, Date> secondChoices = new HashMap<>();++ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.isPreferred())+ firstChoices.put(invitation.getUser(), invitation.getDate());+ else+ secondChoices.put(invitation.getUser(), invitation.getDate());+ }++ // submitter is not preferred+ if (getSubmitter() != null)+ secondChoices.put(getSubmitter(), new Date());++ /* Follow below rules to pick reviewers:+ * 1. If user is excluded previously, it will be considered last.+ * 2. If user is already a reviewer, it will be considered first.+ * 3. Otherwise pick user with least reviews.+ */+ pickList.sort((user1, user2) -> {+ if (firstChoices.containsKey(user1)) {+ if (firstChoices.containsKey(user2))+ return user1.getReviewEffort() - user2.getReviewEffort();+ else+ return -1;+ } else if (firstChoices.containsKey(user2)) {+ return 1;+ } else if (secondChoices.containsKey(user1)) {+ if (secondChoices.containsKey(user2))+ return secondChoices.get(user1).compareTo(secondChoices.get(user2));+ else+ return 1;+ } else if (secondChoices.containsKey(user2)) {+ return -1;+ } else {+ return user1.getReviewEffort() - user2.getReviewEffort();+ }+ });++ List<Account> picked;+ if (count <= pickList.size())+ picked = pickList.subList(0, count);+ else+ picked = pickList;++ for (Account user: picked) {+ boolean found = false;+ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.getUser().equals(user)) {+ invitation.setDate(new Date());+ invitation.setPerferred(true);+ found = true;+ }+ }+ if (!found) {+ PullRequestReviewInvitation invitation = new PullRequestReviewInvitation();+ invitation.setRequest(this);+ invitation.setUser(user);+ getReviewInvitations().add(invitation);+ }+ }++ }++ public static class CriterionHelper {+ public static Criterion ofOpen() {+ return Restrictions.isNull("closeInfo");+ }++ public static Criterion ofClosed() {+ return Restrictions.isNotNull("closeInfo");+ }++ public static Criterion ofTarget(DepotAndBranch target) {+ return Restrictions.and(+ Restrictions.eq("targetDepot", target.getDepot()),+ Restrictions.eq("targetBranch", target.getBranch()));+ }++ public static Criterion ofTargetDepot(Depot target) {+ return Restrictions.eq("targetDepot", target);+ }++ public static Criterion ofSource(DepotAndBranch source) {+ return Restrictions.and(+ Restrictions.eq("sourceDepot", source.getDepot()),+ Restrictions.eq("sourceBranch", source.getBranch()));+ }++ public static Criterion ofSourceDepot(Depot source) {+ return Restrictions.eq("sourceDepot", source);+ }++ public static Criterion ofSubmitter(Account submitter) {+ return Restrictions.eq("submitter", submitter);+ }++ }++ public Date getSubmitDate() {+ return submitDate;+ }++ public void setSubmitDate(Date submitDate) {+ this.submitDate = submitDate;+ }++ /**+ * Get commits pending integration.+ *+ * @return+ * commits pending integration+ */+ public Collection<RevCommit> getPendingCommits() {+ if (pendingCommits == null) {+ pendingCommits = new HashSet<>();+ Depot depot = getTargetDepot();+ try (RevWalk revWalk = new RevWalk(depot.getRepository())) {+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getLatestUpdate().getHeadCommitHash())));+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));+ revWalk.forEach(c->pendingCommits.add(c));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ return pendingCommits;+ }++ /**+ * Merged commits represent commits already merged to target branch since base commit.+ *+ * @return+ * commits already merged to target branch since base commit+ */+ public Collection<RevCommit> getMergedCommits() {+ if (mergedCommits == null) {+ mergedCommits = new HashSet<>();+ Depot depot = getTargetDepot();+ try (RevWalk revWalk = new RevWalk(depot.getRepository())) {+ revWalk.markStart(revWalk.parseCommit(ObjectId.fromString(getTarget().getObjectName())));+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));+ revWalk.forEach(c->mergedCommits.add(c));+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }+ return mergedCommits;+ }++ public List<PullRequestReview> getReviews() {+ if (reviews == null) {+ if (!isNew())+ reviews = GitPlex.getInstance(PullRequestReviewManager.class).findAll(this);+ else+ reviews = new ArrayList<>();+ }+ return reviews;+ }++ /**+ * This method is here for performance consideration. Often we need to load reviews of+ * different updates in a pull request. And we optimize it to load all reviews at once+ * for all updates in a pull request to reduce SQL queries.+ *+ * @param update+ * @return+ */+ public List<PullRequestReview> getReviews(PullRequestUpdate update) {+ List<PullRequestReview> reviews = new ArrayList<>();+ for (PullRequestReview review: getReviews()) {+ if (review.getUpdate().equals(update))+ reviews.add(review);+ }+ return reviews;+ }++ public boolean isReviewEffective(Account user) {+ for (PullRequestReview review: getReviews()) {+ if (review.getUpdate().equals(getLatestUpdate()) && review.getUser().equals(user))+ return true;+ }+ return false;+ }++ /**+ * Calculate list of users can be added as reviewers of this pull request.+ *+ * @return+ * list of potential reviewers+ */+ public List<Account> getPotentialReviewers() {+ List<Account> reviewers = new ArrayList<>();+ Set<Account> alreadyInvited = new HashSet<>();+ for (PullRequestReviewInvitation invitation: getReviewInvitations()) {+ if (invitation.isPreferred())+ alreadyInvited.add(invitation.getUser());+ }+ ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());+ for (Account user: GitPlex.getInstance(Dao.class).findAll(Account.class)) {+ if (user.asSubject().isPermitted(readPerm) && !alreadyInvited.contains(user))+ reviewers.add(user);+ }+ return reviewers;+ }++ @Nullable+ public PullRequestWatch getWatch(Account user) {+ for (PullRequestWatch watch: getWatches()) {+ if (watch.getUser().equals(user))+ return watch;+ }+ return null;+ }++ public String getNumberStr() {+ return numberStr;+ }++ public String getNoSpaceTitle() {+ return noSpaceTitle;+ }++ public long getVersion() {+ return version;+ }++ public String getUUID() {+ return uuid;+ }++ public void setUUID(String uuid) {+ this.uuid = uuid;+ }++ public long getNumber() {+ return number;+ }++ public void setNumber(long number) {+ this.number = number;+ numberStr = String.valueOf(number);+ }++ public List<CodeComment> getCodeComments() {+ if (codeComments == null) {+ codeComments = GitPlex.getInstance(CodeCommentRelationManager.class).findAllCodeComments(this);+ }+ return codeComments;+ }++ @Nullable+ public ComparingInfo getRequestComparingInfo(CodeComment.ComparingInfo commentComparingInfo) {+ List<String> commits = new ArrayList<>();+ commits.add(getBaseCommitHash());+ for (PullRequestUpdate update: getSortedUpdates()) {+ commits.addAll(update.getCommits().stream().map(RevCommit::getName).collect(Collectors.toList()));+ }+ String commit = commentComparingInfo.getCommit();+ CompareContext compareContext = commentComparingInfo.getCompareContext();+ if (commit.equals(compareContext.getCompareCommit())) {+ int index = commits.indexOf(commit);+ if (index == 0) {+ return null;+ } else {+ return new ComparingInfo(commits.get(index-1), commit,+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());+ }+ } else {+ int commitIndex = commits.indexOf(commit);+ int compareCommitIndex = commits.indexOf(compareContext.getCompareCommit());+ if (commitIndex == -1 || compareCommitIndex == -1) {+ return null;+ } else if (compareContext.isLeftSide()) {+ if (compareCommitIndex < commitIndex) {+ return new ComparingInfo(compareContext.getCompareCommit(), commit,+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());+ } else {+ return null;+ }+ } else {+ if (commitIndex < compareCommitIndex) {+ return new ComparingInfo(commit, compareContext.getCompareCommit(),+ compareContext.getWhitespaceOption(), compareContext.getPathFilter());+ } else {+ return null;+ }+ }+ }+ }++ public List<RevCommit> getCommits() {+ List<RevCommit> commits = new ArrayList<>();+ getSortedUpdates().forEach(update->commits.addAll(update.getCommits()));+ return commits;+ }++ public String getCommitMessage() {+ String commitMessage = getTitle() + "\n\n";+ if (getDescription() != null)+ commitMessage += getDescription() + "\n\n";+ commitMessage += "This commit is created as result of integrating pull request #" + getNumber();+ return commitMessage;+ }++ public LastEvent getLastEvent() {+ return lastEvent;+ }++ public void setLastEvent(LastEvent lastEvent) {+ this.lastEvent = lastEvent;+ }++ public Date getLastCodeCommentEventDate() {+ return lastCodeCommentEventDate;+ }++ public void setLastCodeCommentEventDate(Date lastCodeCommentEventDate) {+ this.lastCodeCommentEventDate = lastCodeCommentEventDate;+ }++ public boolean isVisitedAfter(Date date) {+ Account user = SecurityUtils.getAccount();+ if (user != null) {+ Date visitDate = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, this);+ return visitDate != null && visitDate.getTime()>date.getTime();+ } else {+ return true;+ }+ }++ public boolean isMerged() {+ return getTargetDepot().isMergedInto(+ getLatestUpdate().getHeadCommitHash(),+ getTarget().getObjectName());+ }++ public static class ComparingInfo implements Serializable {++ private static final long serialVersionUID = 1L;++ private final String oldCommit;++ private final String newCommit;++ private final String pathFilter;++ private final WhitespaceOption whitespaceOption;++ public ComparingInfo(String oldCommit, String newCommit, WhitespaceOption whitespaceOption, @Nullable String pathFilter) {+ this.oldCommit = oldCommit;+ this.newCommit = newCommit;+ this.whitespaceOption = whitespaceOption;+ this.pathFilter = pathFilter;+ }++ public String getOldCommit() {+ return oldCommit;+ }++ public String getNewCommit() {+ return newCommit;+ }++ public String getPathFilter() {+ return pathFilter;+ }++ public WhitespaceOption getWhitespaceOption() {+ return whitespaceOption;+ }++ }+}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.javaindex 0ed9357d95..015aef54ff 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentRelationManager.java@@ -1,172 +1,173 @@-package com.pmease.gitplex.core.manager.impl;--import java.util.ArrayList;-import java.util.Collection;-import java.util.Collections;-import java.util.HashMap;-import java.util.HashSet;-import java.util.List;-import java.util.Map;--import javax.inject.Inject;-import javax.inject.Singleton;--import org.eclipse.jgit.lib.ObjectId;-import org.eclipse.jgit.revwalk.RevCommit;--import com.pmease.commons.hibernate.Transactional;-import com.pmease.commons.hibernate.dao.AbstractEntityManager;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.loader.Listen;-import com.pmease.commons.wicket.editable.EditableUtils;-import com.pmease.gitplex.core.entity.CodeComment;-import com.pmease.gitplex.core.entity.CodeCommentRelation;-import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.PullRequestUpdate;-import com.pmease.gitplex.core.entity.support.CompareContext;-import com.pmease.gitplex.core.entity.support.LastEvent;-import com.pmease.gitplex.core.event.codecomment.CodeCommentCreated;-import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommented;-import com.pmease.gitplex.core.manager.CodeCommentInfoManager;-import com.pmease.gitplex.core.manager.CodeCommentManager;-import com.pmease.gitplex.core.manager.CodeCommentRelationManager;-import com.pmease.gitplex.core.manager.PullRequestInfoManager;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.VisitInfoManager;--@Singleton-public class DefaultCodeCommentRelationManager extends AbstractEntityManager<CodeCommentRelation>- implements CodeCommentRelationManager {-- private final PullRequestInfoManager pullRequestInfoManager;-- private final CodeCommentInfoManager codeCommentInfoManager;-- private final CodeCommentManager codeCommentManager;-- private final PullRequestManager pullRequestManager;-- private final VisitInfoManager visitInfoManager;-- @Inject- public DefaultCodeCommentRelationManager(Dao dao, PullRequestInfoManager pullRequestInfoManager,- CodeCommentInfoManager codeCommentInfoManager, CodeCommentManager codeCommentManager,- PullRequestManager pullRequestManager, VisitInfoManager visitInfoManager) {- super(dao);- this.pullRequestInfoManager = pullRequestInfoManager;- this.codeCommentInfoManager = codeCommentInfoManager;- this.codeCommentManager = codeCommentManager;- this.pullRequestManager = pullRequestManager;- this.visitInfoManager = visitInfoManager;- }-- /*- * Find out code comments belong to a pull request. A code comment is considered to be- * belong to pull request if its commit and compare commit is covered by commits of- * the pull request. The simplest approach to determine this would be to query the- * database for each commit of the pull request. However that might issue a lot of- * sql queries if there are many commits. To address this issue, at the time of- * querying related comments, we query the comment information store first (which is- * fast) for each commit to see if there are new comments relevant to the pull request.- */- @Transactional- @Override- public List<CodeComment> findAllCodeComments(PullRequest request) {- if (request.getCodeCommentRelations().size() < PullRequest.MAX_CODE_COMMENTS) {- Collection<String> relatedComments = new HashSet<>();- for (CodeCommentRelation relation: request.getCodeCommentRelations()) {- relatedComments.add(relation.getComment().getUUID());- }-- Collection<String> involvedCommits = new HashSet<>();- for (PullRequestUpdate update: request.getUpdates()) {- for (RevCommit commit: update.getCommits())- involvedCommits.add(commit.name());- }- involvedCommits.add(request.getBaseCommitHash());-- Map<String, CodeComment.ComparingInfo> comparingInfos = new HashMap<>();- for (String commit: involvedCommits) {- Map<String, CompareContext> commentsOfCommit = codeCommentInfoManager.getComments(- request.getTargetDepot(), ObjectId.fromString(commit));- for (Map.Entry<String, CompareContext> entry: commentsOfCommit.entrySet()) {- CodeComment.ComparingInfo comparingInfo = new CodeComment.ComparingInfo(commit, entry.getValue());- comparingInfos.put(entry.getKey(), comparingInfo);- }- }-- comparingInfos.keySet().removeAll(relatedComments);-- for (Map.Entry<String, CodeComment.ComparingInfo> entry: comparingInfos.entrySet()) {- String uuid = entry.getKey();- CodeComment.ComparingInfo comparingInfo = entry.getValue();-- if (request.getRequestComparingInfo(comparingInfo) != null) {- CodeComment comment = codeCommentManager.find(uuid);- if (comment == null) {- codeCommentInfoManager.removeComment(request.getTargetDepot(), ObjectId.fromString(comparingInfo.getCommit()), uuid);- } else if (request.getCodeCommentRelations().size() < PullRequest.MAX_CODE_COMMENTS) {- CodeCommentRelation relation = new CodeCommentRelation();- relation.setComment(comment);- relation.setRequest(request);- save(relation);- request.getCodeCommentRelations().add(relation);- }- }- }-- }-- List<CodeComment> comments = new ArrayList<>();- for (CodeCommentRelation relation: request.getCodeCommentRelations()) {- comments.add(relation.getComment());- }- comments.sort(CodeComment::compareTo);- Collections.reverse(comments);-- return comments;- }-- @Transactional- @Override- public void save(CodeCommentRelation entity) {- PullRequest request = entity.getRequest();- CodeComment comment = entity.getComment();- if (entity.isNew() && (request.getLastEvent() == null || comment.getDate().after(request.getLastEvent().getDate()))) {- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(comment.getDate());- lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommented.class));- lastEvent.setUser(comment.getUser());- request.setLastCodeCommentEventDate(comment.getDate());- pullRequestManager.save(request);- }- super.save(entity);- }-- @Transactional- @Listen- public void on(CodeCommentCreated event) {- CodeComment comment = event.getComment();- ObjectId commitId = ObjectId.fromString(comment.getCommentPos().getCommit());- for (String uuid: pullRequestInfoManager.getRequests(comment.getDepot(), commitId)) {- PullRequest request = pullRequestManager.find(uuid);- if (request != null && request.getRequestComparingInfo(comment.getComparingInfo()) != null) {- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(comment.getDate());- lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommented.class));- lastEvent.setUser(comment.getUser());- request.setLastEvent(lastEvent);- request.setLastCodeCommentEventDate(comment.getDate());- pullRequestManager.save(request);-- visitInfoManager.visit(comment.getUser(), request);-- CodeCommentRelation relation = new CodeCommentRelation();- relation.setComment(comment);- relation.setRequest(request);- save(relation);- }- }- }--}+package com.pmease.gitplex.core.manager.impl;++import java.util.ArrayList;+import java.util.Collection;+import java.util.Collections;+import java.util.HashMap;+import java.util.HashSet;+import java.util.List;+import java.util.Map;++import javax.inject.Inject;+import javax.inject.Singleton;++import org.eclipse.jgit.lib.ObjectId;+import org.eclipse.jgit.revwalk.RevCommit;++import com.pmease.commons.hibernate.Transactional;+import com.pmease.commons.hibernate.dao.AbstractEntityManager;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.loader.Listen;+import com.pmease.commons.wicket.editable.EditableUtils;+import com.pmease.gitplex.core.entity.CodeComment;+import com.pmease.gitplex.core.entity.CodeCommentRelation;+import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.PullRequestUpdate;+import com.pmease.gitplex.core.entity.support.CompareContext;+import com.pmease.gitplex.core.entity.support.LastEvent;+import com.pmease.gitplex.core.event.codecomment.CodeCommentCreated;+import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommented;+import com.pmease.gitplex.core.manager.CodeCommentInfoManager;+import com.pmease.gitplex.core.manager.CodeCommentManager;+import com.pmease.gitplex.core.manager.CodeCommentRelationManager;+import com.pmease.gitplex.core.manager.PullRequestInfoManager;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.VisitInfoManager;++@Singleton+public class DefaultCodeCommentRelationManager extends AbstractEntityManager<CodeCommentRelation>+ implements CodeCommentRelationManager {++ private final PullRequestInfoManager pullRequestInfoManager;++ private final CodeCommentInfoManager codeCommentInfoManager;++ private final CodeCommentManager codeCommentManager;++ private final PullRequestManager pullRequestManager;++ private final VisitInfoManager visitInfoManager;++ @Inject+ public DefaultCodeCommentRelationManager(Dao dao, PullRequestInfoManager pullRequestInfoManager,+ CodeCommentInfoManager codeCommentInfoManager, CodeCommentManager codeCommentManager,+ PullRequestManager pullRequestManager, VisitInfoManager visitInfoManager) {+ super(dao);+ this.pullRequestInfoManager = pullRequestInfoManager;+ this.codeCommentInfoManager = codeCommentInfoManager;+ this.codeCommentManager = codeCommentManager;+ this.pullRequestManager = pullRequestManager;+ this.visitInfoManager = visitInfoManager;+ }++ /*+ * Find out code comments belong to a pull request. A code comment is considered to be+ * belong to pull request if its commit and compare commit is covered by commits of+ * the pull request. The simplest approach to determine this would be to query the+ * database for each commit of the pull request. However that might issue a lot of+ * sql queries if there are many commits. To address this issue, at the time of+ * querying related comments, we query the comment information store first (which is+ * fast) for each commit to see if there are new comments relevant to the pull request.+ */+ @Transactional+ @Override+ public List<CodeComment> findAllCodeComments(PullRequest request) {+ if (request.getCodeCommentRelations().size() < PullRequest.MAX_CODE_COMMENTS) {+ Collection<String> relatedComments = new HashSet<>();+ for (CodeCommentRelation relation: request.getCodeCommentRelations()) {+ relatedComments.add(relation.getComment().getUUID());+ }++ Collection<String> involvedCommits = new HashSet<>();+ for (PullRequestUpdate update: request.getUpdates()) {+ for (RevCommit commit: update.getCommits())+ involvedCommits.add(commit.name());+ }+ involvedCommits.add(request.getBaseCommitHash());++ Map<String, CodeComment.ComparingInfo> comparingInfos = new HashMap<>();+ for (String commit: involvedCommits) {+ Map<String, CompareContext> commentsOfCommit = codeCommentInfoManager.getComments(+ request.getTargetDepot(), ObjectId.fromString(commit));+ for (Map.Entry<String, CompareContext> entry: commentsOfCommit.entrySet()) {+ CodeComment.ComparingInfo comparingInfo = new CodeComment.ComparingInfo(commit, entry.getValue());+ comparingInfos.put(entry.getKey(), comparingInfo);+ }+ }++ comparingInfos.keySet().removeAll(relatedComments);++ for (Map.Entry<String, CodeComment.ComparingInfo> entry: comparingInfos.entrySet()) {+ String uuid = entry.getKey();+ CodeComment.ComparingInfo comparingInfo = entry.getValue();++ if (request.getRequestComparingInfo(comparingInfo) != null) {+ CodeComment comment = codeCommentManager.find(uuid);+ if (comment == null) {+ codeCommentInfoManager.removeComment(request.getTargetDepot(), ObjectId.fromString(comparingInfo.getCommit()), uuid);+ } else if (request.getCodeCommentRelations().size() < PullRequest.MAX_CODE_COMMENTS) {+ CodeCommentRelation relation = new CodeCommentRelation();+ relation.setComment(comment);+ relation.setRequest(request);+ save(relation);+ request.getCodeCommentRelations().add(relation);+ }+ }+ }++ }++ List<CodeComment> comments = new ArrayList<>();+ for (CodeCommentRelation relation: request.getCodeCommentRelations()) {+ comments.add(relation.getComment());+ }+ comments.sort(CodeComment::compareTo);+ Collections.reverse(comments);++ return comments;+ }++ @Transactional+ @Override+ public void save(CodeCommentRelation entity) {+ PullRequest request = entity.getRequest();+ CodeComment comment = entity.getComment();+ if (entity.isNew() && (request.getLastEvent() == null+ || comment.getDate().getTime()>request.getLastEvent().getDate().getTime())) {+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(comment.getDate());+ lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommented.class));+ lastEvent.setUser(comment.getUser());+ request.setLastCodeCommentEventDate(comment.getDate());+ pullRequestManager.save(request);+ }+ super.save(entity);+ }++ @Transactional+ @Listen+ public void on(CodeCommentCreated event) {+ CodeComment comment = event.getComment();+ ObjectId commitId = ObjectId.fromString(comment.getCommentPos().getCommit());+ for (String uuid: pullRequestInfoManager.getRequests(comment.getDepot(), commitId)) {+ PullRequest request = pullRequestManager.find(uuid);+ if (request != null && request.getRequestComparingInfo(comment.getComparingInfo()) != null) {+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(comment.getDate());+ lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommented.class));+ lastEvent.setUser(comment.getUser());+ request.setLastEvent(lastEvent);+ request.setLastCodeCommentEventDate(comment.getDate());+ pullRequestManager.save(request);++ visitInfoManager.visit(comment.getUser(), request);++ CodeCommentRelation relation = new CodeCommentRelation();+ relation.setComment(comment);+ relation.setRequest(request);+ save(relation);+ }+ }+ }++}diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.javaindex e69fdf13cf..8bce0cfc20 100644--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestManager.java@@ -1,910 +1,910 @@-package com.pmease.gitplex.core.manager.impl;--import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofOpen;-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSource;-import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTarget;-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_ALWAYS;-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;-import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_APPROVAL;-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_UPDATE;--import java.util.Collection;-import java.util.Date;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.concurrent.Callable;-import java.util.concurrent.atomic.AtomicLong;--import javax.annotation.Nullable;-import javax.inject.Inject;-import javax.inject.Singleton;--import org.apache.shiro.subject.Subject;-import org.apache.shiro.util.ThreadContext;-import org.apache.wicket.request.cycle.RequestCycle;-import org.eclipse.jgit.lib.CommitBuilder;-import org.eclipse.jgit.lib.ObjectId;-import org.eclipse.jgit.lib.ObjectInserter;-import org.eclipse.jgit.lib.PersonIdent;-import org.eclipse.jgit.lib.RefUpdate;-import org.eclipse.jgit.revwalk.RevCommit;-import org.eclipse.jgit.revwalk.RevWalk;-import org.hibernate.Query;-import org.hibernate.criterion.Criterion;-import org.hibernate.criterion.Restrictions;-import org.slf4j.Logger;-import org.slf4j.LoggerFactory;--import com.google.common.base.Preconditions;-import com.google.common.base.Throwables;-import com.google.common.collect.Lists;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.hibernate.Sessional;-import com.pmease.commons.hibernate.Transactional;-import com.pmease.commons.hibernate.UnitOfWork;-import com.pmease.commons.hibernate.dao.AbstractEntityManager;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.hibernate.dao.EntityCriteria;-import com.pmease.commons.loader.Listen;-import com.pmease.commons.loader.ListenerRegistry;-import com.pmease.commons.markdown.MarkdownManager;-import com.pmease.commons.util.concurrent.Prioritized;-import com.pmease.commons.util.match.PatternMatcher;-import com.pmease.commons.wicket.editable.EditableUtils;-import com.pmease.gitplex.core.entity.Account;-import com.pmease.gitplex.core.entity.CodeCommentRelation;-import com.pmease.gitplex.core.entity.CodeCommentReply;-import com.pmease.gitplex.core.entity.Depot;-import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;-import com.pmease.gitplex.core.entity.PullRequestUpdate;-import com.pmease.gitplex.core.entity.support.CloseInfo;-import com.pmease.gitplex.core.entity.support.DepotAndBranch;-import com.pmease.gitplex.core.entity.support.IntegrationPolicy;-import com.pmease.gitplex.core.entity.support.IntegrationPreview;-import com.pmease.gitplex.core.entity.support.LastEvent;-import com.pmease.gitplex.core.event.RefUpdated;-import com.pmease.gitplex.core.event.codecomment.CodeCommentReplied;-import com.pmease.gitplex.core.event.codecomment.CodeCommentResolved;-import com.pmease.gitplex.core.event.codecomment.CodeCommentUnresolved;-import com.pmease.gitplex.core.event.depot.DepotDeleted;-import com.pmease.gitplex.core.event.pullrequest.IntegrationPreviewCalculated;-import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;-import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;-import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentReplied;-import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentResolved;-import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentUnresolved;-import com.pmease.gitplex.core.event.pullrequest.PullRequestCommented;-import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;-import com.pmease.gitplex.core.event.pullrequest.PullRequestDiscarded;-import com.pmease.gitplex.core.event.pullrequest.PullRequestIntegrated;-import com.pmease.gitplex.core.event.pullrequest.PullRequestOpened;-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;-import com.pmease.gitplex.core.event.pullrequest.PullRequestReopened;-import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;-import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;-import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;-import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationDeleted;-import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationFailed;-import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationSucceeded;-import com.pmease.gitplex.core.event.pullrequest.SourceBranchDeleted;-import com.pmease.gitplex.core.event.pullrequest.SourceBranchRestored;-import com.pmease.gitplex.core.manager.AccountManager;-import com.pmease.gitplex.core.manager.BatchWorkManager;-import com.pmease.gitplex.core.manager.NotificationManager;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;-import com.pmease.gitplex.core.manager.PullRequestUpdateManager;-import com.pmease.gitplex.core.manager.support.BatchWorker;-import com.pmease.gitplex.core.security.SecurityUtils;-import com.pmease.gitplex.core.util.ChildAwareMatcher;-import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;-import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;--@Singleton-public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest> implements PullRequestManager {-- private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);-- private static final int UI_PREVIEW_PRIORITY = 10;-- private static final int BACKEND_PREVIEW_PRIORITY = 50;-- private static final PatternMatcher BRANCH_MATCHER = new ChildAwareMatcher();-- private final PullRequestUpdateManager pullRequestUpdateManager;-- private final AccountManager accountManager;-- private final UnitOfWork unitOfWork;-- private final ListenerRegistry listenerRegistry;-- private final PullRequestReviewInvitationManager reviewInvitationManager;-- private final BatchWorkManager batchWorkManager;-- private final Map<String, AtomicLong> nextNumbers = new HashMap<>();-- @Inject- public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,- PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,- NotificationManager notificationManager, MarkdownManager markdownManager,- BatchWorkManager batchWorkManager, ListenerRegistry listenerRegistry,- UnitOfWork unitOfWork) {- super(dao);-- this.pullRequestUpdateManager = pullRequestUpdateManager;- this.reviewInvitationManager = reviewInvitationManager;- this.accountManager = accountManager;- this.batchWorkManager = batchWorkManager;- this.unitOfWork = unitOfWork;- this.listenerRegistry = listenerRegistry;- }-- @Transactional- @Override- public void delete(PullRequest request) {- deleteRefs(request);- dao.remove(request);- }-- @Sessional- @Override- public void deleteRefs(PullRequest request) {- for (PullRequestUpdate update : request.getUpdates())- update.deleteRefs();-- request.deleteRefs();- }-- @Transactional- @Override- public void restoreSourceBranch(PullRequest request, String note) {- Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);- if (request.getSource().getObjectName(false) == null) {- RevCommit latestCommit = request.getLatestUpdate().getHeadCommit();- try {- request.getSourceDepot().git().branchCreate().setName(request.getSourceBranch()).setStartPoint(latestCommit).call();- } catch (Exception e) {- Throwables.propagate(e);- }- request.getSourceDepot().cacheObjectId(request.getSourceBranch(), latestCommit.copy());- listenerRegistry.notify(new SourceBranchRestored(request, accountManager.getCurrent(), note));- }- }-- @Transactional- @Override- public void deleteSourceBranch(PullRequest request, String note) {- Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);-- if (request.getSource().getObjectName(false) != null) {- request.getSource().delete();- listenerRegistry.notify(new SourceBranchDeleted(request, accountManager.getCurrent(), note));- }- }-- @Transactional- @Override- public void reopen(PullRequest request, String note) {- Preconditions.checkState(!request.isOpen(), "Pull request is alreay opened");- updateIfNecessary(request, false);- Account user = accountManager.getCurrent();- if (request.isMerged()) {- closeAsIntegrated(request, true, null);- } else {- request.setCloseInfo(null);-- save(request);- checkAsync(request);-- listenerRegistry.notify(new PullRequestReopened(request, user, note));- }- }-- @Transactional- @Override- public void discard(PullRequest request, String note) {- Account user = accountManager.getCurrent();-- CloseInfo closeInfo = new CloseInfo();- closeInfo.setCloseDate(new Date());- closeInfo.setClosedBy(user);- closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);- request.setCloseInfo(closeInfo);-- dao.persist(request);-- listenerRegistry.notify(new PullRequestDiscarded(request, user, note));- }-- @Transactional- @Override- public void integrate(PullRequest request, String note) {- if (request.getStatus() != PENDING_INTEGRATE)- throw new IllegalStateException("Gate keeper disallows integration right now.");-- IntegrationPreview preview = request.getIntegrationPreview();- if (preview == null)- throw new IllegalStateException("Integration preview has not been calculated yet.");-- String integrated = preview.getIntegrated();- if (integrated == null)- throw new IllegalStateException("There are integration conflicts.");-- Account user = accountManager.getCurrent();-- closeAsIntegrated(request, false, note);-- ObjectId integratedCommitId = ObjectId.fromString(integrated);- RevCommit integratedCommit = request.getTargetDepot().getRevCommit(integratedCommitId);-- Depot targetDepot = request.getTargetDepot();- IntegrationStrategy strategy = request.getIntegrationStrategy();- if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)- && !preview.getIntegrated().equals(preview.getRequestHead())- && !integratedCommit.getFullMessage().equals(request.getCommitMessage())) {- try ( RevWalk revWalk = new RevWalk(targetDepot.getRepository());- ObjectInserter inserter = targetDepot.getRepository().newObjectInserter()) {- RevCommit commit = revWalk.parseCommit(ObjectId.fromString(integrated));- CommitBuilder newCommit = new CommitBuilder();- newCommit.setAuthor(commit.getAuthorIdent());- newCommit.setCommitter(user.asPerson());- newCommit.setMessage(request.getCommitMessage());- newCommit.setTreeId(commit.getTree());- newCommit.setParentIds(commit.getParents());- integrated = inserter.insert(newCommit).name();- inserter.flush();- } catch (Exception e) {- Throwables.propagate(e);- }- }-- integratedCommitId = ObjectId.fromString(integrated);- if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {- Depot sourceDepot = request.getSourceDepot();- RefUpdate refUpdate = sourceDepot.updateRef(request.getSourceRef());- refUpdate.setNewObjectId(integratedCommitId);- ObjectId requestHeadId = ObjectId.fromString(preview.getRequestHead());- refUpdate.setExpectedOldObjectId(requestHeadId);- refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);- GitUtils.updateRef(refUpdate);-- updateIfNecessary(request, false);-- Long requestId = request.getId();- Subject subject = SecurityUtils.getSubject();- ObjectId newCommitId = integratedCommitId;- doUnitOfWorkAfterCommitAsync(new Runnable() {-- @Override- public void run() {- ThreadContext.bind(subject);- try {- PullRequest request = load(requestId);- request.getSourceDepot().cacheObjectId(request.getSourceRef(), newCommitId);- listenerRegistry.notify(new RefUpdated(- request.getSourceDepot(), request.getSourceRef(), requestHeadId, newCommitId));- } finally {- ThreadContext.unbindSubject();- }- }-- });- }-- String targetRef = request.getTargetRef();- ObjectId targetHeadId = ObjectId.fromString(preview.getTargetHead());- RefUpdate refUpdate = targetDepot.updateRef(targetRef);- refUpdate.setRefLogIdent(user.asPerson());- refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);- refUpdate.setExpectedOldObjectId(targetHeadId);- refUpdate.setNewObjectId(integratedCommitId);- GitUtils.updateRef(refUpdate);-- Long requestId = request.getId();- Subject subject = SecurityUtils.getSubject();- ObjectId newCommitId = integratedCommitId;- doUnitOfWorkAfterCommitAsync(new Runnable() {-- @Override- public void run() {- ThreadContext.bind(subject);- try {- PullRequest request = load(requestId);- request.getTargetDepot().cacheObjectId(request.getTargetRef(), newCommitId);- listenerRegistry.notify(new RefUpdated(request.getTargetDepot(), targetRef,- ObjectId.fromString(preview.getTargetHead()), newCommitId));- } finally {- ThreadContext.unbindSubject();- }- }-- });- }-- private long getNextNumber(Depot depot) {- AtomicLong nextNumber;- synchronized (nextNumbers) {- nextNumber = nextNumbers.get(depot.getUUID());- }- if (nextNumber == null) {- long maxNumber;- Query query = getSession().createQuery("select max(number) from PullRequest where targetDepot=:depot");- query.setParameter("depot", depot);- Object result = query.uniqueResult();- if (result != null) {- maxNumber = (Long)result;- } else {- maxNumber = 0;- }-- /*- * do not put the whole method in synchronized block to avoid possible deadlocks- * if there are limited connections.- */- synchronized (nextNumbers) {- nextNumber = nextNumbers.get(depot.getUUID());- if (nextNumber == null) {- nextNumber = new AtomicLong(maxNumber+1);- nextNumbers.put(depot.getUUID(), nextNumber);- }- }- }- return nextNumber.getAndIncrement();- }-- @Transactional- @Override- public void open(PullRequest request) {- request.setNumber(getNextNumber(request.getTargetDepot()));- dao.persist(request);-- RefUpdate refUpdate = request.getTargetDepot().updateRef(request.getBaseRef());- refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));- GitUtils.updateRef(refUpdate);-- for (PullRequestUpdate update: request.getUpdates()) {- pullRequestUpdateManager.save(update, false);- }-- for (PullRequestReviewInvitation invitation: request.getReviewInvitations())- reviewInvitationManager.save(invitation);-- doAfterCommit(new Runnable() {-- @Override- public void run() {- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(UI_PREVIEW_PRIORITY));- }-- });-- listenerRegistry.notify(new PullRequestOpened(request));- }-- @Override- public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {- List<IntegrationStrategy> strategies = null;- for (IntegrationPolicy policy: request.getTargetDepot().getIntegrationPolicies()) {- if (IncludeExcludeUtils.getIncludeExclude(policy.getTargetBranchMatch()).matches(BRANCH_MATCHER, request.getTargetBranch())- && FullBranchMatchUtils.matches(policy.getSourceBranchMatch(), request.getTargetDepot(), request.getSource())) {- strategies = policy.getIntegrationStrategies();- break;- }- }- if (strategies == null)- strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);- return strategies;- }-- @Transactional- @Override- public void changeAssignee(PullRequest request) {- dao.persist(request);-- if (request.isOpen()) {- String note = request.getAssignee().getDisplayName() + " is expected to integrate the pull request";- listenerRegistry.notify(new PullRequestAssigned(request, accountManager.getCurrent(), note));- }- }-- private void onTargetBranchUpdate(PullRequest request) {- String targetHead = request.getTarget().getObjectName();- if (request.getLastIntegrationPreview() == null || !request.getLastIntegrationPreview().getTargetHead().equals(targetHead)) {- if (request.isMerged()) {- closeAsIntegrated(request, true, null);- }- if (request.isOpen()) {- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(BACKEND_PREVIEW_PRIORITY));- }- }- }-- private void closeAsIntegrated(PullRequest request, boolean dueToMerged, String note) {- Account user = accountManager.getCurrent();-- if (dueToMerged)- request.setLastIntegrationPreview(null);-- CloseInfo closeInfo = new CloseInfo();- closeInfo.setCloseDate(new Date());- closeInfo.setClosedBy(user);- closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);- request.setCloseInfo(closeInfo);-- dao.persist(request);-- if (dueToMerged)- note = "Source branch is already merged to target branch by some one";- listenerRegistry.notify(new PullRequestIntegrated(request, user, note));- }-- private void updateIfNecessary(PullRequest request, boolean notifyListeners) {- if (!request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getObjectName())) {- PullRequestUpdate update = new PullRequestUpdate();- update.setRequest(request);- update.setHeadCommitHash(request.getSource().getObjectName());- request.addUpdate(update);- pullRequestUpdateManager.save(update, notifyListeners);- }- }-- /**- * This method might take some time and is not key to pull request logic (even if we- * did not call it, we can always call it later), so normally should be called in an- * executor- */- @Sessional- @Override- public void check(PullRequest request) {- if (request.isOpen()) {- if (request.isMerged()) {- closeAsIntegrated(request, true, null);- } else {- if (request.getStatus() == PENDING_UPDATE) {- listenerRegistry.notify(new PullRequestPendingUpdate(request));- } else if (request.getStatus() == PENDING_INTEGRATE) {- IntegrationPreview integrationPreview = request.getIntegrationPreview();- if (integrationPreview != null- && integrationPreview.getIntegrated() != null- && request.getAssignee() == null) {- integrate(request, "Integrated automatically by system");- } else {- listenerRegistry.notify(new PullRequestPendingIntegration(request));- }- } else if (request.getStatus() == PENDING_APPROVAL) {- Date now = new Date();- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {- if (!invitation.getDate().before(now))- reviewInvitationManager.save(invitation);- }- listenerRegistry.notify(new PullRequestPendingApproval(request));- }- }- }- }-- @Override- public boolean canIntegrate(PullRequest request) {- if (request.getStatus() != PENDING_INTEGRATE) {- return false;- } else {- IntegrationPreview integrationPreview = request.getIntegrationPreview();- return integrationPreview != null && integrationPreview.getIntegrated() != null;- }- }-- @Override- public IntegrationPreview previewIntegration(PullRequest request) {- IntegrationPreview preview = request.getLastIntegrationPreview();- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {- int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));- return null;- } else {- return preview;- }- }-- private BatchWorker getIntegrationPreviewer(PullRequest request) {- Long requestId = request.getId();- return new BatchWorker("request-" + requestId + "-previewIntegration", 1) {-- @Override- public void doWork(Collection<Prioritized> works) {- Preconditions.checkState(works.size() == 1);- unitOfWork.call(new Callable<Void>() {-- @Override- public Void call() throws Exception {- PullRequest request = load(requestId);- try {- IntegrationPreview preview = request.getLastIntegrationPreview();- if (request.isOpen() && (preview == null || preview.isObsolete(request))) {- logger.info("Calculating integration preview of pull request #{} in repository '{}'...",- request.getNumber(), request.getTargetDepot());- String requestHead = request.getLatestUpdate().getHeadCommitHash();- String targetHead = request.getTarget().getObjectName();- Depot targetDepot = request.getTargetDepot();- preview = new IntegrationPreview(targetHead,- request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);- request.setLastIntegrationPreview(preview);- String integrateRef = request.getIntegrateRef();- if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && targetDepot.isMergedInto(targetHead, requestHead)) {- preview.setIntegrated(requestHead);- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);- refUpdate.setNewObjectId(ObjectId.fromString(requestHead));- GitUtils.updateRef(refUpdate);- } else {- PersonIdent user = accountManager.getRoot().asPerson();- ObjectId integrated;- ObjectId requestHeadId = ObjectId.fromString(requestHead);- ObjectId targetHeadId = ObjectId.fromString(targetHead);- if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {- integrated = GitUtils.rebase(targetDepot.getRepository(), targetHeadId, requestHeadId, user);- } else if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {- integrated = GitUtils.rebase(targetDepot.getRepository(), requestHeadId, targetHeadId, user);- } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {- integrated = GitUtils.merge(targetDepot.getRepository(),- requestHeadId, targetHeadId, true, user, request.getCommitMessage());- } else {- integrated = GitUtils.merge(targetDepot.getRepository(),- requestHeadId, targetHeadId, false, user, request.getCommitMessage());- }-- if (integrated != null) {- preview.setIntegrated(integrated.name());- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);- refUpdate.setNewObjectId(integrated);- GitUtils.updateRef(refUpdate);- } else {- RefUpdate refUpdate = targetDepot.updateRef(integrateRef);- GitUtils.deleteRef(refUpdate);- }- }- dao.persist(request);-- if (request.getStatus() == PENDING_INTEGRATE- && preview.getIntegrated() != null- && request.getAssignee() == null) {- integrate(request, "Integrated automatically by GitPlex");- }-- listenerRegistry.notify(new IntegrationPreviewCalculated(request));- logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",- request.getNumber(), request.getTargetDepot());- }- } catch (Exception e) {- logger.error("Error calculating pull request integration preview", e);- }- return null;- }-- });- }-- };- }-- @Transactional- @Listen- public void on(DepotDeleted event) {- for (PullRequest request: event.getDepot().getOutgoingRequests()) {- if (!request.getTargetDepot().equals(event.getDepot()) && request.isOpen())- discard(request, "Source repository is deleted.");- }-- Query query = getSession().createQuery("update PullRequest set sourceDepot=null where "- + "sourceDepot=:depot");- query.setParameter("depot", event.getDepot());- query.executeUpdate();- }-- @Transactional- @Listen- public void on(RefUpdated event) {- String branch = GitUtils.ref2branch(event.getRefName());- if (branch != null) {- DepotAndBranch depotAndBranch = new DepotAndBranch(event.getDepot(), branch);- if (!event.getNewCommit().equals(ObjectId.zeroId())) {- Criterion criterion = Restrictions.and(ofOpen(), ofSource(depotAndBranch));- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (event.getDepot().getObjectId(request.getBaseCommitHash(), false) != null) {- updateIfNecessary(request, true);- if (request.isMerged()) {- closeAsIntegrated(request, true, null);- } else {- checkAsync(request);- }- } else {- logger.error("Unable to update pull request #{} due to unexpected source repository.", request.getNumber());- }- }-- depotAndBranch = new DepotAndBranch(event.getDepot(), branch);- criterion = Restrictions.and(ofOpen(), ofTarget(depotAndBranch));- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (request.getSourceDepot().getObjectId(request.getBaseCommitHash(), false) != null)- onTargetBranchUpdate(request);- else- logger.error("Unable to update pull request #{} due to unexpected target repository.", request.getNumber());- }- } else {- Criterion criterion = Restrictions.and(- ofOpen(),- Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));- for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {- if (request.getTargetDepot().equals(event.getDepot()) && request.getTargetBranch().equals(branch))- discard(request, "Target branch is deleted.");- else- discard(request, "Source branch is deleted.");- }- }- }- }-- @Sessional- @Override- public PullRequest findOpen(DepotAndBranch target, DepotAndBranch source) {- return find(EntityCriteria.of(PullRequest.class)- .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));- }-- @Sessional- @Override- public Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofTarget(target));-- if (sourceDepot != null)- criteria.add(Restrictions.eq("sourceDepot", sourceDepot));- criteria.add(ofOpen());- return findAll(criteria);- }-- @Sessional- @Override- public Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofSource(source));-- if (targetDepot != null)- criteria.add(Restrictions.eq("targetDepot", targetDepot));- criteria.add(ofOpen());- return findAll(criteria);- }-- @Sessional- @Override- public Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget) {- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofOpen());- criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));- return findAll(criteria);- }-- @Sessional- @Override- public void checkSanity() {- logger.info("Checking sanity of pull requests...");-- EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);- criteria.add(ofOpen());- for (PullRequest request: findAll(criteria)) {- Depot sourceDepot = request.getSourceDepot();- if (sourceDepot == null) {- discard(request, "Source repository is deleted.");- } else if (sourceDepot.isValid()) {- String baseCommitHash = request.getBaseCommitHash();-- // only modifies pull request status if source repository is the repository we- // previously worked with. This avoids disaster of closing all pull requests- // if repository storage points to a different location by mistake- if (sourceDepot.getObjectId(baseCommitHash, false) != null) {- String sourceHead = request.getSource().getObjectName(false);- if (sourceHead == null) {- discard(request, "Source branch is deleted.");- } else {- updateIfNecessary(request, false);- if (request.isMerged()) {- closeAsIntegrated(request, true, null);- } else {- checkAsync(request);- }- }- } else {- logger.error("Unable to update pull request #{} due to unexpected source repository", request.getNumber());- }- }-- if (request.isOpen()) {- Depot targetDepot = request.getTargetDepot();- if (targetDepot.isValid()) {- String baseCommitHash = request.getBaseCommitHash();-- // only modifies pull request status if target repository is the repository we- // previously worked with. This avoids disaster of closing all pull requests- // if repository storage points to a different location by mistake- if (targetDepot.getObjectId(baseCommitHash, false) != null) {- String targetHead = request.getTarget().getObjectName(false);- if (targetHead == null)- discard(request, "Target branch is deleted.");- else- onTargetBranchUpdate(request);- } else {- logger.error("Unable to update pull request #{} due to unexpected target repository", request.getNumber());- }- }- }- }- }-- @Sessional- @Override- public int countOpen(Depot depot) {- EntityCriteria<PullRequest> criteria = newCriteria();- criteria.add(PullRequest.CriterionHelper.ofOpen());- criteria.add(PullRequest.CriterionHelper.ofTargetDepot(depot));- return count(criteria);- }-- @Sessional- @Override- public PullRequest find(Depot target, long number) {- EntityCriteria<PullRequest> criteria = newCriteria();- criteria.add(Restrictions.eq("targetDepot", target));- criteria.add(Restrictions.eq("number", number));- return find(criteria);- }-- @Sessional- @Override- public PullRequest find(String uuid) {- EntityCriteria<PullRequest> criteria = newCriteria();- criteria.add(Restrictions.eq("uuid", uuid));- return find(criteria);- }-- @Listen- public void on(CodeCommentReplied event) {- CodeCommentReply reply = event.getReply();- for (CodeCommentRelation relation: reply.getComment().getRelations()) {- PullRequest request = relation.getRequest();- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(reply.getDate());- lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentReplied.class));- lastEvent.setUser(reply.getUser());- request.setLastEvent(lastEvent);- request.setLastCodeCommentEventDate(reply.getDate());- save(request);- }- }-- @Listen- public void on(CodeCommentResolved event) {- for (CodeCommentRelation relation: event.getComment().getRelations()) {- PullRequest request = relation.getRequest();-- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(new Date());- lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentResolved.class));- lastEvent.setUser(event.getUser());- request.setLastEvent(lastEvent);- request.setLastCodeCommentEventDate(lastEvent.getDate());- save(request);- }- }-- @Listen- public void on(CodeCommentUnresolved event) {- for (CodeCommentRelation relation: event.getComment().getRelations()) {- PullRequest request = relation.getRequest();- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(new Date());- lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentUnresolved.class));- lastEvent.setUser(event.getUser());- request.setLastEvent(lastEvent);- request.setLastCodeCommentEventDate(lastEvent.getDate());- save(request);- }- }-- @Transactional- @Listen- public void on(PullRequestUpdated event) {- PullRequest request = event.getRequest();-- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(event.getUpdate().getDate());- lastEvent.setDescription(EditableUtils.getName(event.getClass()));- request.setLastEvent(lastEvent);- save(request);- }-- @Transactional- @Listen- public void on(PullRequestCommented event) {- PullRequest request = event.getRequest();- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(event.getComment().getDate());- lastEvent.setDescription(EditableUtils.getName(event.getClass()));- lastEvent.setUser(event.getComment().getUser());- request.setLastEvent(lastEvent);- save(request);- }-- @Listen- public void on(PullRequestVerificationSucceeded event) {- checkAsync(event.getRequest());- }-- @Listen- public void on(PullRequestVerificationFailed event) {- checkAsync(event.getRequest());- }-- @Transactional- @Listen- public void on(PullRequestApproved event) {- checkAsync(event.getRequest());- }-- @Transactional- @Listen- public void on(PullRequestDisapproved event) {- checkAsync(event.getRequest());- }-- @Transactional- @Listen- public void on(PullRequestVerificationDeleted event) {- checkAsync(event.getRequest());- }-- @Transactional- @Listen- public void on(PullRequestReviewDeleted event) {- checkAsync(event.getRequest());- }-- @Transactional- @Listen- public void on(PullRequestStatusChangeEvent event) {- LastEvent lastEvent = new LastEvent();- lastEvent.setDate(new Date());- lastEvent.setDescription(EditableUtils.getName(event.getClass()));- lastEvent.setUser(event.getUser());- event.getRequest().setLastEvent(lastEvent);- save(event.getRequest());- }-- @Sessional- private void checkAsync(PullRequest request) {- Long requestId = request.getId();- Subject subject = SecurityUtils.getSubject();- doUnitOfWorkAfterCommitAsync(new Runnable() {-- @Override- public void run() {- try {- ThreadContext.bind(subject);- check(load(requestId));- } finally {- ThreadContext.unbindSubject();- }- }-- });- }--}+package com.pmease.gitplex.core.manager.impl;++import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofOpen;+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofSource;+import static com.pmease.gitplex.core.entity.PullRequest.CriterionHelper.ofTarget;+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_ALWAYS;+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_IF_NECESSARY;+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.MERGE_WITH_SQUASH;+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_SOURCE_ONTO_TARGET;+import static com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy.REBASE_TARGET_ONTO_SOURCE;+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_APPROVAL;+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_UPDATE;++import java.util.Collection;+import java.util.Date;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.Callable;+import java.util.concurrent.atomic.AtomicLong;++import javax.annotation.Nullable;+import javax.inject.Inject;+import javax.inject.Singleton;++import org.apache.shiro.subject.Subject;+import org.apache.shiro.util.ThreadContext;+import org.apache.wicket.request.cycle.RequestCycle;+import org.eclipse.jgit.lib.CommitBuilder;+import org.eclipse.jgit.lib.ObjectId;+import org.eclipse.jgit.lib.ObjectInserter;+import org.eclipse.jgit.lib.PersonIdent;+import org.eclipse.jgit.lib.RefUpdate;+import org.eclipse.jgit.revwalk.RevCommit;+import org.eclipse.jgit.revwalk.RevWalk;+import org.hibernate.Query;+import org.hibernate.criterion.Criterion;+import org.hibernate.criterion.Restrictions;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++import com.google.common.base.Preconditions;+import com.google.common.base.Throwables;+import com.google.common.collect.Lists;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.hibernate.Sessional;+import com.pmease.commons.hibernate.Transactional;+import com.pmease.commons.hibernate.UnitOfWork;+import com.pmease.commons.hibernate.dao.AbstractEntityManager;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.hibernate.dao.EntityCriteria;+import com.pmease.commons.loader.Listen;+import com.pmease.commons.loader.ListenerRegistry;+import com.pmease.commons.markdown.MarkdownManager;+import com.pmease.commons.util.concurrent.Prioritized;+import com.pmease.commons.util.match.PatternMatcher;+import com.pmease.commons.wicket.editable.EditableUtils;+import com.pmease.gitplex.core.entity.Account;+import com.pmease.gitplex.core.entity.CodeCommentRelation;+import com.pmease.gitplex.core.entity.CodeCommentReply;+import com.pmease.gitplex.core.entity.Depot;+import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;+import com.pmease.gitplex.core.entity.PullRequestUpdate;+import com.pmease.gitplex.core.entity.support.CloseInfo;+import com.pmease.gitplex.core.entity.support.DepotAndBranch;+import com.pmease.gitplex.core.entity.support.IntegrationPolicy;+import com.pmease.gitplex.core.entity.support.IntegrationPreview;+import com.pmease.gitplex.core.entity.support.LastEvent;+import com.pmease.gitplex.core.event.RefUpdated;+import com.pmease.gitplex.core.event.codecomment.CodeCommentReplied;+import com.pmease.gitplex.core.event.codecomment.CodeCommentResolved;+import com.pmease.gitplex.core.event.codecomment.CodeCommentUnresolved;+import com.pmease.gitplex.core.event.depot.DepotDeleted;+import com.pmease.gitplex.core.event.pullrequest.IntegrationPreviewCalculated;+import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;+import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;+import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentReplied;+import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentResolved;+import com.pmease.gitplex.core.event.pullrequest.PullRequestCodeCommentUnresolved;+import com.pmease.gitplex.core.event.pullrequest.PullRequestCommented;+import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;+import com.pmease.gitplex.core.event.pullrequest.PullRequestDiscarded;+import com.pmease.gitplex.core.event.pullrequest.PullRequestIntegrated;+import com.pmease.gitplex.core.event.pullrequest.PullRequestOpened;+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingApproval;+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;+import com.pmease.gitplex.core.event.pullrequest.PullRequestReopened;+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;+import com.pmease.gitplex.core.event.pullrequest.PullRequestStatusChangeEvent;+import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;+import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationDeleted;+import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationFailed;+import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationSucceeded;+import com.pmease.gitplex.core.event.pullrequest.SourceBranchDeleted;+import com.pmease.gitplex.core.event.pullrequest.SourceBranchRestored;+import com.pmease.gitplex.core.manager.AccountManager;+import com.pmease.gitplex.core.manager.BatchWorkManager;+import com.pmease.gitplex.core.manager.NotificationManager;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;+import com.pmease.gitplex.core.manager.PullRequestUpdateManager;+import com.pmease.gitplex.core.manager.support.BatchWorker;+import com.pmease.gitplex.core.security.SecurityUtils;+import com.pmease.gitplex.core.util.ChildAwareMatcher;+import com.pmease.gitplex.core.util.fullbranchmatch.FullBranchMatchUtils;+import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;++@Singleton+public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest> implements PullRequestManager {++ private static final Logger logger = LoggerFactory.getLogger(DefaultPullRequestManager.class);++ private static final int UI_PREVIEW_PRIORITY = 10;++ private static final int BACKEND_PREVIEW_PRIORITY = 50;++ private static final PatternMatcher BRANCH_MATCHER = new ChildAwareMatcher();++ private final PullRequestUpdateManager pullRequestUpdateManager;++ private final AccountManager accountManager;++ private final UnitOfWork unitOfWork;++ private final ListenerRegistry listenerRegistry;++ private final PullRequestReviewInvitationManager reviewInvitationManager;++ private final BatchWorkManager batchWorkManager;++ private final Map<String, AtomicLong> nextNumbers = new HashMap<>();++ @Inject+ public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,+ PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,+ NotificationManager notificationManager, MarkdownManager markdownManager,+ BatchWorkManager batchWorkManager, ListenerRegistry listenerRegistry,+ UnitOfWork unitOfWork) {+ super(dao);++ this.pullRequestUpdateManager = pullRequestUpdateManager;+ this.reviewInvitationManager = reviewInvitationManager;+ this.accountManager = accountManager;+ this.batchWorkManager = batchWorkManager;+ this.unitOfWork = unitOfWork;+ this.listenerRegistry = listenerRegistry;+ }++ @Transactional+ @Override+ public void delete(PullRequest request) {+ deleteRefs(request);+ dao.remove(request);+ }++ @Sessional+ @Override+ public void deleteRefs(PullRequest request) {+ for (PullRequestUpdate update : request.getUpdates())+ update.deleteRefs();++ request.deleteRefs();+ }++ @Transactional+ @Override+ public void restoreSourceBranch(PullRequest request, String note) {+ Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);+ if (request.getSource().getObjectName(false) == null) {+ RevCommit latestCommit = request.getLatestUpdate().getHeadCommit();+ try {+ request.getSourceDepot().git().branchCreate().setName(request.getSourceBranch()).setStartPoint(latestCommit).call();+ } catch (Exception e) {+ Throwables.propagate(e);+ }+ request.getSourceDepot().cacheObjectId(request.getSourceBranch(), latestCommit.copy());+ listenerRegistry.notify(new SourceBranchRestored(request, accountManager.getCurrent(), note));+ }+ }++ @Transactional+ @Override+ public void deleteSourceBranch(PullRequest request, String note) {+ Preconditions.checkState(!request.isOpen() && request.getSourceDepot() != null);++ if (request.getSource().getObjectName(false) != null) {+ request.getSource().delete();+ listenerRegistry.notify(new SourceBranchDeleted(request, accountManager.getCurrent(), note));+ }+ }++ @Transactional+ @Override+ public void reopen(PullRequest request, String note) {+ Preconditions.checkState(!request.isOpen(), "Pull request is alreay opened");+ updateIfNecessary(request, false);+ Account user = accountManager.getCurrent();+ if (request.isMerged()) {+ closeAsIntegrated(request, true, null);+ } else {+ request.setCloseInfo(null);++ save(request);+ checkAsync(request);++ listenerRegistry.notify(new PullRequestReopened(request, user, note));+ }+ }++ @Transactional+ @Override+ public void discard(PullRequest request, String note) {+ Account user = accountManager.getCurrent();++ CloseInfo closeInfo = new CloseInfo();+ closeInfo.setCloseDate(new Date());+ closeInfo.setClosedBy(user);+ closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);+ request.setCloseInfo(closeInfo);++ dao.persist(request);++ listenerRegistry.notify(new PullRequestDiscarded(request, user, note));+ }++ @Transactional+ @Override+ public void integrate(PullRequest request, String note) {+ if (request.getStatus() != PENDING_INTEGRATE)+ throw new IllegalStateException("Gate keeper disallows integration right now.");++ IntegrationPreview preview = request.getIntegrationPreview();+ if (preview == null)+ throw new IllegalStateException("Integration preview has not been calculated yet.");++ String integrated = preview.getIntegrated();+ if (integrated == null)+ throw new IllegalStateException("There are integration conflicts.");++ Account user = accountManager.getCurrent();++ closeAsIntegrated(request, false, note);++ ObjectId integratedCommitId = ObjectId.fromString(integrated);+ RevCommit integratedCommit = request.getTargetDepot().getRevCommit(integratedCommitId);++ Depot targetDepot = request.getTargetDepot();+ IntegrationStrategy strategy = request.getIntegrationStrategy();+ if ((strategy == MERGE_ALWAYS || strategy == MERGE_IF_NECESSARY || strategy == MERGE_WITH_SQUASH)+ && !preview.getIntegrated().equals(preview.getRequestHead())+ && !integratedCommit.getFullMessage().equals(request.getCommitMessage())) {+ try ( RevWalk revWalk = new RevWalk(targetDepot.getRepository());+ ObjectInserter inserter = targetDepot.getRepository().newObjectInserter()) {+ RevCommit commit = revWalk.parseCommit(ObjectId.fromString(integrated));+ CommitBuilder newCommit = new CommitBuilder();+ newCommit.setAuthor(commit.getAuthorIdent());+ newCommit.setCommitter(user.asPerson());+ newCommit.setMessage(request.getCommitMessage());+ newCommit.setTreeId(commit.getTree());+ newCommit.setParentIds(commit.getParents());+ integrated = inserter.insert(newCommit).name();+ inserter.flush();+ } catch (Exception e) {+ Throwables.propagate(e);+ }+ }++ integratedCommitId = ObjectId.fromString(integrated);+ if (strategy == REBASE_SOURCE_ONTO_TARGET || strategy == MERGE_WITH_SQUASH) {+ Depot sourceDepot = request.getSourceDepot();+ RefUpdate refUpdate = sourceDepot.updateRef(request.getSourceRef());+ refUpdate.setNewObjectId(integratedCommitId);+ ObjectId requestHeadId = ObjectId.fromString(preview.getRequestHead());+ refUpdate.setExpectedOldObjectId(requestHeadId);+ refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);+ GitUtils.updateRef(refUpdate);++ updateIfNecessary(request, false);++ Long requestId = request.getId();+ Subject subject = SecurityUtils.getSubject();+ ObjectId newCommitId = integratedCommitId;+ doUnitOfWorkAfterCommitAsync(new Runnable() {++ @Override+ public void run() {+ ThreadContext.bind(subject);+ try {+ PullRequest request = load(requestId);+ request.getSourceDepot().cacheObjectId(request.getSourceRef(), newCommitId);+ listenerRegistry.notify(new RefUpdated(+ request.getSourceDepot(), request.getSourceRef(), requestHeadId, newCommitId));+ } finally {+ ThreadContext.unbindSubject();+ }+ }++ });+ }++ String targetRef = request.getTargetRef();+ ObjectId targetHeadId = ObjectId.fromString(preview.getTargetHead());+ RefUpdate refUpdate = targetDepot.updateRef(targetRef);+ refUpdate.setRefLogIdent(user.asPerson());+ refUpdate.setRefLogMessage("Pull request #" + request.getNumber(), true);+ refUpdate.setExpectedOldObjectId(targetHeadId);+ refUpdate.setNewObjectId(integratedCommitId);+ GitUtils.updateRef(refUpdate);++ Long requestId = request.getId();+ Subject subject = SecurityUtils.getSubject();+ ObjectId newCommitId = integratedCommitId;+ doUnitOfWorkAfterCommitAsync(new Runnable() {++ @Override+ public void run() {+ ThreadContext.bind(subject);+ try {+ PullRequest request = load(requestId);+ request.getTargetDepot().cacheObjectId(request.getTargetRef(), newCommitId);+ listenerRegistry.notify(new RefUpdated(request.getTargetDepot(), targetRef,+ ObjectId.fromString(preview.getTargetHead()), newCommitId));+ } finally {+ ThreadContext.unbindSubject();+ }+ }++ });+ }++ private long getNextNumber(Depot depot) {+ AtomicLong nextNumber;+ synchronized (nextNumbers) {+ nextNumber = nextNumbers.get(depot.getUUID());+ }+ if (nextNumber == null) {+ long maxNumber;+ Query query = getSession().createQuery("select max(number) from PullRequest where targetDepot=:depot");+ query.setParameter("depot", depot);+ Object result = query.uniqueResult();+ if (result != null) {+ maxNumber = (Long)result;+ } else {+ maxNumber = 0;+ }++ /*+ * do not put the whole method in synchronized block to avoid possible deadlocks+ * if there are limited connections.+ */+ synchronized (nextNumbers) {+ nextNumber = nextNumbers.get(depot.getUUID());+ if (nextNumber == null) {+ nextNumber = new AtomicLong(maxNumber+1);+ nextNumbers.put(depot.getUUID(), nextNumber);+ }+ }+ }+ return nextNumber.getAndIncrement();+ }++ @Transactional+ @Override+ public void open(PullRequest request) {+ request.setNumber(getNextNumber(request.getTargetDepot()));+ dao.persist(request);++ RefUpdate refUpdate = request.getTargetDepot().updateRef(request.getBaseRef());+ refUpdate.setNewObjectId(ObjectId.fromString(request.getBaseCommitHash()));+ GitUtils.updateRef(refUpdate);++ for (PullRequestUpdate update: request.getUpdates()) {+ pullRequestUpdateManager.save(update, false);+ }++ for (PullRequestReviewInvitation invitation: request.getReviewInvitations())+ reviewInvitationManager.save(invitation);++ doAfterCommit(new Runnable() {++ @Override+ public void run() {+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(UI_PREVIEW_PRIORITY));+ }++ });++ listenerRegistry.notify(new PullRequestOpened(request));+ }++ @Override+ public List<IntegrationStrategy> getApplicableIntegrationStrategies(PullRequest request) {+ List<IntegrationStrategy> strategies = null;+ for (IntegrationPolicy policy: request.getTargetDepot().getIntegrationPolicies()) {+ if (IncludeExcludeUtils.getIncludeExclude(policy.getTargetBranchMatch()).matches(BRANCH_MATCHER, request.getTargetBranch())+ && FullBranchMatchUtils.matches(policy.getSourceBranchMatch(), request.getTargetDepot(), request.getSource())) {+ strategies = policy.getIntegrationStrategies();+ break;+ }+ }+ if (strategies == null)+ strategies = Lists.newArrayList(IntegrationStrategy.MERGE_ALWAYS);+ return strategies;+ }++ @Transactional+ @Override+ public void changeAssignee(PullRequest request) {+ dao.persist(request);++ if (request.isOpen()) {+ String note = request.getAssignee().getDisplayName() + " is expected to integrate the pull request";+ listenerRegistry.notify(new PullRequestAssigned(request, accountManager.getCurrent(), note));+ }+ }++ private void onTargetBranchUpdate(PullRequest request) {+ String targetHead = request.getTarget().getObjectName();+ if (request.getLastIntegrationPreview() == null || !request.getLastIntegrationPreview().getTargetHead().equals(targetHead)) {+ if (request.isMerged()) {+ closeAsIntegrated(request, true, null);+ }+ if (request.isOpen()) {+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(BACKEND_PREVIEW_PRIORITY));+ }+ }+ }++ private void closeAsIntegrated(PullRequest request, boolean dueToMerged, String note) {+ Account user = accountManager.getCurrent();++ if (dueToMerged)+ request.setLastIntegrationPreview(null);++ CloseInfo closeInfo = new CloseInfo();+ closeInfo.setCloseDate(new Date());+ closeInfo.setClosedBy(user);+ closeInfo.setCloseStatus(CloseInfo.Status.INTEGRATED);+ request.setCloseInfo(closeInfo);++ dao.persist(request);++ if (dueToMerged)+ note = "Source branch is already merged to target branch by some one";+ listenerRegistry.notify(new PullRequestIntegrated(request, user, note));+ }++ private void updateIfNecessary(PullRequest request, boolean notifyListeners) {+ if (!request.getLatestUpdate().getHeadCommitHash().equals(request.getSource().getObjectName())) {+ PullRequestUpdate update = new PullRequestUpdate();+ update.setRequest(request);+ update.setHeadCommitHash(request.getSource().getObjectName());+ request.addUpdate(update);+ pullRequestUpdateManager.save(update, notifyListeners);+ }+ }++ /**+ * This method might take some time and is not key to pull request logic (even if we+ * did not call it, we can always call it later), so normally should be called in an+ * executor+ */+ @Sessional+ @Override+ public void check(PullRequest request) {+ if (request.isOpen()) {+ if (request.isMerged()) {+ closeAsIntegrated(request, true, null);+ } else {+ if (request.getStatus() == PENDING_UPDATE) {+ listenerRegistry.notify(new PullRequestPendingUpdate(request));+ } else if (request.getStatus() == PENDING_INTEGRATE) {+ IntegrationPreview integrationPreview = request.getIntegrationPreview();+ if (integrationPreview != null+ && integrationPreview.getIntegrated() != null+ && request.getAssignee() == null) {+ integrate(request, "Integrated automatically by system");+ } else {+ listenerRegistry.notify(new PullRequestPendingIntegration(request));+ }+ } else if (request.getStatus() == PENDING_APPROVAL) {+ Date now = new Date();+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {+ if (invitation.getDate().getTime()>=now.getTime())+ reviewInvitationManager.save(invitation);+ }+ listenerRegistry.notify(new PullRequestPendingApproval(request));+ }+ }+ }+ }++ @Override+ public boolean canIntegrate(PullRequest request) {+ if (request.getStatus() != PENDING_INTEGRATE) {+ return false;+ } else {+ IntegrationPreview integrationPreview = request.getIntegrationPreview();+ return integrationPreview != null && integrationPreview.getIntegrated() != null;+ }+ }++ @Override+ public IntegrationPreview previewIntegration(PullRequest request) {+ IntegrationPreview preview = request.getLastIntegrationPreview();+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {+ int priority = RequestCycle.get() != null?UI_PREVIEW_PRIORITY:BACKEND_PREVIEW_PRIORITY;+ batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(priority));+ return null;+ } else {+ return preview;+ }+ }++ private BatchWorker getIntegrationPreviewer(PullRequest request) {+ Long requestId = request.getId();+ return new BatchWorker("request-" + requestId + "-previewIntegration", 1) {++ @Override+ public void doWork(Collection<Prioritized> works) {+ Preconditions.checkState(works.size() == 1);+ unitOfWork.call(new Callable<Void>() {++ @Override+ public Void call() throws Exception {+ PullRequest request = load(requestId);+ try {+ IntegrationPreview preview = request.getLastIntegrationPreview();+ if (request.isOpen() && (preview == null || preview.isObsolete(request))) {+ logger.info("Calculating integration preview of pull request #{} in repository '{}'...",+ request.getNumber(), request.getTargetDepot());+ String requestHead = request.getLatestUpdate().getHeadCommitHash();+ String targetHead = request.getTarget().getObjectName();+ Depot targetDepot = request.getTargetDepot();+ preview = new IntegrationPreview(targetHead,+ request.getLatestUpdate().getHeadCommitHash(), request.getIntegrationStrategy(), null);+ request.setLastIntegrationPreview(preview);+ String integrateRef = request.getIntegrateRef();+ if (preview.getIntegrationStrategy() == MERGE_IF_NECESSARY && targetDepot.isMergedInto(targetHead, requestHead)) {+ preview.setIntegrated(requestHead);+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);+ refUpdate.setNewObjectId(ObjectId.fromString(requestHead));+ GitUtils.updateRef(refUpdate);+ } else {+ PersonIdent user = accountManager.getRoot().asPerson();+ ObjectId integrated;+ ObjectId requestHeadId = ObjectId.fromString(requestHead);+ ObjectId targetHeadId = ObjectId.fromString(targetHead);+ if (preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE) {+ integrated = GitUtils.rebase(targetDepot.getRepository(), targetHeadId, requestHeadId, user);+ } else if (preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET) {+ integrated = GitUtils.rebase(targetDepot.getRepository(), requestHeadId, targetHeadId, user);+ } else if (preview.getIntegrationStrategy() == MERGE_WITH_SQUASH) {+ integrated = GitUtils.merge(targetDepot.getRepository(),+ requestHeadId, targetHeadId, true, user, request.getCommitMessage());+ } else {+ integrated = GitUtils.merge(targetDepot.getRepository(),+ requestHeadId, targetHeadId, false, user, request.getCommitMessage());+ }++ if (integrated != null) {+ preview.setIntegrated(integrated.name());+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);+ refUpdate.setNewObjectId(integrated);+ GitUtils.updateRef(refUpdate);+ } else {+ RefUpdate refUpdate = targetDepot.updateRef(integrateRef);+ GitUtils.deleteRef(refUpdate);+ }+ }+ dao.persist(request);++ if (request.getStatus() == PENDING_INTEGRATE+ && preview.getIntegrated() != null+ && request.getAssignee() == null) {+ integrate(request, "Integrated automatically by GitPlex");+ }++ listenerRegistry.notify(new IntegrationPreviewCalculated(request));+ logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",+ request.getNumber(), request.getTargetDepot());+ }+ } catch (Exception e) {+ logger.error("Error calculating pull request integration preview", e);+ }+ return null;+ }++ });+ }++ };+ }++ @Transactional+ @Listen+ public void on(DepotDeleted event) {+ for (PullRequest request: event.getDepot().getOutgoingRequests()) {+ if (!request.getTargetDepot().equals(event.getDepot()) && request.isOpen())+ discard(request, "Source repository is deleted.");+ }++ Query query = getSession().createQuery("update PullRequest set sourceDepot=null where "+ + "sourceDepot=:depot");+ query.setParameter("depot", event.getDepot());+ query.executeUpdate();+ }++ @Transactional+ @Listen+ public void on(RefUpdated event) {+ String branch = GitUtils.ref2branch(event.getRefName());+ if (branch != null) {+ DepotAndBranch depotAndBranch = new DepotAndBranch(event.getDepot(), branch);+ if (!event.getNewCommit().equals(ObjectId.zeroId())) {+ Criterion criterion = Restrictions.and(ofOpen(), ofSource(depotAndBranch));+ for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (event.getDepot().getObjectId(request.getBaseCommitHash(), false) != null) {+ updateIfNecessary(request, true);+ if (request.isMerged()) {+ closeAsIntegrated(request, true, null);+ } else {+ checkAsync(request);+ }+ } else {+ logger.error("Unable to update pull request #{} due to unexpected source repository.", request.getNumber());+ }+ }++ depotAndBranch = new DepotAndBranch(event.getDepot(), branch);+ criterion = Restrictions.and(ofOpen(), ofTarget(depotAndBranch));+ for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (request.getSourceDepot().getObjectId(request.getBaseCommitHash(), false) != null)+ onTargetBranchUpdate(request);+ else+ logger.error("Unable to update pull request #{} due to unexpected target repository.", request.getNumber());+ }+ } else {+ Criterion criterion = Restrictions.and(+ ofOpen(),+ Restrictions.or(ofSource(depotAndBranch), ofTarget(depotAndBranch)));+ for (PullRequest request: findAll(EntityCriteria.of(PullRequest.class).add(criterion))) {+ if (request.getTargetDepot().equals(event.getDepot()) && request.getTargetBranch().equals(branch))+ discard(request, "Target branch is deleted.");+ else+ discard(request, "Source branch is deleted.");+ }+ }+ }+ }++ @Sessional+ @Override+ public PullRequest findOpen(DepotAndBranch target, DepotAndBranch source) {+ return find(EntityCriteria.of(PullRequest.class)+ .add(ofTarget(target)).add(ofSource(source)).add(ofOpen()));+ }++ @Sessional+ @Override+ public Collection<PullRequest> findAllOpenTo(DepotAndBranch target, @Nullable Depot sourceDepot) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofTarget(target));++ if (sourceDepot != null)+ criteria.add(Restrictions.eq("sourceDepot", sourceDepot));+ criteria.add(ofOpen());+ return findAll(criteria);+ }++ @Sessional+ @Override+ public Collection<PullRequest> findAllOpenFrom(DepotAndBranch source, @Nullable Depot targetDepot) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofSource(source));++ if (targetDepot != null)+ criteria.add(Restrictions.eq("targetDepot", targetDepot));+ criteria.add(ofOpen());+ return findAll(criteria);+ }++ @Sessional+ @Override+ public Collection<PullRequest> findAllOpen(DepotAndBranch sourceOrTarget) {+ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofOpen());+ criteria.add(Restrictions.or(ofSource(sourceOrTarget), ofTarget(sourceOrTarget)));+ return findAll(criteria);+ }++ @Sessional+ @Override+ public void checkSanity() {+ logger.info("Checking sanity of pull requests...");++ EntityCriteria<PullRequest> criteria = EntityCriteria.of(PullRequest.class);+ criteria.add(ofOpen());+ for (PullRequest request: findAll(criteria)) {+ Depot sourceDepot = request.getSourceDepot();+ if (sourceDepot == null) {+ discard(request, "Source repository is deleted.");+ } else if (sourceDepot.isValid()) {+ String baseCommitHash = request.getBaseCommitHash();++ // only modifies pull request status if source repository is the repository we+ // previously worked with. This avoids disaster of closing all pull requests+ // if repository storage points to a different location by mistake+ if (sourceDepot.getObjectId(baseCommitHash, false) != null) {+ String sourceHead = request.getSource().getObjectName(false);+ if (sourceHead == null) {+ discard(request, "Source branch is deleted.");+ } else {+ updateIfNecessary(request, false);+ if (request.isMerged()) {+ closeAsIntegrated(request, true, null);+ } else {+ checkAsync(request);+ }+ }+ } else {+ logger.error("Unable to update pull request #{} due to unexpected source repository", request.getNumber());+ }+ }++ if (request.isOpen()) {+ Depot targetDepot = request.getTargetDepot();+ if (targetDepot.isValid()) {+ String baseCommitHash = request.getBaseCommitHash();++ // only modifies pull request status if target repository is the repository we+ // previously worked with. This avoids disaster of closing all pull requests+ // if repository storage points to a different location by mistake+ if (targetDepot.getObjectId(baseCommitHash, false) != null) {+ String targetHead = request.getTarget().getObjectName(false);+ if (targetHead == null)+ discard(request, "Target branch is deleted.");+ else+ onTargetBranchUpdate(request);+ } else {+ logger.error("Unable to update pull request #{} due to unexpected target repository", request.getNumber());+ }+ }+ }+ }+ }++ @Sessional+ @Override+ public int countOpen(Depot depot) {+ EntityCriteria<PullRequest> criteria = newCriteria();+ criteria.add(PullRequest.CriterionHelper.ofOpen());+ criteria.add(PullRequest.CriterionHelper.ofTargetDepot(depot));+ return count(criteria);+ }++ @Sessional+ @Override+ public PullRequest find(Depot target, long number) {+ EntityCriteria<PullRequest> criteria = newCriteria();+ criteria.add(Restrictions.eq("targetDepot", target));+ criteria.add(Restrictions.eq("number", number));+ return find(criteria);+ }++ @Sessional+ @Override+ public PullRequest find(String uuid) {+ EntityCriteria<PullRequest> criteria = newCriteria();+ criteria.add(Restrictions.eq("uuid", uuid));+ return find(criteria);+ }++ @Listen+ public void on(CodeCommentReplied event) {+ CodeCommentReply reply = event.getReply();+ for (CodeCommentRelation relation: reply.getComment().getRelations()) {+ PullRequest request = relation.getRequest();+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(reply.getDate());+ lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentReplied.class));+ lastEvent.setUser(reply.getUser());+ request.setLastEvent(lastEvent);+ request.setLastCodeCommentEventDate(reply.getDate());+ save(request);+ }+ }++ @Listen+ public void on(CodeCommentResolved event) {+ for (CodeCommentRelation relation: event.getComment().getRelations()) {+ PullRequest request = relation.getRequest();++ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(new Date());+ lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentResolved.class));+ lastEvent.setUser(event.getUser());+ request.setLastEvent(lastEvent);+ request.setLastCodeCommentEventDate(lastEvent.getDate());+ save(request);+ }+ }++ @Listen+ public void on(CodeCommentUnresolved event) {+ for (CodeCommentRelation relation: event.getComment().getRelations()) {+ PullRequest request = relation.getRequest();+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(new Date());+ lastEvent.setDescription(EditableUtils.getName(PullRequestCodeCommentUnresolved.class));+ lastEvent.setUser(event.getUser());+ request.setLastEvent(lastEvent);+ request.setLastCodeCommentEventDate(lastEvent.getDate());+ save(request);+ }+ }++ @Transactional+ @Listen+ public void on(PullRequestUpdated event) {+ PullRequest request = event.getRequest();++ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(event.getUpdate().getDate());+ lastEvent.setDescription(EditableUtils.getName(event.getClass()));+ request.setLastEvent(lastEvent);+ save(request);+ }++ @Transactional+ @Listen+ public void on(PullRequestCommented event) {+ PullRequest request = event.getRequest();+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(event.getComment().getDate());+ lastEvent.setDescription(EditableUtils.getName(event.getClass()));+ lastEvent.setUser(event.getComment().getUser());+ request.setLastEvent(lastEvent);+ save(request);+ }++ @Listen+ public void on(PullRequestVerificationSucceeded event) {+ checkAsync(event.getRequest());+ }++ @Listen+ public void on(PullRequestVerificationFailed event) {+ checkAsync(event.getRequest());+ }++ @Transactional+ @Listen+ public void on(PullRequestApproved event) {+ checkAsync(event.getRequest());+ }++ @Transactional+ @Listen+ public void on(PullRequestDisapproved event) {+ checkAsync(event.getRequest());+ }++ @Transactional+ @Listen+ public void on(PullRequestVerificationDeleted event) {+ checkAsync(event.getRequest());+ }++ @Transactional+ @Listen+ public void on(PullRequestReviewDeleted event) {+ checkAsync(event.getRequest());+ }++ @Transactional+ @Listen+ public void on(PullRequestStatusChangeEvent event) {+ LastEvent lastEvent = new LastEvent();+ lastEvent.setDate(new Date());+ lastEvent.setDescription(EditableUtils.getName(event.getClass()));+ lastEvent.setUser(event.getUser());+ event.getRequest().setLastEvent(lastEvent);+ save(event.getRequest());+ }++ @Sessional+ private void checkAsync(PullRequest request) {+ Long requestId = request.getId();+ Subject subject = SecurityUtils.getSubject();+ doUnitOfWorkAfterCommitAsync(new Runnable() {++ @Override+ public void run() {+ try {+ ThreadContext.bind(subject);+ check(load(requestId));+ } finally {+ ThreadContext.unbindSubject();+ }+ }++ });+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentFilter.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentFilter.javaindex ddff32687c..ed495c7e4c 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentFilter.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentFilter.java@@ -1,207 +1,207 @@-package com.pmease.gitplex.web.component.comment;--import java.io.Serializable;-import java.util.Collection;-import java.util.Date;-import java.util.Iterator;-import java.util.List;--import org.apache.wicket.core.request.handler.IPageRequestHandler;-import org.apache.wicket.request.cycle.RequestCycle;-import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.hibernate.criterion.Restrictions;--import com.pmease.commons.hibernate.dao.EntityCriteria;-import com.pmease.commons.util.match.WildcardUtils;-import com.pmease.commons.wicket.editable.annotation.Editable;-import com.pmease.gitplex.core.annotation.AccountChoice;-import com.pmease.gitplex.core.annotation.FileChoice;-import com.pmease.gitplex.core.entity.CodeComment;--@Editable-public class CodeCommentFilter implements Serializable {-- private static final long serialVersionUID = 1L;-- private static final String PARAM_USER = "user";-- private static final String PARAM_UNRESOLVED = "unresolved";-- private static final String PARAM_PATH = "path";-- private static final String PARAM_TITLE = "title";-- private static final String PARAM_BEFORE = "before";-- private static final String PARAM_AFTER = "after";-- private String userName;-- private boolean unresolved;-- private String path;-- private String title;-- private Date before;-- private Date after;-- @Editable(order=100, name="Created by", description="Choose the user who created the comment")- @AccountChoice- public String getUserName() {- return userName;- }-- public void setUserName(String userName) {- this.userName = userName;- }-- @Editable(order=200, name="Show unresolved only", description="Check this if you only want to show unresolved comments")- public boolean isUnresolved() {- return unresolved;- }-- public void setUnresolved(boolean unresolved) {- this.unresolved = unresolved;- }-- @Editable(order=400, name="Title containing", description="Show comments with title containing specified string")- public String getContent() {- return title;- }-- public void setContent(String content) {- this.title = content;- }-- @Editable(order=500, name="Commented path", description="Show comments on specified path")- @FileChoice("getCommentedFiles")- public String getPath() {- return path;- }-- public void setPath(String path) {- this.path = path;- }-- @Editable(order=600, name="After date", description="Show comments after specified date")- public Date getAfter() {- return after;- }-- public void setAfter(Date after) {- this.after = after;- }-- @Editable(order=700, name="Before date", description="Show comments before specified date")- public Date getBefore() {- return before;- }-- public void setBefore(Date before) {- this.before = before;- }-- public CodeCommentFilter() {- }-- public CodeCommentFilter(PageParameters params) {- userName = params.get(PARAM_USER).toString();- unresolved = "yes".equals(params.get(PARAM_UNRESOLVED).toString());- path = params.get(PARAM_PATH).toString();- title = params.get(PARAM_TITLE).toString();-- String value = params.get(PARAM_BEFORE).toString();- if (value != null)- before = new Date(Long.valueOf(value));-- value = params.get(PARAM_AFTER).toString();- if (value != null)- after = new Date(Long.valueOf(value));- }-- public void fill(EntityCriteria<CodeComment> criteria) {- if (userName != null)- criteria.createCriteria("user").add(Restrictions.eq("name", userName));- if (unresolved)- criteria.add(Restrictions.eq("resolved", false));- if (path != null) {- String pathQuery = path.replace('*', '%');- if (pathQuery.endsWith("/"))- pathQuery += "%";- criteria.add(Restrictions.ilike("path", pathQuery));- }- if (title != null)- criteria.add(Restrictions.ilike("title", "%" + title + "%"));-- if (before != null)- criteria.add(Restrictions.le("createDate", before));- if (after != null)- criteria.add(Restrictions.ge("createDate", after));- }-- public void filter(Collection<CodeComment> comments) {- for (Iterator<CodeComment> it = comments.iterator(); it.hasNext();) {- CodeComment comment = it.next();- if (userName != null) {- if (comment.getUser() == null || !comment.getUser().getName().equals(userName)) {- it.remove();- continue;- }- }- if (unresolved && comment.isResolved()) {- it.remove();- continue;- }- if (path != null) {- if (comment.getCommentPos().getPath() == null) {- it.remove();- continue;- } else {- String matchWith = path;- if (matchWith.endsWith("/"))- matchWith += "*";- if (!WildcardUtils.matchString(matchWith, comment.getCommentPos().getPath())) {- it.remove();- continue;- }- }- }- if (title != null && !comment.getTitle().contains(title)) {- it.remove();- continue;- }- if (before != null && comment.getDate().after(before)) {- it.remove();- continue;- }- if (after != null && comment.getDate().before(after)) {- it.remove();- continue;- }- }- }-- public void fillPageParams(PageParameters params) {- if (userName != null)- params.add(PARAM_USER, userName);- if (unresolved)- params.add(PARAM_UNRESOLVED, "yes");- if (title != null)- params.add(PARAM_TITLE, title);- if (path != null)- params.add(PARAM_PATH, path);- if (before != null)- params.add(PARAM_BEFORE, before.getTime());- if (after != null)- params.add(PARAM_AFTER, after.getTime());- }-- @SuppressWarnings("unused")- private static List<String> getCommentedFiles() {- IPageRequestHandler handler = (IPageRequestHandler) RequestCycle.get().getActiveRequestHandler();- return ((CodeCommentAware)handler.getPage()).getCommentedFiles();- }--}+package com.pmease.gitplex.web.component.comment;++import java.io.Serializable;+import java.util.Collection;+import java.util.Date;+import java.util.Iterator;+import java.util.List;++import org.apache.wicket.core.request.handler.IPageRequestHandler;+import org.apache.wicket.request.cycle.RequestCycle;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.hibernate.criterion.Restrictions;++import com.pmease.commons.hibernate.dao.EntityCriteria;+import com.pmease.commons.util.match.WildcardUtils;+import com.pmease.commons.wicket.editable.annotation.Editable;+import com.pmease.gitplex.core.annotation.AccountChoice;+import com.pmease.gitplex.core.annotation.FileChoice;+import com.pmease.gitplex.core.entity.CodeComment;++@Editable+public class CodeCommentFilter implements Serializable {++ private static final long serialVersionUID = 1L;++ private static final String PARAM_USER = "user";++ private static final String PARAM_UNRESOLVED = "unresolved";++ private static final String PARAM_PATH = "path";++ private static final String PARAM_TITLE = "title";++ private static final String PARAM_BEFORE = "before";++ private static final String PARAM_AFTER = "after";++ private String userName;++ private boolean unresolved;++ private String path;++ private String title;++ private Date before;++ private Date after;++ @Editable(order=100, name="Created by", description="Choose the user who created the comment")+ @AccountChoice+ public String getUserName() {+ return userName;+ }++ public void setUserName(String userName) {+ this.userName = userName;+ }++ @Editable(order=200, name="Show unresolved only", description="Check this if you only want to show unresolved comments")+ public boolean isUnresolved() {+ return unresolved;+ }++ public void setUnresolved(boolean unresolved) {+ this.unresolved = unresolved;+ }++ @Editable(order=400, name="Title containing", description="Show comments with title containing specified string")+ public String getContent() {+ return title;+ }++ public void setContent(String content) {+ this.title = content;+ }++ @Editable(order=500, name="Commented path", description="Show comments on specified path")+ @FileChoice("getCommentedFiles")+ public String getPath() {+ return path;+ }++ public void setPath(String path) {+ this.path = path;+ }++ @Editable(order=600, name="After date", description="Show comments after specified date")+ public Date getAfter() {+ return after;+ }++ public void setAfter(Date after) {+ this.after = after;+ }++ @Editable(order=700, name="Before date", description="Show comments before specified date")+ public Date getBefore() {+ return before;+ }++ public void setBefore(Date before) {+ this.before = before;+ }++ public CodeCommentFilter() {+ }++ public CodeCommentFilter(PageParameters params) {+ userName = params.get(PARAM_USER).toString();+ unresolved = "yes".equals(params.get(PARAM_UNRESOLVED).toString());+ path = params.get(PARAM_PATH).toString();+ title = params.get(PARAM_TITLE).toString();++ String value = params.get(PARAM_BEFORE).toString();+ if (value != null)+ before = new Date(Long.valueOf(value));++ value = params.get(PARAM_AFTER).toString();+ if (value != null)+ after = new Date(Long.valueOf(value));+ }++ public void fill(EntityCriteria<CodeComment> criteria) {+ if (userName != null)+ criteria.createCriteria("user").add(Restrictions.eq("name", userName));+ if (unresolved)+ criteria.add(Restrictions.eq("resolved", false));+ if (path != null) {+ String pathQuery = path.replace('*', '%');+ if (pathQuery.endsWith("/"))+ pathQuery += "%";+ criteria.add(Restrictions.ilike("path", pathQuery));+ }+ if (title != null)+ criteria.add(Restrictions.ilike("title", "%" + title + "%"));++ if (before != null)+ criteria.add(Restrictions.le("createDate", before));+ if (after != null)+ criteria.add(Restrictions.ge("createDate", after));+ }++ public void filter(Collection<CodeComment> comments) {+ for (Iterator<CodeComment> it = comments.iterator(); it.hasNext();) {+ CodeComment comment = it.next();+ if (userName != null) {+ if (comment.getUser() == null || !comment.getUser().getName().equals(userName)) {+ it.remove();+ continue;+ }+ }+ if (unresolved && comment.isResolved()) {+ it.remove();+ continue;+ }+ if (path != null) {+ if (comment.getCommentPos().getPath() == null) {+ it.remove();+ continue;+ } else {+ String matchWith = path;+ if (matchWith.endsWith("/"))+ matchWith += "*";+ if (!WildcardUtils.matchString(matchWith, comment.getCommentPos().getPath())) {+ it.remove();+ continue;+ }+ }+ }+ if (title != null && !comment.getTitle().contains(title)) {+ it.remove();+ continue;+ }+ if (before != null && comment.getDate().getTime()>before.getTime()) {+ it.remove();+ continue;+ }+ if (after != null && comment.getDate().getTime()<after.getTime()) {+ it.remove();+ continue;+ }+ }+ }++ public void fillPageParams(PageParameters params) {+ if (userName != null)+ params.add(PARAM_USER, userName);+ if (unresolved)+ params.add(PARAM_UNRESOLVED, "yes");+ if (title != null)+ params.add(PARAM_TITLE, title);+ if (path != null)+ params.add(PARAM_PATH, path);+ if (before != null)+ params.add(PARAM_BEFORE, before.getTime());+ if (after != null)+ params.add(PARAM_AFTER, after.getTime());+ }++ @SuppressWarnings("unused")+ private static List<String> getCommentedFiles() {+ IPageRequestHandler handler = (IPageRequestHandler) RequestCycle.get().getActiveRequestHandler();+ return ((CodeCommentAware)handler.getPage()).getCommentedFiles();+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.javaindex cbd85fd538..177ffaf8a5 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentPanel.java@@ -1,801 +1,801 @@-package com.pmease.gitplex.web.component.comment;--import java.util.ArrayList;-import java.util.Date;-import java.util.List;--import javax.annotation.Nullable;--import org.apache.commons.lang3.StringUtils;-import org.apache.wicket.Component;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;-import org.apache.wicket.ajax.markup.html.AjaxLink;-import org.apache.wicket.ajax.markup.html.form.AjaxButton;-import org.apache.wicket.behavior.AttributeAppender;-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;-import org.apache.wicket.event.IEvent;-import org.apache.wicket.markup.head.CssHeaderItem;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.form.Form;-import org.apache.wicket.markup.html.form.TextField;-import org.apache.wicket.markup.html.link.Link;-import org.apache.wicket.markup.html.panel.Fragment;-import org.apache.wicket.markup.html.panel.Panel;-import org.apache.wicket.markup.repeater.RepeatingView;-import org.apache.wicket.model.AbstractReadOnlyModel;-import org.apache.wicket.model.LoadableDetachableModel;-import org.apache.wicket.model.Model;-import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.apache.wicket.request.resource.CssResourceReference;-import org.hibernate.StaleObjectStateException;--import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;-import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;-import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;-import com.pmease.commons.wicket.component.markdown.MarkdownPanel;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.Account;-import com.pmease.gitplex.core.entity.CodeComment;-import com.pmease.gitplex.core.entity.CodeCommentReply;-import com.pmease.gitplex.core.entity.CodeCommentStatusChange;-import com.pmease.gitplex.core.entity.Depot;-import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.support.CodeCommentActivity;-import com.pmease.gitplex.core.entity.support.CompareContext;-import com.pmease.gitplex.core.entity.support.DepotAndRevision;-import com.pmease.gitplex.core.manager.CodeCommentManager;-import com.pmease.gitplex.core.manager.CodeCommentReplyManager;-import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;-import com.pmease.gitplex.core.manager.VisitInfoManager;-import com.pmease.gitplex.core.security.SecurityUtils;-import com.pmease.gitplex.web.component.AccountLink;-import com.pmease.gitplex.web.component.avatar.AvatarLink;-import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;-import com.pmease.gitplex.web.util.DateUtils;-import com.pmease.gitplex.web.websocket.CodeCommentChangeRenderer;-import com.pmease.gitplex.web.websocket.CodeCommentChanged;--import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;--@SuppressWarnings("serial")-public abstract class CodeCommentPanel extends Panel {-- private final Long commentId;-- private RepeatingView activitiesView;-- /**- * We pass comment id instead of comment model as we want to make sure that- * comment is always loaded upon usage as this panel is involved in websocket- * update and websocket update does not detach models at end of request which- * may result in Hibernate lazy load exception when the comment is used again- * in next request- *- * @param id- * @param commentId- */- public CodeCommentPanel(String id, Long commentId) {- super(id);- this.commentId = commentId;- }-- protected CodeComment getComment() {- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);- }-- @Override- protected void onAfterRender() {- super.onAfterRender();- Account user = SecurityUtils.getAccount();- if (user != null)- GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());- }-- @Override- public void onEvent(IEvent<?> event) {- super.onEvent(event);-- if (event.getPayload() instanceof CodeCommentChanged) {- CodeCommentChanged codeCommentChanged = (CodeCommentChanged) event.getPayload();- IPartialPageRequestHandler partialPageRequestHandler = codeCommentChanged.getPartialPageRequestHandler();-- Date lastActivityDate;- String prevActivityMarkupId;- if (activitiesView.size() != 0) {- @SuppressWarnings("deprecation")- Component lastReplyContainer = activitiesView.get(activitiesView.size()-1);- CodeCommentReply lastReply = GitPlex.getInstance(CodeCommentReplyManager.class)- .load((Long) lastReplyContainer.getDefaultModelObject());- lastActivityDate = lastReply.getDate();- prevActivityMarkupId = lastReplyContainer.getMarkupId();- } else {- lastActivityDate = getComment().getDate();- prevActivityMarkupId = get("comment").getMarkupId();- }-- PullRequest request = getPullRequest();- List<CodeCommentActivity> activities = new ArrayList<>();- for (CodeCommentReply reply: getComment().getReplies()) {- if (reply.getDate().after(lastActivityDate)- && (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null)) {- activities.add(reply);- }- }- for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {- if (statusChange.getDate().after(lastActivityDate)- && (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null)) {- activities.add(statusChange);- }- }- activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));-- for (CodeCommentActivity activity: activities) {- Component newActivityContainer = newActivityContainer(activitiesView.newChildId(), activity);- activitiesView.add(newActivityContainer);-- String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",- newActivityContainer.getMarkupId(), prevActivityMarkupId);- partialPageRequestHandler.prependJavaScript(script);- partialPageRequestHandler.add(newActivityContainer);- prevActivityMarkupId = newActivityContainer.getMarkupId();- }- }- }-- private WebMarkupContainer newCommentContainer() {- WebMarkupContainer commentContainer = new Fragment("comment", "viewFrag", this);- commentContainer.setOutputMarkupId(true);-- commentContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {-- @Override- protected String load() {- return getComment().isVisitedAfter(getComment().getDate())?"": "new";- }-- }));-- commentContainer.add(new AvatarLink("userAvatar", getComment().getUser()));- commentContainer.add(new AccountLink("userName", getComment().getUser()));- commentContainer.add(new Label("activityDescription", "commented"));- commentContainer.add(new Label("activityDate", DateUtils.formatAge(getComment().getDate())));- commentContainer.add(new Link<Void>("compareContext") {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(!getCompareContext(getComment()).equals(getComment().getCompareContext()));- }-- @Override- public void onClick() {- CodeComment comment = getComment();- CompareContext compareContext = comment.getCompareContext();- PullRequest request = getPullRequest();- if (request != null) {- RequestChangesPage.State state = new RequestChangesPage.State();- state.commentId = comment.getId();- if (compareContext.isLeftSide()) {- state.oldCommit = compareContext.getCompareCommit();- state.newCommit = comment.getCommentPos().getCommit();- } else {- state.oldCommit = comment.getCommentPos().getCommit();- state.newCommit = compareContext.getCompareCommit();- }- state.mark = comment.getCommentPos();- state.pathFilter = compareContext.getPathFilter();- state.whitespaceOption = compareContext.getWhitespaceOption();- PageParameters params = RequestChangesPage.paramsOf(request, state);- setResponsePage(RequestChangesPage.class, params);- } else {- RevisionComparePage.State state = new RevisionComparePage.State();- state.commentId = comment.getId();- state.compareWithMergeBase = false;- if (compareContext.isLeftSide()) {- state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());- state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());- } else {- state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());- state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());- }- state.mark = comment.getCommentPos();- state.pathFilter = compareContext.getPathFilter();- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;- state.whitespaceOption = compareContext.getWhitespaceOption();- PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);- setResponsePage(RevisionComparePage.class, params);- }- }-- }.add(AttributeAppender.append("title", "This comment is added in a different compare context, click to show")));-- MarkdownEditSupport editSupport;- if (SecurityUtils.canModify(getComment())) {- editSupport = new MarkdownEditSupport() {-- @Override- public void setContent(String content) {- CodeComment comment = getComment();- comment.setContent(content);- GitPlex.getInstance(CodeCommentManager.class).save(comment);- }-- @Override- public long getVersion() {- return getComment().getVersion();- }-- };- } else {- editSupport = null;- }- commentContainer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- return getComment().getContent();- }-- }, editSupport));-- WebMarkupContainer foot = new WebMarkupContainer("foot");- foot.setVisible(SecurityUtils.canModify(getComment()));- foot.add(new AjaxLink<Void>("edit") {-- @Override- public void onClick(AjaxRequestTarget target) {- Fragment fragment = new Fragment(commentContainer.getId(), "commentEditFrag", CodeCommentPanel.this);- Form<?> form = new Form<Void>("form");- form.setOutputMarkupId(true);-- TextField<String> titleInput = new TextField<String>("title", Model.of(getComment().getTitle()));- titleInput.setRequired(true);- form.add(titleInput);- CommentInput contentInput = new CommentInput("content", Model.of(getComment().getContent())) {-- @Override- protected AttachmentSupport getAttachmentSupport() {- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());- }-- @Override- protected Depot getDepot() {- return getComment().getDepot();- }-- };- form.add(contentInput);- contentInput.setRequired(true);-- NotificationPanel feedback = new NotificationPanel("feedback", form);- feedback.setOutputMarkupPlaceholderTag(true);- form.add(feedback);-- form.add(new AjaxLink<Void>("cancel") {-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));- }-- @Override- public void onClick(AjaxRequestTarget target) {- WebMarkupContainer commentContainer = newCommentContainer();- fragment.replaceWith(commentContainer);- target.add(commentContainer);- }-- });-- long lastVersion = getComment().getVersion();- form.add(new AjaxButton("save") {-- @Override- protected void onError(AjaxRequestTarget target, Form<?> form) {- super.onError(target, form);- target.add(feedback);- }-- @Override- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {- super.onSubmit(target, form);-- try {- CodeComment comment = getComment();- if (comment.getVersion() != lastVersion)- throw new StaleObjectStateException(CodeComment.class.getName(), comment.getId());- comment.setTitle(titleInput.getModelObject());- comment.setContent(contentInput.getModelObject());- GitPlex.getInstance(CodeCommentManager.class).save(comment);- WebMarkupContainer commentContainer = newCommentContainer();- fragment.replaceWith(commentContainer);- target.add(commentContainer);- onSaveComment(target, comment);- } catch (StaleObjectStateException e) {- error("Some one changed the content you are editing. Reload the page and try again.");- target.add(feedback);- }- }-- });-- fragment.add(form);- fragment.setOutputMarkupId(true);- commentContainer.replaceWith(fragment);- target.add(fragment);- }-- });-- foot.add(new AjaxLink<Void>("delete") {-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);- String confirmMessage;- if (getComment().getReplies().isEmpty()) {- confirmMessage = "Do you really want to delete this comment?";- } else {- confirmMessage = "Deleting this comment will also delete all replies, do you really "- + "want to continue?";- }- attributes.getAjaxCallListeners().add(new ConfirmListener(confirmMessage));- }-- @Override- public void onClick(AjaxRequestTarget target) {- onDeleteComment(target, getComment());- GitPlex.getInstance(CodeCommentManager.class).delete(getComment());- }-- });-- commentContainer.add(foot);- return commentContainer;- }-- private WebMarkupContainer newActivityContainer(String componentId, CodeCommentActivity activity) {- Class<? extends CodeCommentActivity> activityClass = activity.getClass();- Long activityId = activity.getId();- Fragment activityContainer = new Fragment(componentId, "viewFrag", this, Model.of(activityId));- activityContainer.setOutputMarkupId(true);-- activityContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {-- @Override- protected String load() {- return getComment().isVisitedAfter(getActivity(activityClass, activityId).getDate())?"":"new";- }-- }));-- activityContainer.add(new AvatarLink("userAvatar", activity.getUser()));- activityContainer.add(new AccountLink("userName", activity.getUser()));- String activityDescription;- if (activity instanceof CodeCommentStatusChange) {- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;- if (statusChange.isResolved())- activityDescription = "resolved";- else- activityDescription = "unresolved";- } else {- activityDescription = "replied";- }- activityContainer.add(new Label("activityDescription", activityDescription));- activityContainer.add(new Label("activityDate", DateUtils.formatAge(activity.getDate())));- activityContainer.add(new Link<Void>("compareContext") {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(!getCompareContext(getComment()).equals(getActivity(activityClass, activityId).getCompareContext()));- }-- @Override- public void onClick() {- CodeCommentActivity activity = getActivity(activityClass, activityId);- CompareContext compareContext = activity.getCompareContext();- PullRequest request = getPullRequest();- if (request != null) {- RequestChangesPage.State state = new RequestChangesPage.State();- state.commentId = activity.getComment().getId();- if (compareContext.isLeftSide()) {- state.oldCommit = compareContext.getCompareCommit();- state.newCommit = activity.getComment().getCommentPos().getCommit();- } else {- state.oldCommit = activity.getComment().getCommentPos().getCommit();- state.newCommit = compareContext.getCompareCommit();- }- state.mark = activity.getComment().getCommentPos();- state.pathFilter = compareContext.getPathFilter();- state.whitespaceOption = compareContext.getWhitespaceOption();- PageParameters params = RequestChangesPage.paramsOf(request, state);- setResponsePage(RequestChangesPage.class, params);- } else {- RevisionComparePage.State state = new RevisionComparePage.State();- CodeComment comment = activity.getComment();- state.commentId = comment.getId();- state.compareWithMergeBase = false;- if (compareContext.isLeftSide()) {- state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());- state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());- } else {- state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());- state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());- }- state.mark = comment.getCommentPos();- state.pathFilter = compareContext.getPathFilter();- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;- state.whitespaceOption = compareContext.getWhitespaceOption();- PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);- setResponsePage(RevisionComparePage.class, params);- }- }-- }.add(AttributeAppender.append("title", "This reply is added in a different compare context, click to show")));-- if (StringUtils.isNotBlank(activity.getNote())) {- MarkdownEditSupport editSupport;- if (SecurityUtils.canModify(getComment())) {- editSupport = new MarkdownEditSupport() {-- @Override- public void setContent(String content) {- if (activityClass == CodeCommentReply.class) {- CodeCommentReply reply = (CodeCommentReply) activity;- reply.setContent(content);- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);- } else {- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;- statusChange.setNote(content);- GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);- }- }-- @Override- public long getVersion() {- return getActivity(activityClass, activityId).getVersion();- }-- };- } else {- editSupport = null;- }- activityContainer.add(new MarkdownPanel("content", new LoadableDetachableModel<String>() {-- @Override- protected String load() {- return getActivity(activityClass, activityId).getNote();- }-- }, editSupport));-- } else {- activityContainer.add(new Label("content", "<div class='no-note'>No note</div>").setEscapeModelStrings(false));- }-- WebMarkupContainer foot = new WebMarkupContainer("foot");- foot.setVisible(SecurityUtils.canModify(activity));-- foot.add(new AjaxLink<Void>("edit") {-- @Override- public void onClick(AjaxRequestTarget target) {- Fragment fragment = new Fragment(activityContainer.getId(), "activityEditFrag",- CodeCommentPanel.this, Model.of(activityId));- Form<?> form = new Form<Void>("form");- CommentInput contentInput = new CommentInput("content", Model.of(getActivity(activityClass, activityId).getNote())) {-- @Override- protected AttachmentSupport getAttachmentSupport() {- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());- }-- @Override- protected Depot getDepot() {- return getComment().getDepot();- }-- };- contentInput.setRequired(activityClass == CodeCommentReply.class);- form.add(contentInput);-- NotificationPanel feedback = new NotificationPanel("feedback", form);- feedback.setOutputMarkupPlaceholderTag(true);- form.add(feedback);-- form.add(new AjaxLink<Void>("cancel") {-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));- }-- @Override- public void onClick(AjaxRequestTarget target) {- WebMarkupContainer replyContainer = newActivityContainer(componentId, getActivity(activityClass, activityId));- fragment.replaceWith(replyContainer);- target.add(replyContainer);- }-- });-- long lastVersion = getActivity(activityClass, activityId).getVersion();- form.add(new AjaxButton("save") {-- @Override- protected void onError(AjaxRequestTarget target, Form<?> form) {- super.onError(target, form);- target.add(feedback);- }-- @Override- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {- super.onSubmit(target, form);-- try {- CodeCommentActivity activity = getActivity(activityClass, activityId);- if (activity.getVersion() != lastVersion)- throw new StaleObjectStateException(activityClass.getName(), activity.getId());-- if (activityClass == CodeCommentReply.class) {- CodeCommentReply reply = (CodeCommentReply) activity;- reply.setContent(contentInput.getModelObject());- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);- } else {- CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;- statusChange.setNote(contentInput.getModelObject());- GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);- }- WebMarkupContainer activityContainer = newActivityContainer(componentId, getActivity(activityClass, activityId));- fragment.replaceWith(activityContainer);- target.add(activityContainer);- } catch (StaleObjectStateException e) {- error("Some one changed the content you are editing. Reload the page and try again.");- target.add(feedback);- }- }-- }.add(new Label("label", "Save")));-- fragment.add(form);- fragment.setOutputMarkupId(true);- activityContainer.replaceWith(fragment);- target.add(fragment);- }-- });- foot.add(new AjaxLink<Void>("delete") {-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);- attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this reply?"));- }-- @Override- public void onClick(AjaxRequestTarget target) {- activityContainer.remove();- GitPlex.getInstance(CodeCommentReplyManager.class).delete((CodeCommentReply) getActivity(activityClass, activityId));- String script = String.format("$('#%s').remove();", activityContainer.getMarkupId());- target.appendJavaScript(script);- }-- }.setVisible(activity instanceof CodeCommentReply));-- activityContainer.add(foot);- return activityContainer;- }-- private WebMarkupContainer newAddReplyContainer() {- WebMarkupContainer addReplyContainer = new Fragment("addReply", "addReplyFrag", this) {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(SecurityUtils.getAccount() != null);- }-- };- addReplyContainer.setOutputMarkupId(true);- addReplyContainer.add(new AjaxLink<Void>("reply") {-- @Override- public void onClick(AjaxRequestTarget target) {- onAddReply(target, false);- }-- });- return addReplyContainer;- }-- @Override- protected void onInitialize() {- super.onInitialize();-- add(newCommentContainer());-- activitiesView = new RepeatingView("activities");- PullRequest request = getPullRequest();-- List<CodeCommentActivity> activities = new ArrayList<>();- for (CodeCommentReply reply: getComment().getReplies()) {- if (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null) {- activities.add(reply);- }- }- for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {- if (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null) {- activities.add(statusChange);- }- }-- activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));-- for (CodeCommentActivity activity: activities) {- activitiesView.add(newActivityContainer(activitiesView.newChildId(), activity));- }- add(activitiesView);- add(newAddReplyContainer());-- setOutputMarkupId(true);-- add(new CodeCommentChangeRenderer(getComment().getId()));- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);- response.render(CssHeaderItem.forReference(new CssResourceReference(- CodeCommentPanel.class, "code-comment.css")));- }-- private CodeCommentActivity getActivity(Class<? extends CodeCommentActivity> entityClass, Long activityId) {- return GitPlex.getInstance(Dao.class).load(entityClass, activityId);- }-- private void onAddReply(AjaxRequestTarget target, boolean changeStatus) {- Fragment fragment = new Fragment("addReply", "activityEditFrag", CodeCommentPanel.this);- Form<?> form = new Form<Void>("form");- CommentInput contentInput = new CommentInput("content", Model.of("")) {-- @Override- protected AttachmentSupport getAttachmentSupport() {- return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());- }-- @Override- protected Depot getDepot() {- return getComment().getDepot();- }-- };- contentInput.setRequired(!changeStatus);- form.add(contentInput);-- NotificationPanel feedback = new NotificationPanel("feedback", form);- feedback.setOutputMarkupPlaceholderTag(true);- form.add(feedback);-- form.add(new AjaxLink<Void>("cancel") {-- @Override- protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {- super.updateAjaxAttributes(attributes);- attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));- }-- @Override- public void onClick(AjaxRequestTarget target) {- WebMarkupContainer addReplyContainer = newAddReplyContainer();- fragment.replaceWith(addReplyContainer);- target.add(addReplyContainer);- }-- });-- AjaxButton saveButton = new AjaxButton("save") {-- @Override- protected void onError(AjaxRequestTarget target, Form<?> form) {- super.onError(target, form);- target.add(feedback);- }-- @Override- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {- super.onSubmit(target, form);-- Account user = SecurityUtils.getAccount();- CodeComment comment = getComment();- Date date = new Date();- CompareContext compareContext = getCompareContext(comment);- if (changeStatus) {- CodeCommentStatusChange statusChange = new CodeCommentStatusChange();- statusChange.setComment(getComment());- statusChange.setUser(user);- statusChange.setCompareContext(compareContext);- statusChange.setResolved(!comment.isResolved());- statusChange.setDate(date);-- GitPlex.getInstance(CodeCommentManager.class).changeStatus(statusChange);- onStatusChanged(target, fragment, statusChange);- onSaveComment(target, getComment());- } else {- CodeCommentReply reply = new CodeCommentReply();- reply.setComment(comment);- reply.setDate(date);- reply.setUser(user);- reply.setContent(contentInput.getModelObject());- reply.setCompareContext(compareContext);- GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);- onReplyAdded(target, fragment, reply);- }- }-- };- if (changeStatus) {- saveButton.add(new Label("label", getComment().isResolved()?"Confirm unresolve":"Confirm resolve"));- } else {- saveButton.add(new Label("label", "Save"));- saveButton.add(AttributeAppender.append("class", "dirty-aware"));- }- form.add(saveButton);-- fragment.add(form);- fragment.setOutputMarkupId(true);- get("addReply").replaceWith(fragment);- target.add(fragment);- }-- public void onChangeStatus(AjaxRequestTarget target) {- onAddReply(target, true);- }-- private void onStatusChanged(AjaxRequestTarget target, Fragment fragment, CodeCommentStatusChange statusChange) {- WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), statusChange);- activitiesView.add(activityContainer);-- String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",- CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());- target.prependJavaScript(script);- target.add(activityContainer);-- WebMarkupContainer addReplyContainer = newAddReplyContainer();- fragment.replaceWith(addReplyContainer);- target.add(addReplyContainer);- }-- private void onReplyAdded(AjaxRequestTarget target, Fragment fragment, @Nullable CodeCommentReply reply) {- if (reply != null) {- WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), reply);- activitiesView.add(activityContainer);-- String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",- CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());- target.prependJavaScript(script);- target.add(activityContainer);- }-- WebMarkupContainer addReplyContainer = newAddReplyContainer();- fragment.replaceWith(addReplyContainer);- target.add(addReplyContainer);- }-- protected abstract void onDeleteComment(AjaxRequestTarget target, CodeComment comment);-- protected abstract void onSaveComment(AjaxRequestTarget target, CodeComment comment);-- protected abstract CompareContext getCompareContext(CodeComment comment);-- @Nullable- protected abstract PullRequest getPullRequest();-}+package com.pmease.gitplex.web.component.comment;++import java.util.ArrayList;+import java.util.Date;+import java.util.List;++import javax.annotation.Nullable;++import org.apache.commons.lang3.StringUtils;+import org.apache.wicket.Component;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;+import org.apache.wicket.ajax.markup.html.AjaxLink;+import org.apache.wicket.ajax.markup.html.form.AjaxButton;+import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;+import org.apache.wicket.event.IEvent;+import org.apache.wicket.markup.head.CssHeaderItem;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.html.WebMarkupContainer;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.form.Form;+import org.apache.wicket.markup.html.form.TextField;+import org.apache.wicket.markup.html.link.Link;+import org.apache.wicket.markup.html.panel.Fragment;+import org.apache.wicket.markup.html.panel.Panel;+import org.apache.wicket.markup.repeater.RepeatingView;+import org.apache.wicket.model.AbstractReadOnlyModel;+import org.apache.wicket.model.LoadableDetachableModel;+import org.apache.wicket.model.Model;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.apache.wicket.request.resource.CssResourceReference;+import org.hibernate.StaleObjectStateException;++import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.wicket.ajaxlistener.ConfirmLeaveListener;+import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;+import com.pmease.commons.wicket.component.markdown.MarkdownEditSupport;+import com.pmease.commons.wicket.component.markdown.MarkdownPanel;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.Account;+import com.pmease.gitplex.core.entity.CodeComment;+import com.pmease.gitplex.core.entity.CodeCommentReply;+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;+import com.pmease.gitplex.core.entity.Depot;+import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.support.CodeCommentActivity;+import com.pmease.gitplex.core.entity.support.CompareContext;+import com.pmease.gitplex.core.entity.support.DepotAndRevision;+import com.pmease.gitplex.core.manager.CodeCommentManager;+import com.pmease.gitplex.core.manager.CodeCommentReplyManager;+import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;+import com.pmease.gitplex.core.manager.VisitInfoManager;+import com.pmease.gitplex.core.security.SecurityUtils;+import com.pmease.gitplex.web.component.AccountLink;+import com.pmease.gitplex.web.component.avatar.AvatarLink;+import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;+import com.pmease.gitplex.web.util.DateUtils;+import com.pmease.gitplex.web.websocket.CodeCommentChangeRenderer;+import com.pmease.gitplex.web.websocket.CodeCommentChanged;++import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;++@SuppressWarnings("serial")+public abstract class CodeCommentPanel extends Panel {++ private final Long commentId;++ private RepeatingView activitiesView;++ /**+ * We pass comment id instead of comment model as we want to make sure that+ * comment is always loaded upon usage as this panel is involved in websocket+ * update and websocket update does not detach models at end of request which+ * may result in Hibernate lazy load exception when the comment is used again+ * in next request+ *+ * @param id+ * @param commentId+ */+ public CodeCommentPanel(String id, Long commentId) {+ super(id);+ this.commentId = commentId;+ }++ protected CodeComment getComment() {+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);+ }++ @Override+ protected void onAfterRender() {+ super.onAfterRender();+ Account user = SecurityUtils.getAccount();+ if (user != null)+ GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());+ }++ @Override+ public void onEvent(IEvent<?> event) {+ super.onEvent(event);++ if (event.getPayload() instanceof CodeCommentChanged) {+ CodeCommentChanged codeCommentChanged = (CodeCommentChanged) event.getPayload();+ IPartialPageRequestHandler partialPageRequestHandler = codeCommentChanged.getPartialPageRequestHandler();++ Date lastActivityDate;+ String prevActivityMarkupId;+ if (activitiesView.size() != 0) {+ @SuppressWarnings("deprecation")+ Component lastReplyContainer = activitiesView.get(activitiesView.size()-1);+ CodeCommentReply lastReply = GitPlex.getInstance(CodeCommentReplyManager.class)+ .load((Long) lastReplyContainer.getDefaultModelObject());+ lastActivityDate = lastReply.getDate();+ prevActivityMarkupId = lastReplyContainer.getMarkupId();+ } else {+ lastActivityDate = getComment().getDate();+ prevActivityMarkupId = get("comment").getMarkupId();+ }++ PullRequest request = getPullRequest();+ List<CodeCommentActivity> activities = new ArrayList<>();+ for (CodeCommentReply reply: getComment().getReplies()) {+ if (reply.getDate().getTime()>lastActivityDate.getTime()+ && (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null)) {+ activities.add(reply);+ }+ }+ for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {+ if (statusChange.getDate().getTime()>lastActivityDate.getTime()+ && (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null)) {+ activities.add(statusChange);+ }+ }+ activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));++ for (CodeCommentActivity activity: activities) {+ Component newActivityContainer = newActivityContainer(activitiesView.newChildId(), activity);+ activitiesView.add(newActivityContainer);++ String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",+ newActivityContainer.getMarkupId(), prevActivityMarkupId);+ partialPageRequestHandler.prependJavaScript(script);+ partialPageRequestHandler.add(newActivityContainer);+ prevActivityMarkupId = newActivityContainer.getMarkupId();+ }+ }+ }++ private WebMarkupContainer newCommentContainer() {+ WebMarkupContainer commentContainer = new Fragment("comment", "viewFrag", this);+ commentContainer.setOutputMarkupId(true);++ commentContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ return getComment().isVisitedAfter(getComment().getDate())?"": "new";+ }++ }));++ commentContainer.add(new AvatarLink("userAvatar", getComment().getUser()));+ commentContainer.add(new AccountLink("userName", getComment().getUser()));+ commentContainer.add(new Label("activityDescription", "commented"));+ commentContainer.add(new Label("activityDate", DateUtils.formatAge(getComment().getDate())));+ commentContainer.add(new Link<Void>("compareContext") {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(!getCompareContext(getComment()).equals(getComment().getCompareContext()));+ }++ @Override+ public void onClick() {+ CodeComment comment = getComment();+ CompareContext compareContext = comment.getCompareContext();+ PullRequest request = getPullRequest();+ if (request != null) {+ RequestChangesPage.State state = new RequestChangesPage.State();+ state.commentId = comment.getId();+ if (compareContext.isLeftSide()) {+ state.oldCommit = compareContext.getCompareCommit();+ state.newCommit = comment.getCommentPos().getCommit();+ } else {+ state.oldCommit = comment.getCommentPos().getCommit();+ state.newCommit = compareContext.getCompareCommit();+ }+ state.mark = comment.getCommentPos();+ state.pathFilter = compareContext.getPathFilter();+ state.whitespaceOption = compareContext.getWhitespaceOption();+ PageParameters params = RequestChangesPage.paramsOf(request, state);+ setResponsePage(RequestChangesPage.class, params);+ } else {+ RevisionComparePage.State state = new RevisionComparePage.State();+ state.commentId = comment.getId();+ state.compareWithMergeBase = false;+ if (compareContext.isLeftSide()) {+ state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());+ state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());+ } else {+ state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());+ state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());+ }+ state.mark = comment.getCommentPos();+ state.pathFilter = compareContext.getPathFilter();+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;+ state.whitespaceOption = compareContext.getWhitespaceOption();+ PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);+ setResponsePage(RevisionComparePage.class, params);+ }+ }++ }.add(AttributeAppender.append("title", "This comment is added in a different compare context, click to show")));++ MarkdownEditSupport editSupport;+ if (SecurityUtils.canModify(getComment())) {+ editSupport = new MarkdownEditSupport() {++ @Override+ public void setContent(String content) {+ CodeComment comment = getComment();+ comment.setContent(content);+ GitPlex.getInstance(CodeCommentManager.class).save(comment);+ }++ @Override+ public long getVersion() {+ return getComment().getVersion();+ }++ };+ } else {+ editSupport = null;+ }+ commentContainer.add(new MarkdownPanel("content", new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ return getComment().getContent();+ }++ }, editSupport));++ WebMarkupContainer foot = new WebMarkupContainer("foot");+ foot.setVisible(SecurityUtils.canModify(getComment()));+ foot.add(new AjaxLink<Void>("edit") {++ @Override+ public void onClick(AjaxRequestTarget target) {+ Fragment fragment = new Fragment(commentContainer.getId(), "commentEditFrag", CodeCommentPanel.this);+ Form<?> form = new Form<Void>("form");+ form.setOutputMarkupId(true);++ TextField<String> titleInput = new TextField<String>("title", Model.of(getComment().getTitle()));+ titleInput.setRequired(true);+ form.add(titleInput);+ CommentInput contentInput = new CommentInput("content", Model.of(getComment().getContent())) {++ @Override+ protected AttachmentSupport getAttachmentSupport() {+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());+ }++ @Override+ protected Depot getDepot() {+ return getComment().getDepot();+ }++ };+ form.add(contentInput);+ contentInput.setRequired(true);++ NotificationPanel feedback = new NotificationPanel("feedback", form);+ feedback.setOutputMarkupPlaceholderTag(true);+ form.add(feedback);++ form.add(new AjaxLink<Void>("cancel") {++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));+ }++ @Override+ public void onClick(AjaxRequestTarget target) {+ WebMarkupContainer commentContainer = newCommentContainer();+ fragment.replaceWith(commentContainer);+ target.add(commentContainer);+ }++ });++ long lastVersion = getComment().getVersion();+ form.add(new AjaxButton("save") {++ @Override+ protected void onError(AjaxRequestTarget target, Form<?> form) {+ super.onError(target, form);+ target.add(feedback);+ }++ @Override+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {+ super.onSubmit(target, form);++ try {+ CodeComment comment = getComment();+ if (comment.getVersion() != lastVersion)+ throw new StaleObjectStateException(CodeComment.class.getName(), comment.getId());+ comment.setTitle(titleInput.getModelObject());+ comment.setContent(contentInput.getModelObject());+ GitPlex.getInstance(CodeCommentManager.class).save(comment);+ WebMarkupContainer commentContainer = newCommentContainer();+ fragment.replaceWith(commentContainer);+ target.add(commentContainer);+ onSaveComment(target, comment);+ } catch (StaleObjectStateException e) {+ error("Some one changed the content you are editing. Reload the page and try again.");+ target.add(feedback);+ }+ }++ });++ fragment.add(form);+ fragment.setOutputMarkupId(true);+ commentContainer.replaceWith(fragment);+ target.add(fragment);+ }++ });++ foot.add(new AjaxLink<Void>("delete") {++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ String confirmMessage;+ if (getComment().getReplies().isEmpty()) {+ confirmMessage = "Do you really want to delete this comment?";+ } else {+ confirmMessage = "Deleting this comment will also delete all replies, do you really "+ + "want to continue?";+ }+ attributes.getAjaxCallListeners().add(new ConfirmListener(confirmMessage));+ }++ @Override+ public void onClick(AjaxRequestTarget target) {+ onDeleteComment(target, getComment());+ GitPlex.getInstance(CodeCommentManager.class).delete(getComment());+ }++ });++ commentContainer.add(foot);+ return commentContainer;+ }++ private WebMarkupContainer newActivityContainer(String componentId, CodeCommentActivity activity) {+ Class<? extends CodeCommentActivity> activityClass = activity.getClass();+ Long activityId = activity.getId();+ Fragment activityContainer = new Fragment(componentId, "viewFrag", this, Model.of(activityId));+ activityContainer.setOutputMarkupId(true);++ activityContainer.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ return getComment().isVisitedAfter(getActivity(activityClass, activityId).getDate())?"":"new";+ }++ }));++ activityContainer.add(new AvatarLink("userAvatar", activity.getUser()));+ activityContainer.add(new AccountLink("userName", activity.getUser()));+ String activityDescription;+ if (activity instanceof CodeCommentStatusChange) {+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;+ if (statusChange.isResolved())+ activityDescription = "resolved";+ else+ activityDescription = "unresolved";+ } else {+ activityDescription = "replied";+ }+ activityContainer.add(new Label("activityDescription", activityDescription));+ activityContainer.add(new Label("activityDate", DateUtils.formatAge(activity.getDate())));+ activityContainer.add(new Link<Void>("compareContext") {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(!getCompareContext(getComment()).equals(getActivity(activityClass, activityId).getCompareContext()));+ }++ @Override+ public void onClick() {+ CodeCommentActivity activity = getActivity(activityClass, activityId);+ CompareContext compareContext = activity.getCompareContext();+ PullRequest request = getPullRequest();+ if (request != null) {+ RequestChangesPage.State state = new RequestChangesPage.State();+ state.commentId = activity.getComment().getId();+ if (compareContext.isLeftSide()) {+ state.oldCommit = compareContext.getCompareCommit();+ state.newCommit = activity.getComment().getCommentPos().getCommit();+ } else {+ state.oldCommit = activity.getComment().getCommentPos().getCommit();+ state.newCommit = compareContext.getCompareCommit();+ }+ state.mark = activity.getComment().getCommentPos();+ state.pathFilter = compareContext.getPathFilter();+ state.whitespaceOption = compareContext.getWhitespaceOption();+ PageParameters params = RequestChangesPage.paramsOf(request, state);+ setResponsePage(RequestChangesPage.class, params);+ } else {+ RevisionComparePage.State state = new RevisionComparePage.State();+ CodeComment comment = activity.getComment();+ state.commentId = comment.getId();+ state.compareWithMergeBase = false;+ if (compareContext.isLeftSide()) {+ state.leftSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());+ state.rightSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());+ } else {+ state.leftSide = new DepotAndRevision(comment.getDepot(), comment.getCommentPos().getCommit());+ state.rightSide = new DepotAndRevision(comment.getDepot(), compareContext.getCompareCommit());+ }+ state.mark = comment.getCommentPos();+ state.pathFilter = compareContext.getPathFilter();+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;+ state.whitespaceOption = compareContext.getWhitespaceOption();+ PageParameters params = RevisionComparePage.paramsOf(comment.getDepot(), state);+ setResponsePage(RevisionComparePage.class, params);+ }+ }++ }.add(AttributeAppender.append("title", "This reply is added in a different compare context, click to show")));++ if (StringUtils.isNotBlank(activity.getNote())) {+ MarkdownEditSupport editSupport;+ if (SecurityUtils.canModify(getComment())) {+ editSupport = new MarkdownEditSupport() {++ @Override+ public void setContent(String content) {+ if (activityClass == CodeCommentReply.class) {+ CodeCommentReply reply = (CodeCommentReply) activity;+ reply.setContent(content);+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);+ } else {+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;+ statusChange.setNote(content);+ GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);+ }+ }++ @Override+ public long getVersion() {+ return getActivity(activityClass, activityId).getVersion();+ }++ };+ } else {+ editSupport = null;+ }+ activityContainer.add(new MarkdownPanel("content", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ return getActivity(activityClass, activityId).getNote();+ }++ }, editSupport));++ } else {+ activityContainer.add(new Label("content", "<div class='no-note'>No note</div>").setEscapeModelStrings(false));+ }++ WebMarkupContainer foot = new WebMarkupContainer("foot");+ foot.setVisible(SecurityUtils.canModify(activity));++ foot.add(new AjaxLink<Void>("edit") {++ @Override+ public void onClick(AjaxRequestTarget target) {+ Fragment fragment = new Fragment(activityContainer.getId(), "activityEditFrag",+ CodeCommentPanel.this, Model.of(activityId));+ Form<?> form = new Form<Void>("form");+ CommentInput contentInput = new CommentInput("content", Model.of(getActivity(activityClass, activityId).getNote())) {++ @Override+ protected AttachmentSupport getAttachmentSupport() {+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());+ }++ @Override+ protected Depot getDepot() {+ return getComment().getDepot();+ }++ };+ contentInput.setRequired(activityClass == CodeCommentReply.class);+ form.add(contentInput);++ NotificationPanel feedback = new NotificationPanel("feedback", form);+ feedback.setOutputMarkupPlaceholderTag(true);+ form.add(feedback);++ form.add(new AjaxLink<Void>("cancel") {++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));+ }++ @Override+ public void onClick(AjaxRequestTarget target) {+ WebMarkupContainer replyContainer = newActivityContainer(componentId, getActivity(activityClass, activityId));+ fragment.replaceWith(replyContainer);+ target.add(replyContainer);+ }++ });++ long lastVersion = getActivity(activityClass, activityId).getVersion();+ form.add(new AjaxButton("save") {++ @Override+ protected void onError(AjaxRequestTarget target, Form<?> form) {+ super.onError(target, form);+ target.add(feedback);+ }++ @Override+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {+ super.onSubmit(target, form);++ try {+ CodeCommentActivity activity = getActivity(activityClass, activityId);+ if (activity.getVersion() != lastVersion)+ throw new StaleObjectStateException(activityClass.getName(), activity.getId());++ if (activityClass == CodeCommentReply.class) {+ CodeCommentReply reply = (CodeCommentReply) activity;+ reply.setContent(contentInput.getModelObject());+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);+ } else {+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) activity;+ statusChange.setNote(contentInput.getModelObject());+ GitPlex.getInstance(CodeCommentStatusChangeManager.class).save(statusChange);+ }+ WebMarkupContainer activityContainer = newActivityContainer(componentId, getActivity(activityClass, activityId));+ fragment.replaceWith(activityContainer);+ target.add(activityContainer);+ } catch (StaleObjectStateException e) {+ error("Some one changed the content you are editing. Reload the page and try again.");+ target.add(feedback);+ }+ }++ }.add(new Label("label", "Save")));++ fragment.add(form);+ fragment.setOutputMarkupId(true);+ activityContainer.replaceWith(fragment);+ target.add(fragment);+ }++ });+ foot.add(new AjaxLink<Void>("delete") {++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ attributes.getAjaxCallListeners().add(new ConfirmListener("Do you really want to delete this reply?"));+ }++ @Override+ public void onClick(AjaxRequestTarget target) {+ activityContainer.remove();+ GitPlex.getInstance(CodeCommentReplyManager.class).delete((CodeCommentReply) getActivity(activityClass, activityId));+ String script = String.format("$('#%s').remove();", activityContainer.getMarkupId());+ target.appendJavaScript(script);+ }++ }.setVisible(activity instanceof CodeCommentReply));++ activityContainer.add(foot);+ return activityContainer;+ }++ private WebMarkupContainer newAddReplyContainer() {+ WebMarkupContainer addReplyContainer = new Fragment("addReply", "addReplyFrag", this) {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(SecurityUtils.getAccount() != null);+ }++ };+ addReplyContainer.setOutputMarkupId(true);+ addReplyContainer.add(new AjaxLink<Void>("reply") {++ @Override+ public void onClick(AjaxRequestTarget target) {+ onAddReply(target, false);+ }++ });+ return addReplyContainer;+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(newCommentContainer());++ activitiesView = new RepeatingView("activities");+ PullRequest request = getPullRequest();++ List<CodeCommentActivity> activities = new ArrayList<>();+ for (CodeCommentReply reply: getComment().getReplies()) {+ if (request == null || request.getRequestComparingInfo(reply.getComparingInfo()) != null) {+ activities.add(reply);+ }+ }+ for (CodeCommentStatusChange statusChange: getComment().getStatusChanges()) {+ if (request == null || request.getRequestComparingInfo(statusChange.getComparingInfo()) != null) {+ activities.add(statusChange);+ }+ }++ activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));++ for (CodeCommentActivity activity: activities) {+ activitiesView.add(newActivityContainer(activitiesView.newChildId(), activity));+ }+ add(activitiesView);+ add(newAddReplyContainer());++ setOutputMarkupId(true);++ add(new CodeCommentChangeRenderer(getComment().getId()));+ }++ @Override+ public void renderHead(IHeaderResponse response) {+ super.renderHead(response);+ response.render(CssHeaderItem.forReference(new CssResourceReference(+ CodeCommentPanel.class, "code-comment.css")));+ }++ private CodeCommentActivity getActivity(Class<? extends CodeCommentActivity> entityClass, Long activityId) {+ return GitPlex.getInstance(Dao.class).load(entityClass, activityId);+ }++ private void onAddReply(AjaxRequestTarget target, boolean changeStatus) {+ Fragment fragment = new Fragment("addReply", "activityEditFrag", CodeCommentPanel.this);+ Form<?> form = new Form<Void>("form");+ CommentInput contentInput = new CommentInput("content", Model.of("")) {++ @Override+ protected AttachmentSupport getAttachmentSupport() {+ return new DepotAttachmentSupport(getComment().getDepot(), getComment().getUUID());+ }++ @Override+ protected Depot getDepot() {+ return getComment().getDepot();+ }++ };+ contentInput.setRequired(!changeStatus);+ form.add(contentInput);++ NotificationPanel feedback = new NotificationPanel("feedback", form);+ feedback.setOutputMarkupPlaceholderTag(true);+ form.add(feedback);++ form.add(new AjaxLink<Void>("cancel") {++ @Override+ protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {+ super.updateAjaxAttributes(attributes);+ attributes.getAjaxCallListeners().add(new ConfirmLeaveListener(form));+ }++ @Override+ public void onClick(AjaxRequestTarget target) {+ WebMarkupContainer addReplyContainer = newAddReplyContainer();+ fragment.replaceWith(addReplyContainer);+ target.add(addReplyContainer);+ }++ });++ AjaxButton saveButton = new AjaxButton("save") {++ @Override+ protected void onError(AjaxRequestTarget target, Form<?> form) {+ super.onError(target, form);+ target.add(feedback);+ }++ @Override+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {+ super.onSubmit(target, form);++ Account user = SecurityUtils.getAccount();+ CodeComment comment = getComment();+ Date date = new Date();+ CompareContext compareContext = getCompareContext(comment);+ if (changeStatus) {+ CodeCommentStatusChange statusChange = new CodeCommentStatusChange();+ statusChange.setComment(getComment());+ statusChange.setUser(user);+ statusChange.setCompareContext(compareContext);+ statusChange.setResolved(!comment.isResolved());+ statusChange.setDate(date);++ GitPlex.getInstance(CodeCommentManager.class).changeStatus(statusChange);+ onStatusChanged(target, fragment, statusChange);+ onSaveComment(target, getComment());+ } else {+ CodeCommentReply reply = new CodeCommentReply();+ reply.setComment(comment);+ reply.setDate(date);+ reply.setUser(user);+ reply.setContent(contentInput.getModelObject());+ reply.setCompareContext(compareContext);+ GitPlex.getInstance(CodeCommentReplyManager.class).save(reply);+ onReplyAdded(target, fragment, reply);+ }+ }++ };+ if (changeStatus) {+ saveButton.add(new Label("label", getComment().isResolved()?"Confirm unresolve":"Confirm resolve"));+ } else {+ saveButton.add(new Label("label", "Save"));+ saveButton.add(AttributeAppender.append("class", "dirty-aware"));+ }+ form.add(saveButton);++ fragment.add(form);+ fragment.setOutputMarkupId(true);+ get("addReply").replaceWith(fragment);+ target.add(fragment);+ }++ public void onChangeStatus(AjaxRequestTarget target) {+ onAddReply(target, true);+ }++ private void onStatusChanged(AjaxRequestTarget target, Fragment fragment, CodeCommentStatusChange statusChange) {+ WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), statusChange);+ activitiesView.add(activityContainer);++ String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",+ CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());+ target.prependJavaScript(script);+ target.add(activityContainer);++ WebMarkupContainer addReplyContainer = newAddReplyContainer();+ fragment.replaceWith(addReplyContainer);+ target.add(addReplyContainer);+ }++ private void onReplyAdded(AjaxRequestTarget target, Fragment fragment, @Nullable CodeCommentReply reply) {+ if (reply != null) {+ WebMarkupContainer activityContainer = newActivityContainer(activitiesView.newChildId(), reply);+ activitiesView.add(activityContainer);++ String script = String.format("$('#%s .add-reply').before('<div id=\"%s\"></div>');",+ CodeCommentPanel.this.getMarkupId(), activityContainer.getMarkupId());+ target.prependJavaScript(script);+ target.add(activityContainer);+ }++ WebMarkupContainer addReplyContainer = newAddReplyContainer();+ fragment.replaceWith(addReplyContainer);+ target.add(addReplyContainer);+ }++ protected abstract void onDeleteComment(AjaxRequestTarget target, CodeComment comment);++ protected abstract void onSaveComment(AjaxRequestTarget target, CodeComment comment);++ protected abstract CompareContext getCompareContext(CodeComment comment);++ @Nullable+ protected abstract PullRequest getPullRequest();+}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.javaindex afbe800a81..6fa124958e 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerAvatar.java@@ -1,97 +1,97 @@-package com.pmease.gitplex.web.component.pullrequest.requestreviewer;--import java.util.Date;-import java.util.HashSet;-import java.util.Set;--import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.model.IModel;--import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;-import com.pmease.gitplex.core.entity.Account;-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;-import com.pmease.gitplex.core.manager.AccountManager;-import com.pmease.gitplex.core.security.SecurityUtils;-import com.pmease.gitplex.web.component.avatar.RemoveableAvatar;-import com.pmease.gitplex.web.model.EntityModel;-import com.pmease.gitplex.web.model.UserModel;--@SuppressWarnings("serial")-public class ReviewerAvatar extends RemoveableAvatar {-- private final PullRequestReviewInvitation invitation;-- private final IModel<PullRequest> requestModel;-- public ReviewerAvatar(String id, PullRequestReviewInvitation invitation) {- super(id, new UserModel(invitation.getUser()), "Remove reviewer");-- this.invitation = invitation;- requestModel = new EntityModel<PullRequest>(invitation.getRequest());- }-- @Override- protected void onConfigure() {- super.onConfigure();-- PullRequest request = requestModel.getObject();- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();-- boolean reviewEffective = false;- if (!request.isNew())- reviewEffective = request.isReviewEffective(getUser());- setEnabled(request.isOpen() && !reviewEffective- && (currentUser!= null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));- }-- @Override- protected void onAvatarRemove(AjaxRequestTarget target) {- Date now = new Date();- PullRequest request = requestModel.getObject();- Set<Account> prevInvited = new HashSet<>();- for (PullRequestReviewInvitation each: request.getReviewInvitations()) {- if (each.isPreferred())- prevInvited.add(each.getUser());- if (each.getUser().equals(invitation.getUser())) {- each.setPerferred(false);- each.setDate(new Date());- }- }- request.getTargetDepot().getGateKeeper().checkRequest(request);-- Set<Account> nowInvited = new HashSet<>();- for (PullRequestReviewInvitation each: request.getReviewInvitations()) {- if (each.isPreferred())- nowInvited.add(each.getUser());- }-- if (nowInvited.contains(invitation.getUser())) {- getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()- + "' is required by gate keeper and can not be removed");- } else {- nowInvited.removeAll(prevInvited);- if (!nowInvited.isEmpty()) {- getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()- + "' is removed and user '" + nowInvited.iterator().next().getDisplayName()- + "' is added as reviewer automatically to satisfy gate keeper requirement.");- }- }- if (!request.isNew()) {- PullRequestReviewInvitationManager reviewInvitationManager = GitPlex.getInstance(PullRequestReviewInvitationManager.class);- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {- if (!invitation.getDate().before(now))- reviewInvitationManager.save(invitation);- }- }- }-- @Override- protected void onDetach() {- requestModel.detach();-- super.onDetach();- }--}+package com.pmease.gitplex.web.component.pullrequest.requestreviewer;++import java.util.Date;+import java.util.HashSet;+import java.util.Set;++import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.model.IModel;++import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;+import com.pmease.gitplex.core.entity.Account;+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;+import com.pmease.gitplex.core.manager.AccountManager;+import com.pmease.gitplex.core.security.SecurityUtils;+import com.pmease.gitplex.web.component.avatar.RemoveableAvatar;+import com.pmease.gitplex.web.model.EntityModel;+import com.pmease.gitplex.web.model.UserModel;++@SuppressWarnings("serial")+public class ReviewerAvatar extends RemoveableAvatar {++ private final PullRequestReviewInvitation invitation;++ private final IModel<PullRequest> requestModel;++ public ReviewerAvatar(String id, PullRequestReviewInvitation invitation) {+ super(id, new UserModel(invitation.getUser()), "Remove reviewer");++ this.invitation = invitation;+ requestModel = new EntityModel<PullRequest>(invitation.getRequest());+ }++ @Override+ protected void onConfigure() {+ super.onConfigure();++ PullRequest request = requestModel.getObject();+ Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();++ boolean reviewEffective = false;+ if (!request.isNew())+ reviewEffective = request.isReviewEffective(getUser());+ setEnabled(request.isOpen() && !reviewEffective+ && (currentUser!= null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));+ }++ @Override+ protected void onAvatarRemove(AjaxRequestTarget target) {+ Date now = new Date();+ PullRequest request = requestModel.getObject();+ Set<Account> prevInvited = new HashSet<>();+ for (PullRequestReviewInvitation each: request.getReviewInvitations()) {+ if (each.isPreferred())+ prevInvited.add(each.getUser());+ if (each.getUser().equals(invitation.getUser())) {+ each.setPerferred(false);+ each.setDate(new Date());+ }+ }+ request.getTargetDepot().getGateKeeper().checkRequest(request);++ Set<Account> nowInvited = new HashSet<>();+ for (PullRequestReviewInvitation each: request.getReviewInvitations()) {+ if (each.isPreferred())+ nowInvited.add(each.getUser());+ }++ if (nowInvited.contains(invitation.getUser())) {+ getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()+ + "' is required by gate keeper and can not be removed");+ } else {+ nowInvited.removeAll(prevInvited);+ if (!nowInvited.isEmpty()) {+ getSession().warn("Reviewer '" + invitation.getUser().getDisplayName()+ + "' is removed and user '" + nowInvited.iterator().next().getDisplayName()+ + "' is added as reviewer automatically to satisfy gate keeper requirement.");+ }+ }+ if (!request.isNew()) {+ PullRequestReviewInvitationManager reviewInvitationManager = GitPlex.getInstance(PullRequestReviewInvitationManager.class);+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {+ if (invitation.getDate().getTime()>=now.getTime())+ reviewInvitationManager.save(invitation);+ }+ }+ }++ @Override+ protected void onDetach() {+ requestModel.detach();++ super.onDetach();+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.javaindex 677a618748..c01b82bac0 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/file/DepotFilePage.java@@ -1,960 +1,974 @@-package com.pmease.gitplex.web.page.depot.file;--import java.io.IOException;-import java.io.Serializable;-import java.util.ArrayList;-import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.concurrent.atomic.AtomicReference;--import javax.annotation.Nullable;--import org.apache.commons.lang3.StringUtils;-import org.apache.wicket.Component;-import org.apache.wicket.MetaDataKey;-import org.apache.wicket.RestartResponseException;-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.behavior.AttributeAppender;-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;-import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;-import org.apache.wicket.markup.head.CssHeaderItem;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.head.JavaScriptHeaderItem;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.image.Image;-import org.apache.wicket.model.AbstractReadOnlyModel;-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;-import org.apache.wicket.request.IRequestHandler;-import org.apache.wicket.request.cycle.RequestCycle;-import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;-import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.apache.wicket.request.resource.CssResourceReference;-import org.apache.wicket.request.resource.JavaScriptResourceReference;-import org.apache.wicket.request.resource.PackageResourceReference;-import org.eclipse.jgit.lib.Constants;-import org.eclipse.jgit.lib.FileMode;-import org.eclipse.jgit.lib.ObjectId;-import org.eclipse.jgit.revwalk.RevCommit;-import org.eclipse.jgit.revwalk.RevTree;-import org.eclipse.jgit.revwalk.RevWalk;-import org.eclipse.jgit.treewalk.TreeWalk;--import com.google.common.base.Objects;-import com.pmease.commons.git.BlobIdent;-import com.pmease.commons.git.GitUtils;-import com.pmease.commons.git.exception.ObjectNotExistException;-import com.pmease.commons.hibernate.UnitOfWork;-import com.pmease.commons.lang.extractors.TokenPosition;-import com.pmease.commons.loader.ListenerRegistry;-import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;-import com.pmease.commons.wicket.assets.jqueryui.JQueryUIResourceReference;-import com.pmease.commons.wicket.component.menu.MenuItem;-import com.pmease.commons.wicket.component.menu.MenuLink;-import com.pmease.commons.wicket.component.modal.ModalLink;-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;-import com.pmease.commons.wicket.websocket.WebSocketTrait;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.CodeComment;-import com.pmease.gitplex.core.entity.Depot;-import com.pmease.gitplex.core.entity.support.TextRange;-import com.pmease.gitplex.core.event.RefUpdated;-import com.pmease.gitplex.core.manager.CodeCommentManager;-import com.pmease.gitplex.core.security.SecurityUtils;-import com.pmease.gitplex.search.IndexManager;-import com.pmease.gitplex.search.SearchManager;-import com.pmease.gitplex.search.hit.QueryHit;-import com.pmease.gitplex.search.query.BlobQuery;-import com.pmease.gitplex.search.query.TextQuery;-import com.pmease.gitplex.web.WebSession;-import com.pmease.gitplex.web.component.archivemenulink.ArchiveMenuLink;-import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;-import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;-import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;-import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;-import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;-import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;-import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;-import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;-import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;-import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;-import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;-import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;-import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;-import com.pmease.gitplex.web.page.depot.DepotPage;-import com.pmease.gitplex.web.page.depot.NoBranchesPage;--@SuppressWarnings("serial")-public class DepotFilePage extends DepotPage implements BlobViewContext {-- private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {- };-- public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();-- private static class ViewStateKey extends MetaDataKey<String> {- };-- public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();-- private static final String PARAM_REVISION = "revision";-- private static final String PARAM_PATH = "path";-- private static final String PARAM_COMMENT = "comment";-- private static final String PARAM_MODE = "mode";-- private static final String PARAM_QUERY = "query";-- private static final String PARAM_VIEW_STATE = "view_state";-- private static final String PARAM_MARK = "mark";-- private static final String REVISION_PICKER_ID = "revisionPicker";-- private static final String FILE_NAVIGATOR_ID = "fileNavigator";-- private static final String CONTRIBUTION_ID = "contribution";-- private static final String FILE_VIEWER_ID = "fileViewer";-- private static final String SEARCH_RESULD_ID = "searchResult";-- private BlobIdent blobIdent = new BlobIdent();-- private ObjectId resolvedRevision;-- private TextRange mark;-- private Mode mode;-- private Long commentId;-- private Component revisionIndexing;-- private WebMarkupContainer searchResultContainer;-- private AtomicReference<String> newPathRef;-- private final CommitIndexed trait = new CommitIndexed();-- private transient List<QueryHit> queryHits;-- public DepotFilePage(final PageParameters params) {- super(params);-- if (getDepot().getDefaultBranch() == null)- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));-- trait.depotId = getDepot().getId();-- blobIdent.revision = params.get(PARAM_REVISION).toString();- blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());-- blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());- if (blobIdent.revision == null)- blobIdent.revision = getDepot().getDefaultBranch();-- resolvedRevision = getDepot().getObjectId(blobIdent.revision);-- RevCommit commit = getDepot().getRevCommit(blobIdent.revision);- trait.commitId = commit.copy();-- if (blobIdent.path != null) {- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {- RevTree revTree = commit.getTree();- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);- if (treeWalk == null) {- throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path- + "' in revision '" + blobIdent.revision + "'");- }- blobIdent.mode = treeWalk.getRawMode(0);- } catch (IOException e) {- throw new RuntimeException(e);- }- } else {- blobIdent.mode = FileMode.TREE.getBits();- }-- String modeStr = params.get(PARAM_MODE).toString();- if (modeStr != null)- mode = Mode.valueOf(modeStr.toUpperCase());- mark = TextRange.of(params.get(PARAM_MARK).toString());-- String commentIdStr = params.get(PARAM_COMMENT).toString();- if (commentIdStr != null)- commentId = Long.valueOf(commentIdStr);-- queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);- if (queryHits != null) {- WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);- } else {- String symbol = params.get(PARAM_QUERY).toString();- if (symbol != null) {- BlobQuery query = new TextQuery(symbol, false, true, true,- null, null, SearchResultPanel.MAX_QUERY_ENTRIES);- try {- SearchManager searchManager = GitPlex.getInstance(SearchManager.class);- queryHits = searchManager.search(depotModel.getObject(), trait.commitId, query);- } catch (InterruptedException e) {- throw new RuntimeException(e);- }- }- }-- RequestCycle.get().setMetaData(VIEW_STATE_KEY, params.get(PARAM_VIEW_STATE).toString());-- if (mode == Mode.EDIT || mode == Mode.DELETE) {- if (!isOnBranch())- throw new RuntimeException("Files can only be edited on branch");-- String path = blobIdent.path;- if (path != null && blobIdent.isTree())- path += "/";- if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))- unauthorized();- }- }-- @Override- protected void onInitialize() {- super.onInitialize();-- add(new InstantSearchPanel("instantSearch", depotModel, new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- return blobIdent.revision;- }-- }) {-- @Override- protected void onSelect(AjaxRequestTarget target, QueryHit hit) {- BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),- FileMode.REGULAR_FILE.getBits());- DepotFilePage.this.onSelect(target, selected, hit.getTokenPos());- }-- @Override- protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- }-- });-- add(new ModalLink("advancedSearch") {-- @Override- protected Component newContent(String id) {- return new AdvancedSearchPanel(id, depotModel, new AbstractReadOnlyModel<String>() {-- @Override- public String getObject() {- return blobIdent.revision;- }-- }) {-- @Override- protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- close(target);- }-- @Override- protected void onCancel(AjaxRequestTarget target) {- close(target);- }-- @Override- protected BlobIdent getCurrentBlob() {- return blobIdent;- }-- };- }-- });-- add(new ArchiveMenuLink("download", depotModel) {-- @Override- protected String getRevision() {- return blobIdent.revision;- }-- });-- newRevisionPicker(null);-- newFileNavigator(null);-- add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {-- @Override- protected void onInitialize() {- super.onInitialize();- add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));- setOutputMarkupPlaceholderTag(true);- }-- @Override- protected void onConfigure() {- super.onConfigure();-- IndexManager indexManager = GitPlex.getInstance(IndexManager.class);- if (!indexManager.isIndexed(getDepot(), trait.commitId)) {- GitPlex.getInstance(IndexManager.class).asyncIndex(getDepot(), trait.commitId);- setVisible(true);- } else {- setVisible(false);- }- }-- });-- newContributionPanel(null);- newFileViewer(null);-- add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));-- newSearchResult(null, queryHits);-- add(new WebSocketRenderBehavior() {-- @Override- protected WebSocketTrait getTrait() {- return trait;- }-- @Override- protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {- handler.add(revisionIndexing);- resizeWindow(handler);- }-- });- }-- /*- * In case we are on a branch, this operation makes sure that the branch resolves- * to a certain commit during the life cycle of our page, unless the page is- * refreshed. This can avoid the issue that displayed file content and subsequent- * operations encounters different commit if someone commits to the branch while- * we are staying on the page.- */- @Override- protected Map<String, ObjectId> getObjectIdCache() {- Map<String, ObjectId> objectIdCache = new HashMap<>();- if (resolvedRevision != null)- objectIdCache.put(blobIdent.revision, resolvedRevision);- return objectIdCache;- }-- @Override- public CodeComment getOpenComment() {- if (commentId != null)- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);- else- return null;- }-- private void newFileNavigator(@Nullable AjaxRequestTarget target) {- final BlobNameChangeCallback callback;-- if (mode == Mode.EDIT) {- callback = new BlobNameChangeCallback() {-- @Override- public void onChange(AjaxRequestTarget target, String blobName) {- String newPath;- if (blobIdent.isTree()) {- if (blobIdent.path != null)- newPath = blobIdent.path + "/" + blobName;- else- newPath = blobName;- } else {- if (blobIdent.path.contains("/"))- newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;- else- newPath = blobName;- }- newPathRef.set(GitUtils.normalizePath(newPath));- ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());- }-- };- } else {- callback = null;- }-- Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, this, callback) {-- @Override- protected void onNewFile(AjaxRequestTarget target) {- mode = Mode.EDIT;-- newFileNavigator(target);- newContributionPanel(target);- newFileViewer(target);-- pushState(target);- resizeWindow(target);- }-- };- if (target != null) {- replace(fileNavigator);- target.add(fileNavigator);- } else {- add(fileNavigator);- }- }-- private void newContributionPanel(@Nullable AjaxRequestTarget target) {- Component contributionPanel;- if (mode != Mode.EDIT) {- contributionPanel = new AjaxLazyLoadPanel(CONTRIBUTION_ID) {-- @Override- public Component getLoadingComponent(String markupId) {- IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);- String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";- return new Label(markupId, html).setEscapeModelStrings(false);- }-- @Override- protected void onComponentLoaded(Component component, AjaxRequestTarget target) {- super.onComponentLoaded(component, target);- resizeWindow(target);- }-- @Override- public Component getLazyLoadComponent(String markupId) {- return new ContributionPanel(markupId, depotModel, blobIdent);- }-- };- } else {- contributionPanel = new WebMarkupContainer(CONTRIBUTION_ID).setVisible(false);- }- contributionPanel.setOutputMarkupPlaceholderTag(true);- if (target != null) {- replace(contributionPanel);- target.add(contributionPanel);- } else {- add(contributionPanel);- }- }-- private BlobViewPanel renderBlobViewer(String panelId) {- for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {- BlobViewPanel panel = renderer.render(panelId, this);- if (panel != null)- return panel;- }-- throw new IllegalStateException("No applicable blob renderer found.");- }-- private void newFileViewer(@Nullable AjaxRequestTarget target) {- Component fileViewer;- if (mode == Mode.EDIT) {- final String refName = GitUtils.branch2ref(blobIdent.revision);- newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);- fileViewer = new FileEditPanel(- FILE_VIEWER_ID, depotModel, refName,- blobIdent.isTree()?null:blobIdent.path,- blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),- getDepot().getObjectId(blobIdent.revision), mark) {-- @Override- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {- Depot depot = getDepot();- String branch = blobIdent.revision;- depot.cacheObjectId(branch, newCommit);- resolvedRevision = newCommit;- BlobIdent committed = new BlobIdent(- branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());-- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {-- @Override- public void run() {- Depot depot = getDepot();- depot.cacheObjectId(branch, newCommit);- GitPlex.getInstance(ListenerRegistry.class).notify(new RefUpdated(depot, refName, oldCommit, newCommit));- }-- });-- State state = getState();- state.blobIdent = committed;- state.mode = null;- applyState(target, state);- pushState(target);- resizeWindow(target);- }-- @Override- protected void onCancel(AjaxRequestTarget target) {- mode = null;- newFileNavigator(target);- newContributionPanel(target);- newFileViewer(target);- pushState(target);- resizeWindow(target);- }-- };- } else if (mode == Mode.DELETE) {- final String refName = GitUtils.branch2ref(blobIdent.revision);-- CancelListener cancelListener = new CancelListener() {-- @Override- public void onCancel(AjaxRequestTarget target) {- mode = null;- newFileViewer(target);-- pushState(target);- resizeWindow(target);- }-- };-- fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,- null, getDepot().getObjectId(blobIdent.revision), cancelListener) {-- @Override- protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {- Depot depot = getDepot();- String branch = blobIdent.revision;- depot.cacheObjectId(branch, newCommit);- resolvedRevision = newCommit;- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {- RevTree revTree = getDepot().getRevCommit(newCommit).getTree();- String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");- while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {- if (parentPath.contains("/")) {- parentPath = StringUtils.substringBeforeLast(parentPath, "/");- } else {- parentPath = null;- break;- }- }-- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {-- @Override- public void run() {- Depot depot = getDepot();- depot.cacheObjectId(branch, newCommit);- GitPlex.getInstance(ListenerRegistry.class).notify(new RefUpdated(depot, refName, oldCommit, newCommit));- }-- });-- BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());- State state = getState();- state.blobIdent = parentBlobIdent;- state.mode = null;- applyState(target, state);- pushState(target);- resizeWindow(target);- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- };- } else if (blobIdent.path == null || blobIdent.isTree()) {- fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {-- @Override- protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {- DepotFilePage.this.onSelect(target, blobIdent, null);- }-- };- } else {- fileViewer = renderBlobViewer(FILE_VIEWER_ID);- }- if (target != null) {- replace(fileViewer);- target.add(fileViewer);- } else {- add(fileViewer);- }- }-- private void pushState(AjaxRequestTarget target) {- PageParameters params = paramsOf(getDepot(), getState());- CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);- pushState(target, url.toString(), getState());- }-- private State getState() {- State state = new State();- state.blobIdent = new BlobIdent(blobIdent);- state.mark = mark;- state.mode = mode;- state.commentId = commentId;- return state;- }-- private void setState(State state) {- if (!blobIdent.revision.equals(state.blobIdent.revision)) {- blobIdent = new BlobIdent(state.blobIdent);- /*- * a hack to reset resolved revision to null to disable getObjectIdCache()- * temporarily as otherwise getObjectId() method below will always- * resolved to existing value of resolvedRevision- */- resolvedRevision = null;- resolvedRevision = getDepot().getObjectId(blobIdent.revision);- } else {- blobIdent = new BlobIdent(state.blobIdent);- }- mark = state.mark;- mode = state.mode;- commentId = state.commentId;- }-- private void onSelect(AjaxRequestTarget target, String revision) {- State state = getState();- state.blobIdent.revision = revision;- state.commentId = null;- state.mode = null;- state.mark = null;-- if (state.blobIdent.path != null) {- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {- RevTree revTree = getDepot().getRevCommit(revision, true).getTree();- TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);- if (treeWalk != null) {- state.blobIdent.mode = treeWalk.getRawMode(0);- } else {- state.blobIdent.path = null;- state.blobIdent.mode = FileMode.TREE.getBits();- }- } catch (IOException e) {- throw new RuntimeException(e);- }- }-- applyState(target, state);- pushState(target);- resizeWindow(target);- }-- private void newRevisionPicker(@Nullable AjaxRequestTarget target) {- Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {-- @Override- protected String getRevisionUrl(String revision) {- State state = new State();- state.blobIdent.revision = revision;- PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);- return urlFor(DepotFilePage.class, params).toString();- }-- @Override- protected void onSelect(AjaxRequestTarget target, String revision) {- DepotFilePage.this.onSelect(target, revision);- }-- };- if (target != null) {- replace(revisionPicker);- target.add(revisionPicker);- } else {- add(revisionPicker);- }- }-- private void applyState(AjaxRequestTarget target, State state) {- if (!state.blobIdent.revision.equals(blobIdent.revision))- newSearchResult(target, null);-- setState(state);- trait.commitId = getDepot().getRevCommit(blobIdent.revision).getId();-- newRevisionPicker(target);-- newFileNavigator(target);-- target.add(revisionIndexing);-- newContributionPanel(target);- newFileViewer(target);- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);-- response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));- response.render(JavaScriptHeaderItem.forReference(JQueryUIResourceReference.INSTANCE));-- response.render(JavaScriptHeaderItem.forReference(- new JavaScriptResourceReference(DepotFilePage.class, "depot-file.js")));- response.render(CssHeaderItem.forReference(- new CssResourceReference(DepotFilePage.class, "depot-file.css")));- }-- public static PageParameters paramsOf(Depot depot, State state) {- PageParameters params = paramsOf(depot);- if (state.blobIdent.revision != null)- params.set(PARAM_REVISION, state.blobIdent.revision);- if (state.blobIdent.path != null)- params.set(PARAM_PATH, state.blobIdent.path);- if (state.mark != null)- params.set(PARAM_MARK, state.mark.toString());- if (state.commentId != null)- params.set(PARAM_COMMENT, state.commentId);- if (state.mode != null)- params.set(PARAM_MODE, state.mode.name().toLowerCase());- if (state.query != null)- params.set(PARAM_QUERY, state.query);- if (state.viewState != null)- params.set(PARAM_VIEW_STATE, state.viewState);- return params;- }-- private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {- Component searchResult;- if (hits != null) {- searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {-- @Override- protected void onClose(AjaxRequestTarget target) {- newSearchResult(target, null);- resizeWindow(target);- }-- };- if (target != null) {- target.appendJavaScript(""- + "$('#repo-file>.search-result').show(); "- + "$('#repo-file .search-result>.body').focus();");- }- } else {- searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);- if (target != null)- target.appendJavaScript("$('#repo-file>.search-result').hide();");- else- searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));- }- if (target != null) {- searchResultContainer.replace(searchResult);- target.add(searchResult);- } else {- searchResultContainer.add(searchResult);- }- }-- @Override- protected void onPopState(AjaxRequestTarget target, Serializable data) {- super.onPopState(target, data);-- applyState(target, (State) data);- resizeWindow(target);- }-- private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {- partialPageRequestHandler.appendJavaScript("$(window).resize();");- }-- @Override- protected void onSelect(AjaxRequestTarget target, Depot depot) {- setResponsePage(DepotFilePage.class, paramsOf(depot));- }-- static class CommitIndexed implements WebSocketTrait {-- Long depotId;-- volatile ObjectId commitId;-- @Override- public boolean is(WebSocketTrait trait) {- if (trait == null || !(trait instanceof CommitIndexed))- return false;- CommitIndexed other = (CommitIndexed) trait;- return Objects.equal(depotId, other.depotId) && Objects.equal(commitId, other.commitId);- }-- }-- @Override- public BlobIdent getBlobIdent() {- return blobIdent;- }-- @Override- public TextRange getMark() {- return mark;- }-- @Override- public void onMark(AjaxRequestTarget target, TextRange mark) {- this.mark = mark;- pushState(target);- }-- @Override- public String getMarkUrl(TextRange mark) {- State state = getState();- state.blobIdent.revision = resolvedRevision.name();- state.commentId = null;- state.mark = mark;- PageParameters params = paramsOf(getDepot(), state);- return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();- }-- @Override- public Mode getMode() {- return mode;- }-- @Override- public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {- mark = TextRange.of(tokenPos);- if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {- if (mark != null) {- Component fileViewer = get(FILE_VIEWER_ID);- if (fileViewer instanceof SourceViewPanel) {- SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;- sourceViewer.mark(target, mark, true);- } else if (fileViewer instanceof FileEditPanel) {- FileEditPanel fileEditor = (FileEditPanel) fileViewer;- fileEditor.mark(target, mark);- } else {- newFileViewer(target);- resizeWindow(target);- }- }- } else {- DepotFilePage.this.blobIdent.path = blobIdent.path;- DepotFilePage.this.blobIdent.mode = blobIdent.mode;-- mode = null;- commentId = null;-- newFileNavigator(target);- newContributionPanel(target);- newFileViewer(target);-- resizeWindow(target);- }- pushState(target);- }-- @Override- public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {- newSearchResult(target, hits);- resizeWindow(target);- }-- @Override- public void onBlameChange(AjaxRequestTarget target, boolean blame) {- mode = (blame?Mode.BLAME:null);- Component fileViewer = get(FILE_VIEWER_ID);- if (!(fileViewer instanceof SourceViewPanel)) {- newFileViewer(target);- resizeWindow(target);- }- pushState(target);- }-- @Override- public void onDelete(AjaxRequestTarget target) {- mode = Mode.DELETE;-- newFileViewer(target);- pushState(target);- resizeWindow(target);- }-- @Override- public void onEdit(AjaxRequestTarget target) {- mode = Mode.EDIT;-- newFileNavigator(target);- newContributionPanel(target);- newFileViewer(target);- pushState(target);- resizeWindow(target);- }-- @Override- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {- if (comment != null) {- commentId = comment.getId();- mark = comment.getCommentPos().getRange();- } else {- commentId = null;- }- pushState(target);- }-- @Override- public void onAddComment(AjaxRequestTarget target, TextRange mark) {- commentId = null;- this.mark = mark;- pushState(target);- }-- @Override- public boolean isOnBranch() {- return getDepot().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);- }-- @Override- public RevCommit getCommit() {- return getDepot().getRevCommit(getBlobIdent().revision);- }-- @Override- protected boolean isFootVisible() {- return false;- }-- @Override- public List<MenuItem> getMenuItems(MenuLink menuLink) {- if (mode != Mode.EDIT && mode != Mode.DELETE) {- Component fileViewer = get(FILE_VIEWER_ID);- if (fileViewer instanceof BlobViewPanel) {- BlobViewPanel blobViewPanel = (BlobViewPanel) fileViewer;- return blobViewPanel.getMenuItems(menuLink);- }- }- return new ArrayList<>();- }-- public static class State implements Serializable {-- private static final long serialVersionUID = 1L;-- public Long commentId;-- public BlobIdent blobIdent = new BlobIdent();-- public TextRange mark;-- public Mode mode;-- public transient String query;-- public transient String viewState;- }--}+package com.pmease.gitplex.web.page.depot.file;++import java.io.IOException;+import java.io.Serializable;+import java.util.ArrayList;+import java.util.HashMap;+import java.util.List;+import java.util.Map;+import java.util.concurrent.atomic.AtomicReference;++import javax.annotation.Nullable;++import org.apache.commons.lang3.StringUtils;+import org.apache.shiro.subject.Subject;+import org.apache.shiro.util.ThreadContext;+import org.apache.wicket.Component;+import org.apache.wicket.MetaDataKey;+import org.apache.wicket.RestartResponseException;+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;+import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;+import org.apache.wicket.markup.head.CssHeaderItem;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.head.JavaScriptHeaderItem;+import org.apache.wicket.markup.html.WebMarkupContainer;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.image.Image;+import org.apache.wicket.model.AbstractReadOnlyModel;+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;+import org.apache.wicket.request.IRequestHandler;+import org.apache.wicket.request.cycle.RequestCycle;+import org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.apache.wicket.request.resource.CssResourceReference;+import org.apache.wicket.request.resource.JavaScriptResourceReference;+import org.apache.wicket.request.resource.PackageResourceReference;+import org.eclipse.jgit.lib.Constants;+import org.eclipse.jgit.lib.FileMode;+import org.eclipse.jgit.lib.ObjectId;+import org.eclipse.jgit.revwalk.RevCommit;+import org.eclipse.jgit.revwalk.RevTree;+import org.eclipse.jgit.revwalk.RevWalk;+import org.eclipse.jgit.treewalk.TreeWalk;++import com.google.common.base.Objects;+import com.pmease.commons.git.BlobIdent;+import com.pmease.commons.git.GitUtils;+import com.pmease.commons.git.exception.ObjectNotExistException;+import com.pmease.commons.hibernate.UnitOfWork;+import com.pmease.commons.lang.extractors.TokenPosition;+import com.pmease.commons.loader.ListenerRegistry;+import com.pmease.commons.wicket.assets.cookies.CookiesResourceReference;+import com.pmease.commons.wicket.assets.jqueryui.JQueryUIResourceReference;+import com.pmease.commons.wicket.component.menu.MenuItem;+import com.pmease.commons.wicket.component.menu.MenuLink;+import com.pmease.commons.wicket.component.modal.ModalLink;+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;+import com.pmease.commons.wicket.websocket.WebSocketTrait;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.CodeComment;+import com.pmease.gitplex.core.entity.Depot;+import com.pmease.gitplex.core.entity.support.TextRange;+import com.pmease.gitplex.core.event.RefUpdated;+import com.pmease.gitplex.core.manager.CodeCommentManager;+import com.pmease.gitplex.core.security.SecurityUtils;+import com.pmease.gitplex.search.IndexManager;+import com.pmease.gitplex.search.SearchManager;+import com.pmease.gitplex.search.hit.QueryHit;+import com.pmease.gitplex.search.query.BlobQuery;+import com.pmease.gitplex.search.query.TextQuery;+import com.pmease.gitplex.web.WebSession;+import com.pmease.gitplex.web.component.archivemenulink.ArchiveMenuLink;+import com.pmease.gitplex.web.component.depotfile.blobsearch.advanced.AdvancedSearchPanel;+import com.pmease.gitplex.web.component.depotfile.blobsearch.instant.InstantSearchPanel;+import com.pmease.gitplex.web.component.depotfile.blobsearch.result.SearchResultPanel;+import com.pmease.gitplex.web.component.depotfile.blobview.BlobNameChangeCallback;+import com.pmease.gitplex.web.component.depotfile.blobview.BlobRenderer;+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewContext;+import com.pmease.gitplex.web.component.depotfile.blobview.BlobViewPanel;+import com.pmease.gitplex.web.component.depotfile.blobview.source.SourceViewPanel;+import com.pmease.gitplex.web.component.depotfile.editsave.CancelListener;+import com.pmease.gitplex.web.component.depotfile.editsave.EditSavePanel;+import com.pmease.gitplex.web.component.depotfile.fileedit.FileEditPanel;+import com.pmease.gitplex.web.component.depotfile.filelist.FileListPanel;+import com.pmease.gitplex.web.component.depotfile.filenavigator.FileNavigator;+import com.pmease.gitplex.web.component.revisionpicker.RevisionPicker;+import com.pmease.gitplex.web.page.depot.DepotPage;+import com.pmease.gitplex.web.page.depot.NoBranchesPage;++@SuppressWarnings("serial")+public class DepotFilePage extends DepotPage implements BlobViewContext {++ private static class SearchResultKey extends MetaDataKey<ArrayList<QueryHit>> {+ };++ public static final SearchResultKey SEARCH_RESULT_KEY = new SearchResultKey();++ private static class ViewStateKey extends MetaDataKey<String> {+ };++ public static final ViewStateKey VIEW_STATE_KEY = new ViewStateKey();++ private static final String PARAM_REVISION = "revision";++ private static final String PARAM_PATH = "path";++ private static final String PARAM_COMMENT = "comment";++ private static final String PARAM_MODE = "mode";++ private static final String PARAM_QUERY = "query";++ private static final String PARAM_VIEW_STATE = "view_state";++ private static final String PARAM_MARK = "mark";++ private static final String REVISION_PICKER_ID = "revisionPicker";++ private static final String FILE_NAVIGATOR_ID = "fileNavigator";++ private static final String CONTRIBUTION_ID = "contribution";++ private static final String FILE_VIEWER_ID = "fileViewer";++ private static final String SEARCH_RESULD_ID = "searchResult";++ private BlobIdent blobIdent = new BlobIdent();++ private ObjectId resolvedRevision;++ private TextRange mark;++ private Mode mode;++ private Long commentId;++ private Component revisionIndexing;++ private WebMarkupContainer searchResultContainer;++ private AtomicReference<String> newPathRef;++ private final CommitIndexed trait = new CommitIndexed();++ private transient List<QueryHit> queryHits;++ public DepotFilePage(final PageParameters params) {+ super(params);++ if (getDepot().getDefaultBranch() == null)+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));++ trait.depotId = getDepot().getId();++ blobIdent.revision = params.get(PARAM_REVISION).toString();+ blobIdent.path = GitUtils.normalizePath(params.get(PARAM_PATH).toString());++ blobIdent.revision = GitUtils.normalizePath(params.get(PARAM_REVISION).toString());+ if (blobIdent.revision == null)+ blobIdent.revision = getDepot().getDefaultBranch();++ resolvedRevision = getDepot().getObjectId(blobIdent.revision);++ RevCommit commit = getDepot().getRevCommit(blobIdent.revision);+ trait.commitId = commit.copy();++ if (blobIdent.path != null) {+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {+ RevTree revTree = commit.getTree();+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);+ if (treeWalk == null) {+ throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path+ + "' in revision '" + blobIdent.revision + "'");+ }+ blobIdent.mode = treeWalk.getRawMode(0);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ } else {+ blobIdent.mode = FileMode.TREE.getBits();+ }++ String modeStr = params.get(PARAM_MODE).toString();+ if (modeStr != null)+ mode = Mode.valueOf(modeStr.toUpperCase());+ mark = TextRange.of(params.get(PARAM_MARK).toString());++ String commentIdStr = params.get(PARAM_COMMENT).toString();+ if (commentIdStr != null)+ commentId = Long.valueOf(commentIdStr);++ queryHits = WebSession.get().getMetaData(SEARCH_RESULT_KEY);+ if (queryHits != null) {+ WebSession.get().setMetaData(SEARCH_RESULT_KEY, null);+ } else {+ String symbol = params.get(PARAM_QUERY).toString();+ if (symbol != null) {+ BlobQuery query = new TextQuery(symbol, false, true, true,+ null, null, SearchResultPanel.MAX_QUERY_ENTRIES);+ try {+ SearchManager searchManager = GitPlex.getInstance(SearchManager.class);+ queryHits = searchManager.search(depotModel.getObject(), trait.commitId, query);+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ }+ }+ }++ RequestCycle.get().setMetaData(VIEW_STATE_KEY, params.get(PARAM_VIEW_STATE).toString());++ if (mode == Mode.EDIT || mode == Mode.DELETE) {+ if (!isOnBranch())+ throw new RuntimeException("Files can only be edited on branch");++ String path = blobIdent.path;+ if (path != null && blobIdent.isTree())+ path += "/";+ if (!SecurityUtils.canModify(getDepot(), blobIdent.revision, path))+ unauthorized();+ }+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(new InstantSearchPanel("instantSearch", depotModel, new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ return blobIdent.revision;+ }++ }) {++ @Override+ protected void onSelect(AjaxRequestTarget target, QueryHit hit) {+ BlobIdent selected = new BlobIdent(blobIdent.revision, hit.getBlobPath(),+ FileMode.REGULAR_FILE.getBits());+ DepotFilePage.this.onSelect(target, selected, hit.getTokenPos());+ }++ @Override+ protected void onMoreQueried(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ }++ });++ add(new ModalLink("advancedSearch") {++ @Override+ protected Component newContent(String id) {+ return new AdvancedSearchPanel(id, depotModel, new AbstractReadOnlyModel<String>() {++ @Override+ public String getObject() {+ return blobIdent.revision;+ }++ }) {++ @Override+ protected void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ close(target);+ }++ @Override+ protected void onCancel(AjaxRequestTarget target) {+ close(target);+ }++ @Override+ protected BlobIdent getCurrentBlob() {+ return blobIdent;+ }++ };+ }++ });++ add(new ArchiveMenuLink("download", depotModel) {++ @Override+ protected String getRevision() {+ return blobIdent.revision;+ }++ });++ newRevisionPicker(null);++ newFileNavigator(null);++ add(revisionIndexing = new WebMarkupContainer("revisionIndexing") {++ @Override+ protected void onInitialize() {+ super.onInitialize();+ add(new Image("icon", new PackageResourceReference(DepotFilePage.class, "indexing.gif")));+ setOutputMarkupPlaceholderTag(true);+ }++ @Override+ protected void onConfigure() {+ super.onConfigure();++ IndexManager indexManager = GitPlex.getInstance(IndexManager.class);+ if (!indexManager.isIndexed(getDepot(), trait.commitId)) {+ GitPlex.getInstance(IndexManager.class).asyncIndex(getDepot(), trait.commitId);+ setVisible(true);+ } else {+ setVisible(false);+ }+ }++ });++ newContributionPanel(null);+ newFileViewer(null);++ add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));++ newSearchResult(null, queryHits);++ add(new WebSocketRenderBehavior() {++ @Override+ protected WebSocketTrait getTrait() {+ return trait;+ }++ @Override+ protected void onRender(WebSocketRequestHandler handler, WebSocketTrait trait) {+ handler.add(revisionIndexing);+ resizeWindow(handler);+ }++ });+ }++ /*+ * In case we are on a branch, this operation makes sure that the branch resolves+ * to a certain commit during the life cycle of our page, unless the page is+ * refreshed. This can avoid the issue that displayed file content and subsequent+ * operations encounters different commit if someone commits to the branch while+ * we are staying on the page.+ */+ @Override+ protected Map<String, ObjectId> getObjectIdCache() {+ Map<String, ObjectId> objectIdCache = new HashMap<>();+ if (resolvedRevision != null)+ objectIdCache.put(blobIdent.revision, resolvedRevision);+ return objectIdCache;+ }++ @Override+ public CodeComment getOpenComment() {+ if (commentId != null)+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);+ else+ return null;+ }++ private void newFileNavigator(@Nullable AjaxRequestTarget target) {+ final BlobNameChangeCallback callback;++ if (mode == Mode.EDIT) {+ callback = new BlobNameChangeCallback() {++ @Override+ public void onChange(AjaxRequestTarget target, String blobName) {+ String newPath;+ if (blobIdent.isTree()) {+ if (blobIdent.path != null)+ newPath = blobIdent.path + "/" + blobName;+ else+ newPath = blobName;+ } else {+ if (blobIdent.path.contains("/"))+ newPath = StringUtils.substringBeforeLast(blobIdent.path, "/") + "/" + blobName;+ else+ newPath = blobName;+ }+ newPathRef.set(GitUtils.normalizePath(newPath));+ ((FileEditPanel) get(FILE_VIEWER_ID)).onNewPathChange(target, newPathRef.get());+ }++ };+ } else {+ callback = null;+ }++ Component fileNavigator = new FileNavigator(FILE_NAVIGATOR_ID, this, callback) {++ @Override+ protected void onNewFile(AjaxRequestTarget target) {+ mode = Mode.EDIT;++ newFileNavigator(target);+ newContributionPanel(target);+ newFileViewer(target);++ pushState(target);+ resizeWindow(target);+ }++ };+ if (target != null) {+ replace(fileNavigator);+ target.add(fileNavigator);+ } else {+ add(fileNavigator);+ }+ }++ private void newContributionPanel(@Nullable AjaxRequestTarget target) {+ Component contributionPanel;+ if (mode != Mode.EDIT) {+ contributionPanel = new AjaxLazyLoadPanel(CONTRIBUTION_ID) {++ @Override+ public Component getLoadingComponent(String markupId) {+ IRequestHandler handler = new ResourceReferenceRequestHandler(AbstractDefaultAjaxBehavior.INDICATOR);+ String html = "<img src='" + RequestCycle.get().urlFor(handler) + "' class='loading'/> Loading latest commit...";+ return new Label(markupId, html).setEscapeModelStrings(false);+ }++ @Override+ protected void onComponentLoaded(Component component, AjaxRequestTarget target) {+ super.onComponentLoaded(component, target);+ resizeWindow(target);+ }++ @Override+ public Component getLazyLoadComponent(String markupId) {+ return new ContributionPanel(markupId, depotModel, blobIdent);+ }++ };+ } else {+ contributionPanel = new WebMarkupContainer(CONTRIBUTION_ID).setVisible(false);+ }+ contributionPanel.setOutputMarkupPlaceholderTag(true);+ if (target != null) {+ replace(contributionPanel);+ target.add(contributionPanel);+ } else {+ add(contributionPanel);+ }+ }++ private BlobViewPanel renderBlobViewer(String panelId) {+ for (BlobRenderer renderer: GitPlex.getExtensions(BlobRenderer.class)) {+ BlobViewPanel panel = renderer.render(panelId, this);+ if (panel != null)+ return panel;+ }++ throw new IllegalStateException("No applicable blob renderer found.");+ }++ private void newFileViewer(@Nullable AjaxRequestTarget target) {+ Component fileViewer;+ if (mode == Mode.EDIT) {+ final String refName = GitUtils.branch2ref(blobIdent.revision);+ newPathRef = new AtomicReference<>(blobIdent.isTree()?null:blobIdent.path);+ fileViewer = new FileEditPanel(+ FILE_VIEWER_ID, depotModel, refName,+ blobIdent.isTree()?null:blobIdent.path,+ blobIdent.isTree()?"":getDepot().getBlob(blobIdent).getText().getContent(),+ getDepot().getObjectId(blobIdent.revision), mark) {++ @Override+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {+ Depot depot = getDepot();+ String branch = blobIdent.revision;+ depot.cacheObjectId(branch, newCommit);+ resolvedRevision = newCommit;+ BlobIdent committed = new BlobIdent(+ branch, newPathRef.get(), FileMode.REGULAR_FILE.getBits());++ Subject subject = SecurityUtils.getSubject();+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {++ @Override+ public void run() {+ ThreadContext.bind(subject);+ try {+ Depot depot = getDepot();+ depot.cacheObjectId(branch, newCommit);+ GitPlex.getInstance(ListenerRegistry.class).notify(new RefUpdated(depot, refName, oldCommit, newCommit));+ } finally {+ ThreadContext.unbindSubject();+ }+ }++ });++ State state = getState();+ state.blobIdent = committed;+ state.mode = null;+ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ protected void onCancel(AjaxRequestTarget target) {+ mode = null;+ newFileNavigator(target);+ newContributionPanel(target);+ newFileViewer(target);+ pushState(target);+ resizeWindow(target);+ }++ };+ } else if (mode == Mode.DELETE) {+ final String refName = GitUtils.branch2ref(blobIdent.revision);++ CancelListener cancelListener = new CancelListener() {++ @Override+ public void onCancel(AjaxRequestTarget target) {+ mode = null;+ newFileViewer(target);++ pushState(target);+ resizeWindow(target);+ }++ };++ fileViewer = new EditSavePanel(FILE_VIEWER_ID, depotModel, refName, blobIdent.path,+ null, getDepot().getObjectId(blobIdent.revision), cancelListener) {++ @Override+ protected void onCommitted(AjaxRequestTarget target, ObjectId oldCommit, ObjectId newCommit) {+ Depot depot = getDepot();+ String branch = blobIdent.revision;+ depot.cacheObjectId(branch, newCommit);+ resolvedRevision = newCommit;+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {+ RevTree revTree = getDepot().getRevCommit(newCommit).getTree();+ String parentPath = StringUtils.substringBeforeLast(blobIdent.path, "/");+ while (TreeWalk.forPath(getDepot().getRepository(), parentPath, revTree) == null) {+ if (parentPath.contains("/")) {+ parentPath = StringUtils.substringBeforeLast(parentPath, "/");+ } else {+ parentPath = null;+ break;+ }+ }++ Subject subject = SecurityUtils.getSubject();+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {++ @Override+ public void run() {+ ThreadContext.bind(subject);+ try {+ Depot depot = getDepot();+ depot.cacheObjectId(branch, newCommit);+ GitPlex.getInstance(ListenerRegistry.class).notify(new RefUpdated(depot, refName, oldCommit, newCommit));+ } finally {+ ThreadContext.unbindSubject();+ }+ }++ });++ BlobIdent parentBlobIdent = new BlobIdent(branch, parentPath, FileMode.TREE.getBits());+ State state = getState();+ state.blobIdent = parentBlobIdent;+ state.mode = null;+ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ };+ } else if (blobIdent.path == null || blobIdent.isTree()) {+ fileViewer = new FileListPanel(FILE_VIEWER_ID, depotModel, blobIdent) {++ @Override+ protected void onSelect(AjaxRequestTarget target, BlobIdent blobIdent) {+ DepotFilePage.this.onSelect(target, blobIdent, null);+ }++ };+ } else {+ fileViewer = renderBlobViewer(FILE_VIEWER_ID);+ }+ if (target != null) {+ replace(fileViewer);+ target.add(fileViewer);+ } else {+ add(fileViewer);+ }+ }++ private void pushState(AjaxRequestTarget target) {+ PageParameters params = paramsOf(getDepot(), getState());+ CharSequence url = RequestCycle.get().urlFor(DepotFilePage.class, params);+ pushState(target, url.toString(), getState());+ }++ private State getState() {+ State state = new State();+ state.blobIdent = new BlobIdent(blobIdent);+ state.mark = mark;+ state.mode = mode;+ state.commentId = commentId;+ return state;+ }++ private void setState(State state) {+ if (!blobIdent.revision.equals(state.blobIdent.revision)) {+ blobIdent = new BlobIdent(state.blobIdent);+ /*+ * a hack to reset resolved revision to null to disable getObjectIdCache()+ * temporarily as otherwise getObjectId() method below will always+ * resolved to existing value of resolvedRevision+ */+ resolvedRevision = null;+ resolvedRevision = getDepot().getObjectId(blobIdent.revision);+ } else {+ blobIdent = new BlobIdent(state.blobIdent);+ }+ mark = state.mark;+ mode = state.mode;+ commentId = state.commentId;+ }++ private void onSelect(AjaxRequestTarget target, String revision) {+ State state = getState();+ state.blobIdent.revision = revision;+ state.commentId = null;+ state.mode = null;+ state.mark = null;++ if (state.blobIdent.path != null) {+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {+ RevTree revTree = getDepot().getRevCommit(revision, true).getTree();+ TreeWalk treeWalk = TreeWalk.forPath(getDepot().getRepository(), blobIdent.path, revTree);+ if (treeWalk != null) {+ state.blobIdent.mode = treeWalk.getRawMode(0);+ } else {+ state.blobIdent.path = null;+ state.blobIdent.mode = FileMode.TREE.getBits();+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ applyState(target, state);+ pushState(target);+ resizeWindow(target);+ }++ private void newRevisionPicker(@Nullable AjaxRequestTarget target) {+ Component revisionPicker = new RevisionPicker(REVISION_PICKER_ID, depotModel, blobIdent.revision, true) {++ @Override+ protected String getRevisionUrl(String revision) {+ State state = new State();+ state.blobIdent.revision = revision;+ PageParameters params = DepotFilePage.paramsOf(depotModel.getObject(), state);+ return urlFor(DepotFilePage.class, params).toString();+ }++ @Override+ protected void onSelect(AjaxRequestTarget target, String revision) {+ DepotFilePage.this.onSelect(target, revision);+ }++ };+ if (target != null) {+ replace(revisionPicker);+ target.add(revisionPicker);+ } else {+ add(revisionPicker);+ }+ }++ private void applyState(AjaxRequestTarget target, State state) {+ if (!state.blobIdent.revision.equals(blobIdent.revision))+ newSearchResult(target, null);++ setState(state);+ trait.commitId = getDepot().getRevCommit(blobIdent.revision).getId();++ newRevisionPicker(target);++ newFileNavigator(target);++ target.add(revisionIndexing);++ newContributionPanel(target);+ newFileViewer(target);+ }++ @Override+ public void renderHead(IHeaderResponse response) {+ super.renderHead(response);++ response.render(JavaScriptHeaderItem.forReference(CookiesResourceReference.INSTANCE));+ response.render(JavaScriptHeaderItem.forReference(JQueryUIResourceReference.INSTANCE));++ response.render(JavaScriptHeaderItem.forReference(+ new JavaScriptResourceReference(DepotFilePage.class, "depot-file.js")));+ response.render(CssHeaderItem.forReference(+ new CssResourceReference(DepotFilePage.class, "depot-file.css")));+ }++ public static PageParameters paramsOf(Depot depot, State state) {+ PageParameters params = paramsOf(depot);+ if (state.blobIdent.revision != null)+ params.set(PARAM_REVISION, state.blobIdent.revision);+ if (state.blobIdent.path != null)+ params.set(PARAM_PATH, state.blobIdent.path);+ if (state.mark != null)+ params.set(PARAM_MARK, state.mark.toString());+ if (state.commentId != null)+ params.set(PARAM_COMMENT, state.commentId);+ if (state.mode != null)+ params.set(PARAM_MODE, state.mode.name().toLowerCase());+ if (state.query != null)+ params.set(PARAM_QUERY, state.query);+ if (state.viewState != null)+ params.set(PARAM_VIEW_STATE, state.viewState);+ return params;+ }++ private void newSearchResult(@Nullable AjaxRequestTarget target, @Nullable List<QueryHit> hits) {+ Component searchResult;+ if (hits != null) {+ searchResult = new SearchResultPanel(SEARCH_RESULD_ID, this, hits) {++ @Override+ protected void onClose(AjaxRequestTarget target) {+ newSearchResult(target, null);+ resizeWindow(target);+ }++ };+ if (target != null) {+ target.appendJavaScript(""+ + "$('#repo-file>.search-result').show(); "+ + "$('#repo-file .search-result>.body').focus();");+ }+ } else {+ searchResult = new WebMarkupContainer(SEARCH_RESULD_ID).setOutputMarkupId(true);+ if (target != null)+ target.appendJavaScript("$('#repo-file>.search-result').hide();");+ else+ searchResultContainer.add(AttributeAppender.replace("style", "display: none;"));+ }+ if (target != null) {+ searchResultContainer.replace(searchResult);+ target.add(searchResult);+ } else {+ searchResultContainer.add(searchResult);+ }+ }++ @Override+ protected void onPopState(AjaxRequestTarget target, Serializable data) {+ super.onPopState(target, data);++ applyState(target, (State) data);+ resizeWindow(target);+ }++ private void resizeWindow(IPartialPageRequestHandler partialPageRequestHandler) {+ partialPageRequestHandler.appendJavaScript("$(window).resize();");+ }++ @Override+ protected void onSelect(AjaxRequestTarget target, Depot depot) {+ setResponsePage(DepotFilePage.class, paramsOf(depot));+ }++ static class CommitIndexed implements WebSocketTrait {++ Long depotId;++ volatile ObjectId commitId;++ @Override+ public boolean is(WebSocketTrait trait) {+ if (trait == null || !(trait instanceof CommitIndexed))+ return false;+ CommitIndexed other = (CommitIndexed) trait;+ return Objects.equal(depotId, other.depotId) && Objects.equal(commitId, other.commitId);+ }++ }++ @Override+ public BlobIdent getBlobIdent() {+ return blobIdent;+ }++ @Override+ public TextRange getMark() {+ return mark;+ }++ @Override+ public void onMark(AjaxRequestTarget target, TextRange mark) {+ this.mark = mark;+ pushState(target);+ }++ @Override+ public String getMarkUrl(TextRange mark) {+ State state = getState();+ state.blobIdent.revision = resolvedRevision.name();+ state.commentId = null;+ state.mark = mark;+ PageParameters params = paramsOf(getDepot(), state);+ return RequestCycle.get().urlFor(DepotFilePage.class, params).toString();+ }++ @Override+ public Mode getMode() {+ return mode;+ }++ @Override+ public void onSelect(AjaxRequestTarget target, BlobIdent blobIdent, @Nullable TokenPosition tokenPos) {+ mark = TextRange.of(tokenPos);+ if (Objects.equal(DepotFilePage.this.blobIdent.path, blobIdent.path)) {+ if (mark != null) {+ Component fileViewer = get(FILE_VIEWER_ID);+ if (fileViewer instanceof SourceViewPanel) {+ SourceViewPanel sourceViewer = (SourceViewPanel) fileViewer;+ sourceViewer.mark(target, mark, true);+ } else if (fileViewer instanceof FileEditPanel) {+ FileEditPanel fileEditor = (FileEditPanel) fileViewer;+ fileEditor.mark(target, mark);+ } else {+ newFileViewer(target);+ resizeWindow(target);+ }+ }+ } else {+ DepotFilePage.this.blobIdent.path = blobIdent.path;+ DepotFilePage.this.blobIdent.mode = blobIdent.mode;++ mode = null;+ commentId = null;++ newFileNavigator(target);+ newContributionPanel(target);+ newFileViewer(target);++ resizeWindow(target);+ }+ pushState(target);+ }++ @Override+ public void onSearchComplete(AjaxRequestTarget target, List<QueryHit> hits) {+ newSearchResult(target, hits);+ resizeWindow(target);+ }++ @Override+ public void onBlameChange(AjaxRequestTarget target, boolean blame) {+ mode = (blame?Mode.BLAME:null);+ Component fileViewer = get(FILE_VIEWER_ID);+ if (!(fileViewer instanceof SourceViewPanel)) {+ newFileViewer(target);+ resizeWindow(target);+ }+ pushState(target);+ }++ @Override+ public void onDelete(AjaxRequestTarget target) {+ mode = Mode.DELETE;++ newFileViewer(target);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ public void onEdit(AjaxRequestTarget target) {+ mode = Mode.EDIT;++ newFileNavigator(target);+ newContributionPanel(target);+ newFileViewer(target);+ pushState(target);+ resizeWindow(target);+ }++ @Override+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {+ if (comment != null) {+ commentId = comment.getId();+ mark = comment.getCommentPos().getRange();+ } else {+ commentId = null;+ }+ pushState(target);+ }++ @Override+ public void onAddComment(AjaxRequestTarget target, TextRange mark) {+ commentId = null;+ this.mark = mark;+ pushState(target);+ }++ @Override+ public boolean isOnBranch() {+ return getDepot().getRefs(Constants.R_HEADS).containsKey(blobIdent.revision);+ }++ @Override+ public RevCommit getCommit() {+ return getDepot().getRevCommit(getBlobIdent().revision);+ }++ @Override+ protected boolean isFootVisible() {+ return false;+ }++ @Override+ public List<MenuItem> getMenuItems(MenuLink menuLink) {+ if (mode != Mode.EDIT && mode != Mode.DELETE) {+ Component fileViewer = get(FILE_VIEWER_ID);+ if (fileViewer instanceof BlobViewPanel) {+ BlobViewPanel blobViewPanel = (BlobViewPanel) fileViewer;+ return blobViewPanel.getMenuItems(menuLink);+ }+ }+ return new ArrayList<>();+ }++ public static class State implements Serializable {++ private static final long serialVersionUID = 1L;++ public Long commentId;++ public BlobIdent blobIdent = new BlobIdent();++ public TextRange mark;++ public Mode mode;++ public transient String query;++ public transient String viewState;+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.htmlindex 012253716f..a7191a00e9 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.html@@ -1,73 +1,78 @@-<wicket:extend>- <table class="overview">- <tr>- <td class="activities">- <table>- <tr wicket:id="requestActivities" class="activity">- <td wicket:id="avatar" class="avatar"><a wicket:id="avatar"></a></td>- <td class="spacer"></td>- <td wicket:id="content" class="content"></td>- </tr>- </table>- <div wicket:id="addComment" class="add-comment">- <form wicket:id="form" class="leave-confirm">- <div wicket:id="feedback"></div>- <textarea wicket:id="input" class="form-control" rows="5" placeholder="Leave a comment"></textarea>- <div class="actions">- <button wicket:id="comment" class="dirty-aware btn btn-primary">Comment</button>- </div>- </form>- </div>- </td>- <td class="info">- <div class="well">- <div wicket:id="assignee" class="assignee"></div>- <div wicket:id="reviewers" class="reviewers">- <label>Reviewers:</label>- <ul class="clearfix list-unstyled">- <li wicket:id="reviewers" class="pull-left">- <span wicket:id="avatar"></span>- <span wicket:id="result"></span>- </li>- </ul>- <wicket:enclosure child="addReviewer">- <div>- <input wicket:id="addReviewer" type="hidden"></input>- </div>- </wicket:enclosure>- </div>- <div wicket:id="integrationStrategy" class="integration-strategy">- <label>- Integration Strategy:- <span wicket:id="help" class="fa fa-question-circle pointer small"></span>- </label>- <div>- <select wicket:id="editor"></select>- <span wicket:id="viewer"></span>- </div>- </div>- <div wicket:id="watch" class="watch">- <div>- <label>Watch Status:</label>- <select wicket:id="option"></select>- </div>- <div class="help-block"><i class="fa fa-info-circle small"></i> <span wicket:id="help"></span></div>- </div>- </div>- </td>- </tr>- </table>- <wicket:fragment wicket:id="assigneeEditFrag">- <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>- <div>- <input wicket:id="assignee" type="hidden"></input>- </div>- </wicket:fragment>- <wicket:fragment wicket:id="assigneeViewFrag">- <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>- <span wicket:id="assignee" class="avatar"></span>- </wicket:fragment>- <wicket:fragment wicket:id="noAssigneeFrag">- This pull request will be integrated automatically as long as it passes gate keeper check.- </wicket:fragment>+<wicket:extend>+ <table class="overview">+ <tr>+ <td class="activities">+ <table>+ <tr wicket:id="requestActivities" class="activity">+ <td wicket:id="avatar" class="avatar"><a wicket:id="avatar"></a></td>+ <td class="spacer"></td>+ <td wicket:id="content" class="content"></td>+ </tr>+ </table>+ <div wicket:id="addComment" class="add-comment">+ <form wicket:id="form" class="leave-confirm">+ <div wicket:id="feedback"></div>+ <textarea wicket:id="input" class="form-control" rows="5" placeholder="Leave a comment"></textarea>+ <div class="actions">+ <button wicket:id="comment" class="dirty-aware btn btn-primary">Comment</button>+ </div>+ </form>+ </div>+ </td>+ <td class="info">+ <div class="well">+ <div wicket:id="assignee" class="assignee"></div>+ <div wicket:id="reviewers" class="reviewers">+ <label>Reviewers:</label>+ <ul class="clearfix list-unstyled">+ <li wicket:id="reviewers" class="pull-left">+ <span wicket:id="avatar"></span>+ <span wicket:id="result"></span>+ </li>+ </ul>+ <wicket:enclosure child="addReviewer">+ <div>+ <input wicket:id="addReviewer" type="hidden"></input>+ </div>+ </wicket:enclosure>+ </div>+ <div wicket:id="integrationStrategy" class="integration-strategy">+ <label>+ Integration Strategy:+ <span wicket:id="help" class="fa fa-question-circle pointer small"></span>+ </label>+ <div>+ <select wicket:id="editor"></select>+ <span wicket:id="viewer"></span>+ </div>+ </div>+ <div wicket:id="watch" class="watch">+ <div>+ <label>Watch Status:</label>+ <select wicket:id="option"></select>+ </div>+ <div class="help-block"><i class="fa fa-info-circle small"></i> <span wicket:id="help"></span></div>+ </div>+ </div>+ </td>+ </tr>+ </table>+ <wicket:fragment wicket:id="assigneeEditFrag">+ <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>+ <div>+ <input wicket:id="assignee" type="hidden"></input>+ </div>+ </wicket:fragment>+ <wicket:fragment wicket:id="assigneeViewFrag">+ <label>Assigned To: <span wicket:id="help" class="fa fa-question-circle pointer small"></span></label>+ <span wicket:id="assignee" class="avatar"></span>+ </wicket:fragment>+ <wicket:fragment wicket:id="noAssigneeFrag">+ This pull request will be integrated automatically as long as it passes gate keeper check.+ </wicket:fragment>+ <wicket:fragment wicket:id="sinceChangesRowContentFrag">+ <div>+ <span class="icon fa fa-ext fa-file-diff"></span> <a wicket:id="sinceChanges">Changes since last visit</a>+ </div>+ </wicket:fragment></wicket:extend>\ No newline at end of filediff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.javaindex 66f8121326..9382662d7c 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/RequestOverviewPage.java@@ -1,646 +1,708 @@-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;--import java.util.ArrayList;-import java.util.Arrays;-import java.util.List;--import org.apache.wicket.Component;-import org.apache.wicket.ajax.AjaxRequestTarget;-import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;-import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;-import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;-import org.apache.wicket.behavior.AttributeAppender;-import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;-import org.apache.wicket.event.Broadcast;-import org.apache.wicket.event.IEvent;-import org.apache.wicket.markup.head.CssHeaderItem;-import org.apache.wicket.markup.head.IHeaderResponse;-import org.apache.wicket.markup.html.WebMarkupContainer;-import org.apache.wicket.markup.html.basic.Label;-import org.apache.wicket.markup.html.form.DropDownChoice;-import org.apache.wicket.markup.html.form.Form;-import org.apache.wicket.markup.html.form.IChoiceRenderer;-import org.apache.wicket.markup.html.list.ListItem;-import org.apache.wicket.markup.html.list.ListView;-import org.apache.wicket.markup.html.panel.Fragment;-import org.apache.wicket.markup.repeater.RepeatingView;-import org.apache.wicket.model.IModel;-import org.apache.wicket.model.LoadableDetachableModel;-import org.apache.wicket.model.Model;-import org.apache.wicket.request.mapper.parameter.PageParameters;-import org.apache.wicket.request.resource.CssResourceReference;--import com.google.common.base.Preconditions;-import com.pmease.commons.hibernate.dao.Dao;-import com.pmease.commons.wicket.behavior.TooltipBehavior;-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;-import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.Account;-import com.pmease.gitplex.core.entity.Depot;-import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;-import com.pmease.gitplex.core.entity.PullRequestComment;-import com.pmease.gitplex.core.entity.PullRequestReference;-import com.pmease.gitplex.core.entity.PullRequestStatusChange;-import com.pmease.gitplex.core.entity.PullRequestUpdate;-import com.pmease.gitplex.core.entity.PullRequestWatch;-import com.pmease.gitplex.core.entity.PullRequestReview;-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;-import com.pmease.gitplex.core.manager.AccountManager;-import com.pmease.gitplex.core.manager.PullRequestCommentManager;-import com.pmease.gitplex.core.manager.PullRequestManager;-import com.pmease.gitplex.core.security.ObjectPermission;-import com.pmease.gitplex.core.security.SecurityUtils;-import com.pmease.gitplex.web.component.avatar.Avatar;-import com.pmease.gitplex.web.component.avatar.AvatarLink;-import com.pmease.gitplex.web.component.comment.CommentInput;-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;-import com.pmease.gitplex.web.component.pullrequest.ReviewResultIcon;-import com.pmease.gitplex.web.component.pullrequest.requestassignee.AssigneeChoice;-import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerAvatar;-import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerChoice;-import com.pmease.gitplex.web.model.EntityModel;-import com.pmease.gitplex.web.model.ReviewersModel;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.CommentRemoved;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.CommentedActivity;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.OpenedActivity;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.ReferencedActivity;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.StatusChangeActivity;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.UpdatedActivity;-import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;-import com.pmease.gitplex.web.websocket.PullRequestChanged;--import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;-import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig;-import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig.Placement;--@SuppressWarnings("serial")-public class RequestOverviewPage extends RequestDetailPage {-- private static final String ASSIGNEE_HELP = "Assignee has write permission to the "- + "repository and is resonsible for integrating the pull request into "- + "target branch after it passes gate keeper check.";-- private enum WatchStatus {- WATCHING("Watching"),- NOT_WATCHING("Not Watching"),- IGNORE("Ignore");-- private final String displayName;-- WatchStatus(String displayName) {- this.displayName = displayName;- }-- @Override- public String toString() {- return displayName;- }-- };-- private RepeatingView activitiesView;-- public RequestOverviewPage(PageParameters params) {- super(params);- }-- private Component newActivityRow(final String id, PullRequestActivity activity) {- WebMarkupContainer row = new WebMarkupContainer(id, Model.of(activity)) {-- @Override- public void onEvent(IEvent<?> event) {- super.onEvent(event);-- if (event.getPayload() instanceof CommentRemoved) {- CommentRemoved commentRemoved = (CommentRemoved) event.getPayload();- remove();- commentRemoved.getPartialPageRequestHandler().appendJavaScript(String.format("$('#%s').remove();", getMarkupId()));- }- }-- };-- row.setOutputMarkupId(true);-- if (row.get("content") == null)- row.add(activity.render("content"));-- WebMarkupContainer avatarColumn = new WebMarkupContainer("avatar");- row.add(avatarColumn);-- if (activity instanceof OpenedActivity) {- row.add(AttributeAppender.append("class", " discussion"));- avatarColumn.add(new AvatarLink("avatar", ((OpenedActivity)activity).getRequest().getSubmitter(), null));- } else if (activity instanceof CommentedActivity) {- row.add(AttributeAppender.append("class", " discussion"));- avatarColumn.add(new AvatarLink("avatar", ((CommentedActivity)activity).getComment().getUser(), null));- } else {- row.add(AttributeAppender.append("class", " non-discussion"));- avatarColumn.add(new WebMarkupContainer("avatar"));- }-- if (activity instanceof UpdatedActivity)- row.add(AttributeAppender.append("class", " update"));- else- row.add(AttributeAppender.append("class", " non-update"));-- if (!getPullRequest().isVisitedAfter(activity.getDate()))- row.add(AttributeAppender.append("class", "new"));-- return row;- }-- private List<PullRequestActivity> getActivities() {- PullRequest request = getPullRequest();- List<PullRequestActivity> activities = new ArrayList<>();-- activities.add(new OpenedActivity(request));-- for (PullRequestUpdate update: request.getUpdates())- activities.add(new UpdatedActivity(update));-- for (PullRequestComment comment: request.getComments()) {- activities.add(new CommentedActivity(comment));- }-- for (PullRequestReference reference: request.getReferencedBy()) {- activities.add(new ReferencedActivity(reference));- }-- for (PullRequestStatusChange statusChange: request.getStatusChanges()) {- activities.add(new StatusChangeActivity(statusChange));- }-- activities.sort((o1, o2) -> {- if (o1.getDate().before(o2.getDate()))- return -1;- else if (o1.getDate().after(o2.getDate()))- return 1;- else if (o1 instanceof OpenedActivity)- return -1;- else- return 1;- });-- return activities;- }-- @Override- public void onEvent(IEvent<?> event) {- super.onEvent(event);-- if (event.getPayload() instanceof PullRequestChanged) {- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();- IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();- List<PullRequestActivity> activities = getActivities();-- @SuppressWarnings("deprecation")- Component lastActivityRow = activitiesView.get(activitiesView.size()-1);- PullRequestActivity lastAcvitity = (PullRequestActivity) lastActivityRow.getDefaultModelObject();- for (PullRequestActivity activity: activities) {- if (activity.getDate().after(lastAcvitity.getDate())) {- Component newActivityRow = newActivityRow(activitiesView.newChildId(), activity);- activitiesView.add(newActivityRow);-- String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",- newActivityRow.getMarkupId(), lastActivityRow.getMarkupId());- partialPageRequestHandler.prependJavaScript(script);- partialPageRequestHandler.add(newActivityRow);- lastActivityRow = newActivityRow;- }- }- }- }-- @Override- protected void onInitialize() {- super.onInitialize();-- add(activitiesView = new RepeatingView("requestActivities"));- activitiesView.setOutputMarkupId(true);-- List<PullRequestActivity> activities = getActivities();-- for (PullRequestActivity activity: activities)- activitiesView.add(newActivityRow(activitiesView.newChildId(), activity));-- WebMarkupContainer addComment = new WebMarkupContainer("addComment") {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(getLoginUser() != null);- }-- };- addComment.setOutputMarkupId(true);- add(addComment);-- Form<?> form = new Form<Void>("form");- addComment.add(form);-- CommentInput input = new CommentInput("input", Model.of("")) {-- @Override- protected AttachmentSupport getAttachmentSupport() {- return new DepotAttachmentSupport(getDepot(), getPullRequest().getUUID());- }-- @Override- protected Depot getDepot() {- return RequestOverviewPage.this.getDepot();- }-- };- input.setRequired(true);- form.add(input);-- form.add(new NotificationPanel("feedback", input));-- form.add(new AjaxSubmitLink("comment") {-- @Override- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {- super.onSubmit(target, form);-- PullRequestComment comment = new PullRequestComment();- comment.setRequest(getPullRequest());- comment.setUser(getLoginUser());- comment.setContent(input.getModelObject());- GitPlex.getInstance(PullRequestCommentManager.class).save(comment);- input.setModelObject("");-- target.add(addComment);-- @SuppressWarnings("deprecation")- Component lastActivityRow = activitiesView.get(activitiesView.size()-1);- Component newActivityRow = newActivityRow(activitiesView.newChildId(), new CommentedActivity(comment));- activitiesView.add(newActivityRow);-- String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",- newActivityRow.getMarkupId(), lastActivityRow.getMarkupId());- target.prependJavaScript(script);- target.add(newActivityRow);- }-- @Override- protected void onError(AjaxRequestTarget target, Form<?> form) {- super.onError(target, form);- target.add(form);- }-- });-- add(newIntegrationStrategyContainer());- add(newAssigneeContainer());- add(newReviewersContainer());- add(newWatchContainer());- }-- private WebMarkupContainer newIntegrationStrategyContainer() {- WebMarkupContainer integrationStrategyContainer = new WebMarkupContainer("integrationStrategy") {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(getPullRequest().isOpen());- }-- };-- PullRequest request = getPullRequest();-- final List<IntegrationStrategy> strategies =- GitPlex.getInstance(PullRequestManager.class).getApplicableIntegrationStrategies(request);- if (!strategies.contains(request.getIntegrationStrategy())) {- request.setIntegrationStrategy(strategies.get(0));- GitPlex.getInstance(Dao.class).persist(request);- }- IModel<IntegrationStrategy> strategyModel = new IModel<IntegrationStrategy>() {-- @Override- public void detach() {- }-- @Override- public IntegrationStrategy getObject() {- return getPullRequest().getIntegrationStrategy();- }-- @Override- public void setObject(IntegrationStrategy object) {- getPullRequest().setIntegrationStrategy(object);- }-- };-- DropDownChoice<IntegrationStrategy> editor =- new DropDownChoice<IntegrationStrategy>("editor", strategyModel, strategies) {-- @Override- protected void onConfigure() {- super.onConfigure();-- ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());- setVisible(SecurityUtils.getSubject().isPermitted(writePermission) && strategies.size() > 1);- }-- };- editor.add(new OnChangeAjaxBehavior() {-- @Override- protected void onUpdate(AjaxRequestTarget target) {- GitPlex.getInstance(Dao.class).persist(getPullRequest());- send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));- }-- });- integrationStrategyContainer.add(editor);-- integrationStrategyContainer.add(new Label("viewer", request.getIntegrationStrategy()) {-- @Override- protected void onConfigure() {- super.onConfigure();-- ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());- setVisible(!SecurityUtils.getSubject().isPermitted(writePermission) || strategies.size() == 1);- }-- });-- ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());-- if (!SecurityUtils.getSubject().isPermitted(writePermission) || strategies.size() == 1) {- integrationStrategyContainer.add(new WebMarkupContainer("help").add(- new TooltipBehavior(Model.of(getPullRequest().getIntegrationStrategy().getDescription()))));- } else {- StringBuilder strategyHelp = new StringBuilder("<dl class='integration-strategy-help'>");-- for (IntegrationStrategy strategy: strategies) {- strategyHelp.append("<dt>").append(strategy.toString()).append("</dt>");- strategyHelp.append("<dd>").append(strategy.getDescription()).append("</dd>");- }-- strategyHelp.append("</dl>");-- integrationStrategyContainer.add(new WebMarkupContainer("help")- .add(AttributeAppender.append("data-html", "true"))- .add(new TooltipBehavior(Model.of(strategyHelp.toString()), new TooltipConfig().withPlacement(Placement.left))));- }-- return integrationStrategyContainer;- }-- private WebMarkupContainer newWatchContainer() {- final WebMarkupContainer watchContainer = new WebMarkupContainer("watch") {-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(getLoginUser() != null);- }-- };-- watchContainer.setOutputMarkupId(true);-- final IModel<WatchStatus> optionModel = new LoadableDetachableModel<WatchStatus>() {-- @Override- protected WatchStatus load() {- PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());- if (watch != null) {- if (watch.isIgnore())- return WatchStatus.IGNORE;- else- return WatchStatus.WATCHING;- } else {- return WatchStatus.NOT_WATCHING;- }- }-- };-- List<WatchStatus> options = Arrays.asList(WatchStatus.values());-- IChoiceRenderer<WatchStatus> choiceRenderer = new IChoiceRenderer<WatchStatus>() {-- @Override- public Object getDisplayValue(WatchStatus object) {- return object.toString();- }-- @Override- public String getIdValue(WatchStatus object, int index) {- return object.name();- }-- @Override- public WatchStatus getObject(String id, IModel<? extends List<? extends WatchStatus>> choices) {- return WatchStatus.valueOf(id);- }-- };- DropDownChoice<WatchStatus> choice = new DropDownChoice<>("option", optionModel,- options, choiceRenderer);-- choice.add(new OnChangeAjaxBehavior() {-- @Override- protected void onUpdate(AjaxRequestTarget target) {- PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());- Dao dao = GitPlex.getInstance(Dao.class);- if (optionModel.getObject() == WatchStatus.WATCHING) {- if (watch != null) {- watch.setIgnore(false);- watch.setReason(null);- } else {- watch = new PullRequestWatch();- watch.setRequest(getPullRequest());- watch.setUser(getLoginUser());- getPullRequest().getWatches().add(watch);- }- dao.persist(watch);- } else if (optionModel.getObject() == WatchStatus.NOT_WATCHING) {- if (watch != null) {- dao.remove(watch);- getPullRequest().getWatches().remove(watch);- }- } else {- if (watch != null) {- watch.setIgnore(true);- } else {- watch = new PullRequestWatch();- watch.setRequest(getPullRequest());- watch.setUser(getLoginUser());- watch.setIgnore(true);- getPullRequest().getWatches().add(watch);- }- dao.persist(watch);- }- target.add(watchContainer);- }-- });- watchContainer.add(choice);- watchContainer.add(new Label("help", new LoadableDetachableModel<String>() {-- @Override- protected String load() {- PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());- if (watch != null) {- if (watch.isIgnore()) {- return "Ignore notifications irrelevant to me.";- } else if (watch.getReason() != null) {- return watch.getReason();- } else {- return "You will be notified of any activities.";- }- } else {- return "Ignore notifications irrelevant to me, but start to watch once I am involved.";- }- }-- }));-- return watchContainer;- }-- private Component newAssigneeContainer() {- PullRequest request = getPullRequest();-- Fragment assigneeContainer;- Account assignee = request.getAssignee();- Account currentUser = getLoginUser();- boolean canChangeAssignee = request.isOpen()- && (currentUser != null && currentUser.equals(request.getSubmitter())- || SecurityUtils.canManage(getDepot()));- if (assignee != null) {-- if (canChangeAssignee) {- assigneeContainer = new Fragment("assignee", "assigneeEditFrag", this);- assigneeContainer.add(new WebMarkupContainer("help").add(new TooltipBehavior(Model.of(ASSIGNEE_HELP))));-- AssigneeChoice choice = new AssigneeChoice("assignee", depotModel, new IModel<Account>() {-- @Override- public void detach() {- }-- @Override- public Account getObject() {- return getPullRequest().getAssignee();- }-- @Override- public void setObject(Account object) {- getPullRequest().setAssignee(object);- }-- });- choice.setRequired(true);- assigneeContainer.add(choice);- choice.add(new AjaxFormComponentUpdatingBehavior("change") {-- @Override- protected void onUpdate(AjaxRequestTarget target) {- Preconditions.checkNotNull(getPullRequest().getAssignee());- GitPlex.getInstance(PullRequestManager.class).changeAssignee(getPullRequest());- }-- });- } else {- assigneeContainer = new Fragment("assignee", "assigneeViewFrag", this);- assigneeContainer.add(new WebMarkupContainer("help").add(new TooltipBehavior(Model.of(ASSIGNEE_HELP))));- assigneeContainer.add(new Avatar("assignee", assignee, new TooltipConfig()));- }- } else {- assigneeContainer = new Fragment("assignee", "noAssigneeFrag", this);- }-- return assigneeContainer;- }-- private WebMarkupContainer newReviewersContainer() {- final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {-- @Override- protected void onConfigure() {- super.onConfigure();-- PullRequest request = getPullRequest();- if (request.getReviewInvitations().isEmpty()) {- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();- setVisible(request.isOpen()- && !request.getPotentialReviewers().isEmpty()- && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotAdmin(request.getTarget().getDepot()))));- } else {- setVisible(true);- }- }-- };- reviewersContainer.setOutputMarkupId(true);- reviewersContainer.add(new ListView<PullRequestReviewInvitation>("reviewers", new ReviewersModel(requestModel)) {-- @Override- protected void populateItem(ListItem<PullRequestReviewInvitation> item) {- PullRequestReviewInvitation invitation = item.getModelObject();- item.add(new ReviewerAvatar("avatar", invitation) {-- @Override- protected void onAvatarRemove(AjaxRequestTarget target) {- super.onAvatarRemove(target);-- target.add(reviewersContainer);- send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));- }-- });-- List<PullRequestReview> userReviews = new ArrayList<>();- for (PullRequestReview review: getPullRequest().getReviews()) {- if (review.getUser().equals(invitation.getUser()))- userReviews.add(review);- }- if (!userReviews.isEmpty()) {- PullRequestReview review = userReviews.get(userReviews.size()-1);- item.add(new ReviewResultIcon("result", new EntityModel<PullRequestReview>(review)));- } else {- item.add(new WebMarkupContainer("result").setVisible(false));- }- }-- });-- reviewersContainer.add(new ReviewerChoice("addReviewer", requestModel) {-- @Override- protected void onSelect(AjaxRequestTarget target, Account user) {- super.onSelect(target, user);-- target.add(reviewersContainer);- send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));- }-- });-- return reviewersContainer;- }-- @Override- protected void onSelect(AjaxRequestTarget target, Depot depot) {- setResponsePage(RequestListPage.class, paramsOf(depot));- }-- @Override- public void renderHead(IHeaderResponse response) {- super.renderHead(response);- response.render(CssHeaderItem.forReference(- new CssResourceReference(RequestOverviewPage.class, "request-overview.css")));- }--}+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.Date;+import java.util.List;++import org.apache.wicket.Component;+import org.apache.wicket.ajax.AjaxRequestTarget;+import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;+import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;+import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;+import org.apache.wicket.behavior.AttributeAppender;+import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;+import org.apache.wicket.event.Broadcast;+import org.apache.wicket.event.IEvent;+import org.apache.wicket.markup.head.CssHeaderItem;+import org.apache.wicket.markup.head.IHeaderResponse;+import org.apache.wicket.markup.html.WebMarkupContainer;+import org.apache.wicket.markup.html.basic.Label;+import org.apache.wicket.markup.html.form.DropDownChoice;+import org.apache.wicket.markup.html.form.Form;+import org.apache.wicket.markup.html.form.IChoiceRenderer;+import org.apache.wicket.markup.html.list.ListItem;+import org.apache.wicket.markup.html.list.ListView;+import org.apache.wicket.markup.html.panel.Fragment;+import org.apache.wicket.markup.repeater.RepeatingView;+import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;+import org.apache.wicket.model.Model;+import org.apache.wicket.request.mapper.parameter.PageParameters;+import org.apache.wicket.request.resource.CssResourceReference;+import org.joda.time.DateTime;++import com.google.common.base.Preconditions;+import com.pmease.commons.hibernate.dao.Dao;+import com.pmease.commons.wicket.behavior.TooltipBehavior;+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;+import com.pmease.gitplex.core.GitPlex;+import com.pmease.gitplex.core.entity.Account;+import com.pmease.gitplex.core.entity.Depot;+import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.PullRequest.IntegrationStrategy;+import com.pmease.gitplex.core.entity.PullRequestComment;+import com.pmease.gitplex.core.entity.PullRequestReference;+import com.pmease.gitplex.core.entity.PullRequestStatusChange;+import com.pmease.gitplex.core.entity.PullRequestUpdate;+import com.pmease.gitplex.core.entity.PullRequestWatch;+import com.pmease.gitplex.core.entity.PullRequestReview;+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;+import com.pmease.gitplex.core.manager.AccountManager;+import com.pmease.gitplex.core.manager.PullRequestCommentManager;+import com.pmease.gitplex.core.manager.PullRequestManager;+import com.pmease.gitplex.core.security.ObjectPermission;+import com.pmease.gitplex.core.security.SecurityUtils;+import com.pmease.gitplex.web.component.avatar.Avatar;+import com.pmease.gitplex.web.component.avatar.AvatarLink;+import com.pmease.gitplex.web.component.comment.CommentInput;+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;+import com.pmease.gitplex.web.component.pullrequest.ReviewResultIcon;+import com.pmease.gitplex.web.component.pullrequest.requestassignee.AssigneeChoice;+import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerAvatar;+import com.pmease.gitplex.web.component.pullrequest.requestreviewer.ReviewerChoice;+import com.pmease.gitplex.web.model.EntityModel;+import com.pmease.gitplex.web.model.ReviewersModel;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.CommentRemoved;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.CommentedActivity;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.OpenedActivity;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.ReferencedActivity;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.StatusChangeActivity;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.activity.UpdatedActivity;+import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;+import com.pmease.gitplex.web.websocket.PullRequestChanged;++import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;+import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig;+import de.agilecoders.wicket.core.markup.html.bootstrap.components.TooltipConfig.Placement;++@SuppressWarnings("serial")+public class RequestOverviewPage extends RequestDetailPage {++ private static final String ASSIGNEE_HELP = "Assignee has write permission to the "+ + "repository and is resonsible for integrating the pull request into "+ + "target branch after it passes gate keeper check.";++ private enum WatchStatus {+ WATCHING("Watching"),+ NOT_WATCHING("Not Watching"),+ IGNORE("Ignore");++ private final String displayName;++ WatchStatus(String displayName) {+ this.displayName = displayName;+ }++ @Override+ public String toString() {+ return displayName;+ }++ };++ private RepeatingView activitiesView;++ public RequestOverviewPage(PageParameters params) {+ super(params);+ }++ private Component newActivityRow(String id, PullRequestActivity activity) {+ WebMarkupContainer row = new WebMarkupContainer(id, Model.of(activity)) {++ @Override+ public void onEvent(IEvent<?> event) {+ super.onEvent(event);++ if (event.getPayload() instanceof CommentRemoved) {+ CommentRemoved commentRemoved = (CommentRemoved) event.getPayload();+ remove();+ commentRemoved.getPartialPageRequestHandler().appendJavaScript(String.format("$('#%s').remove();", getMarkupId()));+ }+ }++ };++ row.setOutputMarkupId(true);++ if (row.get("content") == null)+ row.add(activity.render("content"));++ WebMarkupContainer avatarColumn = new WebMarkupContainer("avatar");+ row.add(avatarColumn);++ if (activity instanceof OpenedActivity) {+ row.add(AttributeAppender.append("class", " discussion"));+ avatarColumn.add(new AvatarLink("avatar", ((OpenedActivity)activity).getRequest().getSubmitter(), null));+ } else if (activity instanceof CommentedActivity) {+ row.add(AttributeAppender.append("class", " discussion"));+ avatarColumn.add(new AvatarLink("avatar", ((CommentedActivity)activity).getComment().getUser(), null));+ } else {+ row.add(AttributeAppender.append("class", " non-discussion"));+ avatarColumn.add(new WebMarkupContainer("avatar"));+ }++ if (activity instanceof UpdatedActivity)+ row.add(AttributeAppender.append("class", " update"));+ else+ row.add(AttributeAppender.append("class", " non-update"));++ return row;+ }++ private List<PullRequestActivity> getActivities() {+ PullRequest request = getPullRequest();+ List<PullRequestActivity> activities = new ArrayList<>();++ activities.add(new OpenedActivity(request));++ for (PullRequestUpdate update: request.getUpdates())+ activities.add(new UpdatedActivity(update));++ for (PullRequestComment comment: request.getComments()) {+ activities.add(new CommentedActivity(comment));+ }++ for (PullRequestReference reference: request.getReferencedBy()) {+ activities.add(new ReferencedActivity(reference));+ }++ for (PullRequestStatusChange statusChange: request.getStatusChanges()) {+ activities.add(new StatusChangeActivity(statusChange));+ }++ activities.sort((o1, o2) -> {+ if (o1.getDate().getTime()<o2.getDate().getTime())+ return -1;+ else if (o1.getDate().getTime()>o2.getDate().getTime())+ return 1;+ else if (o1 instanceof OpenedActivity)+ return -1;+ else+ return 1;+ });++ return activities;+ }++ @Override+ public void onEvent(IEvent<?> event) {+ super.onEvent(event);++ if (event.getPayload() instanceof PullRequestChanged) {+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();+ IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();+ List<PullRequestActivity> activities = getActivities();++ PullRequest request = getPullRequest();+ @SuppressWarnings("deprecation")+ Component prevActivityRow = activitiesView.get(activitiesView.size()-1);+ PullRequestActivity lastActivity = (PullRequestActivity) prevActivityRow.getDefaultModelObject();+ for (PullRequestActivity activity: activities) {+ if (activity.getDate().getTime()>lastActivity.getDate().getTime()) {+ Component newActivityRow = newActivityRow(activitiesView.newChildId(), activity);+ Component sinceChangesRow = null;+ if (!request.isVisitedAfter(activity.getDate())) {+ PullRequestActivity prevActivity = (PullRequestActivity) prevActivityRow.getDefaultModelObject();+ if (request.isVisitedAfter(prevActivity.getDate())) {+ Date sinceDate = new DateTime(activity.getDate()).minusMillis(1).toDate();+ sinceChangesRow = newSinceChangesRow(activitiesView.newChildId(), sinceDate);+ activitiesView.add(sinceChangesRow);+ String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",+ sinceChangesRow.getMarkupId(), prevActivityRow.getMarkupId());+ partialPageRequestHandler.prependJavaScript(script);+ partialPageRequestHandler.add(sinceChangesRow);+ }+ newActivityRow.add(AttributeAppender.append("class", "new"));+ if (activity instanceof UpdatedActivity) {+ partialPageRequestHandler.appendJavaScript("$('tr.since-changes').addClass('visible');");+ }+ }+ activitiesView.add(newActivityRow);++ String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",+ newActivityRow.getMarkupId(),+ sinceChangesRow!=null?sinceChangesRow.getMarkupId():prevActivityRow.getMarkupId());+ partialPageRequestHandler.prependJavaScript(script);+ partialPageRequestHandler.add(newActivityRow);++ prevActivityRow = newActivityRow;+ }+ }+ }+ }++ private Component newSinceChangesRow(String id, Date sinceDate) {+ WebMarkupContainer row = new WebMarkupContainer(id);+ row.setOutputMarkupId(true);+ row.add(AttributeAppender.append("class", " non-discussion"));++ WebMarkupContainer avatarColumn = new WebMarkupContainer("avatar");+ avatarColumn.add(new WebMarkupContainer("avatar"));+ row.add(avatarColumn);++ WebMarkupContainer contentColumn = new Fragment("content", "sinceChangesRowContentFrag", this);+ contentColumn.add(new SinceChangesLink("sinceChanges", requestModel, sinceDate));+ row.add(contentColumn);++ row.add(AttributeAppender.append("class", "since-changes"));++ return row;+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(activitiesView = new RepeatingView("requestActivities"));+ activitiesView.setOutputMarkupId(true);++ List<PullRequestActivity> activities = getActivities();++ PullRequest request = getPullRequest();+ Component sinceChangesRow = null;+ boolean visible = false;+ for (int i=0; i<activities.size(); i++) {+ PullRequestActivity activity = activities.get(i);+ Component row = newActivityRow(activitiesView.newChildId(), activity);+ if (!request.isVisitedAfter(activity.getDate())) {+ row.add(AttributeAppender.append("class", "new"));+ if (sinceChangesRow == null) {+ if (i != 0) {+ Date prevActivityDate = activities.get(i-1).getDate();+ if (request.isVisitedAfter(prevActivityDate)) {+ Date sinceDate = new DateTime(activity.getDate()).minusMillis(1).toDate();+ System.out.println(sinceDate.getTime());+ sinceChangesRow = newSinceChangesRow(activitiesView.newChildId(), sinceDate);+ activitiesView.add(sinceChangesRow);+ }+ }+ }+ if (activity instanceof UpdatedActivity) {+ visible = true;+ }+ }+ if (sinceChangesRow != null && visible)+ sinceChangesRow.add(AttributeAppender.append("class", "visible"));+ activitiesView.add(row);+ }++ WebMarkupContainer addComment = new WebMarkupContainer("addComment") {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(getLoginUser() != null);+ }++ };+ addComment.setOutputMarkupId(true);+ add(addComment);++ Form<?> form = new Form<Void>("form");+ addComment.add(form);++ CommentInput input = new CommentInput("input", Model.of("")) {++ @Override+ protected AttachmentSupport getAttachmentSupport() {+ return new DepotAttachmentSupport(getDepot(), getPullRequest().getUUID());+ }++ @Override+ protected Depot getDepot() {+ return RequestOverviewPage.this.getDepot();+ }++ };+ input.setRequired(true);+ form.add(input);++ form.add(new NotificationPanel("feedback", input));++ form.add(new AjaxSubmitLink("comment") {++ @Override+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {+ super.onSubmit(target, form);++ PullRequestComment comment = new PullRequestComment();+ comment.setRequest(getPullRequest());+ comment.setUser(getLoginUser());+ comment.setContent(input.getModelObject());+ GitPlex.getInstance(PullRequestCommentManager.class).save(comment);+ input.setModelObject("");++ target.add(addComment);++ @SuppressWarnings("deprecation")+ Component lastActivityRow = activitiesView.get(activitiesView.size()-1);+ Component newActivityRow = newActivityRow(activitiesView.newChildId(), new CommentedActivity(comment));+ activitiesView.add(newActivityRow);++ String script = String.format("$(\"<tr id='%s'></tr>\").insertAfter('#%s');",+ newActivityRow.getMarkupId(), lastActivityRow.getMarkupId());+ target.prependJavaScript(script);+ target.add(newActivityRow);+ }++ @Override+ protected void onError(AjaxRequestTarget target, Form<?> form) {+ super.onError(target, form);+ target.add(form);+ }++ });++ add(newIntegrationStrategyContainer());+ add(newAssigneeContainer());+ add(newReviewersContainer());+ add(newWatchContainer());+ }++ private WebMarkupContainer newIntegrationStrategyContainer() {+ WebMarkupContainer integrationStrategyContainer = new WebMarkupContainer("integrationStrategy") {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(getPullRequest().isOpen());+ }++ };++ PullRequest request = getPullRequest();++ final List<IntegrationStrategy> strategies =+ GitPlex.getInstance(PullRequestManager.class).getApplicableIntegrationStrategies(request);+ if (!strategies.contains(request.getIntegrationStrategy())) {+ request.setIntegrationStrategy(strategies.get(0));+ GitPlex.getInstance(Dao.class).persist(request);+ }+ IModel<IntegrationStrategy> strategyModel = new IModel<IntegrationStrategy>() {++ @Override+ public void detach() {+ }++ @Override+ public IntegrationStrategy getObject() {+ return getPullRequest().getIntegrationStrategy();+ }++ @Override+ public void setObject(IntegrationStrategy object) {+ getPullRequest().setIntegrationStrategy(object);+ }++ };++ DropDownChoice<IntegrationStrategy> editor =+ new DropDownChoice<IntegrationStrategy>("editor", strategyModel, strategies) {++ @Override+ protected void onConfigure() {+ super.onConfigure();++ ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());+ setVisible(SecurityUtils.getSubject().isPermitted(writePermission) && strategies.size() > 1);+ }++ };+ editor.add(new OnChangeAjaxBehavior() {++ @Override+ protected void onUpdate(AjaxRequestTarget target) {+ GitPlex.getInstance(Dao.class).persist(getPullRequest());+ send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));+ }++ });+ integrationStrategyContainer.add(editor);++ integrationStrategyContainer.add(new Label("viewer", request.getIntegrationStrategy()) {++ @Override+ protected void onConfigure() {+ super.onConfigure();++ ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());+ setVisible(!SecurityUtils.getSubject().isPermitted(writePermission) || strategies.size() == 1);+ }++ });++ ObjectPermission writePermission = ObjectPermission.ofDepotWrite(getDepot());++ if (!SecurityUtils.getSubject().isPermitted(writePermission) || strategies.size() == 1) {+ integrationStrategyContainer.add(new WebMarkupContainer("help").add(+ new TooltipBehavior(Model.of(getPullRequest().getIntegrationStrategy().getDescription()))));+ } else {+ StringBuilder strategyHelp = new StringBuilder("<dl class='integration-strategy-help'>");++ for (IntegrationStrategy strategy: strategies) {+ strategyHelp.append("<dt>").append(strategy.toString()).append("</dt>");+ strategyHelp.append("<dd>").append(strategy.getDescription()).append("</dd>");+ }++ strategyHelp.append("</dl>");++ integrationStrategyContainer.add(new WebMarkupContainer("help")+ .add(AttributeAppender.append("data-html", "true"))+ .add(new TooltipBehavior(Model.of(strategyHelp.toString()), new TooltipConfig().withPlacement(Placement.left))));+ }++ return integrationStrategyContainer;+ }++ private WebMarkupContainer newWatchContainer() {+ final WebMarkupContainer watchContainer = new WebMarkupContainer("watch") {++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(getLoginUser() != null);+ }++ };++ watchContainer.setOutputMarkupId(true);++ final IModel<WatchStatus> optionModel = new LoadableDetachableModel<WatchStatus>() {++ @Override+ protected WatchStatus load() {+ PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());+ if (watch != null) {+ if (watch.isIgnore())+ return WatchStatus.IGNORE;+ else+ return WatchStatus.WATCHING;+ } else {+ return WatchStatus.NOT_WATCHING;+ }+ }++ };++ List<WatchStatus> options = Arrays.asList(WatchStatus.values());++ IChoiceRenderer<WatchStatus> choiceRenderer = new IChoiceRenderer<WatchStatus>() {++ @Override+ public Object getDisplayValue(WatchStatus object) {+ return object.toString();+ }++ @Override+ public String getIdValue(WatchStatus object, int index) {+ return object.name();+ }++ @Override+ public WatchStatus getObject(String id, IModel<? extends List<? extends WatchStatus>> choices) {+ return WatchStatus.valueOf(id);+ }++ };+ DropDownChoice<WatchStatus> choice = new DropDownChoice<>("option", optionModel,+ options, choiceRenderer);++ choice.add(new OnChangeAjaxBehavior() {++ @Override+ protected void onUpdate(AjaxRequestTarget target) {+ PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());+ Dao dao = GitPlex.getInstance(Dao.class);+ if (optionModel.getObject() == WatchStatus.WATCHING) {+ if (watch != null) {+ watch.setIgnore(false);+ watch.setReason(null);+ } else {+ watch = new PullRequestWatch();+ watch.setRequest(getPullRequest());+ watch.setUser(getLoginUser());+ getPullRequest().getWatches().add(watch);+ }+ dao.persist(watch);+ } else if (optionModel.getObject() == WatchStatus.NOT_WATCHING) {+ if (watch != null) {+ dao.remove(watch);+ getPullRequest().getWatches().remove(watch);+ }+ } else {+ if (watch != null) {+ watch.setIgnore(true);+ } else {+ watch = new PullRequestWatch();+ watch.setRequest(getPullRequest());+ watch.setUser(getLoginUser());+ watch.setIgnore(true);+ getPullRequest().getWatches().add(watch);+ }+ dao.persist(watch);+ }+ target.add(watchContainer);+ }++ });+ watchContainer.add(choice);+ watchContainer.add(new Label("help", new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ PullRequestWatch watch = getPullRequest().getWatch(getLoginUser());+ if (watch != null) {+ if (watch.isIgnore()) {+ return "Ignore notifications irrelevant to me.";+ } else if (watch.getReason() != null) {+ return watch.getReason();+ } else {+ return "You will be notified of any activities.";+ }+ } else {+ return "Ignore notifications irrelevant to me, but start to watch once I am involved.";+ }+ }++ }));++ return watchContainer;+ }++ private Component newAssigneeContainer() {+ PullRequest request = getPullRequest();++ Fragment assigneeContainer;+ Account assignee = request.getAssignee();+ Account currentUser = getLoginUser();+ boolean canChangeAssignee = request.isOpen()+ && (currentUser != null && currentUser.equals(request.getSubmitter())+ || SecurityUtils.canManage(getDepot()));+ if (assignee != null) {++ if (canChangeAssignee) {+ assigneeContainer = new Fragment("assignee", "assigneeEditFrag", this);+ assigneeContainer.add(new WebMarkupContainer("help").add(new TooltipBehavior(Model.of(ASSIGNEE_HELP))));++ AssigneeChoice choice = new AssigneeChoice("assignee", depotModel, new IModel<Account>() {++ @Override+ public void detach() {+ }++ @Override+ public Account getObject() {+ return getPullRequest().getAssignee();+ }++ @Override+ public void setObject(Account object) {+ getPullRequest().setAssignee(object);+ }++ });+ choice.setRequired(true);+ assigneeContainer.add(choice);+ choice.add(new AjaxFormComponentUpdatingBehavior("change") {++ @Override+ protected void onUpdate(AjaxRequestTarget target) {+ Preconditions.checkNotNull(getPullRequest().getAssignee());+ GitPlex.getInstance(PullRequestManager.class).changeAssignee(getPullRequest());+ }++ });+ } else {+ assigneeContainer = new Fragment("assignee", "assigneeViewFrag", this);+ assigneeContainer.add(new WebMarkupContainer("help").add(new TooltipBehavior(Model.of(ASSIGNEE_HELP))));+ assigneeContainer.add(new Avatar("assignee", assignee, new TooltipConfig()));+ }+ } else {+ assigneeContainer = new Fragment("assignee", "noAssigneeFrag", this);+ }++ return assigneeContainer;+ }++ private WebMarkupContainer newReviewersContainer() {+ final WebMarkupContainer reviewersContainer = new WebMarkupContainer("reviewers") {++ @Override+ protected void onConfigure() {+ super.onConfigure();++ PullRequest request = getPullRequest();+ if (request.getReviewInvitations().isEmpty()) {+ Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();+ setVisible(request.isOpen()+ && !request.getPotentialReviewers().isEmpty()+ && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.getSubject().isPermitted(ObjectPermission.ofDepotAdmin(request.getTarget().getDepot()))));+ } else {+ setVisible(true);+ }+ }++ };+ reviewersContainer.setOutputMarkupId(true);+ reviewersContainer.add(new ListView<PullRequestReviewInvitation>("reviewers", new ReviewersModel(requestModel)) {++ @Override+ protected void populateItem(ListItem<PullRequestReviewInvitation> item) {+ PullRequestReviewInvitation invitation = item.getModelObject();+ item.add(new ReviewerAvatar("avatar", invitation) {++ @Override+ protected void onAvatarRemove(AjaxRequestTarget target) {+ super.onAvatarRemove(target);++ target.add(reviewersContainer);+ send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));+ }++ });++ List<PullRequestReview> userReviews = new ArrayList<>();+ for (PullRequestReview review: getPullRequest().getReviews()) {+ if (review.getUser().equals(invitation.getUser()))+ userReviews.add(review);+ }+ if (!userReviews.isEmpty()) {+ PullRequestReview review = userReviews.get(userReviews.size()-1);+ item.add(new ReviewResultIcon("result", new EntityModel<PullRequestReview>(review)));+ } else {+ item.add(new WebMarkupContainer("result").setVisible(false));+ }+ }++ });++ reviewersContainer.add(new ReviewerChoice("addReviewer", requestModel) {++ @Override+ protected void onSelect(AjaxRequestTarget target, Account user) {+ super.onSelect(target, user);++ target.add(reviewersContainer);+ send(getPage(), Broadcast.BREADTH, new PullRequestChanged(target, getPullRequest()));+ }++ });++ return reviewersContainer;+ }++ @Override+ protected void onSelect(AjaxRequestTarget target, Depot depot) {+ setResponsePage(RequestListPage.class, paramsOf(depot));+ }++ @Override+ public void renderHead(IHeaderResponse response) {+ super.renderHead(response);+ response.render(CssHeaderItem.forReference(+ new CssResourceReference(RequestOverviewPage.class, "request-overview.css")));+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.javaindex c2e6bbc658..41607cc568 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/SinceChangesLink.java@@ -1,88 +1,86 @@-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;--import java.util.Date;--import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;-import org.apache.wicket.event.IEvent;-import org.apache.wicket.markup.html.link.BookmarkablePageLink;-import org.apache.wicket.model.IModel;-import org.apache.wicket.model.LoadableDetachableModel;-import org.apache.wicket.request.mapper.parameter.PageParameters;--import com.pmease.gitplex.core.entity.PullRequest;-import com.pmease.gitplex.core.entity.PullRequestUpdate;-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;-import com.pmease.gitplex.web.websocket.PullRequestChanged;--@SuppressWarnings("serial")-public class SinceChangesLink extends BookmarkablePageLink<Void> {-- private final IModel<PullRequest> requestModel;-- private final Date sinceDate;-- private final IModel<String> oldCommitModel = new LoadableDetachableModel<String>() {-- @Override- protected String load() {- PullRequest request = requestModel.getObject();- String commit = request.getBaseCommitHash();- for (int i=request.getSortedUpdates().size()-1; i>=0; i--) {- PullRequestUpdate update = request.getSortedUpdates().get(i);- if (update.getDate().before(sinceDate)) {- commit = update.getHeadCommitHash();- break;- }- }- return commit;- }-- };-- public SinceChangesLink(String id, IModel<PullRequest> requestModel, Date sinceDate) {- super(id, RequestChangesPage.class);- this.requestModel = requestModel;- this.sinceDate = sinceDate;- }-- @Override- public PageParameters getPageParameters() {- PullRequest request = requestModel.getObject();- RequestChangesPage.State state = new RequestChangesPage.State();- state.oldCommit = oldCommitModel.getObject();- state.newCommit = request.getLatestUpdate().getHeadCommitHash();- return RequestChangesPage.paramsOf(request, state);- }-- @Override- public void onEvent(IEvent<?> event) {- super.onEvent(event);-- if (event.getPayload() instanceof PullRequestChanged) {- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();- IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();- partialPageRequestHandler.add(this);- }- }-- @Override- protected void onInitialize() {- super.onInitialize();- setOutputMarkupPlaceholderTag(true);- }-- @Override- protected void onConfigure() {- super.onConfigure();- setVisible(!oldCommitModel.getObject().equals(requestModel.getObject().getLatestUpdate().getHeadCommitHash()));- }-- @Override- protected void onDetach() {- requestModel.detach();- oldCommitModel.detach();-- super.onDetach();- }--}+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview;++import java.util.Date;++import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;+import org.apache.wicket.event.IEvent;+import org.apache.wicket.markup.html.link.BookmarkablePageLink;+import org.apache.wicket.model.IModel;+import org.apache.wicket.model.LoadableDetachableModel;+import org.apache.wicket.request.mapper.parameter.PageParameters;++import com.pmease.gitplex.core.entity.PullRequest;+import com.pmease.gitplex.core.entity.PullRequestUpdate;+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;+import com.pmease.gitplex.web.websocket.PullRequestChanged;++@SuppressWarnings("serial")+public class SinceChangesLink extends BookmarkablePageLink<Void> {++ private final IModel<PullRequest> requestModel;++ private final Date sinceDate;++ private final IModel<String> oldCommitModel = new LoadableDetachableModel<String>() {++ @Override+ protected String load() {+ PullRequest request = requestModel.getObject();+ String commit = request.getBaseCommitHash();+ for (PullRequestUpdate update: request.getSortedUpdates()) {+ if (update.getDate().getTime()<sinceDate.getTime()) {+ commit = update.getHeadCommitHash();+ }+ }+ return commit;+ }++ };++ public SinceChangesLink(String id, IModel<PullRequest> requestModel, Date sinceDate) {+ super(id, RequestChangesPage.class);+ this.requestModel = requestModel;+ this.sinceDate = sinceDate;+ }++ @Override+ public PageParameters getPageParameters() {+ PullRequest request = requestModel.getObject();+ RequestChangesPage.State state = new RequestChangesPage.State();+ state.oldCommit = oldCommitModel.getObject();+ state.newCommit = request.getLatestUpdate().getHeadCommitHash();+ return RequestChangesPage.paramsOf(request, state);+ }++ @Override+ public void onEvent(IEvent<?> event) {+ super.onEvent(event);++ if (event.getPayload() instanceof PullRequestChanged) {+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();+ IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();+ partialPageRequestHandler.add(this);+ }+ }++ @Override+ protected void onInitialize() {+ super.onInitialize();+ setOutputMarkupPlaceholderTag(true);+ }++ @Override+ protected void onConfigure() {+ super.onConfigure();+ setVisible(!oldCommitModel.getObject().equals(requestModel.getObject().getLatestUpdate().getHeadCommitHash()));+ }++ @Override+ protected void onDetach() {+ requestModel.detach();+ oldCommitModel.detach();++ super.onDetach();+ }++}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.cssindex 852a14f187..cada6a4b43 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/request-overview.css@@ -1,301 +1,313 @@-#request-detail>.overview>tbody>tr>td.activities {- width: 75%;- padding-right: 16px;-}-#request-detail .activities>table {- margin-bottom: 20px;- table-layout: fixed;- border-bottom: 1px solid #CCC;-}-#request-detail tr.activity>td.spacer {- border-right: 1px solid #E8E8E8;-}-#request-detail td.avatar {- width: 48px;- border-left: 4px solid white;- padding-left: 8px;-}-#request-detail td.spacer {- width: 30px;-}-#request-detail .discussion>td.content>div.activity {- position: relative;- border: 1px solid #CCC;- border-radius: 4px;- background: white;- margin-left: -15px;-}-#request-detail .discussion>td.content>div.activity:before {- display: inline-block;- position: absolute;- top: 10px;- left: -8px;- border-top: 8px solid transparent;- border-bottom: 8px solid transparent;- border-right: 8px solid #CBCBCB;- content: "";-}-#request-detail .discussion>td.content>.activity:after {- display: inline-block;- position: absolute;- top: 11px;- left: -7px;- border-top: 7px solid transparent;- border-bottom: 7px solid transparent;- border-right: 7px solid #F5F5F5;- content: "";-}-#request-detail div.activity>.body>.actions {- margin-top: 8px;-}-#request-detail div.activity>.body>.actions>a {- margin-right: 0;- font-size: 13px;-}-#request-detail .discussion+.discussion>td {- padding-top: 30px;-}-#request-detail .discussion:last-child>td {- padding-bottom: 20px;-}-#request-detail .non-discussion:last-child>td.content {- padding-bottom: 20px;-}-#request-detail .non-discussion>td.content {- border-top: 1px solid #EEE;-}-#request-detail .discussion+.non-discussion>td.content,-#request-detail .update+.update>td.content {- border-top: none;-}-#request-detail .discussion>.avatar img {- width: 40px;- height: 40px;-}-#request-detail .non-discussion>td.content {- font-size: 13px;- padding: 10px 0;-}--#request-detail div.activity, #request-detail div.activity a {- color: #999;-}-#request-detail div.activity>div.body {- color: #444;-}--#request-detail div.activity .operations>* {- color: #DDD;- margin-left: 4px;-}-#request-detail div.activity:hover .operations>* {- color: #999;-}-#request-detail div.activity .user a {- color: #666;- font-weight: bold;- font-style: normal;-}-#request-detail .non-discussion div.activity {- margin-left: -14px;-}-#request-detail .non-discussion div.activity>.head>.icon {- border-radius: 13px;- background: #5CA7F8;- width: 26px;- height: 26px;- color: white;- padding: 6px;- margin-right: 4px;-}-#request-detail .discussion div.activity>.head {- padding: 10px;- border-radius: 4px 4px 0 0;- background: #F5F5F5;-}-#request-detail .discussion div.activity>.body {- padding: 12px;-}-#request-detail .non-discussion div.activity>.body {- margin: 8px 0 0 36px;-}-#request-detail .non-discussion div.activity .user a {- font-weight: normal;-}--#request-detail .non-discussion>td.avatar img {- display: none;-}-#request-detail .activities tr.activity>.content>.update {- color: #777;- margin-left: -7px;-}-#request-detail .activities tr.activity>.content>.update>.alert {- margin: 0 0 8px 28px;-}-#request-detail .activities tr.activity>.content>.update a {- color: #555;-}-#request-detail .activities tr.activity>.content>.update td {- padding: 4px 0;-}-#request-detail .activities tr.activity>.content>.update td.status {- width: 120px;-}-#request-detail .update+.update>td.content>div {- margin-top: -16px;-}-#request-detail .update+.update>td.content>div>.alert {- margin-top: 16px;-}-#request-detail .discussion+.non-discussion>td.content {- padding-top: 16px;-}-#request-detail .non-discussion+.discussion>td {- padding-top: 8px;-}--#request-detail .activities tr.activity>.content>.update td.detail {- padding-left: 13px;- padding-right: 8px;-}-#request-detail .activities tr.activity>.content>.update td.detail .commit-message {- padding-left: 4px;-}-#request-detail .activities tr.activity>.content>.update td.icon {- width: 1px;- padding-top: 7px;-}-#request-detail .activities tr.activity>.content>.update td.status {- text-align: right;- white-space: nowrap;-}-#request-detail .activities tr.activity>.content>.update tr:hover td {- background: #F5F5F5;-}-#request-detail .activities tr.activity>.content>.update tr.integrated td.icon .fa {- color: #35A612;-}-#request-detail .activities tr.activity>.content>.update tr.rebased td a {- color: #AAA;-}-#request-detail .activities tr.activity>.content>.update tr.rebased td.icon .fa {- color: #CCC;-}-#request-detail .activities tr.activity>.content>.update tr.rebased img.avatar {- opacity: 0.5;-}-#request-detail .activities tr.activity>.content>.update td.status .successful {- color: #35A612;-}-#request-detail .activities tr.activity>.content>.update td.status .failed {- color: #F93333;-}-#request-detail .activities tr.activity>.content>.update td.status .running {- color: #AFAD1F;-}-#request-detail .activities tr.activity.new>.avatar {- border-color: #4667EE;-}--#request-detail .activities tr.activity>.content>.assigned>.head>.icon {- padding-left: 8px;-}-#request-detail .activities tr.activity>.content>.discarded>.head>.icon {- background: #F93333;- padding-left: 7px;-}-#request-detail .activities tr.activity>.content>.integrated>.head>.icon {- background: #35A612;-}-#request-detail .activities tr.activity>.content>.approved>.head>.icon,-#request-detail .activities tr.activity>.content>.verification-succeeded>.head>.icon {- background: #35A612;-}-#request-detail .activities tr.activity>.content>.disapproved>.head>.icon,-#request-detail .activities tr.activity>.content>.verification-failed>.head>.icon {- background: #F93333;-}-#request-detail .activities tr.activity>.content>.deleted-review>.head>.icon,-#request-detail .activities tr.activity>.content>.deleted-verification>.head>.icon,-#request-detail .activities tr.activity>.content>.deleted-source-branch>.head>.icon {- padding-top: 6px;- padding-left: 8px;-}-#request-detail .activities tr.activity>.content>.restored-source-branch>.head>.icon,-#request-detail .activities tr.activity>.content>.reopened>.head>.icon {- padding-left: 8px;-}-#request-detail .activities tr.activity>.content>.reference>.head>.icon {- padding-left: 8px;-}-#request-detail .activities tr.activity>.content>.reference>.head {- margin-bottom: 10px;-}-#request-detail .activities tr.activity>.content>.reference>.body {- margin-left: 36px;- font-size: 15px;-}-#request-detail .activities tr.activity>.content>.reference>.body a {- color: #333;-}-#request-detail .activities tr.activity>.content>.reference>.body a .number {- color: #999;-}-#request-detail .activities tr.activity>.content>.reference>.body .status .help {- display: none;-}-#request-detail .activities tr.activity>.content>.open .feedback .alert {- margin-bottom: 8px;-}--#request-detail .info>div>div {- border-bottom: 1px dotted #BBB;- margin-bottom: 16px;- padding-bottom: 16px;- color: #666;-}-#request-detail .info>div>div:last-child {- border-bottom: none;- margin-bottom: 0;- padding-bottom: 0;-}-#request-detail .info .help-block {- margin-bottom: 0;- color: #888;-}-#request-detail .info .fa.small {- font-size: 14px;- vertical-align: middle;-}-#request-detail .info label {- margin-right: 4px;- font-weight: normal;-}-#request-detail .info .select2-container {- width: 100%;-}-#request-detail .info .avatar {- width: 24px;- height: 24px;-}-#request-detail .info .select2-container .avatar {- width: 20px;- height: 20px;-}--#request-detail .info .reviewers ul {- margin-bottom: 0;-}-#request-detail .info .reviewers li {- margin-right: 20px;- margin-bottom: 10px;- position: relative;-}-#request-detail .info .reviewers li a:hover {- text-decoration: none;-}--#request-detail .info .reviewers .review-result {- top: -4px;-}+#request-detail>.overview>tbody>tr>td.activities {+ width: 75%;+ padding-right: 16px;+}+#request-detail .activities>table {+ margin-bottom: 20px;+ table-layout: fixed;+ border-bottom: 1px solid #CCC;+}+#request-detail tr.activity>td.spacer {+ border-right: 1px solid #E8E8E8;+}+#request-detail td.avatar {+ width: 48px;+ border-left: 4px solid white;+ padding-left: 8px;+}+#request-detail td.spacer {+ width: 30px;+}+#request-detail .discussion>td.content>div.activity {+ position: relative;+ border: 1px solid #CCC;+ border-radius: 4px;+ background: white;+ margin-left: -15px;+}+#request-detail .discussion>td.content>div.activity:before {+ display: inline-block;+ position: absolute;+ top: 10px;+ left: -8px;+ border-top: 8px solid transparent;+ border-bottom: 8px solid transparent;+ border-right: 8px solid #CBCBCB;+ content: "";+}+#request-detail .discussion>td.content>.activity:after {+ display: inline-block;+ position: absolute;+ top: 11px;+ left: -7px;+ border-top: 7px solid transparent;+ border-bottom: 7px solid transparent;+ border-right: 7px solid #F5F5F5;+ content: "";+}+#request-detail div.activity>.body>.actions {+ margin-top: 8px;+}+#request-detail div.activity>.body>.actions>a {+ margin-right: 0;+ font-size: 13px;+}+#request-detail .discussion+.discussion>td {+ padding-top: 30px;+}+#request-detail .discussion:last-child>td {+ padding-bottom: 20px;+}+#request-detail .non-discussion:last-child>td.content {+ padding-bottom: 20px;+}+#request-detail .non-discussion>td.content {+ border-top: 1px solid #EEE;+}+#request-detail .discussion+.non-discussion>td.content,+#request-detail .update+.update>td.content {+ border-top: none;+}+#request-detail .discussion>.avatar img {+ width: 40px;+ height: 40px;+}+#request-detail .non-discussion>td.content {+ font-size: 13px;+ padding: 10px 0;+}++#request-detail div.activity, #request-detail div.activity a {+ color: #999;+}+#request-detail div.activity>div.body {+ color: #444;+}++#request-detail div.activity .operations>* {+ color: #DDD;+ margin-left: 4px;+}+#request-detail div.activity:hover .operations>* {+ color: #999;+}+#request-detail div.activity .user a {+ color: #666;+ font-weight: bold;+ font-style: normal;+}+#request-detail tr.activity.since-changes {+ display: none;+}+#request-detail tr.activity.since-changes.visible {+ display: table-row;+}+#request-detail .non-discussion div.activity,+#request-detail tr.activity.since-changes td.content>div {+ margin-left: -14px;+}+#request-detail tr.activity.since-changes td.content>div a {+ font-size: 16px;+}++#request-detail .non-discussion div.activity>.head>.icon,+#request-detail tr.activity.since-changes .icon {+ border-radius: 13px;+ background: #5CA7F8;+ width: 26px;+ height: 26px;+ color: white;+ padding: 6px;+ margin-right: 4px;+}+#request-detail .discussion div.activity>.head {+ padding: 10px;+ border-radius: 4px 4px 0 0;+ background: #F5F5F5;+}+#request-detail .discussion div.activity>.body {+ padding: 12px;+}+#request-detail .non-discussion div.activity>.body {+ margin: 8px 0 0 36px;+}+#request-detail .non-discussion div.activity .user a {+ font-weight: normal;+}++#request-detail .non-discussion>td.avatar img {+ display: none;+}+#request-detail .activities tr.activity>.content>.update {+ color: #777;+ margin-left: -7px;+}+#request-detail .activities tr.activity>.content>.update>.alert {+ margin: 0 0 8px 28px;+}+#request-detail .activities tr.activity>.content>.update a {+ color: #555;+}+#request-detail .activities tr.activity>.content>.update td {+ padding: 4px 0;+}+#request-detail .activities tr.activity>.content>.update td.status {+ width: 120px;+}+#request-detail .update+.update>td.content>div {+ margin-top: -16px;+}+#request-detail .update+.update>td.content>div>.alert {+ margin-top: 16px;+}+#request-detail .discussion+.non-discussion>td.content {+ padding-top: 16px;+}+#request-detail .non-discussion+.discussion>td {+ padding-top: 8px;+}++#request-detail .activities tr.activity>.content>.update td.detail {+ padding-left: 13px;+ padding-right: 8px;+}+#request-detail .activities tr.activity>.content>.update td.detail .commit-message {+ padding-left: 4px;+}+#request-detail .activities tr.activity>.content>.update td.icon {+ width: 1px;+ padding-top: 7px;+}+#request-detail .activities tr.activity>.content>.update td.status {+ text-align: right;+ white-space: nowrap;+}+#request-detail .activities tr.activity>.content>.update tr:hover td {+ background: #F5F5F5;+}+#request-detail .activities tr.activity>.content>.update tr.integrated td.icon .fa {+ color: #35A612;+}+#request-detail .activities tr.activity>.content>.update tr.rebased td a {+ color: #AAA;+}+#request-detail .activities tr.activity>.content>.update tr.rebased td.icon .fa {+ color: #CCC;+}+#request-detail .activities tr.activity>.content>.update tr.rebased img.avatar {+ opacity: 0.5;+}+#request-detail .activities tr.activity>.content>.update td.status .successful {+ color: #35A612;+}+#request-detail .activities tr.activity>.content>.update td.status .failed {+ color: #F93333;+}+#request-detail .activities tr.activity>.content>.update td.status .running {+ color: #AFAD1F;+}+#request-detail .activities tr.activity.new>.avatar {+ border-color: #4667EE;+}++#request-detail .activities tr.activity>.content>.assigned>.head>.icon {+ padding-left: 8px;+}+#request-detail .activities tr.activity>.content>.discarded>.head>.icon {+ background: #F93333;+ padding-left: 7px;+}+#request-detail .activities tr.activity>.content>.integrated>.head>.icon {+ background: #35A612;+}+#request-detail .activities tr.activity>.content>.approved>.head>.icon,+#request-detail .activities tr.activity>.content>.verification-succeeded>.head>.icon {+ background: #35A612;+}+#request-detail .activities tr.activity>.content>.disapproved>.head>.icon,+#request-detail .activities tr.activity>.content>.verification-failed>.head>.icon {+ background: #F93333;+}+#request-detail .activities tr.activity>.content>.deleted-review>.head>.icon,+#request-detail .activities tr.activity>.content>.deleted-verification>.head>.icon,+#request-detail .activities tr.activity>.content>.deleted-source-branch>.head>.icon {+ padding-top: 6px;+ padding-left: 8px;+}+#request-detail .activities tr.activity>.content>.restored-source-branch>.head>.icon,+#request-detail .activities tr.activity>.content>.reopened>.head>.icon {+ padding-left: 8px;+}+#request-detail .activities tr.activity>.content>.reference>.head>.icon {+ padding-left: 8px;+}+#request-detail .activities tr.activity>.content>.reference>.head {+ margin-bottom: 10px;+}+#request-detail .activities tr.activity>.content>.reference>.body {+ margin-left: 36px;+ font-size: 15px;+}+#request-detail .activities tr.activity>.content>.reference>.body a {+ color: #333;+}+#request-detail .activities tr.activity>.content>.reference>.body a .number {+ color: #999;+}+#request-detail .activities tr.activity>.content>.reference>.body .status .help {+ display: none;+}+#request-detail .activities tr.activity>.content>.open .feedback .alert {+ margin-bottom: 8px;+}++#request-detail .info>div>div {+ border-bottom: 1px dotted #BBB;+ margin-bottom: 16px;+ padding-bottom: 16px;+ color: #666;+}+#request-detail .info>div>div:last-child {+ border-bottom: none;+ margin-bottom: 0;+ padding-bottom: 0;+}+#request-detail .info .help-block {+ margin-bottom: 0;+ color: #888;+}+#request-detail .info .fa.small {+ font-size: 14px;+ vertical-align: middle;+}+#request-detail .info label {+ margin-right: 4px;+ font-weight: normal;+}+#request-detail .info .select2-container {+ width: 100%;+}+#request-detail .info .avatar {+ width: 24px;+ height: 24px;+}+#request-detail .info .select2-container .avatar {+ width: 20px;+ height: 20px;+}++#request-detail .info .reviewers ul {+ margin-bottom: 0;+}+#request-detail .info .reviewers li {+ margin-right: 20px;+ margin-bottom: 10px;+ position: relative;+}+#request-detail .info .reviewers li a:hover {+ text-decoration: none;+}++#request-detail .info .reviewers .review-result {+ top: -4px;+}diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.javaindex da40a956ed..61685ea2a9 100644--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.java@@ -1,29 +1,23 @@-package com.pmease.gitplex.web.page.test;--import org.apache.wicket.markup.html.link.Link;--import com.pmease.gitplex.core.GitPlex;-import com.pmease.gitplex.core.entity.PullRequestVerification;-import com.pmease.gitplex.core.manager.PullRequestVerificationManager;-import com.pmease.gitplex.web.page.base.BasePage;--@SuppressWarnings("serial")-public class TestPage extends BasePage {-- @Override- protected void onInitialize() {- super.onInitialize();-- add(new Link<Void>("test") {-- @Override- public void onClick() {- PullRequestVerificationManager verificationManager = GitPlex.getInstance(PullRequestVerificationManager.class);- PullRequestVerification verification = verificationManager.load(1L);- verificationManager.delete(verification);- }-- });- }--}+package com.pmease.gitplex.web.page.test;++import org.apache.wicket.markup.html.link.Link;++import com.pmease.gitplex.web.page.base.BasePage;++@SuppressWarnings("serial")+public class TestPage extends BasePage {++ @Override+ protected void onInitialize() {+ super.onInitialize();++ add(new Link<Void>("test") {++ @Override+ public void onClick() {+ }++ });+ }++}