Skip to content

The Unified and Autonomous Development Platform

Refactor pull request notification

robin shine4b9200ec70d0
diff --git a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
index 7d817df888..34a1af5310 100644
--- a/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
+++ b/commons.hibernate/src/main/java/com/pmease/commons/hibernate/dao/DefaultDao.java
@@ -1,175 +1,175 @@
-package com.pmease.commons.hibernate.dao;
-
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-
-import javax.inject.Inject;
-import javax.inject.Provider;
-import javax.inject.Singleton;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.criterion.Projections;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.loader.ManagedSerializedForm;
-
-@Singleton
-@SuppressWarnings("unchecked")
-public class DefaultDao implements Dao, Serializable {
-
- private final Provider<Session> sessionProvider;
-
- private final ListenerRegistry listenerRegistry;
-
- private final ExecutorService executorService;
-
- private final UnitOfWork unitOfWork;
-
- @Inject
- public DefaultDao(Provider<Session> sessionProvider, UnitOfWork unitOfWork,
- ListenerRegistry listenerRegistry, ExecutorService executorService) {
- this.sessionProvider = sessionProvider;
- this.unitOfWork = unitOfWork;
- this.listenerRegistry = listenerRegistry;
- this.executorService = executorService;
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {
- return (T) getSession().get(unproxy(getSession(), entityClass), entityId);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {
- return (T) getSession().load(unproxy(getSession(), entityClass), entityId);
- }
-
- @Transactional
- @Override
- public void persist(AbstractEntity entity) {
- boolean isNew = entity.isNew();
- getSession().saveOrUpdate(entity);
- listenerRegistry.notify(new EntityPersisted(entity, isNew));
- }
-
- @Transactional
- @Override
- public void remove(AbstractEntity entity) {
- getSession().delete(entity);
- listenerRegistry.notify(new EntityRemoved(entity));
- }
-
- @Override
- public Session getSession() {
- return sessionProvider.get();
- }
-
- protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {
- //class meta data will be null if entityClass is not registered with Hibernate or when
- //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).
- //So if a class is not recognized, we will look at superclasses to see if
- //it is a proxy.
- while (session.getSessionFactory().getClassMetadata(entityClass) == null) {
- entityClass = (Class<T>) entityClass.getSuperclass();
- if (Object.class.equals(entityClass))
- return null;
- }
-
- return entityClass;
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- if (firstResult != 0)
- criteria.setFirstResult(firstResult);
- if (maxResults != 0)
- criteria.setMaxResults(maxResults);
- return criteria.list();
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {
- return findRange(entityCriteria, 0, 0);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- criteria.setFirstResult(0);
- criteria.setMaxResults(1);
- return (T) criteria.uniqueResult();
- }
-
- @Override
- public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {
- Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
- criteria.setProjection(Projections.rowCount());
- return ((Long) criteria.uniqueResult()).intValue();
- }
-
- public Object writeReplace() throws ObjectStreamException {
- return new ManagedSerializedForm(Dao.class);
- }
-
- @Sessional
- @Override
- public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {
- return findRange(EntityCriteria.of(entityClass), 0, 0);
- }
-
- @Override
- public void doAfterCommit(Runnable runnable) {
- getSession().getTransaction().registerSynchronization(new Synchronization() {
-
- @Override
- public void beforeCompletion() {
- }
-
- @Override
- public void afterCompletion(int status) {
- if (status == Status.STATUS_COMMITTED)
- runnable.run();
- }
- });
- }
-
- @Override
- public void doAfterCommitAsync(Runnable runnable) {
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- executorService.submit(runnable);
- }
-
- });
- }
-
- @Override
- public void doUnitOfWorkAfterCommitAsync(Runnable runnable) {
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- unitOfWork.doAsync(runnable);
- }
-
- });
- }
-
-}
+package com.pmease.commons.hibernate.dao;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+import javax.transaction.Status;
+import javax.transaction.Synchronization;
+
+import org.hibernate.Criteria;
+import org.hibernate.Session;
+import org.hibernate.criterion.Projections;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.loader.ManagedSerializedForm;
+
+@Singleton
+@SuppressWarnings("unchecked")
+public class DefaultDao implements Dao, Serializable {
+
+ private final Provider<Session> sessionProvider;
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final ExecutorService executorService;
+
+ private final UnitOfWork unitOfWork;
+
+ @Inject
+ public DefaultDao(Provider<Session> sessionProvider, UnitOfWork unitOfWork,
+ ListenerRegistry listenerRegistry, ExecutorService executorService) {
+ this.sessionProvider = sessionProvider;
+ this.unitOfWork = unitOfWork;
+ this.listenerRegistry = listenerRegistry;
+ this.executorService = executorService;
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T get(Class<T> entityClass, Long entityId) {
+ return (T) getSession().get(unproxy(getSession(), entityClass), entityId);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T load(Class<T> entityClass, Long entityId) {
+ return (T) getSession().load(unproxy(getSession(), entityClass), entityId);
+ }
+
+ @Transactional
+ @Override
+ public void persist(AbstractEntity entity) {
+ boolean isNew = entity.isNew();
+ getSession().saveOrUpdate(entity);
+ listenerRegistry.post(new EntityPersisted(entity, isNew));
+ }
+
+ @Transactional
+ @Override
+ public void remove(AbstractEntity entity) {
+ getSession().delete(entity);
+ listenerRegistry.post(new EntityRemoved(entity));
+ }
+
+ @Override
+ public Session getSession() {
+ return sessionProvider.get();
+ }
+
+ protected <T extends AbstractEntity> Class<T> unproxy(Session session, Class<T> entityClass) {
+ //class meta data will be null if entityClass is not registered with Hibernate or when
+ //it is a Hibernate proxy class (e.x. test.googlecode.genericdao.model.Person_$$_javassist_5).
+ //So if a class is not recognized, we will look at superclasses to see if
+ //it is a proxy.
+ while (session.getSessionFactory().getClassMetadata(entityClass) == null) {
+ entityClass = (Class<T>) entityClass.getSuperclass();
+ if (Object.class.equals(entityClass))
+ return null;
+ }
+
+ return entityClass;
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findRange(EntityCriteria<T> entityCriteria, int firstResult, int maxResults) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ if (firstResult != 0)
+ criteria.setFirstResult(firstResult);
+ if (maxResults != 0)
+ criteria.setMaxResults(maxResults);
+ return criteria.list();
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findAll(EntityCriteria<T> entityCriteria) {
+ return findRange(entityCriteria, 0, 0);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> T find(EntityCriteria<T> entityCriteria) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ criteria.setFirstResult(0);
+ criteria.setMaxResults(1);
+ return (T) criteria.uniqueResult();
+ }
+
+ @Override
+ public <T extends AbstractEntity> int count(EntityCriteria<T> entityCriteria) {
+ Criteria criteria = entityCriteria.getExecutableCriteria(getSession());
+ criteria.setProjection(Projections.rowCount());
+ return ((Long) criteria.uniqueResult()).intValue();
+ }
+
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(Dao.class);
+ }
+
+ @Sessional
+ @Override
+ public <T extends AbstractEntity> List<T> findAll(Class<T> entityClass) {
+ return findRange(EntityCriteria.of(entityClass), 0, 0);
+ }
+
+ @Override
+ public void doAfterCommit(Runnable runnable) {
+ getSession().getTransaction().registerSynchronization(new Synchronization() {
+
+ @Override
+ public void beforeCompletion() {
+ }
+
+ @Override
+ public void afterCompletion(int status) {
+ if (status == Status.STATUS_COMMITTED)
+ runnable.run();
+ }
+ });
+ }
+
+ @Override
+ public void doAfterCommitAsync(Runnable runnable) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ executorService.submit(runnable);
+ }
+
+ });
+ }
+
+ @Override
+ public void doUnitOfWorkAfterCommitAsync(Runnable runnable) {
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ unitOfWork.doAsync(runnable);
+ }
+
+ });
+ }
+
+}
diff --git a/commons.loader/src/main/java/com/pmease/commons/loader/DefaultListenerRegistry.java b/commons.loader/src/main/java/com/pmease/commons/loader/DefaultListenerRegistry.java
index 4175e028e0..560aa4e2db 100644
--- a/commons.loader/src/main/java/com/pmease/commons/loader/DefaultListenerRegistry.java
+++ b/commons.loader/src/main/java/com/pmease/commons/loader/DefaultListenerRegistry.java
@@ -1,73 +1,73 @@
-package com.pmease.commons.loader;
-
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.inject.Singleton;
-
-@Singleton
-public class DefaultListenerRegistry implements ListenerRegistry {
-
- private volatile Map<Object, Collection<Method>> listenerMethods;
-
- private Map<Class<?>, Collection<Listener>> listeners = new ConcurrentHashMap<>();
-
- private Map<Object, Collection<Method>> getListenerMethods() {
- if (this.listenerMethods == null) {
- Map<Object, Collection<Method>> listenersBySingleton = new HashMap<>();
- for (Object singleton: AppLoader.getSingletons()) {
- Collection<Method> listeners = new ArrayList<>();
- Class<?> current = singleton.getClass();
- Set<Class<?>> encounteredEventTypes = new HashSet<>();
- while (current != Object.class) {
- for (Method method: current.getDeclaredMethods()) {
- if (method.isAnnotationPresent(Listen.class)) {
- if (method.getParameterTypes().length != 1) {
- throw new RuntimeException("Listener method " + method + " should have only one parameter");
- }
- Class<?> eventType = method.getParameterTypes()[0];
- if (!encounteredEventTypes.contains(eventType)) {
- listeners.add(method);
- encounteredEventTypes.add(eventType);
- }
- }
- }
- current = current.getSuperclass();
- }
- listenersBySingleton.put(singleton, listeners);
- }
- this.listenerMethods = listenersBySingleton;
- }
- return this.listenerMethods;
- }
-
- private Collection<Listener> getListeners(Class<?> eventType) {
- Collection<Listener> listeners = this.listeners.get(eventType);
- if (listeners == null) {
- listeners = new ArrayList<>();
- for (Map.Entry<Object, Collection<Method>> entry: getListenerMethods().entrySet()) {
- for (Method method: entry.getValue()) {
- Class<?> paramType = method.getParameterTypes()[0];
- if (paramType.isAssignableFrom(eventType))
- listeners.add(new Listener(entry.getKey(), method));
- }
- }
- this.listeners.put(eventType, listeners);
- }
- return listeners;
- }
-
- @Override
- public void notify(Object event) {
- for (Listener listener: getListeners(event.getClass())) {
- listener.notify(event);
- }
- }
-
-}
+package com.pmease.commons.loader;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import javax.inject.Singleton;
+
+@Singleton
+public class DefaultListenerRegistry implements ListenerRegistry {
+
+ private volatile Map<Object, Collection<Method>> listenerMethods;
+
+ private Map<Class<?>, Collection<Listener>> listeners = new ConcurrentHashMap<>();
+
+ private Map<Object, Collection<Method>> getListenerMethods() {
+ if (this.listenerMethods == null) {
+ Map<Object, Collection<Method>> listenersBySingleton = new HashMap<>();
+ for (Object singleton: AppLoader.getSingletons()) {
+ Collection<Method> listeners = new ArrayList<>();
+ Class<?> current = singleton.getClass();
+ Set<Class<?>> encounteredEventTypes = new HashSet<>();
+ while (current != Object.class) {
+ for (Method method: current.getDeclaredMethods()) {
+ if (method.isAnnotationPresent(Listen.class)) {
+ if (method.getParameterTypes().length != 1) {
+ throw new RuntimeException("Listener method " + method + " should have only one parameter");
+ }
+ Class<?> eventType = method.getParameterTypes()[0];
+ if (!encounteredEventTypes.contains(eventType)) {
+ listeners.add(method);
+ encounteredEventTypes.add(eventType);
+ }
+ }
+ }
+ current = current.getSuperclass();
+ }
+ listenersBySingleton.put(singleton, listeners);
+ }
+ this.listenerMethods = listenersBySingleton;
+ }
+ return this.listenerMethods;
+ }
+
+ private Collection<Listener> getListeners(Class<?> eventType) {
+ Collection<Listener> listeners = this.listeners.get(eventType);
+ if (listeners == null) {
+ listeners = new ArrayList<>();
+ for (Map.Entry<Object, Collection<Method>> entry: getListenerMethods().entrySet()) {
+ for (Method method: entry.getValue()) {
+ Class<?> paramType = method.getParameterTypes()[0];
+ if (paramType.isAssignableFrom(eventType))
+ listeners.add(new Listener(entry.getKey(), method));
+ }
+ }
+ this.listeners.put(eventType, listeners);
+ }
+ return listeners;
+ }
+
+ @Override
+ public void post(Object event) {
+ for (Listener listener: getListeners(event.getClass())) {
+ listener.notify(event);
+ }
+ }
+
+}
diff --git a/commons.loader/src/main/java/com/pmease/commons/loader/ListenerRegistry.java b/commons.loader/src/main/java/com/pmease/commons/loader/ListenerRegistry.java
index 27eddb0af7..5a7a8d48d3 100644
--- a/commons.loader/src/main/java/com/pmease/commons/loader/ListenerRegistry.java
+++ b/commons.loader/src/main/java/com/pmease/commons/loader/ListenerRegistry.java
@@ -1,7 +1,7 @@
-package com.pmease.commons.loader;
-
-public interface ListenerRegistry {
-
- void notify(Object event);
-
-}
+package com.pmease.commons.loader;
+
+public interface ListenerRegistry {
+
+ void post(Object event);
+
+}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
index d8453f6f67..f2595f1e19 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/CommonPage.java
@@ -136,5 +136,8 @@ public abstract class CommonPage extends WebPage {
public Collection<WebSocketRegion> getWebSocketRegions() {
return new ArrayList<>();
}
-
+
+ public void afterInitialWebSocketRender() {
+
+ }
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js
index 06dd2758de..7721f09ccf 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/assets/common.js
@@ -231,7 +231,7 @@ pmease.commons = {
if ($ajaxLoadingIndicator[0].timer)
clearTimeout($ajaxLoadingIndicator[0].timer);
$ajaxLoadingIndicator[0].timer = setTimeout(function() {
- if (!$ajaxLoadingIndicator.is(":visible"))
+ if (!$ajaxLoadingIndicator.is(":visible") && $(".ajax-indicator:visible").length == 0)
$ajaxLoadingIndicator.show();
}, 2000);
});
@@ -373,7 +373,7 @@ pmease.commons = {
websocket: {
setupCallback: function() {
Wicket.Event.subscribe("/websocket/message", function(jqEvent, message) {
- if (message == "RenderCallback")
+ if (message == "InitialRenderCallback" || message == "RenderCallback")
Wicket.WebSocket.send(message);
else if (message == "ErrorMessage")
$("#websocket-error").show();
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/testform/TestFormBehavior.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/testform/TestFormBehavior.java
index 1864275105..edbde4ae28 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/testform/TestFormBehavior.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/behavior/testform/TestFormBehavior.java
@@ -26,7 +26,8 @@ public abstract class TestFormBehavior extends AbstractDefaultAjaxBehavior {
+ "$button.removeAttr('disabled');"
+ "$button.val($button[0].prevValue);"
+ "$button.html($button[0].prevHtml);"
- + "$button.closest('form').append('%s');",
+ + "$button.closest('form').append('%s');"
+ + "$button.removeClass('ajax-indicator');",
getComponent().getMarkupId(), feedbackHtml));
}
@@ -37,6 +38,7 @@ public abstract class TestFormBehavior extends AbstractDefaultAjaxBehavior {
+ "$button[0].prevHtml = $button.html();"
+ "$button.val($button.val() + ' in progress...');"
+ "$button.html($button.html() + ' in progress...');"
+ + "$button.addClass('ajax-indicator');"
+ "$button.closest('form').children('.test-feedback').remove();",
getComponent().getMarkupId()));
target.appendJavaScript(getCallbackScript());
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/datatable/EntityDataProvider.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/datatable/EntityDataProvider.java
index 87c948158a..78d21427dd 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/datatable/EntityDataProvider.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/datatable/EntityDataProvider.java
@@ -49,7 +49,7 @@ public class EntityDataProvider<T extends AbstractEntity> extends SortableDataPr
@Override
public IModel<T> model(AbstractEntity entity) {
- final Long entityId = entity.getId();
+ Long entityId = entity.getId();
return new LoadableDetachableModel<T>() {
@Override
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/wizard/Wizard.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/wizard/Wizard.java
index f04e7a36e9..337b9103e5 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/component/wizard/Wizard.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/component/wizard/Wizard.java
@@ -28,8 +28,6 @@ import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel
@SuppressWarnings("serial")
public abstract class Wizard extends Panel {
- private static final String STEP_CONTENT_ID = "content";
-
private List<? extends WizardStep> steps;
private int activeStepIndex;
@@ -45,7 +43,7 @@ public abstract class Wizard extends Panel {
protected void onInitialize() {
super.onInitialize();
- final Form<?> form = new Form<Void>("form");
+ Form<?> form = new Form<Void>("form");
form.add(new Label("title", new AbstractReadOnlyModel<String>() {
@Override
@@ -57,13 +55,13 @@ public abstract class Wizard extends Panel {
}));
form.add(new NotificationPanel("feedback", form));
- form.add(getActiveStep().render(STEP_CONTENT_ID));
+ form.add(getActiveStep().render("content"));
form.add(new Link<Void>("previous") {
@Override
public void onClick() {
activeStepIndex--;
- form.replace(getActiveStep().render(STEP_CONTENT_ID));
+ form.replace(getActiveStep().render("content"));
}
@Override
@@ -89,7 +87,7 @@ public abstract class Wizard extends Panel {
if (activeStepIndex == steps.size() - 1)
finished();
else
- form.replace(getActiveStep().render(STEP_CONTENT_ID));
+ form.replace(getActiveStep().render("content"));
}
@Override
@@ -106,7 +104,7 @@ public abstract class Wizard extends Panel {
super.onSubmit();
getActiveStep().complete();
activeStepIndex++;
- form.replace(getActiveStep().render(STEP_CONTENT_ID));
+ form.replace(getActiveStep().render("content"));
}
@Override
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
index 0af3d60dd4..7c96586478 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/DefaultWebSocketManager.java
@@ -78,11 +78,13 @@ public class DefaultWebSocketManager implements WebSocketManager {
public void render(WebSocketRegion region, @Nullable PageKey sourcePageKey) {
try {
for (IWebSocketConnection connection: connectionRegistry.getConnections(application)) {
- PageKey pageKey = ((WebSocketConnection) connection).getPageKey();
- if (connection.isOpen()
- && (sourcePageKey == null || !sourcePageKey.equals(pageKey))
- && containsRegion(connection, region)) {
- connection.sendMessage(RENDER_CALLBACK);
+ synchronized (connection) {
+ PageKey pageKey = ((WebSocketConnection) connection).getPageKey();
+ if (connection.isOpen()
+ && (sourcePageKey == null || !sourcePageKey.equals(pageKey))
+ && containsRegion(connection, region)) {
+ connection.sendMessage(RENDER_CALLBACK);
+ }
}
}
} catch (Exception e) {
@@ -105,9 +107,11 @@ public class DefaultWebSocketManager implements WebSocketManager {
@Override
public void onConnect(WebSocketConnection connection) {
- try {
- connection.sendMessage(RENDER_CALLBACK);
- } catch (IOException e) {
+ synchronized (connection) {
+ try {
+ connection.sendMessage(INITIAL_RENDER_CALLBACK);
+ } catch (IOException e) {
+ }
}
}
@@ -118,11 +122,13 @@ public class DefaultWebSocketManager implements WebSocketManager {
@Override
public void run() {
for (IWebSocketConnection connection: new SimpleWebSocketConnectionRegistry().getConnections(application)) {
- if (connection.isOpen()) {
- try {
- connection.sendMessage(WebSocketManager.KEEP_ALIVE);
- } catch (IOException e) {
- throw new RuntimeException(e);
+ synchronized (connection) {
+ if (connection.isOpen()) {
+ try {
+ connection.sendMessage(WebSocketManager.KEEP_ALIVE);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
}
}
}
diff --git a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
index de0b5997c5..dd9ed51acb 100644
--- a/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
+++ b/commons.wicket/src/main/java/com/pmease/commons/wicket/websocket/WebSocketManager.java
@@ -2,16 +2,26 @@ package com.pmease.commons.wicket.websocket;
import javax.annotation.Nullable;
+import org.apache.wicket.MetaDataKey;
+
import com.pmease.commons.wicket.CommonPage;
public interface WebSocketManager {
static final String ERROR_MESSAGE = "ErrorMessage";
+ static final String INITIAL_RENDER_CALLBACK = "InitialRenderCallback";
+
static final String RENDER_CALLBACK = "RenderCallback";
static final String KEEP_ALIVE = "KeepAlive";
+ static final MetaDataKey<Boolean> INITIAL_RENDER = new MetaDataKey<Boolean>() {
+
+ private static final long serialVersionUID = 1L;
+
+ };
+
void onRegionChange(CommonPage page);
void onDestroySession(String sessionId);
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.java
index 264b7dafee..2f8f688ad9 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
@@ -4,6 +4,7 @@ import org.apache.wicket.Component;
import org.apache.wicket.protocol.ws.api.WebSocketBehavior;
import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
import org.apache.wicket.protocol.ws.api.message.TextMessage;
+import org.apache.wicket.request.cycle.RequestCycle;
@SuppressWarnings("serial")
public abstract class WebSocketRenderBehavior extends WebSocketBehavior {
@@ -20,7 +21,8 @@ public abstract class WebSocketRenderBehavior extends WebSocketBehavior {
protected void onMessage(WebSocketRequestHandler handler, TextMessage message) {
super.onMessage(handler, message);
- if (message.getText().equals("RenderCallback")) {
+ if (message.getText().equals(WebSocketManager.INITIAL_RENDER_CALLBACK)
+ || message.getText().equals(WebSocketManager.RENDER_CALLBACK)) {
onRender(handler);
}
}
@@ -29,6 +31,18 @@ public abstract class WebSocketRenderBehavior extends WebSocketBehavior {
return component;
}
+ @Override
+ public void detach(Component component) {
+ Boolean initialRender = RequestCycle.get().getMetaData(WebSocketManager.INITIAL_RENDER);
+ if (initialRender != null && initialRender.booleanValue())
+ onInitialRenderDetach();
+ super.detach(component);
+ }
+
+ protected void onInitialRenderDetach() {
+
+ }
+
protected abstract void onRender(WebSocketRequestHandler handler);
}
diff --git a/commons.wicket/src/main/java/org/apache/wicket/protocol/ws/api/AbstractWebSocketProcessor.java b/commons.wicket/src/main/java/org/apache/wicket/protocol/ws/api/AbstractWebSocketProcessor.java
index 90fb3c840c..b270db8a12 100644
--- a/commons.wicket/src/main/java/org/apache/wicket/protocol/ws/api/AbstractWebSocketProcessor.java
+++ b/commons.wicket/src/main/java/org/apache/wicket/protocol/ws/api/AbstractWebSocketProcessor.java
@@ -215,6 +215,13 @@ public abstract class AbstractWebSocketProcessor implements IWebSocketProcessor
RequestCycle requestCycle = createRequestCycle(requestMapper, webResponse);
ThreadContext.setRequestCycle(requestCycle);
+ if (message instanceof TextMessage) {
+ TextMessage textMessage = (TextMessage) message;
+ if (textMessage.getText().equals(WebSocketManager.INITIAL_RENDER_CALLBACK)) {
+ requestCycle.setMetaData(WebSocketManager.INITIAL_RENDER, true);
+ }
+ }
+
ThreadContext.setApplication(application);
Session session;
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
index d3c47636f9..7f4f6bb8f1 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/CoreModule.java
@@ -19,7 +19,7 @@ import com.pmease.commons.loader.ImplementationProvider;
import com.pmease.commons.shiro.AbstractRealm;
import com.pmease.commons.util.ClassUtils;
import com.pmease.gitplex.core.entity.EntityLocator;
-import com.pmease.gitplex.core.entity.persistlistener.ListenerLocator;
+import com.pmease.gitplex.core.entity.persistlistener.PersistListenerLocator;
import com.pmease.gitplex.core.manager.AccountManager;
import com.pmease.gitplex.core.manager.AttachmentManager;
import com.pmease.gitplex.core.manager.BatchWorkManager;
@@ -34,7 +34,7 @@ import com.pmease.gitplex.core.manager.ConfigManager;
import com.pmease.gitplex.core.manager.DataManager;
import com.pmease.gitplex.core.manager.DepotManager;
import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.manager.NotificationManager;
+import com.pmease.gitplex.core.manager.PullRequestNotificationManager;
import com.pmease.gitplex.core.manager.OrganizationMembershipManager;
import com.pmease.gitplex.core.manager.PullRequestCommentManager;
import com.pmease.gitplex.core.manager.PullRequestInfoManager;
@@ -50,6 +50,7 @@ import com.pmease.gitplex.core.manager.TeamManager;
import com.pmease.gitplex.core.manager.TeamMembershipManager;
import com.pmease.gitplex.core.manager.UserAuthorizationManager;
import com.pmease.gitplex.core.manager.PullRequestVerificationManager;
+import com.pmease.gitplex.core.manager.PullRequestWatchManager;
import com.pmease.gitplex.core.manager.VisitInfoManager;
import com.pmease.gitplex.core.manager.WorkExecutor;
import com.pmease.gitplex.core.manager.impl.DefaultAccountManager;
@@ -82,6 +83,7 @@ import com.pmease.gitplex.core.manager.impl.DefaultTeamManager;
import com.pmease.gitplex.core.manager.impl.DefaultTeamMembershipManager;
import com.pmease.gitplex.core.manager.impl.DefaultUserAuthorizationManager;
import com.pmease.gitplex.core.manager.impl.DefaultPullRequestVerificationManager;
+import com.pmease.gitplex.core.manager.impl.DefaultPullRequestWatchManager;
import com.pmease.gitplex.core.manager.impl.DefaultVisitInfoManager;
import com.pmease.gitplex.core.manager.impl.DefaultWorkExecutor;
import com.pmease.gitplex.core.security.SecurityRealm;
@@ -174,7 +176,8 @@ public class CoreModule extends AbstractPluginModule {
bind(PullRequestReviewManager.class).to(DefaultPullRequestReviewManager.class);
bind(MailManager.class).to(DefaultMailManager.class);
bind(BranchWatchManager.class).to(DefaultBranchWatchManager.class);
- bind(NotificationManager.class).to(DefaultPullRequestNotificationManager.class);
+ bind(PullRequestNotificationManager.class).to(DefaultPullRequestNotificationManager.class);
+ bind(PullRequestWatchManager.class).to(DefaultPullRequestWatchManager.class);
bind(CommitInfoManager.class).to(DefaultCommitInfoManager.class);
bind(PullRequestInfoManager.class).to(DefaultPullRequestInfoManager.class);
bind(CodeCommentInfoManager.class).to(DefaultCodeCommentInfoManager.class);
@@ -195,7 +198,7 @@ public class CoreModule extends AbstractPluginModule {
bind(AbstractRealm.class).to(SecurityRealm.class);
- contributeFromPackage(PersistListener.class, ListenerLocator.class);
+ contributeFromPackage(PersistListener.class, PersistListenerLocator.class);
}
@Override
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/GitPlex.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/GitPlex.java
index 02ee7a27ce..83c9dc2d7f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/GitPlex.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/GitPlex.java
@@ -1,166 +1,166 @@
-package com.pmease.gitplex.core;
-
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.List;
-import java.util.Set;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.shiro.util.ThreadContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.loader.AbstractPlugin;
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.loader.AppName;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.loader.ManagedSerializedForm;
-import com.pmease.commons.util.init.InitStage;
-import com.pmease.commons.util.init.ManualConfig;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
-import com.pmease.gitplex.core.event.lifecycle.SystemStopped;
-import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.DataManager;
-import com.pmease.gitplex.core.setting.ServerConfig;
-
-public class GitPlex extends AbstractPlugin implements Serializable {
-
- private static final Logger logger = LoggerFactory.getLogger(GitPlex.class);
-
- private final ConfigManager configManager;
-
- private final DataManager dataManager;
-
- private final AccountManager accountManager;
-
- private final ServerConfig serverConfig;
-
- private final String appName;
-
- private volatile InitStage initStage;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public GitPlex(ServerConfig serverConfig, DataManager dataManager, ConfigManager configManager,
- AccountManager accountManager, ListenerRegistry listenerRegistry, @AppName String appName) {
- this.configManager = configManager;
- this.dataManager = dataManager;
- this.serverConfig = serverConfig;
- this.accountManager = accountManager;
- this.listenerRegistry = listenerRegistry;
-
- this.appName = appName;
-
- initStage = new InitStage("Server is Starting...");
- }
-
- @Override
- @Sessional
- public void start() {
- List<ManualConfig> manualConfigs = dataManager.init();
-
- if (!manualConfigs.isEmpty()) {
- logger.warn("Please set up the server at " + guessServerUrl());
- initStage = new InitStage("Server Setup", manualConfigs);
-
- initStage.waitFor();
- }
-
- ThreadContext.bind(accountManager.getRoot().asSubject());
-
- listenerRegistry.notify(new SystemStarting());
- }
-
- @Sessional
- @Override
- public void postStart() {
- initStage = null;
-
- listenerRegistry.notify(new SystemStarted());
-
- ThreadContext.unbindSubject();
-
- logger.info("Server is ready at " + configManager.getSystemSetting().getServerUrl() + ".");
- }
-
- public String guessServerUrl() {
- String hostName;
- try {
- hostName = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException e) {
- throw new RuntimeException(e);
- }
-
- String serverUrl;
- if (serverConfig.getHttpPort() != 0)
- serverUrl = "http://" + hostName + ":" + serverConfig.getHttpPort();
- else
- serverUrl = "https://" + hostName + ":" + serverConfig.getSslConfig().getPort();
-
- return StringUtils.stripEnd(serverUrl, "/");
- }
-
- public String getAppName() {
- return appName;
- }
-
- /**
- * This method can be called from different UI threads, so we clone initStage to
- * make it thread-safe.
- * <p>
- * @return
- * cloned initStage, or <tt>null</tt> if system initialization is completed
- */
- public @Nullable InitStage getInitStage() {
- if (initStage != null) {
- return initStage.clone();
- } else {
- return null;
- }
- }
-
- public boolean isReady() {
- return initStage == null;
- }
-
- public static GitPlex getInstance() {
- return AppLoader.getInstance(GitPlex.class);
- }
-
- public static <T> T getInstance(Class<T> type) {
- return AppLoader.getInstance(type);
- }
-
- public static <T> Set<T> getExtensions(Class<T> extensionPoint) {
- return AppLoader.getExtensions(extensionPoint);
- }
-
- @Sessional
- @Override
- public void preStop() {
- ThreadContext.bind(accountManager.getRoot().asSubject());
- listenerRegistry.notify(new SystemStopping());
- }
-
- @Sessional
- @Override
- public void stop() {
- listenerRegistry.notify(new SystemStopped());
- ThreadContext.unbindSubject();
- }
-
- public Object writeReplace() throws ObjectStreamException {
- return new ManagedSerializedForm(GitPlex.class);
- }
-
-}
+package com.pmease.gitplex.core;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.List;
+import java.util.Set;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.shiro.util.ThreadContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.loader.AbstractPlugin;
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.loader.AppName;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.loader.ManagedSerializedForm;
+import com.pmease.commons.util.init.InitStage;
+import com.pmease.commons.util.init.ManualConfig;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
+import com.pmease.gitplex.core.event.lifecycle.SystemStopped;
+import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.DataManager;
+import com.pmease.gitplex.core.setting.ServerConfig;
+
+public class GitPlex extends AbstractPlugin implements Serializable {
+
+ private static final Logger logger = LoggerFactory.getLogger(GitPlex.class);
+
+ private final ConfigManager configManager;
+
+ private final DataManager dataManager;
+
+ private final AccountManager accountManager;
+
+ private final ServerConfig serverConfig;
+
+ private final String appName;
+
+ private volatile InitStage initStage;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public GitPlex(ServerConfig serverConfig, DataManager dataManager, ConfigManager configManager,
+ AccountManager accountManager, ListenerRegistry listenerRegistry, @AppName String appName) {
+ this.configManager = configManager;
+ this.dataManager = dataManager;
+ this.serverConfig = serverConfig;
+ this.accountManager = accountManager;
+ this.listenerRegistry = listenerRegistry;
+
+ this.appName = appName;
+
+ initStage = new InitStage("Server is Starting...");
+ }
+
+ @Override
+ @Sessional
+ public void start() {
+ List<ManualConfig> manualConfigs = dataManager.init();
+
+ if (!manualConfigs.isEmpty()) {
+ logger.warn("Please set up the server at " + guessServerUrl());
+ initStage = new InitStage("Server Setup", manualConfigs);
+
+ initStage.waitFor();
+ }
+
+ ThreadContext.bind(accountManager.getRoot().asSubject());
+
+ listenerRegistry.post(new SystemStarting());
+ }
+
+ @Sessional
+ @Override
+ public void postStart() {
+ initStage = null;
+
+ listenerRegistry.post(new SystemStarted());
+
+ ThreadContext.unbindSubject();
+
+ logger.info("Server is ready at " + configManager.getSystemSetting().getServerUrl() + ".");
+ }
+
+ public String guessServerUrl() {
+ String hostName;
+ try {
+ hostName = InetAddress.getLocalHost().getHostName();
+ } catch (UnknownHostException e) {
+ throw new RuntimeException(e);
+ }
+
+ String serverUrl;
+ if (serverConfig.getHttpPort() != 0)
+ serverUrl = "http://" + hostName + ":" + serverConfig.getHttpPort();
+ else
+ serverUrl = "https://" + hostName + ":" + serverConfig.getSslConfig().getPort();
+
+ return StringUtils.stripEnd(serverUrl, "/");
+ }
+
+ public String getAppName() {
+ return appName;
+ }
+
+ /**
+ * This method can be called from different UI threads, so we clone initStage to
+ * make it thread-safe.
+ * <p>
+ * @return
+ * cloned initStage, or <tt>null</tt> if system initialization is completed
+ */
+ public @Nullable InitStage getInitStage() {
+ if (initStage != null) {
+ return initStage.clone();
+ } else {
+ return null;
+ }
+ }
+
+ public boolean isReady() {
+ return initStage == null;
+ }
+
+ public static GitPlex getInstance() {
+ return AppLoader.getInstance(GitPlex.class);
+ }
+
+ public static <T> T getInstance(Class<T> type) {
+ return AppLoader.getInstance(type);
+ }
+
+ public static <T> Set<T> getExtensions(Class<T> extensionPoint) {
+ return AppLoader.getExtensions(extensionPoint);
+ }
+
+ @Sessional
+ @Override
+ public void preStop() {
+ ThreadContext.bind(accountManager.getRoot().asSubject());
+ listenerRegistry.post(new SystemStopping());
+ }
+
+ @Sessional
+ @Override
+ public void stop() {
+ listenerRegistry.post(new SystemStopped());
+ ThreadContext.unbindSubject();
+ }
+
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(GitPlex.class);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/BranchWatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/BranchWatch.java
index ef283560b8..8da97762f5 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/BranchWatch.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/BranchWatch.java
@@ -1,55 +1,55 @@
-package com.pmease.gitplex.core.entity;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-
-@Entity
-@Table(uniqueConstraints={
- @UniqueConstraint(columnNames={"branch", "g_user_id"})
-})
-public class BranchWatch extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Depot depot;
-
- @Column(nullable=false)
- private String branch;
-
- public Depot getDepot() {
- return depot;
- }
-
- public void setDepot(Depot depot) {
- this.depot = depot;
- }
-
- public String getBranch() {
- return branch;
- }
-
- public void setBranch(String branch) {
- this.branch = branch;
- }
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Account user;
-
- public Account getUser() {
- return user;
- }
-
- public void setUser(Account user) {
- this.user = user;
- }
-}
+package com.pmease.gitplex.core.entity;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+
+@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_depot_id", "branch", "g_user_id"})
+})
+public class BranchWatch extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Depot depot;
+
+ @Column(nullable=false)
+ private String branch;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Account user;
+
+ public Depot getDepot() {
+ return depot;
+ }
+
+ public void setDepot(Depot depot) {
+ this.depot = depot;
+ }
+
+ public String getBranch() {
+ return branch;
+ }
+
+ public void setBranch(String branch) {
+ this.branch = branch;
+ }
+
+ public Account getUser() {
+ return user;
+ }
+
+ public void setUser(Account user) {
+ this.user = user;
+ }
+}
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.java
index a4992f02cc..e1effb71dd 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
@@ -4,6 +4,7 @@ import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
+import java.util.List;
import java.util.UUID;
import javax.annotation.Nullable;
@@ -24,9 +25,11 @@ import org.hibernate.annotations.DynamicUpdate;
import com.pmease.commons.hibernate.AbstractEntity;
import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
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.event.codecomment.CodeCommentEvent;
import com.pmease.gitplex.core.manager.VisitInfoManager;
import com.pmease.gitplex.core.security.SecurityUtils;
@@ -86,6 +89,8 @@ public class CodeComment extends AbstractEntity {
@Column(nullable=false)
private String uuid = UUID.randomUUID().toString();
+ private transient List<CodeCommentActivity> activities;
+
public Depot getDepot() {
return depot;
}
@@ -195,6 +200,14 @@ public class CodeComment extends AbstractEntity {
public void setLastEvent(LastEvent lastEvent) {
this.lastEvent = lastEvent;
}
+
+ public void setLastEvent(CodeCommentEvent event) {
+ LastEvent lastEvent = new LastEvent();
+ lastEvent.setDate(event.getDate());
+ lastEvent.setType(event.getClass());
+ lastEvent.setUser(event.getUser());
+ setLastEvent(lastEvent);
+ }
public boolean isVisitedAfter(Date date) {
Account user = SecurityUtils.getAccount();
@@ -210,6 +223,25 @@ public class CodeComment extends AbstractEntity {
return new ComparingInfo(commentPos.getCommit(), compareContext);
}
+ public List<CodeCommentActivity> getActivities() {
+ if (activities == null) {
+ activities= new ArrayList<>();
+ activities.addAll(getReplies());
+ activities.addAll(getStatusChanges());
+ activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
+ }
+ return activities;
+ }
+
+ public CompareContext getLastCompareContext() {
+ if (!getActivities().isEmpty()) {
+ CodeCommentActivity lastActivity = activities.get(activities.size()-1);
+ return lastActivity.getCompareContext();
+ } else {
+ return getCompareContext();
+ }
+ }
+
public static class ComparingInfo implements Serializable {
private static final long serialVersionUID = 1L;
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
index 180614b9c3..39182d2f2c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/Depot.java
@@ -1,939 +1,939 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-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.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.stream.Collectors;
-
-import javax.annotation.Nullable;
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-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 javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import org.apache.commons.lang3.SerializationUtils;
-import org.eclipse.jgit.api.CreateBranchCommand;
-import org.eclipse.jgit.api.Git;
-import org.eclipse.jgit.api.TagCommand;
-import org.eclipse.jgit.api.errors.GitAPIException;
-import org.eclipse.jgit.diff.DiffEntry;
-import org.eclipse.jgit.diff.DiffFormatter;
-import org.eclipse.jgit.diff.MyersDiff;
-import org.eclipse.jgit.diff.RawTextComparator;
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.lib.PersonIdent;
-import org.eclipse.jgit.lib.Ref;
-import org.eclipse.jgit.lib.RefUpdate;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
-import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
-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 org.eclipse.jgit.util.io.NullOutputStream;
-import org.hibernate.annotations.Cache;
-import org.hibernate.annotations.CacheConcurrencyStrategy;
-import org.hibernate.annotations.DynamicUpdate;
-import org.hibernate.validator.constraints.NotEmpty;
-
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.pmease.commons.git.Blob;
-import com.pmease.commons.git.BlobIdent;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.RefInfo;
-import com.pmease.commons.git.Submodule;
-import com.pmease.commons.git.exception.NotFileException;
-import com.pmease.commons.git.exception.ObjectNotExistException;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.LockUtils;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Markdown;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
-import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.VisitInfoManager;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.core.security.protectedobject.AccountBelonging;
-import com.pmease.gitplex.core.security.protectedobject.ProtectedObject;
-import com.pmease.gitplex.core.util.validation.DepotName;
-
-@Entity
-@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_account_id", "name"})})
-@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
-@DynamicUpdate
-@Editable
-public class Depot extends AbstractEntity implements AccountBelonging {
-
- private static final long serialVersionUID = 1L;
-
- public static final String FQN_SEPARATOR = "/";
-
- public static final String REF_FQN_SEPARATOR = ":";
-
- public static final String REFS_GITPLEX = "refs/gitplex/";
-
- private static final int LAST_COMMITS_CACHE_THRESHOLD = 1000;
-
- private static final int MAX_READ_BLOB_SIZE = 5*1024*1024;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Account account;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=true)
- private Depot forkedFrom;
-
- @Column(nullable=false)
- private String name;
-
- private String description;
-
- private boolean publicRead;
-
- @Column(nullable=false)
- private String uuid = UUID.randomUUID().toString();
-
- /*
- * Optimistic lock is necessary to ensure database integrity when update
- * gate keepers and integration policies upon depot renaming/deletion
- */
- @Version
- private long version;
-
- @Lob
- @Column(nullable=false, length=65535)
- private ArrayList<GateKeeper> gateKeepers = new ArrayList<>();
-
- @Lob
- @Column(nullable=false, length=65535)
- private ArrayList<IntegrationPolicy> integrationPolicies = new ArrayList<>();
-
- @Column(nullable=false)
- private Date createdAt = new Date();
-
- @OneToMany(mappedBy="targetDepot", cascade=CascadeType.REMOVE)
- private Collection<PullRequest> incomingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="sourceDepot")
- private Collection<PullRequest> outgoingRequests = new ArrayList<>();
-
- @OneToMany(mappedBy="forkedFrom")
- private Collection<Depot> forks = new ArrayList<>();
-
- @OneToMany(mappedBy="depot", cascade=CascadeType.REMOVE)
- private Collection<TeamAuthorization> authorizedTeams = new ArrayList<>();
-
- @OneToMany(mappedBy="depot", cascade=CascadeType.REMOVE)
- private Collection<UserAuthorization> authorizedUsers = new ArrayList<>();
-
- private transient Repository repository;
-
- private transient Map<BlobIdent, Blob> blobCache;
-
- private transient Map<String, Optional<ObjectId>> objectIdCache;
-
- private transient Map<String, Optional<Ref>> refCache;
-
- private transient Optional<String> defaultBranch;
-
- @Override
- public Account getAccount() {
- return account;
- }
-
- public void setAccount(Account account) {
- this.account = account;
- }
-
- @Editable(order=100)
- @DepotName
- @NotEmpty
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- @Editable(order=200, description="Optionally describe the repository")
- @Markdown
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- @Editable(order=300, name="Public", description="Whether or not this repository can be read by everyone")
- public boolean isPublicRead() {
- return publicRead;
- }
-
- public void setPublicRead(boolean publicRead) {
- this.publicRead = publicRead;
- }
-
- public String getUUID() {
- return uuid;
- }
-
- public void setUUID(String uuid) {
- this.uuid = uuid;
- }
-
- @NotNull
- @Valid
- public List<GateKeeper> getGateKeepers() {
- return gateKeepers;
- }
-
- public void setGateKeepers(ArrayList<GateKeeper> gateKeepers) {
- this.gateKeepers = gateKeepers;
- }
-
- @Valid
- public List<IntegrationPolicy> getIntegrationPolicies() {
- return integrationPolicies;
- }
-
- public void setIntegrationPolicies(ArrayList<IntegrationPolicy> integrationPolicies) {
- this.integrationPolicies = integrationPolicies;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
-
- public Collection<PullRequest> getIncomingRequests() {
- return incomingRequests;
- }
-
- public void setIncomingRequests(Collection<PullRequest> incomingRequests) {
- this.incomingRequests = incomingRequests;
- }
-
- public Collection<PullRequest> getOutgoingRequests() {
- return outgoingRequests;
- }
-
- public void setOutgoingRequests(Collection<PullRequest> outgoingRequests) {
- this.outgoingRequests = outgoingRequests;
- }
-
- public Depot getForkedFrom() {
- return forkedFrom;
- }
-
- public void setForkedFrom(Depot forkedFrom) {
- this.forkedFrom = forkedFrom;
- }
-
- public Collection<Depot> getForks() {
- return forks;
- }
-
- public void setForks(Collection<Depot> forks) {
- this.forks = forks;
- }
-
- public List<RefInfo> getBranches() {
- return getRefInfos(Constants.R_HEADS);
- }
-
- public List<RefInfo> getTags() {
- return getRefInfos(Constants.R_TAGS);
- }
-
- public List<RefInfo> getRefInfos(String prefix) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- List<Ref> refs = new ArrayList<Ref>(getRepository().getRefDatabase().getRefs(prefix).values());
- List<RefInfo> refInfos = refs.stream()
- .map(ref->new RefInfo(revWalk, ref))
- .filter(refInfo->refInfo.getPeeledObj() instanceof RevCommit)
- .collect(Collectors.toList());
- Collections.sort(refInfos);
- Collections.reverse(refInfos);
- return refInfos;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public boolean has(ProtectedObject object) {
- if (object instanceof Depot) {
- Depot depot = (Depot) object;
- return depot.getId().equals(getId());
- } else {
- return false;
- }
- }
-
- public String getFQN() {
- return getAccount().getName() + FQN_SEPARATOR + getName();
- }
-
- public static String getNameByFQN(String repositoryFQN) {
- return StringUtils.substringAfterLast(repositoryFQN, FQN_SEPARATOR);
- }
-
- public static String getUserNameByFQN(String repositoryFQN) {
- return StringUtils.substringBeforeLast(repositoryFQN, FQN_SEPARATOR);
- }
-
- @Override
- public String toString() {
- return getFQN();
- }
-
- public Git git() {
- return Git.wrap(getRepository());
- }
-
- public File getDirectory() {
- return AppLoader.getInstance(StorageManager.class).getGitDir(this);
- }
-
- /**
- * Whether or not specified git represents a valid repository git. This can be used to tell
- * apart a GitPlex repository git from some other Git repositories.
- *
- * @return
- * <tt>true</tt> if valid; <tt>false</tt> otherwise
- */
- public boolean isValid() {
- return isGitHookValid("pre-receive") && isGitHookValid("post-receive");
- }
-
- public boolean isGitHookValid(String hookName) {
- File hookFile = new File(getDirectory(), "hooks/" + hookName);
- if (!hookFile.exists())
- return false;
-
- try {
- String content = FileUtils.readFileToString(hookFile);
- if (!content.contains("GITPLEX_USER_ID"))
- return false;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- if (!hookFile.canExecute())
- return false;
-
- return true;
- }
-
- public GateKeeper getGateKeeper() {
- AndGateKeeper andGateKeeper = new AndGateKeeper();
- for (GateKeeper each: getGateKeepers())
- andGateKeeper.getGateKeepers().add(each);
- return andGateKeeper;
- }
-
- /**
- * Find fork root of this repository.
- *
- * @return
- * fork root of this repository, or <tt>null</tt> if the repository is not
- * forked from any other repository
- */
- public @Nullable Depot findForkRoot() {
- if (forkedFrom != null) {
- Depot forkedRoot = forkedFrom.findForkRoot();
- if (forkedRoot != null)
- return forkedRoot;
- else
- return forkedFrom;
- } else {
- return null;
- }
- }
-
- /**
- * Find all descendant repositories forking from current repository.
- *
- * @return
- * all descendant repositories forking from current repository
- */
- public List<Depot> findForkDescendants() {
- List<Depot> descendants = new ArrayList<>();
- for (Depot fork: getForks()) {
- if (fork.getDefaultBranch() != null)
- descendants.add(fork);
- descendants.addAll(fork.findForkDescendants());
- }
-
- return descendants;
- }
-
- /**
- * Find all comparable repositories of current repository. Comparable repositories can
- * be connected via forks, and can be compared/pulled.
- *
- * @return
- * comparable repositories of current repository, with current repository also
- * included in the collection
- */
- public List<Depot> findAffinals() {
- List<Depot> affinals = new ArrayList<Depot>();
- Depot forkRoot = findForkRoot();
- if (forkRoot != null) {
- affinals.add(forkRoot);
- affinals.addAll(forkRoot.findForkDescendants());
- } else {
- affinals.add(this);
- affinals.addAll(findForkDescendants());
- }
- affinals.sort((repo1, repo2) -> {
- if (repo1.getAccount().equals(repo2.getAccount()))
- return repo1.getName().compareTo(repo2.getName());
- else
- return repo1.getAccount().getName().compareTo(repo2.getAccount().getName());
- });
- return affinals;
- }
-
- public Repository getRepository() {
- if (repository == null) {
- repository = GitPlex.getInstance(DepotManager.class).getRepository(this);
- }
- return repository;
- }
-
- public RevCommit getMergeBase(String commit1, String commit2) {
- return GitUtils.getMergeBase(getRepository(), getObjectId(commit1), getObjectId(commit2));
- }
-
- public boolean isMergedInto(String base, String tip) {
- return GitUtils.isMergedInto(getRepository(), getObjectId(base), getObjectId(tip));
- }
-
- public String getUrl() {
- return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl() + "/" + getFQN();
- }
-
- @Nullable
- public String getDefaultBranch() {
- if (defaultBranch == null) {
- try {
- Ref headRef = getRepository().findRef("HEAD");
- if (headRef.isSymbolic()
- && headRef.getTarget().getName().startsWith(Constants.R_HEADS)
- && headRef.getObjectId() != null) {
- defaultBranch = Optional.of(Repository.shortenRefName(headRef.getTarget().getName()));
- } else {
- defaultBranch = Optional.absent();
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return defaultBranch.orNull();
- }
-
- private Blob readBlob(ObjectLoader objectLoader, BlobIdent ident) {
- long blobSize = objectLoader.getSize();
- if (blobSize > MAX_READ_BLOB_SIZE) {
- try (InputStream is = objectLoader.openStream()) {
- byte[] bytes = new byte[MAX_READ_BLOB_SIZE];
- is.read(bytes);
- return new Blob(ident, bytes, blobSize);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- } else {
- return new Blob(ident, objectLoader.getCachedBytes());
- }
- }
-
- private Map<BlobIdent, Blob> getBlobCache() {
- if (blobCache == null) {
- synchronized(this) {
- if (blobCache == null)
- blobCache = new ConcurrentHashMap<>();
- }
- }
- return blobCache;
- }
-
- /**
- * Read blob content and cache result in repository in case the same blob
- * content is requested again.
- *
- * We made this method thread-safe as we are using ForkJoinPool to calculate
- * diffs of multiple blob changes concurrently, and this method will be
- * accessed concurrently in that special case.
- *
- * @param blobIdent
- * ident of the blob
- * @return
- * blob of specified blob ident
- * @throws
- * ObjectNotExistException if blob of specified ident can not be found in repository
- *
- */
- public Blob getBlob(BlobIdent blobIdent) {
- Preconditions.checkArgument(blobIdent.revision!=null && blobIdent.path!=null && blobIdent.mode!=null,
- "Revision, path and mode of ident param should be specified");
-
- Blob blob = getBlobCache().get(blobIdent);
- if (blob == null) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId revId = getObjectId(blobIdent.revision);
- RevTree revTree = revWalk.parseCommit(revId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getRepository(), blobIdent.path, revTree);
- if (treeWalk != null) {
- if (blobIdent.isGitLink()) {
- String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
- if (url == null)
- throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
- String hash = treeWalk.getObjectId(0).name();
- blob = new Blob(blobIdent, new Submodule(url, hash).toString().getBytes());
- } else if (blobIdent.isTree()) {
- throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
- } else {
- ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
- blob = readBlob(objectLoader, blobIdent);
- }
- getBlobCache().put(blobIdent, blob);
- } else {
- throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path + "' in revision '" + blobIdent.revision + "'");
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return blob;
- }
-
- public InputStream getInputStream(BlobIdent ident) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- ObjectId commitId = getObjectId(ident.revision);
- RevTree revTree = revWalk.parseCommit(commitId).getTree();
- TreeWalk treeWalk = TreeWalk.forPath(getRepository(), ident.path, revTree);
- if (treeWalk != null) {
- ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
- return objectLoader.openStream();
- } else {
- throw new ObjectNotExistException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Get cached object id of specified revision.
- *
- * @param revision
- * revision to resolve object id for
- * @param mustExist
- * true to have the method throwing exception instead
- * of returning null if the revision does not exist
- * @return
- * object id of specified revision, or <tt>null</tt> if revision
- * does not exist and mustExist is specified as false
- */
- @Nullable
- public ObjectId getObjectId(String revision, boolean mustExist) {
- if (objectIdCache == null)
- objectIdCache = new HashMap<>();
-
- Optional<ObjectId> optional = objectIdCache.get(revision);
- if (optional == null) {
- optional = Optional.fromNullable(GitUtils.resolve(getRepository(), revision));
- objectIdCache.put(revision, optional);
- }
- if (mustExist && !optional.isPresent())
- throw new ObjectNotExistException("Unable to find object '" + revision + "'");
- return optional.orNull();
- }
-
- public ObjectId getObjectId(String revision) {
- return getObjectId(revision, true);
- }
-
- public void cacheObjectId(String revision, @Nullable ObjectId objectId) {
- if (objectIdCache == null)
- objectIdCache = new HashMap<>();
-
- objectIdCache.put(revision, Optional.fromNullable(objectId));
- }
-
- public List<DiffEntry> getDiffs(String oldRev, String newRev) {
- List<DiffEntry> diffs = new ArrayList<>();
- try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
- diffFormatter.setRepository(getRepository());
- diffFormatter.setDetectRenames(true);
- diffFormatter.setDiffAlgorithm(MyersDiff.INSTANCE);
- diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
- AnyObjectId oldRevId = getObjectId(oldRev);
- AnyObjectId newRevId = getObjectId(newRev);
- for (DiffEntry entry: diffFormatter.scan(oldRevId, newRevId)) {
- if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
- || !Objects.equal(entry.getOldMode(), entry.getNewMode())
- || entry.getOldId()==null || !entry.getOldId().isComplete()
- || entry.getNewId()== null || !entry.getNewId().isComplete()
- || !entry.getOldId().equals(entry.getNewId())) {
- diffs.add(entry);
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return diffs;
- }
-
- public LastCommitsOfChildren getLastCommitsOfChildren(String revision, @Nullable String path) {
- if (path == null)
- path = "";
-
- final File cacheDir = new File(
- GitPlex.getInstance(StorageManager.class).getInfoDir(this),
- "last_commits/" + path + "/gitplex_last_commits");
-
- final ReadWriteLock lock;
- try {
- lock = LockUtils.getReadWriteLock(cacheDir.getCanonicalPath());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- final Set<ObjectId> commitIds = new HashSet<>();
-
- lock.readLock().lock();
- try {
- if (cacheDir.exists()) {
- for (String each: cacheDir.list())
- commitIds.add(ObjectId.fromString(each));
- }
- } finally {
- lock.readLock().unlock();
- }
-
- org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache cache;
- if (!commitIds.isEmpty()) {
- cache = new org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache() {
-
- @SuppressWarnings("unchecked")
- @Override
- public Map<String, Value> getLastCommitsOfChildren(ObjectId commitId) {
- if (commitIds.contains(commitId)) {
- lock.readLock().lock();
- try {
- byte[] bytes = FileUtils.readFileToByteArray(new File(cacheDir, commitId.name()));
- return (Map<String, Value>) SerializationUtils.deserialize(bytes);
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- lock.readLock().unlock();
- }
- } else {
- return null;
- }
- }
-
- };
- } else {
- cache = null;
- }
-
- final AnyObjectId commitId = getObjectId(revision);
-
- long time = System.currentTimeMillis();
- LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(getRepository(), commitId, path, cache);
- long elapsed = System.currentTimeMillis()-time;
- if (elapsed > LAST_COMMITS_CACHE_THRESHOLD) {
- lock.writeLock().lock();
- try {
- if (!cacheDir.exists())
- FileUtils.createDir(cacheDir);
- FileUtils.writeByteArrayToFile(
- new File(cacheDir, commitId.name()),
- SerializationUtils.serialize(lastCommits));
- } catch (IOException e) {
- throw new RuntimeException(e);
- } finally {
- lock.writeLock().unlock();
- }
- }
- return lastCommits;
- }
-
- @Nullable
- public Ref getRef(String revision) {
- if (refCache == null)
- refCache = new HashMap<>();
- Optional<Ref> optional = refCache.get(revision);
- if (optional == null) {
- try {
- optional = Optional.fromNullable(getRepository().findRef(revision));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- refCache.put(revision, optional);
- }
- return optional.orNull();
- }
-
- @Nullable
- public RevCommit getRevCommit(String revision, boolean mustExist) {
- RevCommit commit;
- ObjectId revId = getObjectId(revision, mustExist);
- if (revId != null) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- commit = GitUtils.parseCommit(revWalk, revId);
- }
- } else {
- commit = null;
- }
- if (mustExist && commit == null)
- throw new ObjectNotExistException("Unable to find commit: " + revision);
- else
- return commit;
- }
-
- public RevCommit getRevCommit(String revision) {
- return getRevCommit(revision, true);
- }
-
- @Nullable
- public RevCommit getRevCommit(ObjectId revId, boolean mustExist) {
- try (RevWalk revWalk = new RevWalk(getRepository())) {
- RevCommit commit = GitUtils.parseCommit(revWalk, revId);
- if (mustExist && commit == null)
- throw new ObjectNotExistException("Unable to find commit: " + revId.name());
- else
- return commit;
- }
- }
-
- public RevCommit getRevCommit(ObjectId revId) {
- return getRevCommit(revId, true);
- }
-
- public Map<String, Ref> getRefs(String prefix) {
- try {
- return getRepository().getRefDatabase().getRefs(prefix);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public Map<String, String> getSubmodules(String revision) {
- Map<String, String> submodules = new HashMap<>();
-
- Blob blob = getBlob(new BlobIdent(revision, ".gitmodules", FileMode.REGULAR_FILE.getBits()));
- String content = new String(blob.getBytes());
-
- String path = null;
- String url = null;
-
- for (String line: StringUtils.splitAndTrim(content, "\r\n")) {
- if (line.startsWith("[") && line.endsWith("]")) {
- if (path != null && url != null)
- submodules.put(path, url);
-
- path = url = null;
- } else if (line.startsWith("path")) {
- path = StringUtils.substringAfter(line, "=").trim();
- } else if (line.startsWith("url")) {
- url = StringUtils.substringAfter(line, "=").trim();
- }
- }
- if (path != null && url != null)
- submodules.put(path, url);
-
- return submodules;
- }
-
- public void deleteBranch(String branch) {
- String refName = GitUtils.branch2ref(branch);
- ObjectId commitId = getRevCommit(refName).getId();
- try {
- git().branchDelete().setForce(true).setBranchNames(branch).call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(getId());
- GitPlex.getInstance(ListenerRegistry.class).notify(
- new RefUpdated(depot, refName, commitId, ObjectId.zeroId()));
- }
-
- });
- }
-
- public void createBranch(String branchName, String branchRevision) {
- try {
- CreateBranchCommand command = git().branchCreate();
- command.setName(branchName);
- command.setStartPoint(getRevCommit(branchRevision));
- command.call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void tag(String tagName, String tagRevision, PersonIdent taggerIdent, @Nullable String tagMessage) {
- try {
- TagCommand tag = git().tag();
- tag.setName(tagName);
- if (tagMessage != null)
- tag.setMessage(tagMessage);
- tag.setTagger(taggerIdent);
- tag.setObjectId(getRevCommit(tagRevision));
- tag.call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- }
-
- public void deleteTag(String tag) {
- String refName = GitUtils.tag2ref(tag);
- ObjectId commitId = getRevCommit(refName).getId();
- try {
- git().tagDelete().setTags(tag).call();
- } catch (GitAPIException e) {
- throw new RuntimeException(e);
- }
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(getId());
- GitPlex.getInstance(ListenerRegistry.class).notify(
- new RefUpdated(depot, refName, commitId, ObjectId.zeroId()));
- }
-
- });
- }
-
- public Collection<TeamAuthorization> getAuthorizedTeams() {
- return authorizedTeams;
- }
-
- public void setAuthorizedTeams(Collection<TeamAuthorization> authorizedTeams) {
- this.authorizedTeams = authorizedTeams;
- }
-
- public Collection<UserAuthorization> getAuthorizedUsers() {
- return authorizedUsers;
- }
-
- public void setAuthorizedUsers(Collection<UserAuthorization> authorizedUsers) {
- this.authorizedUsers = authorizedUsers;
- }
-
- public long getVersion() {
- return version;
- }
-
- public boolean matches(@Nullable String searchTerm) {
- if (searchTerm == null)
- searchTerm = "";
- else
- searchTerm = searchTerm.toLowerCase().trim();
-
- return getName().toLowerCase().contains(searchTerm);
- }
-
- public boolean matchesFQN(@Nullable String searchTerm) {
- if (searchTerm == null)
- searchTerm = "";
- else
- searchTerm = searchTerm.toLowerCase().trim();
-
- return getFQN().toLowerCase().contains(searchTerm);
- }
-
- public RefUpdate updateRef(String refName) {
- try {
- return getRepository().updateRef(refName);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- public int compareTo(AbstractEntity entity) {
- Depot depot = (Depot) entity;
- if (getAccount().equals(depot.getAccount())) {
- return getName().compareTo(depot.getName());
- } else {
- return getAccount().compareTo(depot.getAccount());
- }
- }
-
- public static int compareLastVisit(Depot depot1, Depot depot2) {
- Account user = SecurityUtils.getAccount();
- if (user != null) {
- Date date1 = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, depot1);
- Date date2 = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, depot2);
- if (date1 != null) {
- if (date2 != null)
- return date2.compareTo(date1);
- else
- return -1;
- } else {
- if (date2 != null)
- return 1;
- else
- return depot1.compareTo(depot2);
- }
- } else {
- return depot1.compareTo(depot2);
- }
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+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.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.stream.Collectors;
+
+import javax.annotation.Nullable;
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+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 javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.eclipse.jgit.api.CreateBranchCommand;
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.api.TagCommand;
+import org.eclipse.jgit.api.errors.GitAPIException;
+import org.eclipse.jgit.diff.DiffEntry;
+import org.eclipse.jgit.diff.DiffFormatter;
+import org.eclipse.jgit.diff.MyersDiff;
+import org.eclipse.jgit.diff.RawTextComparator;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.lib.Ref;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren;
+import org.eclipse.jgit.revwalk.LastCommitsOfChildren.Value;
+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 org.eclipse.jgit.util.io.NullOutputStream;
+import org.hibernate.annotations.Cache;
+import org.hibernate.annotations.CacheConcurrencyStrategy;
+import org.hibernate.annotations.DynamicUpdate;
+import org.hibernate.validator.constraints.NotEmpty;
+
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.pmease.commons.git.Blob;
+import com.pmease.commons.git.BlobIdent;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.RefInfo;
+import com.pmease.commons.git.Submodule;
+import com.pmease.commons.git.exception.NotFileException;
+import com.pmease.commons.git.exception.ObjectNotExistException;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.LockUtils;
+import com.pmease.commons.util.StringUtils;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Markdown;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.gatekeeper.AndGateKeeper;
+import com.pmease.gitplex.core.gatekeeper.GateKeeper;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.VisitInfoManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.core.security.protectedobject.AccountBelonging;
+import com.pmease.gitplex.core.security.protectedobject.ProtectedObject;
+import com.pmease.gitplex.core.util.validation.DepotName;
+
+@Entity
+@Table(uniqueConstraints={@UniqueConstraint(columnNames={"g_account_id", "name"})})
+@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
+@DynamicUpdate
+@Editable
+public class Depot extends AbstractEntity implements AccountBelonging {
+
+ private static final long serialVersionUID = 1L;
+
+ public static final String FQN_SEPARATOR = "/";
+
+ public static final String REF_FQN_SEPARATOR = ":";
+
+ public static final String REFS_GITPLEX = "refs/gitplex/";
+
+ private static final int LAST_COMMITS_CACHE_THRESHOLD = 1000;
+
+ private static final int MAX_READ_BLOB_SIZE = 5*1024*1024;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Account account;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=true)
+ private Depot forkedFrom;
+
+ @Column(nullable=false)
+ private String name;
+
+ private String description;
+
+ private boolean publicRead;
+
+ @Column(nullable=false)
+ private String uuid = UUID.randomUUID().toString();
+
+ /*
+ * Optimistic lock is necessary to ensure database integrity when update
+ * gate keepers and integration policies upon depot renaming/deletion
+ */
+ @Version
+ private long version;
+
+ @Lob
+ @Column(nullable=false, length=65535)
+ private ArrayList<GateKeeper> gateKeepers = new ArrayList<>();
+
+ @Lob
+ @Column(nullable=false, length=65535)
+ private ArrayList<IntegrationPolicy> integrationPolicies = new ArrayList<>();
+
+ @Column(nullable=false)
+ private Date createdAt = new Date();
+
+ @OneToMany(mappedBy="targetDepot", cascade=CascadeType.REMOVE)
+ private Collection<PullRequest> incomingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="sourceDepot")
+ private Collection<PullRequest> outgoingRequests = new ArrayList<>();
+
+ @OneToMany(mappedBy="forkedFrom")
+ private Collection<Depot> forks = new ArrayList<>();
+
+ @OneToMany(mappedBy="depot", cascade=CascadeType.REMOVE)
+ private Collection<TeamAuthorization> authorizedTeams = new ArrayList<>();
+
+ @OneToMany(mappedBy="depot", cascade=CascadeType.REMOVE)
+ private Collection<UserAuthorization> authorizedUsers = new ArrayList<>();
+
+ private transient Repository repository;
+
+ private transient Map<BlobIdent, Blob> blobCache;
+
+ private transient Map<String, Optional<ObjectId>> objectIdCache;
+
+ private transient Map<String, Optional<Ref>> refCache;
+
+ private transient Optional<String> defaultBranch;
+
+ @Override
+ public Account getAccount() {
+ return account;
+ }
+
+ public void setAccount(Account account) {
+ this.account = account;
+ }
+
+ @Editable(order=100)
+ @DepotName
+ @NotEmpty
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Editable(order=200, description="Optionally describe the repository")
+ @Markdown
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ @Editable(order=300, name="Public", description="Whether or not this repository can be read by everyone")
+ public boolean isPublicRead() {
+ return publicRead;
+ }
+
+ public void setPublicRead(boolean publicRead) {
+ this.publicRead = publicRead;
+ }
+
+ public String getUUID() {
+ return uuid;
+ }
+
+ public void setUUID(String uuid) {
+ this.uuid = uuid;
+ }
+
+ @NotNull
+ @Valid
+ public List<GateKeeper> getGateKeepers() {
+ return gateKeepers;
+ }
+
+ public void setGateKeepers(ArrayList<GateKeeper> gateKeepers) {
+ this.gateKeepers = gateKeepers;
+ }
+
+ @Valid
+ public List<IntegrationPolicy> getIntegrationPolicies() {
+ return integrationPolicies;
+ }
+
+ public void setIntegrationPolicies(ArrayList<IntegrationPolicy> integrationPolicies) {
+ this.integrationPolicies = integrationPolicies;
+ }
+
+ public Date getCreatedAt() {
+ return createdAt;
+ }
+
+ public void setCreatedAt(Date createdAt) {
+ this.createdAt = createdAt;
+ }
+
+ public Collection<PullRequest> getIncomingRequests() {
+ return incomingRequests;
+ }
+
+ public void setIncomingRequests(Collection<PullRequest> incomingRequests) {
+ this.incomingRequests = incomingRequests;
+ }
+
+ public Collection<PullRequest> getOutgoingRequests() {
+ return outgoingRequests;
+ }
+
+ public void setOutgoingRequests(Collection<PullRequest> outgoingRequests) {
+ this.outgoingRequests = outgoingRequests;
+ }
+
+ public Depot getForkedFrom() {
+ return forkedFrom;
+ }
+
+ public void setForkedFrom(Depot forkedFrom) {
+ this.forkedFrom = forkedFrom;
+ }
+
+ public Collection<Depot> getForks() {
+ return forks;
+ }
+
+ public void setForks(Collection<Depot> forks) {
+ this.forks = forks;
+ }
+
+ public List<RefInfo> getBranches() {
+ return getRefInfos(Constants.R_HEADS);
+ }
+
+ public List<RefInfo> getTags() {
+ return getRefInfos(Constants.R_TAGS);
+ }
+
+ public List<RefInfo> getRefInfos(String prefix) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ List<Ref> refs = new ArrayList<Ref>(getRepository().getRefDatabase().getRefs(prefix).values());
+ List<RefInfo> refInfos = refs.stream()
+ .map(ref->new RefInfo(revWalk, ref))
+ .filter(refInfo->refInfo.getPeeledObj() instanceof RevCommit)
+ .collect(Collectors.toList());
+ Collections.sort(refInfos);
+ Collections.reverse(refInfos);
+ return refInfos;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public boolean has(ProtectedObject object) {
+ if (object instanceof Depot) {
+ Depot depot = (Depot) object;
+ return depot.getId().equals(getId());
+ } else {
+ return false;
+ }
+ }
+
+ public String getFQN() {
+ return getAccount().getName() + FQN_SEPARATOR + getName();
+ }
+
+ public static String getNameByFQN(String repositoryFQN) {
+ return StringUtils.substringAfterLast(repositoryFQN, FQN_SEPARATOR);
+ }
+
+ public static String getUserNameByFQN(String repositoryFQN) {
+ return StringUtils.substringBeforeLast(repositoryFQN, FQN_SEPARATOR);
+ }
+
+ @Override
+ public String toString() {
+ return getFQN();
+ }
+
+ public Git git() {
+ return Git.wrap(getRepository());
+ }
+
+ public File getDirectory() {
+ return AppLoader.getInstance(StorageManager.class).getGitDir(this);
+ }
+
+ /**
+ * Whether or not specified git represents a valid repository git. This can be used to tell
+ * apart a GitPlex repository git from some other Git repositories.
+ *
+ * @return
+ * <tt>true</tt> if valid; <tt>false</tt> otherwise
+ */
+ public boolean isValid() {
+ return isGitHookValid("pre-receive") && isGitHookValid("post-receive");
+ }
+
+ public boolean isGitHookValid(String hookName) {
+ File hookFile = new File(getDirectory(), "hooks/" + hookName);
+ if (!hookFile.exists())
+ return false;
+
+ try {
+ String content = FileUtils.readFileToString(hookFile);
+ if (!content.contains("GITPLEX_USER_ID"))
+ return false;
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ if (!hookFile.canExecute())
+ return false;
+
+ return true;
+ }
+
+ public GateKeeper getGateKeeper() {
+ AndGateKeeper andGateKeeper = new AndGateKeeper();
+ for (GateKeeper each: getGateKeepers())
+ andGateKeeper.getGateKeepers().add(each);
+ return andGateKeeper;
+ }
+
+ /**
+ * Find fork root of this repository.
+ *
+ * @return
+ * fork root of this repository, or <tt>null</tt> if the repository is not
+ * forked from any other repository
+ */
+ public @Nullable Depot findForkRoot() {
+ if (forkedFrom != null) {
+ Depot forkedRoot = forkedFrom.findForkRoot();
+ if (forkedRoot != null)
+ return forkedRoot;
+ else
+ return forkedFrom;
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Find all descendant repositories forking from current repository.
+ *
+ * @return
+ * all descendant repositories forking from current repository
+ */
+ public List<Depot> findForkDescendants() {
+ List<Depot> descendants = new ArrayList<>();
+ for (Depot fork: getForks()) {
+ if (fork.getDefaultBranch() != null)
+ descendants.add(fork);
+ descendants.addAll(fork.findForkDescendants());
+ }
+
+ return descendants;
+ }
+
+ /**
+ * Find all comparable repositories of current repository. Comparable repositories can
+ * be connected via forks, and can be compared/pulled.
+ *
+ * @return
+ * comparable repositories of current repository, with current repository also
+ * included in the collection
+ */
+ public List<Depot> findAffinals() {
+ List<Depot> affinals = new ArrayList<Depot>();
+ Depot forkRoot = findForkRoot();
+ if (forkRoot != null) {
+ affinals.add(forkRoot);
+ affinals.addAll(forkRoot.findForkDescendants());
+ } else {
+ affinals.add(this);
+ affinals.addAll(findForkDescendants());
+ }
+ affinals.sort((repo1, repo2) -> {
+ if (repo1.getAccount().equals(repo2.getAccount()))
+ return repo1.getName().compareTo(repo2.getName());
+ else
+ return repo1.getAccount().getName().compareTo(repo2.getAccount().getName());
+ });
+ return affinals;
+ }
+
+ public Repository getRepository() {
+ if (repository == null) {
+ repository = GitPlex.getInstance(DepotManager.class).getRepository(this);
+ }
+ return repository;
+ }
+
+ public RevCommit getMergeBase(String commit1, String commit2) {
+ return GitUtils.getMergeBase(getRepository(), getObjectId(commit1), getObjectId(commit2));
+ }
+
+ public boolean isMergedInto(String base, String tip) {
+ return GitUtils.isMergedInto(getRepository(), getObjectId(base), getObjectId(tip));
+ }
+
+ public String getUrl() {
+ return GitPlex.getInstance(ConfigManager.class).getSystemSetting().getServerUrl() + "/" + getFQN();
+ }
+
+ @Nullable
+ public String getDefaultBranch() {
+ if (defaultBranch == null) {
+ try {
+ Ref headRef = getRepository().findRef("HEAD");
+ if (headRef.isSymbolic()
+ && headRef.getTarget().getName().startsWith(Constants.R_HEADS)
+ && headRef.getObjectId() != null) {
+ defaultBranch = Optional.of(Repository.shortenRefName(headRef.getTarget().getName()));
+ } else {
+ defaultBranch = Optional.absent();
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return defaultBranch.orNull();
+ }
+
+ private Blob readBlob(ObjectLoader objectLoader, BlobIdent ident) {
+ long blobSize = objectLoader.getSize();
+ if (blobSize > MAX_READ_BLOB_SIZE) {
+ try (InputStream is = objectLoader.openStream()) {
+ byte[] bytes = new byte[MAX_READ_BLOB_SIZE];
+ is.read(bytes);
+ return new Blob(ident, bytes, blobSize);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return new Blob(ident, objectLoader.getCachedBytes());
+ }
+ }
+
+ private Map<BlobIdent, Blob> getBlobCache() {
+ if (blobCache == null) {
+ synchronized(this) {
+ if (blobCache == null)
+ blobCache = new ConcurrentHashMap<>();
+ }
+ }
+ return blobCache;
+ }
+
+ /**
+ * Read blob content and cache result in repository in case the same blob
+ * content is requested again.
+ *
+ * We made this method thread-safe as we are using ForkJoinPool to calculate
+ * diffs of multiple blob changes concurrently, and this method will be
+ * accessed concurrently in that special case.
+ *
+ * @param blobIdent
+ * ident of the blob
+ * @return
+ * blob of specified blob ident
+ * @throws
+ * ObjectNotExistException if blob of specified ident can not be found in repository
+ *
+ */
+ public Blob getBlob(BlobIdent blobIdent) {
+ Preconditions.checkArgument(blobIdent.revision!=null && blobIdent.path!=null && blobIdent.mode!=null,
+ "Revision, path and mode of ident param should be specified");
+
+ Blob blob = getBlobCache().get(blobIdent);
+ if (blob == null) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId revId = getObjectId(blobIdent.revision);
+ RevTree revTree = revWalk.parseCommit(revId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getRepository(), blobIdent.path, revTree);
+ if (treeWalk != null) {
+ if (blobIdent.isGitLink()) {
+ String url = getSubmodules(blobIdent.revision).get(blobIdent.path);
+ if (url == null)
+ throw new ObjectNotExistException("Unable to find submodule '" + blobIdent.path + "' in .gitmodules");
+ String hash = treeWalk.getObjectId(0).name();
+ blob = new Blob(blobIdent, new Submodule(url, hash).toString().getBytes());
+ } else if (blobIdent.isTree()) {
+ throw new NotFileException("Path '" + blobIdent.path + "' is a tree");
+ } else {
+ ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
+ blob = readBlob(objectLoader, blobIdent);
+ }
+ getBlobCache().put(blobIdent, blob);
+ } else {
+ throw new ObjectNotExistException("Unable to find blob path '" + blobIdent.path + "' in revision '" + blobIdent.revision + "'");
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return blob;
+ }
+
+ public InputStream getInputStream(BlobIdent ident) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ ObjectId commitId = getObjectId(ident.revision);
+ RevTree revTree = revWalk.parseCommit(commitId).getTree();
+ TreeWalk treeWalk = TreeWalk.forPath(getRepository(), ident.path, revTree);
+ if (treeWalk != null) {
+ ObjectLoader objectLoader = treeWalk.getObjectReader().open(treeWalk.getObjectId(0));
+ return objectLoader.openStream();
+ } else {
+ throw new ObjectNotExistException("Unable to find blob path '" + ident.path + "' in revision '" + ident.revision + "'");
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * Get cached object id of specified revision.
+ *
+ * @param revision
+ * revision to resolve object id for
+ * @param mustExist
+ * true to have the method throwing exception instead
+ * of returning null if the revision does not exist
+ * @return
+ * object id of specified revision, or <tt>null</tt> if revision
+ * does not exist and mustExist is specified as false
+ */
+ @Nullable
+ public ObjectId getObjectId(String revision, boolean mustExist) {
+ if (objectIdCache == null)
+ objectIdCache = new HashMap<>();
+
+ Optional<ObjectId> optional = objectIdCache.get(revision);
+ if (optional == null) {
+ optional = Optional.fromNullable(GitUtils.resolve(getRepository(), revision));
+ objectIdCache.put(revision, optional);
+ }
+ if (mustExist && !optional.isPresent())
+ throw new ObjectNotExistException("Unable to find object '" + revision + "'");
+ return optional.orNull();
+ }
+
+ public ObjectId getObjectId(String revision) {
+ return getObjectId(revision, true);
+ }
+
+ public void cacheObjectId(String revision, @Nullable ObjectId objectId) {
+ if (objectIdCache == null)
+ objectIdCache = new HashMap<>();
+
+ objectIdCache.put(revision, Optional.fromNullable(objectId));
+ }
+
+ public List<DiffEntry> getDiffs(String oldRev, String newRev) {
+ List<DiffEntry> diffs = new ArrayList<>();
+ try (DiffFormatter diffFormatter = new DiffFormatter(NullOutputStream.INSTANCE);) {
+ diffFormatter.setRepository(getRepository());
+ diffFormatter.setDetectRenames(true);
+ diffFormatter.setDiffAlgorithm(MyersDiff.INSTANCE);
+ diffFormatter.setDiffComparator(RawTextComparator.DEFAULT);
+ AnyObjectId oldRevId = getObjectId(oldRev);
+ AnyObjectId newRevId = getObjectId(newRev);
+ for (DiffEntry entry: diffFormatter.scan(oldRevId, newRevId)) {
+ if (!Objects.equal(entry.getOldPath(), entry.getNewPath())
+ || !Objects.equal(entry.getOldMode(), entry.getNewMode())
+ || entry.getOldId()==null || !entry.getOldId().isComplete()
+ || entry.getNewId()== null || !entry.getNewId().isComplete()
+ || !entry.getOldId().equals(entry.getNewId())) {
+ diffs.add(entry);
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return diffs;
+ }
+
+ public LastCommitsOfChildren getLastCommitsOfChildren(String revision, @Nullable String path) {
+ if (path == null)
+ path = "";
+
+ final File cacheDir = new File(
+ GitPlex.getInstance(StorageManager.class).getInfoDir(this),
+ "last_commits/" + path + "/gitplex_last_commits");
+
+ final ReadWriteLock lock;
+ try {
+ lock = LockUtils.getReadWriteLock(cacheDir.getCanonicalPath());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ final Set<ObjectId> commitIds = new HashSet<>();
+
+ lock.readLock().lock();
+ try {
+ if (cacheDir.exists()) {
+ for (String each: cacheDir.list())
+ commitIds.add(ObjectId.fromString(each));
+ }
+ } finally {
+ lock.readLock().unlock();
+ }
+
+ org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache cache;
+ if (!commitIds.isEmpty()) {
+ cache = new org.eclipse.jgit.revwalk.LastCommitsOfChildren.Cache() {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public Map<String, Value> getLastCommitsOfChildren(ObjectId commitId) {
+ if (commitIds.contains(commitId)) {
+ lock.readLock().lock();
+ try {
+ byte[] bytes = FileUtils.readFileToByteArray(new File(cacheDir, commitId.name()));
+ return (Map<String, Value>) SerializationUtils.deserialize(bytes);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ lock.readLock().unlock();
+ }
+ } else {
+ return null;
+ }
+ }
+
+ };
+ } else {
+ cache = null;
+ }
+
+ final AnyObjectId commitId = getObjectId(revision);
+
+ long time = System.currentTimeMillis();
+ LastCommitsOfChildren lastCommits = new LastCommitsOfChildren(getRepository(), commitId, path, cache);
+ long elapsed = System.currentTimeMillis()-time;
+ if (elapsed > LAST_COMMITS_CACHE_THRESHOLD) {
+ lock.writeLock().lock();
+ try {
+ if (!cacheDir.exists())
+ FileUtils.createDir(cacheDir);
+ FileUtils.writeByteArrayToFile(
+ new File(cacheDir, commitId.name()),
+ SerializationUtils.serialize(lastCommits));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ } finally {
+ lock.writeLock().unlock();
+ }
+ }
+ return lastCommits;
+ }
+
+ @Nullable
+ public Ref getRef(String revision) {
+ if (refCache == null)
+ refCache = new HashMap<>();
+ Optional<Ref> optional = refCache.get(revision);
+ if (optional == null) {
+ try {
+ optional = Optional.fromNullable(getRepository().findRef(revision));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ refCache.put(revision, optional);
+ }
+ return optional.orNull();
+ }
+
+ @Nullable
+ public RevCommit getRevCommit(String revision, boolean mustExist) {
+ RevCommit commit;
+ ObjectId revId = getObjectId(revision, mustExist);
+ if (revId != null) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ commit = GitUtils.parseCommit(revWalk, revId);
+ }
+ } else {
+ commit = null;
+ }
+ if (mustExist && commit == null)
+ throw new ObjectNotExistException("Unable to find commit: " + revision);
+ else
+ return commit;
+ }
+
+ public RevCommit getRevCommit(String revision) {
+ return getRevCommit(revision, true);
+ }
+
+ @Nullable
+ public RevCommit getRevCommit(ObjectId revId, boolean mustExist) {
+ try (RevWalk revWalk = new RevWalk(getRepository())) {
+ RevCommit commit = GitUtils.parseCommit(revWalk, revId);
+ if (mustExist && commit == null)
+ throw new ObjectNotExistException("Unable to find commit: " + revId.name());
+ else
+ return commit;
+ }
+ }
+
+ public RevCommit getRevCommit(ObjectId revId) {
+ return getRevCommit(revId, true);
+ }
+
+ public Map<String, Ref> getRefs(String prefix) {
+ try {
+ return getRepository().getRefDatabase().getRefs(prefix);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public Map<String, String> getSubmodules(String revision) {
+ Map<String, String> submodules = new HashMap<>();
+
+ Blob blob = getBlob(new BlobIdent(revision, ".gitmodules", FileMode.REGULAR_FILE.getBits()));
+ String content = new String(blob.getBytes());
+
+ String path = null;
+ String url = null;
+
+ for (String line: StringUtils.splitAndTrim(content, "\r\n")) {
+ if (line.startsWith("[") && line.endsWith("]")) {
+ if (path != null && url != null)
+ submodules.put(path, url);
+
+ path = url = null;
+ } else if (line.startsWith("path")) {
+ path = StringUtils.substringAfter(line, "=").trim();
+ } else if (line.startsWith("url")) {
+ url = StringUtils.substringAfter(line, "=").trim();
+ }
+ }
+ if (path != null && url != null)
+ submodules.put(path, url);
+
+ return submodules;
+ }
+
+ public void deleteBranch(String branch) {
+ String refName = GitUtils.branch2ref(branch);
+ ObjectId commitId = getRevCommit(refName).getId();
+ try {
+ git().branchDelete().setForce(true).setBranchNames(branch).call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(getId());
+ GitPlex.getInstance(ListenerRegistry.class).post(
+ new RefUpdated(depot, refName, commitId, ObjectId.zeroId()));
+ }
+
+ });
+ }
+
+ public void createBranch(String branchName, String branchRevision) {
+ try {
+ CreateBranchCommand command = git().branchCreate();
+ command.setName(branchName);
+ command.setStartPoint(getRevCommit(branchRevision));
+ command.call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void tag(String tagName, String tagRevision, PersonIdent taggerIdent, @Nullable String tagMessage) {
+ try {
+ TagCommand tag = git().tag();
+ tag.setName(tagName);
+ if (tagMessage != null)
+ tag.setMessage(tagMessage);
+ tag.setTagger(taggerIdent);
+ tag.setObjectId(getRevCommit(tagRevision));
+ tag.call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void deleteTag(String tag) {
+ String refName = GitUtils.tag2ref(tag);
+ ObjectId commitId = getRevCommit(refName).getId();
+ try {
+ git().tagDelete().setTags(tag).call();
+ } catch (GitAPIException e) {
+ throw new RuntimeException(e);
+ }
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(getId());
+ GitPlex.getInstance(ListenerRegistry.class).post(
+ new RefUpdated(depot, refName, commitId, ObjectId.zeroId()));
+ }
+
+ });
+ }
+
+ public Collection<TeamAuthorization> getAuthorizedTeams() {
+ return authorizedTeams;
+ }
+
+ public void setAuthorizedTeams(Collection<TeamAuthorization> authorizedTeams) {
+ this.authorizedTeams = authorizedTeams;
+ }
+
+ public Collection<UserAuthorization> getAuthorizedUsers() {
+ return authorizedUsers;
+ }
+
+ public void setAuthorizedUsers(Collection<UserAuthorization> authorizedUsers) {
+ this.authorizedUsers = authorizedUsers;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ public boolean matches(@Nullable String searchTerm) {
+ if (searchTerm == null)
+ searchTerm = "";
+ else
+ searchTerm = searchTerm.toLowerCase().trim();
+
+ return getName().toLowerCase().contains(searchTerm);
+ }
+
+ public boolean matchesFQN(@Nullable String searchTerm) {
+ if (searchTerm == null)
+ searchTerm = "";
+ else
+ searchTerm = searchTerm.toLowerCase().trim();
+
+ return getFQN().toLowerCase().contains(searchTerm);
+ }
+
+ public RefUpdate updateRef(String refName) {
+ try {
+ return getRepository().updateRef(refName);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public int compareTo(AbstractEntity entity) {
+ Depot depot = (Depot) entity;
+ if (getAccount().equals(depot.getAccount())) {
+ return getName().compareTo(depot.getName());
+ } else {
+ return getAccount().compareTo(depot.getAccount());
+ }
+ }
+
+ public static int compareLastVisit(Depot depot1, Depot depot2) {
+ Account user = SecurityUtils.getAccount();
+ if (user != null) {
+ Date date1 = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, depot1);
+ Date date2 = GitPlex.getInstance(VisitInfoManager.class).getVisitDate(user, depot2);
+ if (date1 != null) {
+ if (date2 != null)
+ return date2.compareTo(date1);
+ else
+ return -1;
+ } else {
+ if (date2 != null)
+ return 1;
+ else
+ return depot1.compareTo(depot2);
+ }
+ } else {
+ return depot1.compareTo(depot2);
+ }
+ }
+
+}
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.java
index 67accffdcd..e2da3fe620 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
@@ -50,8 +50,13 @@ 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.event.pullrequest.PullRequestChangeEvent;
+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.PullRequestCodeCommented;
import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
import com.pmease.gitplex.core.manager.CodeCommentRelationManager;
@@ -224,7 +229,7 @@ public class PullRequest extends AbstractEntity {
@OneToMany(mappedBy="request", cascade=CascadeType.REMOVE)
private Collection<PullRequestWatch> watches = new ArrayList<>();
- private transient CheckResult checkResult;
+ private transient GateCheckResult gateCheckResult;
private transient List<PullRequestUpdate> sortedUpdates;
@@ -468,9 +473,9 @@ public class PullRequest extends AbstractEntity {
return Status.INTEGRATED;
else
return Status.DISCARDED;
- } else if (getCheckResult() instanceof Pending || getCheckResult() instanceof Blocking)
+ } else if (checkGates(false) instanceof Pending || checkGates(false) instanceof Blocking)
return Status.PENDING_APPROVAL;
- else if (getCheckResult() instanceof Failed)
+ else if (checkGates(false) instanceof Failed)
return Status.PENDING_UPDATE;
else
return Status.PENDING_INTEGRATE;
@@ -501,15 +506,15 @@ public class PullRequest extends AbstractEntity {
}
/**
- * Get gate keeper check result.
+ * Check against gate keeper.
*
* @return
- * check result of this pull request has not been refreshed yet
+ * gate check result
*/
- public CheckResult getCheckResult() {
- if (checkResult == null)
- checkResult = getTargetDepot().getGateKeeper().checkRequest(this);
- return checkResult;
+ public GateCheckResult checkGates(boolean recheck) {
+ if (gateCheckResult == null || recheck)
+ gateCheckResult = getTargetDepot().getGateKeeper().checkRequest(this);
+ return gateCheckResult;
}
/**
@@ -644,7 +649,7 @@ public class PullRequest extends AbstractEntity {
Set<Account> lastChoices = new HashSet<>();
for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
- if (!invitation.isExcluded())
+ if (invitation.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED)
firstChoices.add(invitation.getUser());
else
lastChoices.add(invitation.getUser());
@@ -684,12 +689,14 @@ public class PullRequest extends AbstractEntity {
for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
if (invitation.getUser().equals(user)) {
invitation.setDate(new Date());
- invitation.setExcluded(false);
+ invitation.setStatus(PullRequestReviewInvitation.Status.ADDED_BY_RULE);
found = true;
}
}
if (!found) {
PullRequestReviewInvitation invitation = new PullRequestReviewInvitation();
+ invitation.setDate(new Date());
+ invitation.setStatus(PullRequestReviewInvitation.Status.ADDED_BY_RULE);
invitation.setRequest(this);
invitation.setUser(user);
getReviewInvitations().add(invitation);
@@ -828,7 +835,7 @@ public class PullRequest extends AbstractEntity {
List<Account> reviewers = new ArrayList<>();
Set<Account> alreadyInvited = new HashSet<>();
for (PullRequestReviewInvitation invitation: getReviewInvitations()) {
- if (!invitation.isExcluded())
+ if (invitation.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED)
alreadyInvited.add(invitation.getUser());
}
ObjectPermission readPerm = ObjectPermission.ofDepotRead(getTargetDepot());
@@ -970,6 +977,21 @@ public class PullRequest extends AbstractEntity {
getTarget().getObjectName());
}
+ public void setLastEvent(PullRequestChangeEvent event) {
+ LastEvent lastEvent = new LastEvent();
+ lastEvent.setDate(event.getDate());
+ lastEvent.setType(event.getClass());
+ lastEvent.setUser(event.getUser());
+ setLastEvent(lastEvent);
+
+ if (event instanceof PullRequestCodeCommented
+ || event instanceof PullRequestCodeCommentReplied
+ || event instanceof PullRequestCodeCommentResolved
+ || event instanceof PullRequestCodeCommentUnresolved) {
+ setLastCodeCommentEventDate(event.getDate());
+ }
+ }
+
public static class ComparingInfo implements Serializable {
private static final long serialVersionUID = 1L;
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
index 7876117482..9aa7b1806b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestReviewInvitation.java
@@ -1,68 +1,70 @@
-package com.pmease.gitplex.core.entity;
-
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.Table;
-import javax.persistence.UniqueConstraint;
-
-import com.pmease.commons.hibernate.AbstractEntity;
-
-@Entity
-@Table(uniqueConstraints={
- @UniqueConstraint(columnNames={"g_user_id", "g_request_id"})
-})
-public class PullRequestReviewInvitation extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private Account user;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- private boolean excluded;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- public Account getUser() {
- return user;
- }
-
- public void setUser(Account user) {
- this.user = user;
- }
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public boolean isExcluded() {
- return excluded;
- }
-
- public void setExcluded(boolean excluded) {
- this.excluded = excluded;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.Table;
+import javax.persistence.UniqueConstraint;
+
+import com.pmease.commons.hibernate.AbstractEntity;
+
+@Entity
+@Table(uniqueConstraints={
+ @UniqueConstraint(columnNames={"g_user_id", "g_request_id"})
+})
+public class PullRequestReviewInvitation extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ public enum Status {ADDED_BY_RULE, ADDED_MANUALLY, EXCLUDED}
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private Account user;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ private Status status;
+
+ @Column(nullable=false)
+ private Date date;
+
+ public Account getUser() {
+ return user;
+ }
+
+ public void setUser(Account user) {
+ this.user = user;
+ }
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
index 9caedaafe6..468d609d4a 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/PullRequestUpdate.java
@@ -1,288 +1,288 @@
-package com.pmease.gitplex.core.entity;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.persistence.CascadeType;
-import javax.persistence.Column;
-import javax.persistence.Entity;
-import javax.persistence.FetchType;
-import javax.persistence.Index;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-import javax.persistence.OneToMany;
-import javax.persistence.Table;
-
-import org.eclipse.jgit.errors.IncorrectObjectTypeException;
-import org.eclipse.jgit.errors.MissingObjectException;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.revwalk.filter.RevFilter;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.AbstractEntity;
-import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
-
-@Entity
-@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
-public class PullRequestUpdate extends AbstractEntity {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(nullable=false)
- private PullRequest request;
-
- @Column(nullable=false)
- private String headCommitHash;
-
- @Column(nullable=false)
- private String mergeCommitHash;
-
- @Column(nullable=false)
- private Date date = new Date();
-
- @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
- private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
-
- @Column(nullable=false)
- private String uuid = UUID.randomUUID().toString();
-
- private transient List<RevCommit> commits;
-
- private transient Collection<String> changedFiles;
-
- public PullRequest getRequest() {
- return request;
- }
-
- public void setRequest(PullRequest request) {
- this.request = request;
- }
-
- public String getHeadCommitHash() {
- return headCommitHash;
- }
-
- public void setHeadCommitHash(String headCommitHash) {
- this.headCommitHash = headCommitHash;
- }
-
- public String getMergeCommitHash() {
- return mergeCommitHash;
- }
-
- public void setMergeCommitHash(String mergeCommitHash) {
- this.mergeCommitHash = mergeCommitHash;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Collection<PullRequestReview> getReviews() {
- return getRequest().getReviews(this);
- }
-
- @JsonProperty
- public String getHeadRef() {
- Preconditions.checkNotNull(getId());
- return Depot.REFS_GITPLEX + "updates/" + getId();
- }
-
- /**
- * List reviews against this update and all subsequent updates.
- * <p>
- * @return
- * list of found reviews, ordered by associated updates reversely
- */
- public List<PullRequestReview> listReviewsOnwards() {
- List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
- Set<Account> excludedReviewers = new HashSet<>();
- for (PullRequestReviewInvitation invitation: getRequest().getReviewInvitations()) {
- if (invitation.isExcluded())
- excludedReviewers.add(invitation.getUser());
- }
- for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
- for (PullRequestReview review: update.getReviews()) {
- if (!excludedReviewers.contains(review.getUser()))
- reviews.add(review);
- }
- if (update.equals(this))
- break;
- }
-
- return reviews;
- }
-
- public void deleteRefs() {
- GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
- }
-
- /**
- * Get changed files of this update since previous update. This calculation
- * excludes changes introduced by commits from target branch (this will
- * happen if some commits were merged from target branch to source branch)
- */
- public Collection<String> getChangedFiles() {
- if (changedFiles == null) {
- changedFiles = new HashSet<>();
- Repository repository = getRequest().getTargetDepot().getRepository();
- try ( RevWalk revWalk = new RevWalk(repository);
- TreeWalk treeWalk = new TreeWalk(repository)) {
- RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
- RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(mergeCommit);
- revWalk.markStart(baseCommit);
- revWalk.setRevFilter(RevFilter.MERGE_BASE);
- RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
- treeWalk.setRecursive(true);
- if (mergeBase.equals(baseCommit)) {
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else if (mergeBase.equals(mergeCommit)) {
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(headCommit.getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- while (treeWalk.next())
- changedFiles.add(treeWalk.getPathString());
- } else {
- treeWalk.addTree(headCommit.getTree());
- treeWalk.addTree(baseCommit.getTree());
- treeWalk.addTree(mergeCommit.getTree());
- treeWalk.setFilter(new TreeFilter() {
-
- @Override
- public boolean include(TreeWalk walker)
- throws MissingObjectException, IncorrectObjectTypeException, IOException {
- int m0 = walker.getRawMode(0);
-
- // only include the path if the file is modified in head commit
- // compared to base commit and that modification is not introduced
- // by commit from target branch
- return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
- && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
- }
-
- @Override
- public boolean shouldBeRecursive() {
- return false;
- }
-
- @Override
- public TreeFilter clone() {
- return this;
- }
-
- });
- while (treeWalk.next()) {
- changedFiles.add(treeWalk.getPathString());
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- return changedFiles;
- }
-
- public String getBaseCommitHash() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommitHash();
- else
- return request.getBaseCommitHash();
- }
-
- /**
- * Base commit represents head commit of last update, or base commit of the request
- * for the first update. Base commit is used to calculate commits belonging to
- * current update.
- *
- * @return
- * base commit of this update
- */
- public RevCommit getBaseCommit() {
- PullRequest request = getRequest();
-
- int index = request.getSortedUpdates().indexOf(this);
- if (index > 0)
- return request.getSortedUpdates().get(index-1).getHeadCommit();
- else
- return request.getBaseCommit();
- }
-
- public String getUUID() {
- return uuid;
- }
-
- public void setUUID(String uuid) {
- this.uuid = uuid;
- }
-
- /**
- * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
- * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
- * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findAllCodeComments(PullRequest)} for
- * details
- *
- * @return
- * commits belonging to this update ordered by commit id
- */
- public List<RevCommit> getCommits() {
- if (commits == null) {
- commits = new ArrayList<>();
-
- try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
- RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
- revWalk.markStart(headCommit);
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
-
- /*
- * Instead of excluding commits reachable from target branch, we exclude commits reachable
- * from the merge commit to achieve two purposes:
- * 1. commits merged back into target branch after this update can still be included in this
- * update
- * 2. commits of this update will remain unchanged even if tip of the target branch changes
- */
- revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
-
- revWalk.forEach(c->commits.add(c));
- if (commits.isEmpty())
- commits.add(headCommit);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- Collections.reverse(commits);
- }
- return commits;
- }
-
- public RevCommit getHeadCommit() {
- return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
- }
-
-}
+package com.pmease.gitplex.core.entity;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.UUID;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.FetchType;
+import javax.persistence.Index;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+import javax.persistence.OneToMany;
+import javax.persistence.Table;
+
+import org.eclipse.jgit.errors.IncorrectObjectTypeException;
+import org.eclipse.jgit.errors.MissingObjectException;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.revwalk.filter.RevFilter;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.AbstractEntity;
+import com.pmease.gitplex.core.manager.impl.DefaultCodeCommentRelationManager;
+
+@Entity
+@Table(indexes={@Index(columnList="uuid"), @Index(columnList="date")})
+public class PullRequestUpdate extends AbstractEntity {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(nullable=false)
+ private PullRequest request;
+
+ @Column(nullable=false)
+ private String headCommitHash;
+
+ @Column(nullable=false)
+ private String mergeCommitHash;
+
+ @Column(nullable=false)
+ private Date date = new Date();
+
+ @OneToMany(mappedBy="update", cascade=CascadeType.REMOVE)
+ private Collection<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+
+ @Column(nullable=false)
+ private String uuid = UUID.randomUUID().toString();
+
+ private transient List<RevCommit> commits;
+
+ private transient Collection<String> changedFiles;
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public void setRequest(PullRequest request) {
+ this.request = request;
+ }
+
+ public String getHeadCommitHash() {
+ return headCommitHash;
+ }
+
+ public void setHeadCommitHash(String headCommitHash) {
+ this.headCommitHash = headCommitHash;
+ }
+
+ public String getMergeCommitHash() {
+ return mergeCommitHash;
+ }
+
+ public void setMergeCommitHash(String mergeCommitHash) {
+ this.mergeCommitHash = mergeCommitHash;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Collection<PullRequestReview> getReviews() {
+ return getRequest().getReviews(this);
+ }
+
+ @JsonProperty
+ public String getHeadRef() {
+ Preconditions.checkNotNull(getId());
+ return Depot.REFS_GITPLEX + "updates/" + getId();
+ }
+
+ /**
+ * List reviews against this update and all subsequent updates.
+ * <p>
+ * @return
+ * list of found reviews, ordered by associated updates reversely
+ */
+ public List<PullRequestReview> listReviewsOnwards() {
+ List<PullRequestReview> reviews = new ArrayList<PullRequestReview>();
+ Set<Account> excludedReviewers = new HashSet<>();
+ for (PullRequestReviewInvitation invitation: getRequest().getReviewInvitations()) {
+ if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED)
+ excludedReviewers.add(invitation.getUser());
+ }
+ for (PullRequestUpdate update: getRequest().getEffectiveUpdates()) {
+ for (PullRequestReview review: update.getReviews()) {
+ if (!excludedReviewers.contains(review.getUser()))
+ reviews.add(review);
+ }
+ if (update.equals(this))
+ break;
+ }
+
+ return reviews;
+ }
+
+ public void deleteRefs() {
+ GitUtils.deleteRef(getRequest().getTargetDepot().updateRef(getHeadRef()));
+ }
+
+ /**
+ * Get changed files of this update since previous update. This calculation
+ * excludes changes introduced by commits from target branch (this will
+ * happen if some commits were merged from target branch to source branch)
+ */
+ public Collection<String> getChangedFiles() {
+ if (changedFiles == null) {
+ changedFiles = new HashSet<>();
+ Repository repository = getRequest().getTargetDepot().getRepository();
+ try ( RevWalk revWalk = new RevWalk(repository);
+ TreeWalk treeWalk = new TreeWalk(repository)) {
+ RevCommit mergeCommit = revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash()));
+ RevCommit baseCommit = revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash()));
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(mergeCommit);
+ revWalk.markStart(baseCommit);
+ revWalk.setRevFilter(RevFilter.MERGE_BASE);
+ RevCommit mergeBase = Preconditions.checkNotNull(revWalk.next());
+ treeWalk.setRecursive(true);
+ if (mergeBase.equals(baseCommit)) {
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else if (mergeBase.equals(mergeCommit)) {
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ while (treeWalk.next())
+ changedFiles.add(treeWalk.getPathString());
+ } else {
+ treeWalk.addTree(headCommit.getTree());
+ treeWalk.addTree(baseCommit.getTree());
+ treeWalk.addTree(mergeCommit.getTree());
+ treeWalk.setFilter(new TreeFilter() {
+
+ @Override
+ public boolean include(TreeWalk walker)
+ throws MissingObjectException, IncorrectObjectTypeException, IOException {
+ int m0 = walker.getRawMode(0);
+
+ // only include the path if the file is modified in head commit
+ // compared to base commit and that modification is not introduced
+ // by commit from target branch
+ return (walker.getRawMode(1) != m0 || !walker.idEqual(1, 0))
+ && (walker.getRawMode(2) != m0 || !walker.idEqual(2, 0));
+ }
+
+ @Override
+ public boolean shouldBeRecursive() {
+ return false;
+ }
+
+ @Override
+ public TreeFilter clone() {
+ return this;
+ }
+
+ });
+ while (treeWalk.next()) {
+ changedFiles.add(treeWalk.getPathString());
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ return changedFiles;
+ }
+
+ public String getBaseCommitHash() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommitHash();
+ else
+ return request.getBaseCommitHash();
+ }
+
+ /**
+ * Base commit represents head commit of last update, or base commit of the request
+ * for the first update. Base commit is used to calculate commits belonging to
+ * current update.
+ *
+ * @return
+ * base commit of this update
+ */
+ public RevCommit getBaseCommit() {
+ PullRequest request = getRequest();
+
+ int index = request.getSortedUpdates().indexOf(this);
+ if (index > 0)
+ return request.getSortedUpdates().get(index-1).getHeadCommit();
+ else
+ return request.getBaseCommit();
+ }
+
+ public String getUUID() {
+ return uuid;
+ }
+
+ public void setUUID(String uuid) {
+ this.uuid = uuid;
+ }
+
+ /**
+ * Get commits belonging to this update, reversely ordered by commit traversing. The list of commit will remain
+ * unchanged even if tip of target branch changes. This assumption is key to our caching of code comment to
+ * to pull request relations. Check {@link DefaultCodeCommentRelationManager#findAllCodeComments(PullRequest)} for
+ * details
+ *
+ * @return
+ * commits belonging to this update ordered by commit id
+ */
+ public List<RevCommit> getCommits() {
+ if (commits == null) {
+ commits = new ArrayList<>();
+
+ try (RevWalk revWalk = new RevWalk(getRequest().getTargetDepot().getRepository())) {
+ RevCommit headCommit = revWalk.parseCommit(ObjectId.fromString(getHeadCommitHash()));
+ revWalk.markStart(headCommit);
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getBaseCommitHash())));
+
+ /*
+ * Instead of excluding commits reachable from target branch, we exclude commits reachable
+ * from the merge commit to achieve two purposes:
+ * 1. commits merged back into target branch after this update can still be included in this
+ * update
+ * 2. commits of this update will remain unchanged even if tip of the target branch changes
+ */
+ revWalk.markUninteresting(revWalk.parseCommit(ObjectId.fromString(getMergeCommitHash())));
+
+ revWalk.forEach(c->commits.add(c));
+ if (commits.isEmpty())
+ commits.add(headCommit);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ Collections.reverse(commits);
+ }
+ return commits;
+ }
+
+ public RevCommit getHeadCommit() {
+ return request.getTargetDepot().getRevCommit(ObjectId.fromString(getHeadCommitHash()));
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/AccountMentionGenerator.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/AccountMentionGenerator.java
new file mode 100644
index 0000000000..d8b279b320
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/AccountMentionGenerator.java
@@ -0,0 +1,253 @@
+package com.pmease.gitplex.core.entity.persistlistener;
+
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.HashSet;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.wicket.util.lang.Objects;
+import org.hibernate.CallbackException;
+import org.hibernate.type.Type;
+
+import com.pmease.commons.hibernate.PersistListener;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.markdown.MarkdownManager;
+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.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestComment;
+import com.pmease.gitplex.core.entity.PullRequestStatusChange;
+import com.pmease.gitplex.core.event.mention.AccountMentionedInCodeComment;
+import com.pmease.gitplex.core.event.mention.AccountMentionedInPullRequest;
+import com.pmease.gitplex.core.util.markdown.MentionParser;
+
+@Singleton
+public class AccountMentionGenerator implements PersistListener {
+
+ private final MarkdownManager markdownManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public AccountMentionGenerator(MarkdownManager markdownManager, ListenerRegistry listenerRegistry) {
+ this.markdownManager = markdownManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Override
+ public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ return false;
+ }
+
+ private Collection<Account> parseNewMentions(String content, String prevContent) {
+ Collection<Account> newMentions;
+ if (!Objects.equal(content, prevContent)) {
+ MentionParser mentionParser = new MentionParser();
+ if (content != null) {
+ newMentions = mentionParser.parseMentions(markdownManager.parse(content));
+ } else {
+ newMentions = new HashSet<>();
+ }
+ if (prevContent != null)
+ newMentions.removeAll(mentionParser.parseMentions(markdownManager.parse(prevContent)));
+ } else {
+ newMentions = new HashSet<>();
+ }
+ return newMentions;
+ }
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
+ String[] propertyNames, Type[] types) throws CallbackException {
+ if (entity instanceof PullRequest) {
+ PullRequest request = (PullRequest) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("description")) {
+ String description = (String) currentState[i];
+ String prevDescription = (String) previousState[i];
+ for (Account account: parseNewMentions(description, prevDescription)) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ request, account, description));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestComment) {
+ PullRequestComment comment = (PullRequestComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) currentState[i];
+ String prevContent = (String) previousState[i];
+ for (Account account: parseNewMentions(content, prevContent)) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ comment.getRequest(), account, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestStatusChange) {
+ PullRequestStatusChange statusChange = (PullRequestStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) currentState[i];
+ String prevNote = (String) previousState[i];
+ for (Account account: parseNewMentions(note, prevNote)) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ statusChange.getRequest(), account, note));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeComment) {
+ CodeComment comment = (CodeComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) currentState[i];
+ String prevContent = (String) previousState[i];
+ for (Account account: parseNewMentions(content, prevContent)) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ comment, account, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeCommentReply) {
+ CodeCommentReply reply = (CodeCommentReply) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) currentState[i];
+ String prevContent = (String) previousState[i];
+ for (Account account: parseNewMentions(content, prevContent)) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ reply.getComment(), account, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeCommentStatusChange) {
+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) currentState[i];
+ String prevNote = (String) previousState[i];
+ for (Account account: parseNewMentions(note, prevNote)) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ statusChange.getComment(), account, note));
+ }
+ break;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ @Override
+ public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ if (entity instanceof PullRequest) {
+ PullRequest request = (PullRequest) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("description")) {
+ String description = (String) state[i];
+ if (description != null) {
+ String html = markdownManager.parse(description);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ request, user, description));
+ }
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestComment) {
+ PullRequestComment comment = (PullRequestComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) state[i];
+ String html = markdownManager.parse(content);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ comment.getRequest(), user, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestStatusChange) {
+ PullRequestStatusChange statusChange = (PullRequestStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) state[i];
+ if (note != null) {
+ String html = markdownManager.parse(note);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInPullRequest(
+ statusChange.getRequest(), user, note));
+ }
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeComment) {
+ CodeComment comment = (CodeComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) state[i];
+ String html = markdownManager.parse(content);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ comment, user, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeCommentReply) {
+ CodeCommentReply reply = (CodeCommentReply) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) state[i];
+ String html = markdownManager.parse(content);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ reply.getComment(), user, content));
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof CodeCommentStatusChange) {
+ CodeCommentStatusChange statusChange = (CodeCommentStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) state[i];
+ if (note != null) {
+ String html = markdownManager.parse(note);
+ Collection<Account> mentions = new MentionParser().parseMentions(html);
+ for (Account user: mentions) {
+ listenerRegistry.post(new AccountMentionedInCodeComment(
+ statusChange.getComment(), user, note));
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/ListenerLocator.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PersistListenerLocator.java
similarity index 58%
rename from gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/ListenerLocator.java
rename to gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PersistListenerLocator.java
index d91c7c0e26..4a0dcd463f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/ListenerLocator.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PersistListenerLocator.java
@@ -1,5 +1,5 @@
package com.pmease.gitplex.core.entity.persistlistener;
-public class ListenerLocator {
+public class PersistListenerLocator {
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestPersistListener.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestPersistListener.java
deleted file mode 100644
index 35d025b4d6..0000000000
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestPersistListener.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package com.pmease.gitplex.core.entity.persistlistener;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.HashSet;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.wicket.util.lang.Objects;
-import org.hibernate.CallbackException;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.type.Type;
-
-import com.pmease.commons.hibernate.PersistListener;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReference;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentioned;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.util.markdown.MentionParser;
-import com.pmease.gitplex.core.util.markdown.PullRequestParser;
-
-@Singleton
-public class PullRequestPersistListener implements PersistListener {
-
- private final MarkdownManager markdownManager;
-
- private final ListenerRegistry listenerRegistry;
-
- private final Dao dao;
-
- private final AccountManager userManager;
-
- @Inject
- public PullRequestPersistListener(MarkdownManager markdownManager,
- ListenerRegistry listenerRegistry, Dao dao, AccountManager userManager) {
- this.markdownManager = markdownManager;
- this.listenerRegistry = listenerRegistry;
- this.dao = dao;
- this.userManager = userManager;
- }
-
- @Override
- public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- return false;
- }
-
- @Override
- public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
- String[] propertyNames, Type[] types) throws CallbackException {
- if (entity instanceof PullRequest) {
- PullRequest request = (PullRequest) entity;
- for (int i=0; i<propertyNames.length; i++) {
- if (propertyNames[i].equals("description")) {
- String description = (String) currentState[i];
- String prevDescription = (String) previousState[i];
- if (!Objects.equal(description, prevDescription)) {
- MentionParser mentionParser = new MentionParser();
- Collection<Account> mentions;
- String html;
- if (description != null) {
- html = markdownManager.parse(description);
- mentions = mentionParser.parseMentions(html);
- } else {
- mentions = new HashSet<>();
- html = null;
- }
- if (prevDescription != null)
- mentions.removeAll(mentionParser.parseMentions(markdownManager.parse(prevDescription)));
- for (Account user: mentions) {
- listenerRegistry.notify(new AccountMentioned((PullRequest) entity, user));
- }
-
- if (html != null) {
- for (PullRequest referenced: new PullRequestParser().parseRequests(html))
- saveReference(referenced, request);
- }
- }
- break;
- }
- }
- }
- return false;
- }
-
- private void saveReference(PullRequest referenced, PullRequest referencedBy) {
- if (!referenced.equals(referencedBy)) {
- EntityCriteria<PullRequestReference> criteria = EntityCriteria.of(PullRequestReference.class);
- criteria.add(Restrictions.eq("referenced", referenced));
- criteria.add(Restrictions.eq("referencedBy", referencedBy));
- if (dao.find(criteria) == null) {
- PullRequestReference reference = new PullRequestReference();
- reference.setReferencedBy(referencedBy);
- reference.setReferenced(referenced);
- reference.setUser(userManager.getCurrent());
- dao.persist(reference);
- }
- }
- }
-
- @Override
- public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- if (entity instanceof PullRequest) {
- PullRequest request = (PullRequest) entity;
- for (int i=0; i<propertyNames.length; i++) {
- if (propertyNames[i].equals("description")) {
- String description = (String) state[i];
- if (description != null) {
- String html = markdownManager.parse(description);
- Collection<Account> mentions = new MentionParser().parseMentions(html);
- for (Account user: mentions) {
- listenerRegistry.notify(new AccountMentioned((PullRequest) entity, user));
- }
-
- for (PullRequest referenced: new PullRequestParser().parseRequests(html))
- saveReference(referenced, request);
- }
- }
- }
- }
- return true;
- }
-
- @Override
- public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- }
-
-}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestCommentPersistListener.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestReferenceGenerator.java
similarity index 55%
rename from gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestCommentPersistListener.java
rename to gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestReferenceGenerator.java
index 58730f4a2e..421d7357b4 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestCommentPersistListener.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/persistlistener/PullRequestReferenceGenerator.java
@@ -1,130 +1,169 @@
-package com.pmease.gitplex.core.entity.persistlistener;
-
-import java.io.Serializable;
-import java.util.Collection;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.CallbackException;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.type.Type;
-
-import com.pmease.commons.hibernate.PersistListener;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.markdown.MarkdownManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-import com.pmease.gitplex.core.entity.PullRequestReference;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentionedInComment;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.util.markdown.MentionParser;
-import com.pmease.gitplex.core.util.markdown.PullRequestParser;
-
-@Singleton
-public class PullRequestCommentPersistListener implements PersistListener {
-
- private final MarkdownManager markdownManager;
-
- private final Dao dao;
-
- private final AccountManager userManager;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public PullRequestCommentPersistListener(MarkdownManager markdownManager, Dao dao,
- AccountManager userManager, ListenerRegistry listenerRegistry) {
- this.markdownManager = markdownManager;
- this.dao = dao;
- this.userManager = userManager;
- this.listenerRegistry = listenerRegistry;
- }
-
- @Override
- public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- return false;
- }
-
- @Override
- public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
- String[] propertyNames, Type[] types) throws CallbackException {
- if (entity instanceof PullRequestComment) {
- PullRequestComment comment = (PullRequestComment) entity;
- for (int i=0; i<propertyNames.length; i++) {
- if (propertyNames[i].equals("content")) {
- String content = (String) currentState[i];
- String prevContent = (String) previousState[i];
- if (!content.equals(prevContent)) {
- String html = markdownManager.parse(content);
- String prevHtml = markdownManager.parse(prevContent);
-
- MentionParser mentionParser = new MentionParser();
- Collection<Account> mentions = mentionParser.parseMentions(html);
-
- mentions.removeAll(mentionParser.parseMentions(prevHtml));
- for (Account user: mentions) {
- listenerRegistry.notify(new AccountMentionedInComment((PullRequestComment) entity, user));
- }
-
- Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
- for (PullRequest request: requests)
- saveReference(request, comment.getRequest());
- }
- break;
- }
- }
- }
- return false;
- }
-
- @Override
- public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- if (entity instanceof PullRequestComment) {
- PullRequestComment comment = (PullRequestComment) entity;
- for (int i=0; i<propertyNames.length; i++) {
- if (propertyNames[i].equals("content")) {
- String content = (String) state[i];
- String html = markdownManager.parse(content);
- Collection<Account> mentions = new MentionParser().parseMentions(html);
- for (Account user: mentions) {
- listenerRegistry.notify(new AccountMentionedInComment((PullRequestComment) entity, user));
- }
-
- Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
- for (PullRequest request: requests)
- saveReference(request, comment.getRequest());
-
- break;
- }
- }
- }
- return false;
- }
-
- private void saveReference(PullRequest referenced, PullRequest referencedBy) {
- if (!referenced.equals(referencedBy)) {
- EntityCriteria<PullRequestReference> criteria = EntityCriteria.of(PullRequestReference.class);
- criteria.add(Restrictions.eq("referenced", referenced));
- criteria.add(Restrictions.eq("referencedBy", referencedBy));
- if (dao.find(criteria) == null) {
- PullRequestReference reference = new PullRequestReference();
- reference.setReferencedBy(referencedBy);
- reference.setReferenced(referenced);
- reference.setUser(userManager.getCurrent());
- dao.persist(reference);
- }
- }
- }
-
- @Override
- public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
- throws CallbackException {
- }
-
-}
+package com.pmease.gitplex.core.entity.persistlistener;
+
+import java.io.Serializable;
+import java.util.Collection;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.wicket.util.lang.Objects;
+import org.hibernate.CallbackException;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.type.Type;
+
+import com.pmease.commons.hibernate.PersistListener;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.gitplex.core.entity.PullRequest;
+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.manager.AccountManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+import com.pmease.gitplex.core.util.markdown.PullRequestParser;
+
+@Singleton
+public class PullRequestReferenceGenerator implements PersistListener {
+
+ private final MarkdownManager markdownManager;
+
+ private final Dao dao;
+
+ private final AccountManager userManager;
+
+ @Inject
+ public PullRequestReferenceGenerator(MarkdownManager markdownManager,
+ Dao dao, AccountManager userManager,
+ UrlManager urlManager) {
+ this.markdownManager = markdownManager;
+ this.dao = dao;
+ this.userManager = userManager;
+ }
+
+ @Override
+ public boolean onLoad(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ return false;
+ }
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState,
+ String[] propertyNames, Type[] types) throws CallbackException {
+ if (entity instanceof PullRequest) {
+ PullRequest request = (PullRequest) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("description")) {
+ String description = (String) currentState[i];
+ String prevDescription = (String) previousState[i];
+ if (!Objects.equal(description, prevDescription) && description != null) {
+ String html = markdownManager.parse(description);
+ for (PullRequest referenced: new PullRequestParser().parseRequests(html))
+ saveReference(referenced, request);
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestComment) {
+ PullRequestComment comment = (PullRequestComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) currentState[i];
+ String prevContent = (String) previousState[i];
+ if (!content.equals(prevContent)) {
+ String html = markdownManager.parse(content);
+ Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
+ for (PullRequest request: requests)
+ saveReference(request, comment.getRequest());
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestStatusChange) {
+ PullRequestStatusChange statusChange = (PullRequestStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) currentState[i];
+ String prevNote = (String) previousState[i];
+ if (!note.equals(prevNote)) {
+ String html = markdownManager.parse(note);
+ Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
+ for (PullRequest request: requests)
+ saveReference(request, statusChange.getRequest());
+ }
+ break;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ private void saveReference(PullRequest referenced, PullRequest referencedBy) {
+ if (!referenced.equals(referencedBy)) {
+ EntityCriteria<PullRequestReference> criteria = EntityCriteria.of(PullRequestReference.class);
+ criteria.add(Restrictions.eq("referenced", referenced));
+ criteria.add(Restrictions.eq("referencedBy", referencedBy));
+ if (dao.find(criteria) == null) {
+ PullRequestReference reference = new PullRequestReference();
+ reference.setReferencedBy(referencedBy);
+ reference.setReferenced(referenced);
+ reference.setUser(userManager.getCurrent());
+ dao.persist(reference);
+ }
+ }
+ }
+
+ @Override
+ public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ if (entity instanceof PullRequest) {
+ PullRequest request = (PullRequest) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("description")) {
+ String description = (String) state[i];
+ if (description != null) {
+ String html = markdownManager.parse(description);
+ for (PullRequest referenced: new PullRequestParser().parseRequests(html))
+ saveReference(referenced, request);
+ }
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestComment) {
+ PullRequestComment comment = (PullRequestComment) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("content")) {
+ String content = (String) state[i];
+ String html = markdownManager.parse(content);
+ Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
+ for (PullRequest request: requests)
+ saveReference(request, comment.getRequest());
+ break;
+ }
+ }
+ } else if (entity instanceof PullRequestStatusChange) {
+ PullRequestStatusChange statusChange = (PullRequestStatusChange) entity;
+ for (int i=0; i<propertyNames.length; i++) {
+ if (propertyNames[i].equals("note")) {
+ String note = (String) state[i];
+ if (note != null) {
+ String html = markdownManager.parse(note);
+ Collection<PullRequest> requests = new PullRequestParser().parseRequests(html);
+ for (PullRequest request: requests)
+ saveReference(request, statusChange.getRequest());
+ }
+ break;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ @Override
+ public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types)
+ throws CallbackException {
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/LastEvent.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/LastEvent.java
index c2bf1b7b43..b8ef61cca1 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/LastEvent.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/entity/support/LastEvent.java
@@ -1,53 +1,53 @@
-package com.pmease.gitplex.core.entity.support;
-
-import java.io.Serializable;
-import java.util.Date;
-
-import javax.persistence.Column;
-import javax.persistence.Embeddable;
-import javax.persistence.FetchType;
-import javax.persistence.JoinColumn;
-import javax.persistence.ManyToOne;
-
-import com.pmease.gitplex.core.entity.Account;
-
-@Embeddable
-public class LastEvent implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- @ManyToOne(fetch=FetchType.LAZY)
- @JoinColumn(name="LAST_EVENT_USER")
- private Account user;
-
- @Column(name="LAST_EVENT_DESC")
- private String description;
-
- @Column(name="LAST_EVENT_DATE")
- private Date date;
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public Date getDate() {
- return date;
- }
-
- public void setDate(Date date) {
- this.date = date;
- }
-
- public Account getUser() {
- return user;
- }
-
- public void setUser(Account user) {
- this.user = user;
- }
-
-}
+package com.pmease.gitplex.core.entity.support;
+
+import java.io.Serializable;
+import java.util.Date;
+
+import javax.persistence.Column;
+import javax.persistence.Embeddable;
+import javax.persistence.FetchType;
+import javax.persistence.JoinColumn;
+import javax.persistence.ManyToOne;
+
+import com.pmease.gitplex.core.entity.Account;
+
+@Embeddable
+public class LastEvent implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ @ManyToOne(fetch=FetchType.LAZY)
+ @JoinColumn(name="LAST_EVENT_USER")
+ private Account user;
+
+ @Column(name="LAST_EVENT_DESC")
+ private Class<?> type;
+
+ @Column(name="LAST_EVENT_DATE")
+ private Date date;
+
+ public Class<?> getType() {
+ return type;
+ }
+
+ public void setType(Class<?> type) {
+ this.type = type;
+ }
+
+ public Date getDate() {
+ return date;
+ }
+
+ public void setDate(Date date) {
+ this.date = date;
+ }
+
+ public Account getUser() {
+ return user;
+ }
+
+ public void setUser(Account user) {
+ this.user = user;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentCreated.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentCreated.java
index 25861da99f..f140d05e40 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentCreated.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentCreated.java
@@ -7,7 +7,7 @@ import com.pmease.gitplex.core.entity.CodeComment;
public class CodeCommentCreated extends CodeCommentEvent {
public CodeCommentCreated(CodeComment comment) {
- super(comment);
+ super(comment, comment.getUser(), comment.getDate());
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentEvent.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentEvent.java
index 79097cce90..3c415b5f5f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentEvent.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentEvent.java
@@ -1,17 +1,34 @@
package com.pmease.gitplex.core.event.codecomment;
+import java.util.Date;
+
+import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.CodeComment;
public abstract class CodeCommentEvent {
private final CodeComment comment;
- public CodeCommentEvent(CodeComment comment) {
+ private final Account user;
+
+ private final Date date;
+
+ public CodeCommentEvent(CodeComment comment, Account user, Date date) {
this.comment = comment;
+ this.user = user;
+ this.date = date;
}
public CodeComment getComment() {
return comment;
}
+
+ public Account getUser() {
+ return user;
+ }
+
+ public Date getDate() {
+ return date;
+ }
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentReplied.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentReplied.java
index bfe1cddbe3..8c52f26a2f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentReplied.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentReplied.java
@@ -9,7 +9,7 @@ public class CodeCommentReplied extends CodeCommentEvent {
private final CodeCommentReply reply;
public CodeCommentReplied(CodeCommentReply reply) {
- super(reply.getComment());
+ super(reply.getComment(), reply.getUser(), reply.getDate());
this.reply = reply;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentResolved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentResolved.java
index 8498bfb825..b4efdcfacd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentResolved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentResolved.java
@@ -1,21 +1,20 @@
package com.pmease.gitplex.core.event.codecomment;
import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
@Editable(name="resolved")
public class CodeCommentResolved extends CodeCommentEvent {
- private final Account user;
+ private final CodeCommentStatusChange statusChange;
- public CodeCommentResolved(CodeComment comment, Account user) {
- super(comment);
- this.user = user;
+ public CodeCommentResolved(CodeCommentStatusChange statusChange) {
+ super(statusChange.getComment(), statusChange.getUser(), statusChange.getDate());
+ this.statusChange = statusChange;
}
- public Account getUser() {
- return user;
+ public CodeCommentStatusChange getStatusChange() {
+ return statusChange;
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentUnresolved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentUnresolved.java
index ee7f42ad3d..9030a58271 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentUnresolved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/codecomment/CodeCommentUnresolved.java
@@ -1,21 +1,21 @@
package com.pmease.gitplex.core.event.codecomment;
import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
@Editable(name="unresolved")
public class CodeCommentUnresolved extends CodeCommentEvent {
- private final Account user;
+ private final CodeCommentStatusChange statusChange;
- public CodeCommentUnresolved(CodeComment comment, Account user) {
- super(comment);
- this.user = user;
+ public CodeCommentUnresolved(CodeCommentStatusChange statusChange) {
+ super(statusChange.getComment(), statusChange.getUser(), statusChange.getDate());
+ this.statusChange = statusChange;
}
- public Account getUser() {
- return user;
+ public CodeCommentStatusChange getStatusChange() {
+ return statusChange;
}
}
+
\ No newline at end of file
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInCodeComment.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInCodeComment.java
new file mode 100644
index 0000000000..5aeb163813
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInCodeComment.java
@@ -0,0 +1,32 @@
+package com.pmease.gitplex.core.event.mention;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.CodeComment;
+
+public class AccountMentionedInCodeComment {
+
+ private final Account user;
+
+ private final String markdown;
+
+ private final CodeComment comment;
+
+ public AccountMentionedInCodeComment(CodeComment comment, Account user, String markdown) {
+ this.comment = comment;
+ this.user = user;
+ this.markdown = markdown;
+ }
+
+ public Account getUser() {
+ return user;
+ }
+
+ public String getMarkdown() {
+ return markdown;
+ }
+
+ public CodeComment getComment() {
+ return comment;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInPullRequest.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInPullRequest.java
new file mode 100644
index 0000000000..b8d2520fb7
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/mention/AccountMentionedInPullRequest.java
@@ -0,0 +1,32 @@
+package com.pmease.gitplex.core.event.mention;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public class AccountMentionedInPullRequest {
+
+ private final PullRequest request;
+
+ private final Account user;
+
+ private final String markdown;
+
+ public AccountMentionedInPullRequest(PullRequest request, Account user, String markdown) {
+ this.request = request;
+ this.user = user;
+ this.markdown = markdown;
+ }
+
+ public PullRequest getRequest() {
+ return request;
+ }
+
+ public Account getUser() {
+ return user;
+ }
+
+ public String getMarkdown() {
+ return markdown;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentioned.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentioned.java
deleted file mode 100644
index 8eac13d7b8..0000000000
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentioned.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public class AccountMentioned extends PullRequestNotificationEvent {
-
- private final Account user;
-
- public AccountMentioned(PullRequest request, Account user) {
- super(request);
- this.user = user;
- }
-
- public Account getUser() {
- return user;
- }
-
-}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentionedInComment.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentionedInComment.java
deleted file mode 100644
index d7c431c931..0000000000
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/AccountMentionedInComment.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-
-public class AccountMentionedInComment extends PullRequestNotificationEvent {
-
- private final PullRequestComment comment;
-
- private final Account user;
-
- public AccountMentionedInComment(PullRequestComment comment, Account user) {
- super(comment.getRequest());
- this.comment = comment;
- this.user = user;
- }
-
- public PullRequestComment getComment() {
- return comment;
- }
-
- public Account getUser() {
- return user;
- }
-
-}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/IntegrationPreviewCalculated.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/IntegrationPreviewCalculated.java
index 61b9ef220f..89c5a5e6fc 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/IntegrationPreviewCalculated.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/IntegrationPreviewCalculated.java
@@ -1,11 +1,13 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.gitplex.core.entity.PullRequest;
public class IntegrationPreviewCalculated extends PullRequestChangeEvent {
public IntegrationPreviewCalculated(PullRequest request) {
- super(request);
+ super(request, null, new Date());
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/MarkdownAware.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/MarkdownAware.java
new file mode 100644
index 0000000000..ad4860dd11
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/MarkdownAware.java
@@ -0,0 +1,7 @@
+package com.pmease.gitplex.core.event.pullrequest;
+
+import javax.annotation.Nullable;
+
+public interface MarkdownAware {
+ @Nullable String getMarkdown();
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestApproved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestApproved.java
index af81464aac..06bce5efab 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestApproved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestApproved.java
@@ -9,7 +9,7 @@ public class PullRequestApproved extends PullRequestStatusChangeEvent {
private final PullRequestReview review;
public PullRequestApproved(PullRequestReview review, String note) {
- super(review.getUpdate().getRequest(), review.getUser(), note);
+ super(review.getUpdate().getRequest(), review.getUser(), review.getDate(), note);
this.review = review;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestAssigned.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestAssigned.java
index 4e1f994bb6..aea2e9bcf8 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestAssigned.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestAssigned.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequest;
@@ -8,7 +10,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
public class PullRequestAssigned extends PullRequestStatusChangeEvent {
public PullRequestAssigned(PullRequest request, Account user, String note) {
- super(request, user, note);
+ super(request, user, new Date(), note);
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestChangeEvent.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestChangeEvent.java
index c489e3fb67..8eb2417c14 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestChangeEvent.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestChangeEvent.java
@@ -1,11 +1,31 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
+import javax.annotation.Nullable;
+
+import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequest;
public abstract class PullRequestChangeEvent extends PullRequestEvent {
- public PullRequestChangeEvent(PullRequest request) {
+ private final Account user;
+
+ private final Date date;
+
+ public PullRequestChangeEvent(PullRequest request, @Nullable Account user, Date date) {
super(request);
+ this.user = user;
+ this.date = date;
+ }
+
+ @Nullable
+ public Account getUser() {
+ return user;
+ }
+
+ public Date getDate() {
+ return date;
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentReplied.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentReplied.java
index 5a852c8ac8..a1c553a4dd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentReplied.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentReplied.java
@@ -5,12 +5,12 @@ import com.pmease.gitplex.core.entity.CodeCommentReply;
import com.pmease.gitplex.core.entity.PullRequest;
@Editable(name="replied code comment")
-public class PullRequestCodeCommentReplied extends PullRequestChangeEvent {
+public class PullRequestCodeCommentReplied extends PullRequestChangeEvent implements MarkdownAware {
private final CodeCommentReply reply;
public PullRequestCodeCommentReplied(PullRequest request, CodeCommentReply reply) {
- super(request);
+ super(request, reply.getUser(), reply.getDate());
this.reply = reply;
}
@@ -18,4 +18,9 @@ public class PullRequestCodeCommentReplied extends PullRequestChangeEvent {
return reply;
}
+ @Override
+ public String getMarkdown() {
+ return getReply().getContent();
+ }
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentResolved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentResolved.java
index 072515141f..881e70ed4b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentResolved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentResolved.java
@@ -1,21 +1,26 @@
package com.pmease.gitplex.core.event.pullrequest;
import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
import com.pmease.gitplex.core.entity.PullRequest;
@Editable(name="resolved code comment")
-public class PullRequestCodeCommentResolved extends PullRequestChangeEvent {
+public class PullRequestCodeCommentResolved extends PullRequestChangeEvent implements MarkdownAware {
- private final CodeComment comment;
+ private final CodeCommentStatusChange statusChange;
- public PullRequestCodeCommentResolved(PullRequest request, CodeComment comment) {
- super(request);
- this.comment = comment;
+ public PullRequestCodeCommentResolved(PullRequest request, CodeCommentStatusChange statusChange) {
+ super(request, statusChange.getUser(), statusChange.getDate());
+ this.statusChange = statusChange;
}
- public CodeComment getComment() {
- return comment;
+ public CodeCommentStatusChange getStatusChange() {
+ return statusChange;
+ }
+
+ @Override
+ public String getMarkdown() {
+ return getStatusChange().getNote();
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentUnresolved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentUnresolved.java
index aae9fac0fe..462a561065 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentUnresolved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommentUnresolved.java
@@ -1,21 +1,26 @@
package com.pmease.gitplex.core.event.pullrequest;
import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentStatusChange;
import com.pmease.gitplex.core.entity.PullRequest;
-@Editable(name="unresolved code comment")
-public class PullRequestCodeCommentUnresolved extends PullRequestChangeEvent {
+@Editable(name="Unresolved code comment")
+public class PullRequestCodeCommentUnresolved extends PullRequestChangeEvent implements MarkdownAware {
- private final CodeComment comment;
+ private final CodeCommentStatusChange statusChange;
- public PullRequestCodeCommentUnresolved(PullRequest request, CodeComment comment) {
- super(request);
- this.comment = comment;
+ public PullRequestCodeCommentUnresolved(PullRequest request, CodeCommentStatusChange statusChange) {
+ super(request, statusChange.getUser(), statusChange.getDate());
+ this.statusChange = statusChange;
}
- public CodeComment getComment() {
- return comment;
+ public CodeCommentStatusChange getStatusChange() {
+ return statusChange;
+ }
+
+ @Override
+ public String getMarkdown() {
+ return getStatusChange().getNote();
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommented.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommented.java
index 965d37ade7..7164d81204 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommented.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCodeCommented.java
@@ -5,12 +5,12 @@ import com.pmease.gitplex.core.entity.CodeComment;
import com.pmease.gitplex.core.entity.PullRequest;
@Editable(name="commented code")
-public class PullRequestCodeCommented extends PullRequestChangeEvent {
+public class PullRequestCodeCommented extends PullRequestChangeEvent implements MarkdownAware {
private final CodeComment comment;
public PullRequestCodeCommented(PullRequest request, CodeComment comment) {
- super(request);
+ super(request, comment.getUser(), comment.getDate());
this.comment = comment;
}
@@ -18,4 +18,9 @@ public class PullRequestCodeCommented extends PullRequestChangeEvent {
return comment;
}
+ @Override
+ public String getMarkdown() {
+ return getComment().getContent();
+ }
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCommented.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCommented.java
index afac755d99..159ab2c70b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCommented.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestCommented.java
@@ -4,12 +4,12 @@ import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequestComment;
@Editable(name="commented")
-public class PullRequestCommented extends PullRequestChangeEvent {
+public class PullRequestCommented extends PullRequestChangeEvent implements MarkdownAware {
private final PullRequestComment comment;
public PullRequestCommented(PullRequestComment comment) {
- super(comment.getRequest());
+ super(comment.getRequest(), comment.getUser(), comment.getDate());
this.comment = comment;
}
@@ -17,4 +17,9 @@ public class PullRequestCommented extends PullRequestChangeEvent {
return comment;
}
+ @Override
+ public String getMarkdown() {
+ return getComment().getContent();
+ }
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDisapproved.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDisapproved.java
index 42212d000b..2e2883c09f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDisapproved.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDisapproved.java
@@ -9,7 +9,7 @@ public class PullRequestDisapproved extends PullRequestStatusChangeEvent {
private final PullRequestReview review;
public PullRequestDisapproved(PullRequestReview review, String note) {
- super(review.getUpdate().getRequest(), review.getUser(), note);
+ super(review.getUpdate().getRequest(), review.getUser(), review.getDate(), note);
this.review = review;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDiscarded.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDiscarded.java
index 91c6b680da..162396e78e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDiscarded.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestDiscarded.java
@@ -8,7 +8,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
public class PullRequestDiscarded extends PullRequestStatusChangeEvent {
public PullRequestDiscarded(PullRequest request, Account user, String note) {
- super(request, user, note);
+ super(request, user, request.getCloseInfo().getCloseDate(), note);
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestIntegrated.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestIntegrated.java
index aad8c7ae36..ad20631d4e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestIntegrated.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestIntegrated.java
@@ -8,7 +8,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
public class PullRequestIntegrated extends PullRequestStatusChangeEvent {
public PullRequestIntegrated(PullRequest request, Account user, String note) {
- super(request, user, note);
+ super(request, user, request.getCloseInfo().getCloseDate(), note);
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestNotificationEvent.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestNotificationEvent.java
deleted file mode 100644
index 90aa997c2c..0000000000
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestNotificationEvent.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public abstract class PullRequestNotificationEvent extends PullRequestEvent {
-
- public PullRequestNotificationEvent(PullRequest request) {
- super(request);
- }
-
-}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestOpened.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestOpened.java
index 614eec8b18..0ad8c62683 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestOpened.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestOpened.java
@@ -4,10 +4,15 @@ import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequest;
@Editable(name="opened")
-public class PullRequestOpened extends PullRequestChangeEvent {
+public class PullRequestOpened extends PullRequestChangeEvent implements MarkdownAware {
public PullRequestOpened(PullRequest request) {
- super(request);
+ super(request, request.getSubmitter(), request.getSubmitDate());
+ }
+
+ @Override
+ public String getMarkdown() {
+ return getRequest().getDescription();
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingApproval.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingApproval.java
index de4c608b70..887c838bd1 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingApproval.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingApproval.java
@@ -1,11 +1,11 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public class PullRequestPendingApproval extends PullRequestNotificationEvent {
-
- public PullRequestPendingApproval(PullRequest request) {
- super(request);
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public class PullRequestPendingApproval extends PullRequestEvent {
+
+ public PullRequestPendingApproval(PullRequest request) {
+ super(request);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingIntegration.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingIntegration.java
index 563d3c1bb0..7910d7e244 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingIntegration.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingIntegration.java
@@ -1,11 +1,11 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public class PullRequestPendingIntegration extends PullRequestNotificationEvent {
-
- public PullRequestPendingIntegration(PullRequest request) {
- super(request);
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public class PullRequestPendingIntegration extends PullRequestEvent {
+
+ public PullRequestPendingIntegration(PullRequest request) {
+ super(request);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingUpdate.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingUpdate.java
index cbe67f2e55..46150868f7 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingUpdate.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestPendingUpdate.java
@@ -1,11 +1,11 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public class PullRequestPendingUpdate extends PullRequestNotificationEvent {
-
- public PullRequestPendingUpdate(PullRequest request) {
- super(request);
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public class PullRequestPendingUpdate extends PullRequestEvent {
+
+ public PullRequestPendingUpdate(PullRequest request) {
+ super(request);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReopened.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReopened.java
index 714f22f22c..f3db4feb37 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReopened.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReopened.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequest;
@@ -8,7 +10,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
public class PullRequestReopened extends PullRequestStatusChangeEvent {
public PullRequestReopened(PullRequest request, Account user, String note) {
- super(request, user, note);
+ super(request, user, new Date(), note);
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewDeleted.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewDeleted.java
index 70bf013dd8..6e038d2778 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewDeleted.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewDeleted.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequestReview;
@@ -10,7 +12,7 @@ public class PullRequestReviewDeleted extends PullRequestStatusChangeEvent {
private final PullRequestReview review;
public PullRequestReviewDeleted(PullRequestReview review, Account user, String note) {
- super(review.getUpdate().getRequest(), user, note);
+ super(review.getUpdate().getRequest(), user, new Date(), note);
this.review = review;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/InvitingPullRequestReview.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewInvitationChanged.java
similarity index 64%
rename from gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/InvitingPullRequestReview.java
rename to gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewInvitationChanged.java
index 088d924b69..69574783e5 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/InvitingPullRequestReview.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestReviewInvitationChanged.java
@@ -1,18 +1,18 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-
-public class InvitingPullRequestReview extends PullRequestNotificationEvent {
-
- private final PullRequestReviewInvitation invitation;
-
- public InvitingPullRequestReview(PullRequestReviewInvitation invitation) {
- super(invitation.getRequest());
- this.invitation = invitation;
- }
-
- public PullRequestReviewInvitation getInvitation() {
- return invitation;
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+
+public class PullRequestReviewInvitationChanged extends PullRequestEvent {
+
+ private final PullRequestReviewInvitation invitation;
+
+ public PullRequestReviewInvitationChanged(PullRequestReviewInvitation invitation) {
+ super(invitation.getRequest());
+ this.invitation = invitation;
+ }
+
+ public PullRequestReviewInvitation getInvitation() {
+ return invitation;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestStatusChangeEvent.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestStatusChangeEvent.java
index 59d38a2ab3..3ac8acf1a7 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestStatusChangeEvent.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestStatusChangeEvent.java
@@ -1,29 +1,29 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import javax.annotation.Nullable;
-
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-
-public abstract class PullRequestStatusChangeEvent extends PullRequestChangeEvent {
-
- private final Account user;
-
- private final String note;
-
- public PullRequestStatusChangeEvent(PullRequest request, Account user, @Nullable String note) {
- super(request);
- this.user = user;
- this.note = note;
- }
-
- public Account getUser() {
- return user;
- }
-
- @Nullable
- public String getNote() {
- return note;
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import java.util.Date;
+
+import javax.annotation.Nullable;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public abstract class PullRequestStatusChangeEvent extends PullRequestChangeEvent implements MarkdownAware {
+
+ private final String note;
+
+ public PullRequestStatusChangeEvent(PullRequest request, Account user, Date date, @Nullable String note) {
+ super(request, user, date);
+ this.note = note;
+ }
+
+ @Nullable
+ public String getNote() {
+ return note;
+ }
+
+ @Override
+ public String getMarkdown() {
+ return getNote();
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestUpdated.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestUpdated.java
index 439b2a197a..034cae0f1c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestUpdated.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestUpdated.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequestUpdate;
@@ -9,7 +11,7 @@ public class PullRequestUpdated extends PullRequestChangeEvent {
private final PullRequestUpdate update;
public PullRequestUpdated(PullRequestUpdate update) {
- super(update.getRequest());
+ super(update.getRequest(), null, new Date());
this.update = update;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationDeleted.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationDeleted.java
index c5faf3b417..8f8c3812ef 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationDeleted.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationDeleted.java
@@ -1,5 +1,7 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequestVerification;
@@ -10,7 +12,7 @@ public class PullRequestVerificationDeleted extends PullRequestStatusChangeEvent
private final PullRequestVerification verification;
public PullRequestVerificationDeleted(PullRequestVerification verification, Account user) {
- super(verification.getRequest(), user, "configuration: " + verification.getConfiguration());
+ super(verification.getRequest(), user, new Date(), "configuration: " + verification.getConfiguration());
this.verification = verification;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationFailed.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationFailed.java
index ddd0c0ec4f..17d541adcd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationFailed.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationFailed.java
@@ -1,15 +1,17 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequestVerification;
-@Editable(name="verification failed", icon="fa fa-thumbs-o-down")
+@Editable(name="completed verification (failed)", icon="fa fa-thumbs-o-down")
public class PullRequestVerificationFailed extends PullRequestStatusChangeEvent {
private final PullRequestVerification verification;
public PullRequestVerificationFailed(PullRequestVerification verification) {
- super(verification.getRequest(), verification.getUser(),
+ super(verification.getRequest(), verification.getUser(), new Date(),
"configuration: " + verification.getConfiguration() + "\n"
+ "message: " + verification.getMessage());
this.verification = verification;
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationRunning.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationRunning.java
index e1bc18f651..17a26da738 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationRunning.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationRunning.java
@@ -1,13 +1,17 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequestVerification;
+@Editable(name="ran verification", icon="fa fa-cog")
public class PullRequestVerificationRunning extends PullRequestChangeEvent {
private final PullRequestVerification verification;
public PullRequestVerificationRunning(PullRequestVerification verification) {
- super(verification.getRequest());
+ super(verification.getRequest(), verification.getUser(), new Date());
this.verification = verification;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationSucceeded.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationSucceeded.java
index c5214c5c58..9dabd6d272 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationSucceeded.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/PullRequestVerificationSucceeded.java
@@ -1,15 +1,17 @@
package com.pmease.gitplex.core.event.pullrequest;
+import java.util.Date;
+
import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.PullRequestVerification;
-@Editable(name="verification succeeded", icon="fa fa-thumbs-o-up")
+@Editable(name="completed verification (successful)", icon="fa fa-thumbs-o-up")
public class PullRequestVerificationSucceeded extends PullRequestStatusChangeEvent {
private final PullRequestVerification verification;
public PullRequestVerificationSucceeded(PullRequestVerification verification) {
- super(verification.getRequest(), verification.getUser(),
+ super(verification.getRequest(), verification.getUser(), new Date(),
"configuration: " + verification.getConfiguration() + "\n"
+ "message: " + verification.getMessage());
this.verification = verification;
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchDeleted.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchDeleted.java
index 923d08d893..5e54020ccc 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchDeleted.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchDeleted.java
@@ -1,14 +1,16 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-
-@Editable(name="deleted source branch", icon="fa fa-times")
-public class SourceBranchDeleted extends PullRequestStatusChangeEvent {
-
- public SourceBranchDeleted(PullRequest request, Account user, String note) {
- super(request, user, note);
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import java.util.Date;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+@Editable(name="deleted source branch", icon="fa fa-times")
+public class SourceBranchDeleted extends PullRequestStatusChangeEvent {
+
+ public SourceBranchDeleted(PullRequest request, Account user, String note) {
+ super(request, user, new Date(), note);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchRestored.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchRestored.java
index 82c0a194a8..23f0646028 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchRestored.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/event/pullrequest/SourceBranchRestored.java
@@ -1,14 +1,16 @@
-package com.pmease.gitplex.core.event.pullrequest;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-
-@Editable(name="restored source branch", icon="fa fa-repeat")
-public class SourceBranchRestored extends PullRequestStatusChangeEvent {
-
- public SourceBranchRestored(PullRequest request, Account user, String note) {
- super(request, user, note);
- }
-
-}
+package com.pmease.gitplex.core.event.pullrequest;
+
+import java.util.Date;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+@Editable(name="restored source branch", icon="fa fa-repeat")
+public class SourceBranchRestored extends PullRequestStatusChangeEvent {
+
+ public SourceBranchRestored(PullRequest request, Account user, String note) {
+ super(request, user, new Date(), note);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AbstractGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AbstractGateKeeper.java
index c89b417307..b9732ac1ec 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AbstractGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AbstractGateKeeper.java
@@ -1,156 +1,156 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.Account;
-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.Ignored;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-
-@Editable
-public abstract class AbstractGateKeeper implements GateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- private boolean enabled = true;
-
- public boolean isEnabled() {
- return enabled;
- }
-
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- @Override
- public CheckResult checkRequest(PullRequest request) {
- if (enabled)
- return doCheckRequest(request);
- else
- return ignored();
- }
-
- @Override
- public CheckResult checkFile(Account user, Depot depot, String branch, String file) {
- if (isEnabled())
- return doCheckFile(user, depot, branch, file);
- else
- return ignored();
- }
-
- @Override
- public CheckResult checkPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
- if (isEnabled())
- return doCheckPush(user, depot, refName, oldCommit, newCommit);
- else
- return ignored();
- }
-
- /**
- * Check gate keeper against specified pull request without considering enable flag. This is
- * typically used to determine whether or not to accept a pull request.
- *
- * @param request
- * pull request to be checked
- * @return
- * result of the check
- */
- protected abstract CheckResult doCheckRequest(PullRequest request);
-
- /**
- * Check if specified user can modify specified file in specified branch, without considering enable flag.
- *
- * @param user
- * user to be checked
- * @param branch
- * branch to be checked
- * @param file
- * file to be checked
- * @return
- * result of the check
- */
- protected abstract CheckResult doCheckFile(Account user, Depot depot, String branch, @Nullable String file);
-
- /**
- * Check if specified user can push specified commit to specified branch, without considering enable flag.
- *
- * @param user
- * user to be checked
- * @param branch
- * branch to be checked
- * @param commit
- * commit to be checked
- * @return
- * result of the check
- */
- protected abstract CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit);
-
- protected CheckResult ignored() {
- return new Ignored();
- }
-
- protected CheckResult passed(List<String> reasons) {
- return new Passed(reasons);
- }
-
- protected CheckResult failed(List<String> reasons) {
- return new Failed(reasons);
- }
-
- protected CheckResult pending(List<String> reasons) {
- return new Pending(reasons);
- }
-
- protected CheckResult blocking(List<String> reasons) {
- return new Blocking(reasons);
- }
-
- @Override
- public void onDepotRename(Depot renamedDepot, String oldName) {
- }
-
- @Override
- public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
- Account originalAccount) {
- return false;
- }
-
- @Override
- public void onAccountRename(String oldName, String newName) {
- }
-
- @Override
- public boolean onAccountDelete(String accountName) {
- return false;
- }
-
- @Override
- public boolean onDepotDelete(Depot depot) {
- return false;
- }
-
- @Override
- public void onTeamRename(String oldName, String newName) {
- }
-
- @Override
- public boolean onTeamDelete(String teamName) {
- return false;
- }
-
- @Override
- public boolean onRefDelete(String refName) {
- return false;
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Ignored;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+
+@Editable
+public abstract class AbstractGateKeeper implements GateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ private boolean enabled = true;
+
+ public boolean isEnabled() {
+ return enabled;
+ }
+
+ public void setEnabled(boolean enabled) {
+ this.enabled = enabled;
+ }
+
+ @Override
+ public GateCheckResult checkRequest(PullRequest request) {
+ if (enabled)
+ return doCheckRequest(request);
+ else
+ return ignored();
+ }
+
+ @Override
+ public GateCheckResult checkFile(Account user, Depot depot, String branch, String file) {
+ if (isEnabled())
+ return doCheckFile(user, depot, branch, file);
+ else
+ return ignored();
+ }
+
+ @Override
+ public GateCheckResult checkPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ if (isEnabled())
+ return doCheckPush(user, depot, refName, oldCommit, newCommit);
+ else
+ return ignored();
+ }
+
+ /**
+ * Check gate keeper against specified pull request without considering enable flag. This is
+ * typically used to determine whether or not to accept a pull request.
+ *
+ * @param request
+ * pull request to be checked
+ * @return
+ * result of the check
+ */
+ protected abstract GateCheckResult doCheckRequest(PullRequest request);
+
+ /**
+ * Check if specified user can modify specified file in specified branch, without considering enable flag.
+ *
+ * @param user
+ * user to be checked
+ * @param branch
+ * branch to be checked
+ * @param file
+ * file to be checked
+ * @return
+ * result of the check
+ */
+ protected abstract GateCheckResult doCheckFile(Account user, Depot depot, String branch, @Nullable String file);
+
+ /**
+ * Check if specified user can push specified commit to specified branch, without considering enable flag.
+ *
+ * @param user
+ * user to be checked
+ * @param branch
+ * branch to be checked
+ * @param commit
+ * commit to be checked
+ * @return
+ * result of the check
+ */
+ protected abstract GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit);
+
+ protected GateCheckResult ignored() {
+ return new Ignored();
+ }
+
+ protected GateCheckResult passed(List<String> reasons) {
+ return new Passed(reasons);
+ }
+
+ protected GateCheckResult failed(List<String> reasons) {
+ return new Failed(reasons);
+ }
+
+ protected GateCheckResult pending(List<String> reasons) {
+ return new Pending(reasons);
+ }
+
+ protected GateCheckResult blocking(List<String> reasons) {
+ return new Blocking(reasons);
+ }
+
+ @Override
+ public void onDepotRename(Depot renamedDepot, String oldName) {
+ }
+
+ @Override
+ public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
+ Account originalAccount) {
+ return false;
+ }
+
+ @Override
+ public void onAccountRename(String oldName, String newName) {
+ }
+
+ @Override
+ public boolean onAccountDelete(String accountName) {
+ return false;
+ }
+
+ @Override
+ public boolean onDepotDelete(Depot depot) {
+ return false;
+ }
+
+ @Override
+ public void onTeamRename(String oldName, String newName) {
+ }
+
+ @Override
+ public boolean onTeamDelete(String teamName) {
+ return false;
+ }
+
+ @Override
+ public boolean onRefDelete(String refName) {
+ return false;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AndGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AndGateKeeper.java
index 471f8156ec..b8857ee0cd 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AndGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/AndGateKeeper.java
@@ -1,47 +1,47 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Horizontal;
-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.Passed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-
-@Editable(name="And Composition", icon="fa-object-group", order=100,
- category=GateKeeper.CATEGORY_COMPOSITION,
- description="This gate keeper will be passed if all contained gate keepers are passed")
-@Horizontal
-public class AndGateKeeper extends AndOrGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected CheckResult aggregate(Checker checker) {
- List<String> pendingReasons = new ArrayList<String>();
- List<String> acceptReasons = new ArrayList<String>();
-
- for (GateKeeper each: getGateKeepers()) {
- CheckResult result = checker.check(each);
- if (result instanceof Passed) {
- acceptReasons.addAll(result.getReasons());
- } else if (result instanceof Failed) {
- return result;
- } else if (result instanceof Blocking) {
- result.getReasons().addAll(pendingReasons);
- return result;
- } else if (result instanceof Pending) {
- pendingReasons.addAll(result.getReasons());
- }
- }
-
- if (!pendingReasons.isEmpty())
- return pending(pendingReasons);
- else
- return passed(acceptReasons);
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Horizontal;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+
+@Editable(name="And Composition", icon="fa-object-group", order=100,
+ category=GateKeeper.CATEGORY_COMPOSITION,
+ description="This gate keeper will be passed if all contained gate keepers are passed")
+@Horizontal
+public class AndGateKeeper extends AndOrGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected GateCheckResult aggregate(Checker checker) {
+ List<String> pendingReasons = new ArrayList<String>();
+ List<String> acceptReasons = new ArrayList<String>();
+
+ for (GateKeeper each: getGateKeepers()) {
+ GateCheckResult result = checker.check(each);
+ if (result instanceof Passed) {
+ acceptReasons.addAll(result.getReasons());
+ } else if (result instanceof Failed) {
+ return result;
+ } else if (result instanceof Blocking) {
+ result.getReasons().addAll(pendingReasons);
+ return result;
+ } else if (result instanceof Pending) {
+ pendingReasons.addAll(result.getReasons());
+ }
+ }
+
+ if (!pendingReasons.isEmpty())
+ return pending(pendingReasons);
+ else
+ return passed(acceptReasons);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/CompositeGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/CompositeGateKeeper.java
index ced6285215..b723c058da 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/CompositeGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/CompositeGateKeeper.java
@@ -1,57 +1,57 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-
-public abstract class CompositeGateKeeper extends AbstractGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- public static interface Checker {
- CheckResult check(GateKeeper gateKeeper);
- }
-
- protected abstract CheckResult aggregate(Checker checker);
-
- @Override
- public CheckResult doCheckRequest(final PullRequest request) {
- return aggregate(new Checker() {
-
- @Override
- public CheckResult check(GateKeeper gateKeeper) {
- return gateKeeper.checkRequest(request);
- }
-
- });
- }
-
- @Override
- protected CheckResult doCheckFile(final Account user, final Depot depot, final String branch, final String file) {
- return aggregate(new Checker() {
-
- @Override
- public CheckResult check(GateKeeper gateKeeper) {
- return gateKeeper.checkFile(user, depot, branch, file);
- }
-
- });
- }
-
- @Override
- protected CheckResult doCheckPush(final Account user, final Depot depot, final String refName,
- final ObjectId oldCommit, final ObjectId newCommit) {
- return aggregate(new Checker() {
-
- @Override
- public CheckResult check(GateKeeper gateKeeper) {
- return gateKeeper.checkPush(user, depot, refName, oldCommit, newCommit);
- }
-
- });
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+
+public abstract class CompositeGateKeeper extends AbstractGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ public static interface Checker {
+ GateCheckResult check(GateKeeper gateKeeper);
+ }
+
+ protected abstract GateCheckResult aggregate(Checker checker);
+
+ @Override
+ public GateCheckResult doCheckRequest(final PullRequest request) {
+ return aggregate(new Checker() {
+
+ @Override
+ public GateCheckResult check(GateKeeper gateKeeper) {
+ return gateKeeper.checkRequest(request);
+ }
+
+ });
+ }
+
+ @Override
+ protected GateCheckResult doCheckFile(final Account user, final Depot depot, final String branch, final String file) {
+ return aggregate(new Checker() {
+
+ @Override
+ public GateCheckResult check(GateKeeper gateKeeper) {
+ return gateKeeper.checkFile(user, depot, branch, file);
+ }
+
+ });
+ }
+
+ @Override
+ protected GateCheckResult doCheckPush(final Account user, final Depot depot, final String refName,
+ final ObjectId oldCommit, final ObjectId newCommit) {
+ return aggregate(new Checker() {
+
+ @Override
+ public GateCheckResult check(GateKeeper gateKeeper) {
+ return gateKeeper.checkPush(user, depot, refName, oldCommit, newCommit);
+ }
+
+ });
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/DefaultGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/DefaultGateKeeper.java
index 5abacec444..052e06abac 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/DefaultGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/DefaultGateKeeper.java
@@ -1,31 +1,31 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-
-@Editable
-public class DefaultGateKeeper extends AbstractGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public CheckResult doCheckRequest(PullRequest request) {
- return ignored();
- }
-
- @Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
- return ignored();
- }
-
- @Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
- return ignored();
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+
+@Editable
+public class DefaultGateKeeper extends AbstractGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public GateCheckResult doCheckRequest(PullRequest request) {
+ return ignored();
+ }
+
+ @Override
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ return ignored();
+ }
+
+ @Override
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ return ignored();
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/GateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/GateKeeper.java
index 9ddba7646a..d5d2f77a28 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/GateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/GateKeeper.java
@@ -1,83 +1,83 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.io.Serializable;
-
-import javax.annotation.Nullable;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-
-@Editable(name="Misc")
-public interface GateKeeper extends Serializable {
-
- String CATEGORY_BASIC = "Basic Gate Keepers";
-
- String CATEGORY_USER = "Check Approver/Submitter";
-
- String CATEGORY_COMPOSITION = "Gate Keeper Compositions";
-
- /**
- * Check the gate keeper against specified request. This is typically used to determine
- * whether or not to accept a pull request.
- *
- * @param request
- * pull request to be checked
- * @return
- * result of the check
- */
- CheckResult checkRequest(PullRequest request);
-
- /**
- * Check if specified user can modify specified file in specified branch.
- *
- * @param user
- * user to be checked
- * @param branch
- * branch to be checked
- * @param file
- * file to be checked, use <tt>null</tt> to ignore checking of file, that is,
- * only check the branch
- * @return
- * result of the check.
- */
- CheckResult checkFile(Account user, Depot depot, String branch, @Nullable String file);
-
- /**
- * Check if specified user can push specified commit to specified ref.
- *
- * @param user
- * user to be checked
- * @param refName
- * refName to be checked
- * @param oldCommitHash
- * old commit of the ref
- * @param newCommitHash
- * new commit of the ref
- * @return
- * result of the check
- */
- CheckResult checkPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit);
-
- void onDepotRename(Depot renamedDepot, String oldName);
-
- boolean onDepotDelete(Depot depot);
-
- boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot, Account originalAccount);
-
- void onTeamRename(String oldName, String newName);
-
- boolean onTeamDelete(String teamName);
-
- void onAccountRename(String oldName, String newName);
-
- boolean onAccountDelete(String accountName);
-
- boolean onRefDelete(String refName);
-
- boolean isEnabled();
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.io.Serializable;
+
+import javax.annotation.Nullable;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+
+@Editable(name="Misc")
+public interface GateKeeper extends Serializable {
+
+ String CATEGORY_BASIC = "Basic Gate Keepers";
+
+ String CATEGORY_USER = "Check Approver/Submitter";
+
+ String CATEGORY_COMPOSITION = "Gate Keeper Compositions";
+
+ /**
+ * Check the gate keeper against specified request. This is typically used to determine
+ * whether or not to accept a pull request.
+ *
+ * @param request
+ * pull request to be checked
+ * @return
+ * result of the check
+ */
+ GateCheckResult checkRequest(PullRequest request);
+
+ /**
+ * Check if specified user can modify specified file in specified branch.
+ *
+ * @param user
+ * user to be checked
+ * @param branch
+ * branch to be checked
+ * @param file
+ * file to be checked, use <tt>null</tt> to ignore checking of file, that is,
+ * only check the branch
+ * @return
+ * result of the check.
+ */
+ GateCheckResult checkFile(Account user, Depot depot, String branch, @Nullable String file);
+
+ /**
+ * Check if specified user can push specified commit to specified ref.
+ *
+ * @param user
+ * user to be checked
+ * @param refName
+ * refName to be checked
+ * @param oldCommitHash
+ * old commit of the ref
+ * @param newCommitHash
+ * new commit of the ref
+ * @return
+ * result of the check
+ */
+ GateCheckResult checkPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit);
+
+ void onDepotRename(Depot renamedDepot, String oldName);
+
+ boolean onDepotDelete(Depot depot);
+
+ boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot, Account originalAccount);
+
+ void onTeamRename(String oldName, String newName);
+
+ boolean onTeamDelete(String teamName);
+
+ void onAccountRename(String oldName, String newName);
+
+ boolean onAccountDelete(String accountName);
+
+ boolean onRefDelete(String refName);
+
+ boolean isEnabled();
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedTeam.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedTeam.java
index e5b4c26ce5..fe8924fe0f 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedTeam.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedTeam.java
@@ -12,7 +12,7 @@ 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.PullRequestReview;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
@Editable(order=100, icon="fa-group", category=GateKeeper.CATEGORY_USER, description=
"This gate keeper will be passed if the commit is approved by specified number of users "
@@ -34,7 +34,7 @@ public class IfApprovedBySpecifiedTeam extends TeamAwareGateKeeper {
}
@Override
- public CheckResult doCheckRequest(PullRequest request) {
+ public GateCheckResult doCheckRequest(PullRequest request) {
int approvals = 0;
int pendings = 0;
@@ -65,13 +65,13 @@ public class IfApprovedBySpecifiedTeam extends TeamAwareGateKeeper {
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
return pending(Lists.newArrayList("Need to be approved by at least " + getLeastApprovals()
+ " member(s) of team " + getTeamName()));
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return pending(Lists.newArrayList("Need to be approved by at least " + getLeastApprovals()
+ " member(s) of team " + getTeamName()));
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
index 6effae8560..a1eb166a87 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfApprovedBySpecifiedUser.java
@@ -13,7 +13,7 @@ import com.pmease.gitplex.core.entity.Depot;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.PullRequestReview;
import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.manager.AccountManager;
@Editable(order=200, icon="fa-user", category=GateKeeper.CATEGORY_USER, description=
@@ -36,7 +36,7 @@ public class IfApprovedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- public CheckResult doCheckRequest(PullRequest request) {
+ public GateCheckResult doCheckRequest(PullRequest request) {
Account user = Preconditions.checkNotNull(GitPlex.getInstance(AccountManager.class).find(userName));
PullRequestReview.Result result = user.checkReviewSince(request.getReferentialUpdate());
@@ -52,12 +52,12 @@ public class IfApprovedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return pending(Lists.newArrayList("Need approval from " + user.getName()));
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
return pending(Lists.newArrayList("Need approval from " + user.getName()));
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedTeam.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedTeam.java
index 37620e8b15..4d7a0f9fd8 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedTeam.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedTeam.java
@@ -12,7 +12,7 @@ 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.PullRequestReview;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
@Editable(order=300, icon="fa-group", category=GateKeeper.CATEGORY_USER, description=
"This gate keeper will be passed if the commit gets specified number "
@@ -36,7 +36,7 @@ public class IfDisapprovedBySpecifiedTeam extends TeamAwareGateKeeper {
}
@Override
- protected CheckResult doCheckRequest(PullRequest request) {
+ protected GateCheckResult doCheckRequest(PullRequest request) {
int disapprovals = 0;
Collection<Account> members = getTeamMembers(request.getTargetDepot().getAccount());
@@ -57,12 +57,12 @@ public class IfDisapprovedBySpecifiedTeam extends TeamAwareGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return failed(Lists.newArrayList("Not disapproved by anyone from team " + getTeamName()));
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit,
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit,
ObjectId newCommit) {
return failed(Lists.newArrayList("Not disapproved by anyone from team " + getTeamName()));
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
index 1ae4f50870..89d4542a8c 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfDisapprovedBySpecifiedUser.java
@@ -12,7 +12,7 @@ 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.PullRequestReview;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.manager.AccountManager;
@Editable(order=300, icon="fa-group", category=GateKeeper.CATEGORY_USER, description=
@@ -37,7 +37,7 @@ public class IfDisapprovedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckRequest(PullRequest request) {
+ protected GateCheckResult doCheckRequest(PullRequest request) {
Account user = Preconditions.checkNotNull(GitPlex.getInstance(AccountManager.class).find(userName));
PullRequestReview.Result result = user.checkReviewSince(request.getReferentialUpdate());
if (result == PullRequestReview.Result.DISAPPROVE) {
@@ -48,12 +48,12 @@ public class IfDisapprovedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return failed(Lists.newArrayList("Not disapproved by " + userName));
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit,
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit,
ObjectId newCommit) {
return failed(Lists.newArrayList("Not disapproved by " + userName));
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPerformSpecifiedOperations.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPerformSpecifiedOperations.java
index 3da5f53371..ed23afc435 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPerformSpecifiedOperations.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPerformSpecifiedOperations.java
@@ -1,125 +1,125 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.validation.ConstraintValidatorContext;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.google.common.collect.Lists;
-import com.pmease.commons.validation.ClassValidating;
-import com.pmease.commons.validation.Validatable;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-
-@Editable(order=200, icon="fa-wrench", description=
- "This gate keeper will be passed if one of specified operations is performed")
-@ClassValidating
-public class IfPerformSpecifiedOperations extends AbstractGateKeeper implements Validatable {
-
- private static final long serialVersionUID = 1L;
-
- private boolean createRef;
-
- private boolean updateRef;
-
- private boolean deleteRef;
-
- @Editable(order=100, description="Creates a ref such as branch, tag, etc.")
- public boolean isCreateRef() {
- return createRef;
- }
-
- public void setCreateRef(boolean createRef) {
- this.createRef = createRef;
- }
-
- @Editable(order=200, description="Updates a ref such as branch, tag, etc.")
- public boolean isUpdateRef() {
- return updateRef;
- }
-
- public void setUpdateRef(boolean updateRef) {
- this.updateRef = updateRef;
- }
-
- @Editable(order=300, description="Deletes a ref such as branch, tag, etc.")
- public boolean isDeleteRef() {
- return deleteRef;
- }
-
- public void setDeleteRef(boolean deleteRef) {
- this.deleteRef = deleteRef;
- }
-
- private CheckResult checkUpdate() {
- if (updateRef) {
- return passed(Lists.newArrayList("Ref is being updated"));
- }
- List<String> reasons = new ArrayList<>();
- if (deleteRef) {
- reasons.add("Ref is not being deleted");
- }
- if (createRef) {
- reasons.add("Ref is not being created");
- }
- return failed(reasons);
- }
-
- @Override
- public CheckResult doCheckRequest(PullRequest request) {
- return checkUpdate();
- }
-
- @Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
- return checkUpdate();
- }
-
- @Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
- if (oldCommit.equals(ObjectId.zeroId())) {
- if (createRef) {
- return passed(Lists.newArrayList("Ref is being created"));
- }
- List<String> reasons = new ArrayList<>();
- if (updateRef) {
- reasons.add("Ref is not being updated");
- }
- if (deleteRef) {
- reasons.add("Ref is not being deleted");
- }
- return failed(reasons);
- } else if (newCommit.equals(ObjectId.zeroId())) {
- if (deleteRef) {
- return passed(Lists.newArrayList("Ref is being deleted"));
- }
- List<String> reasons = new ArrayList<>();
- if (createRef) {
- reasons.add("Ref is not being created");
- }
- if (updateRef) {
- reasons.add("Ref is not being updated");
- }
- return failed(reasons);
- } else {
- return checkUpdate();
- }
- }
-
- @Override
- public boolean isValid(ConstraintValidatorContext context) {
- if (!createRef && !updateRef && !deleteRef) {
- context.disableDefaultConstraintViolation();
- context.buildConstraintViolationWithTemplate("Please select at least one operation").addConstraintViolation();
- return false;
- } else {
- return true;
- }
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.validation.ConstraintValidatorContext;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.google.common.collect.Lists;
+import com.pmease.commons.validation.ClassValidating;
+import com.pmease.commons.validation.Validatable;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+
+@Editable(order=200, icon="fa-wrench", description=
+ "This gate keeper will be passed if one of specified operations is performed")
+@ClassValidating
+public class IfPerformSpecifiedOperations extends AbstractGateKeeper implements Validatable {
+
+ private static final long serialVersionUID = 1L;
+
+ private boolean createRef;
+
+ private boolean updateRef;
+
+ private boolean deleteRef;
+
+ @Editable(order=100, description="Creates a ref such as branch, tag, etc.")
+ public boolean isCreateRef() {
+ return createRef;
+ }
+
+ public void setCreateRef(boolean createRef) {
+ this.createRef = createRef;
+ }
+
+ @Editable(order=200, description="Updates a ref such as branch, tag, etc.")
+ public boolean isUpdateRef() {
+ return updateRef;
+ }
+
+ public void setUpdateRef(boolean updateRef) {
+ this.updateRef = updateRef;
+ }
+
+ @Editable(order=300, description="Deletes a ref such as branch, tag, etc.")
+ public boolean isDeleteRef() {
+ return deleteRef;
+ }
+
+ public void setDeleteRef(boolean deleteRef) {
+ this.deleteRef = deleteRef;
+ }
+
+ private GateCheckResult checkUpdate() {
+ if (updateRef) {
+ return passed(Lists.newArrayList("Ref is being updated"));
+ }
+ List<String> reasons = new ArrayList<>();
+ if (deleteRef) {
+ reasons.add("Ref is not being deleted");
+ }
+ if (createRef) {
+ reasons.add("Ref is not being created");
+ }
+ return failed(reasons);
+ }
+
+ @Override
+ public GateCheckResult doCheckRequest(PullRequest request) {
+ return checkUpdate();
+ }
+
+ @Override
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ return checkUpdate();
+ }
+
+ @Override
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ if (oldCommit.equals(ObjectId.zeroId())) {
+ if (createRef) {
+ return passed(Lists.newArrayList("Ref is being created"));
+ }
+ List<String> reasons = new ArrayList<>();
+ if (updateRef) {
+ reasons.add("Ref is not being updated");
+ }
+ if (deleteRef) {
+ reasons.add("Ref is not being deleted");
+ }
+ return failed(reasons);
+ } else if (newCommit.equals(ObjectId.zeroId())) {
+ if (deleteRef) {
+ return passed(Lists.newArrayList("Ref is being deleted"));
+ }
+ List<String> reasons = new ArrayList<>();
+ if (createRef) {
+ reasons.add("Ref is not being created");
+ }
+ if (updateRef) {
+ reasons.add("Ref is not being updated");
+ }
+ return failed(reasons);
+ } else {
+ return checkUpdate();
+ }
+ }
+
+ @Override
+ public boolean isValid(ConstraintValidatorContext context) {
+ if (!createRef && !updateRef && !deleteRef) {
+ context.disableDefaultConstraintViolation();
+ context.buildConstraintViolationWithTemplate("Please select at least one operation").addConstraintViolation();
+ return false;
+ } else {
+ return true;
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
index 52d0901afa..34388f363d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfPushWithoutRewritingHistory.java
@@ -7,7 +7,7 @@ import com.pmease.commons.wicket.editable.annotation.Editable;
import com.pmease.gitplex.core.entity.Depot;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
@Editable(order=2000, icon="fa-ext fa-repo-lock", description="This gate keeper will be passed if the push "
+ "operation does not rewrite history of target branch. Rewriting history of public branches "
@@ -18,17 +18,17 @@ public class IfPushWithoutRewritingHistory extends AbstractGateKeeper {
private static final long serialVersionUID = 1L;
@Override
- protected CheckResult doCheckRequest(PullRequest request) {
+ protected GateCheckResult doCheckRequest(PullRequest request) {
return ignored();
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return ignored();
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
if (!oldCommit.equals(ObjectId.zeroId()) && !newCommit.equals(ObjectId.zeroId())) {
if (depot.isMergedInto(oldCommit.name(), newCommit.name()))
return passed(Lists.newArrayList("Push operation does not rewrite history"));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
index 8b1a8a2c02..1e8c726680 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmitWithGerritStylePatch.java
@@ -12,7 +12,7 @@ import com.pmease.commons.wicket.editable.annotation.Editable;
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.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
@Editable(order=3000, icon="fa-ext fa-file-diff", description="This gate keeper will be passed if the pull request "
+ "is submitted with gerrit style patch, that is, only one commit is submitted for review at "
@@ -22,7 +22,7 @@ public class IfSubmitWithGerritStylePatch extends AbstractGateKeeper {
private static final long serialVersionUID = 1L;
@Override
- protected CheckResult doCheckRequest(PullRequest request) {
+ protected GateCheckResult doCheckRequest(PullRequest request) {
String branchHead = request.getBaseCommitHash();
String requestHead = request.getLatestUpdate().getHeadCommitHash();
Depot depot = request.getTargetDepot();
@@ -40,12 +40,12 @@ public class IfSubmitWithGerritStylePatch extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return ignored();
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
return ignored();
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedTeam.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedTeam.java
index 0901388f9b..880c298d0d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedTeam.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedTeam.java
@@ -1,46 +1,46 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.util.Collection;
-
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.google.common.collect.Lists;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-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.gatekeeper.checkresult.CheckResult;
-
-@Editable(order=500, icon="fa-group", category=GateKeeper.CATEGORY_USER, description=
- "This gate keeper will be passed if the commit is submitted by a member of specified team")
-public class IfSubmittedBySpecifiedTeam extends TeamAwareGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public CheckResult doCheckRequest(PullRequest request) {
- return checkSubmitter(request.getSubmitter(), request.getTargetDepot().getAccount());
- }
-
- private CheckResult checkSubmitter(Account user, Account organization) {
- if (user != null) {
- Collection<Account> members = getTeamMembers(organization);
- if (members.contains(user)) {
- return passed(Lists.newArrayList("Submitted by a member of team " + getTeamName()));
- }
- }
- return failed(Lists.newArrayList("Not submitted by a member of team " + getTeamName()));
- }
-
- @Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName,
- ObjectId oldCommit, ObjectId newCommit) {
- return checkSubmitter(user, depot.getAccount());
- }
-
- @Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
- return checkSubmitter(user, depot.getAccount());
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.util.Collection;
+
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.google.common.collect.Lists;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+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.gatekeeper.checkresult.GateCheckResult;
+
+@Editable(order=500, icon="fa-group", category=GateKeeper.CATEGORY_USER, description=
+ "This gate keeper will be passed if the commit is submitted by a member of specified team")
+public class IfSubmittedBySpecifiedTeam extends TeamAwareGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public GateCheckResult doCheckRequest(PullRequest request) {
+ return checkSubmitter(request.getSubmitter(), request.getTargetDepot().getAccount());
+ }
+
+ private GateCheckResult checkSubmitter(Account user, Account organization) {
+ if (user != null) {
+ Collection<Account> members = getTeamMembers(organization);
+ if (members.contains(user)) {
+ return passed(Lists.newArrayList("Submitted by a member of team " + getTeamName()));
+ }
+ }
+ return failed(Lists.newArrayList("Not submitted by a member of team " + getTeamName()));
+ }
+
+ @Override
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName,
+ ObjectId oldCommit, ObjectId newCommit) {
+ return checkSubmitter(user, depot.getAccount());
+ }
+
+ @Override
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ return checkSubmitter(user, depot.getAccount());
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
index feca78aa3e..4f46caf0ac 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfSubmittedBySpecifiedUser.java
@@ -11,7 +11,7 @@ import com.pmease.gitplex.core.annotation.AccountChoice;
import com.pmease.gitplex.core.entity.Depot;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.manager.AccountManager;
@Editable(order=600, icon="fa-user", category=GateKeeper.CATEGORY_USER, description=
@@ -34,11 +34,11 @@ public class IfSubmittedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- public CheckResult doCheckRequest(PullRequest request) {
+ public GateCheckResult doCheckRequest(PullRequest request) {
return checkSubmitter(request.getSubmitter());
}
- private CheckResult checkSubmitter(Account user) {
+ private GateCheckResult checkSubmitter(Account user) {
Account expectedUser = Preconditions.checkNotNull(GitPlex.getInstance(AccountManager.class).find(userName));
if (expectedUser.equals(user))
return passed(Lists.newArrayList("Submitted by " + expectedUser.getDisplayName()));
@@ -47,12 +47,12 @@ public class IfSubmittedBySpecifiedUser extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
return checkSubmitter(user);
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
return checkSubmitter(user);
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfThenGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfThenGateKeeper.java
index 4a96fb0911..e2ddca770e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfThenGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfThenGateKeeper.java
@@ -1,113 +1,113 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Horizontal;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-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.Passed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-
-@Editable(name="If...Then... Composition", order=300, icon="fa-object-group",
- category=GateKeeper.CATEGORY_COMPOSITION,
- description="If first gate keeper is passed, then go ahead to check second gate keeper")
-@Horizontal
-public class IfThenGateKeeper extends CompositeGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- private GateKeeper ifGate = new DefaultGateKeeper();
-
- private GateKeeper thenGate = new DefaultGateKeeper();
-
- @Valid
- @NotNull
- public GateKeeper getIfGate() {
- return ifGate;
- }
-
- public void setIfGate(GateKeeper ifGate) {
- this.ifGate = ifGate;
- }
-
- @Valid
- @NotNull
- public GateKeeper getThenGate() {
- return thenGate;
- }
-
- public void setThenGate(GateKeeper thenGate) {
- this.thenGate = thenGate;
- }
-
- @Override
- protected CheckResult aggregate(Checker checker) {
- CheckResult ifResult = checker.check(getIfGate());
- if (ifResult instanceof Passed) {
- return checker.check(getThenGate());
- } else if (ifResult instanceof Failed) {
- return passed(ifResult.getReasons());
- } else if (ifResult instanceof Blocking) {
- return ifResult;
- } else if (ifResult instanceof Pending) {
- CheckResult thenResult = checker.check(getThenGate());
- if (thenResult instanceof Passed)
- return thenResult;
- else
- return ifResult;
- } else {
- return ifResult;
- }
- }
-
- @Override
- public void onDepotRename(Depot renamedDepot, String oldName) {
- ifGate.onDepotRename(renamedDepot, oldName);
- thenGate.onDepotRename(renamedDepot, oldName);
- }
-
- @Override
- public void onAccountRename(String oldName, String newName) {
- ifGate.onAccountRename(oldName, newName);
- thenGate.onAccountRename(oldName, newName);
- }
-
- @Override
- public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
- Account originalAccount) {
- return ifGate.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, originalAccount)
- || thenGate.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, originalAccount);
- }
-
- @Override
- public boolean onAccountDelete(String accountName) {
- return ifGate.onAccountDelete(accountName) || thenGate.onAccountDelete(accountName);
- }
-
- @Override
- public boolean onDepotDelete(Depot depot) {
- return ifGate.onDepotDelete(depot) || thenGate.onDepotDelete(depot);
- }
-
- @Override
- public void onTeamRename(String oldName, String newName) {
- ifGate.onTeamRename(oldName, newName);
- thenGate.onTeamRename(oldName, newName);
- }
-
- @Override
- public boolean onTeamDelete(String teamName) {
- return ifGate.onTeamDelete(teamName) || thenGate.onTeamDelete(teamName);
- }
-
- @Override
- public boolean onRefDelete(String refName) {
- return ifGate.onRefDelete(refName) || thenGate.onRefDelete(refName);
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Horizontal;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+
+@Editable(name="If...Then... Composition", order=300, icon="fa-object-group",
+ category=GateKeeper.CATEGORY_COMPOSITION,
+ description="If first gate keeper is passed, then go ahead to check second gate keeper")
+@Horizontal
+public class IfThenGateKeeper extends CompositeGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ private GateKeeper ifGate = new DefaultGateKeeper();
+
+ private GateKeeper thenGate = new DefaultGateKeeper();
+
+ @Valid
+ @NotNull
+ public GateKeeper getIfGate() {
+ return ifGate;
+ }
+
+ public void setIfGate(GateKeeper ifGate) {
+ this.ifGate = ifGate;
+ }
+
+ @Valid
+ @NotNull
+ public GateKeeper getThenGate() {
+ return thenGate;
+ }
+
+ public void setThenGate(GateKeeper thenGate) {
+ this.thenGate = thenGate;
+ }
+
+ @Override
+ protected GateCheckResult aggregate(Checker checker) {
+ GateCheckResult ifResult = checker.check(getIfGate());
+ if (ifResult instanceof Passed) {
+ return checker.check(getThenGate());
+ } else if (ifResult instanceof Failed) {
+ return passed(ifResult.getReasons());
+ } else if (ifResult instanceof Blocking) {
+ return ifResult;
+ } else if (ifResult instanceof Pending) {
+ GateCheckResult thenResult = checker.check(getThenGate());
+ if (thenResult instanceof Passed)
+ return thenResult;
+ else
+ return ifResult;
+ } else {
+ return ifResult;
+ }
+ }
+
+ @Override
+ public void onDepotRename(Depot renamedDepot, String oldName) {
+ ifGate.onDepotRename(renamedDepot, oldName);
+ thenGate.onDepotRename(renamedDepot, oldName);
+ }
+
+ @Override
+ public void onAccountRename(String oldName, String newName) {
+ ifGate.onAccountRename(oldName, newName);
+ thenGate.onAccountRename(oldName, newName);
+ }
+
+ @Override
+ public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
+ Account originalAccount) {
+ return ifGate.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, originalAccount)
+ || thenGate.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, originalAccount);
+ }
+
+ @Override
+ public boolean onAccountDelete(String accountName) {
+ return ifGate.onAccountDelete(accountName) || thenGate.onAccountDelete(accountName);
+ }
+
+ @Override
+ public boolean onDepotDelete(Depot depot) {
+ return ifGate.onDepotDelete(depot) || thenGate.onDepotDelete(depot);
+ }
+
+ @Override
+ public void onTeamRename(String oldName, String newName) {
+ ifGate.onTeamRename(oldName, newName);
+ thenGate.onTeamRename(oldName, newName);
+ }
+
+ @Override
+ public boolean onTeamDelete(String teamName) {
+ return ifGate.onTeamDelete(teamName) || thenGate.onTeamDelete(teamName);
+ }
+
+ @Override
+ public boolean onRefDelete(String refName) {
+ return ifGate.onRefDelete(refName) || thenGate.onRefDelete(refName);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
index 70185172ee..30b62b7dba 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedFiles.java
@@ -14,7 +14,7 @@ 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.PullRequestUpdate;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.util.ChildAwareMatcher;
import com.pmease.gitplex.core.util.ParentAwareMatcher;
import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;
@@ -47,7 +47,7 @@ public class IfTouchSpecifiedFiles extends AbstractGateKeeper {
}
@Override
- public CheckResult doCheckRequest(PullRequest request) {
+ public GateCheckResult doCheckRequest(PullRequest request) {
for (PullRequestUpdate update: request.getEffectiveUpdates()) {
for (String file: update.getChangedFiles()) {
if (matches(file)) {
@@ -61,7 +61,7 @@ public class IfTouchSpecifiedFiles extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
if (file != null) {
if (matches(file))
return passed(Lists.newArrayList("Touched files match '" + pathMatch + "'"));
@@ -73,7 +73,7 @@ public class IfTouchSpecifiedFiles extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
if (!oldCommit.equals(ObjectId.zeroId()) && !newCommit.equals(ObjectId.zeroId())) {
try (TreeWalk treeWalk = new TreeWalk(depot.getRepository())) {
treeWalk.addTree(depot.getRevCommit(oldCommit));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedRefs.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedRefs.java
index 30f287532b..9a79c5f6d2 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedRefs.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfTouchSpecifiedRefs.java
@@ -1,84 +1,84 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import org.eclipse.jgit.lib.ObjectId;
-import org.hibernate.validator.constraints.NotEmpty;
-
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.util.match.PatternMatcher;
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.gitplex.core.annotation.RefMatch;
-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.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.util.ChildAwareMatcher;
-import com.pmease.gitplex.core.util.ParentAwareMatcher;
-import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeParser;
-import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;
-
-@Editable(order=100, icon="fa-code-fork", description=
- "This gate keeper will be passed if specified refs is being touched")
-public class IfTouchSpecifiedRefs extends AbstractGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- private static final PatternMatcher INCLUDE_MATCHER = new ParentAwareMatcher();
-
- private static final PatternMatcher EXCLUDE_MATCHER = new ChildAwareMatcher();
-
- private String refMatch;
-
- @Editable(name="Refs to Match", order=100)
- @RefMatch
- @NotEmpty
- public String getRefMatch() {
- return refMatch;
- }
-
- public void setRefMatch(String refMatch) {
- this.refMatch = refMatch;
- }
-
- private CheckResult doCheck(String refName) {
- if (IncludeExcludeUtils.getIncludeExclude(refMatch).matches(INCLUDE_MATCHER, EXCLUDE_MATCHER, refName)) {
- return passed(Lists.newArrayList("Target ref matches '" + refMatch + "'"));
- } else {
- return failed(Lists.newArrayList("Target ref does not match '" + refMatch + "'"));
- }
- }
-
- @Override
- public CheckResult doCheckRequest(PullRequest request) {
- return doCheck(request.getTargetRef());
- }
-
- @Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
- return doCheck(GitUtils.branch2ref(branch));
- }
-
- @Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
- return doCheck(refName);
- }
-
- @Override
- public boolean onRefDelete(String refName) {
- StringBuilder builder = new StringBuilder();
- for (IncludeExcludeParser.CriteriaContext criteriaContext: IncludeExcludeUtils.parse(refMatch).criteria()) {
- if (criteriaContext.includeMatch() != null) {
- String value = IncludeExcludeUtils.getValue(criteriaContext.includeMatch().Value());
- if (!value.equals(refName))
- builder.append(String.format("include(%s) ", value));
- } else {
- String value = IncludeExcludeUtils.getValue(criteriaContext.excludeMatch().Value());
- if (!value.equals(refName))
- builder.append(String.format("exclude(%s) ", value));
- }
- }
- refMatch = builder.toString().trim();
- return refMatch.length() == 0;
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import org.eclipse.jgit.lib.ObjectId;
+import org.hibernate.validator.constraints.NotEmpty;
+
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.util.match.PatternMatcher;
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.gitplex.core.annotation.RefMatch;
+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.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.util.ChildAwareMatcher;
+import com.pmease.gitplex.core.util.ParentAwareMatcher;
+import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeParser;
+import com.pmease.gitplex.core.util.includeexclude.IncludeExcludeUtils;
+
+@Editable(order=100, icon="fa-code-fork", description=
+ "This gate keeper will be passed if specified refs is being touched")
+public class IfTouchSpecifiedRefs extends AbstractGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final PatternMatcher INCLUDE_MATCHER = new ParentAwareMatcher();
+
+ private static final PatternMatcher EXCLUDE_MATCHER = new ChildAwareMatcher();
+
+ private String refMatch;
+
+ @Editable(name="Refs to Match", order=100)
+ @RefMatch
+ @NotEmpty
+ public String getRefMatch() {
+ return refMatch;
+ }
+
+ public void setRefMatch(String refMatch) {
+ this.refMatch = refMatch;
+ }
+
+ private GateCheckResult doCheck(String refName) {
+ if (IncludeExcludeUtils.getIncludeExclude(refMatch).matches(INCLUDE_MATCHER, EXCLUDE_MATCHER, refName)) {
+ return passed(Lists.newArrayList("Target ref matches '" + refMatch + "'"));
+ } else {
+ return failed(Lists.newArrayList("Target ref does not match '" + refMatch + "'"));
+ }
+ }
+
+ @Override
+ public GateCheckResult doCheckRequest(PullRequest request) {
+ return doCheck(request.getTargetRef());
+ }
+
+ @Override
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ return doCheck(GitUtils.branch2ref(branch));
+ }
+
+ @Override
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ return doCheck(refName);
+ }
+
+ @Override
+ public boolean onRefDelete(String refName) {
+ StringBuilder builder = new StringBuilder();
+ for (IncludeExcludeParser.CriteriaContext criteriaContext: IncludeExcludeUtils.parse(refMatch).criteria()) {
+ if (criteriaContext.includeMatch() != null) {
+ String value = IncludeExcludeUtils.getValue(criteriaContext.includeMatch().Value());
+ if (!value.equals(refName))
+ builder.append(String.format("include(%s) ", value));
+ } else {
+ String value = IncludeExcludeUtils.getValue(criteriaContext.excludeMatch().Value());
+ if (!value.equals(refName))
+ builder.append(String.format("exclude(%s) ", value));
+ }
+ }
+ refMatch = builder.toString().trim();
+ return refMatch.length() == 0;
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
index 7a16df7e1f..cc723987e9 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/IfVerifiedByBuilds.java
@@ -14,7 +14,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.PullRequestVerification;
import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.manager.PullRequestVerificationManager;
@Editable(icon="fa-check-circle", order=1000,
@@ -64,7 +64,7 @@ public class IfVerifiedByBuilds extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckRequest(PullRequest request) {
+ protected GateCheckResult doCheckRequest(PullRequest request) {
if (request.isNew()) {
if (blockMode)
return blocking(Lists.newArrayList("To be verified by build"));
@@ -118,7 +118,7 @@ public class IfVerifiedByBuilds extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
+ protected GateCheckResult doCheckFile(Account user, Depot depot, String branch, String file) {
if (blockMode)
return blocking(Lists.newArrayList("Not verified by build"));
else
@@ -126,7 +126,7 @@ public class IfVerifiedByBuilds extends AbstractGateKeeper {
}
@Override
- protected CheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
+ protected GateCheckResult doCheckPush(Account user, Depot depot, String refName, ObjectId oldCommit, ObjectId newCommit) {
if (!oldCommit.equals(ObjectId.zeroId()) && !newCommit.equals(ObjectId.zeroId())) {
if (blockMode) {
return blocking(Lists.newArrayList("Has to be verified by builds"));
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/NotGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/NotGateKeeper.java
index c4bc5d7a11..d03ac4185b 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/NotGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/NotGateKeeper.java
@@ -1,86 +1,86 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import javax.validation.Valid;
-import javax.validation.constraints.NotNull;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Horizontal;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
-
-@Editable(name="Not Composition", order=400, icon="fa-object-group", category=GateKeeper.CATEGORY_COMPOSITION,
- description="This gate keeper will be passed if contained gate keeper is not passed")
-@Horizontal
-public class NotGateKeeper extends CompositeGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- private GateKeeper gateKeeper = new DefaultGateKeeper();
-
- @Valid
- @NotNull
- public GateKeeper getGateKeeper() {
- return gateKeeper;
- }
-
- public void setGateKeeper(GateKeeper gateKeeper) {
- this.gateKeeper = gateKeeper;
- }
-
- @Override
- protected CheckResult aggregate(Checker checker) {
- CheckResult result = checker.check(getGateKeeper());
-
- if (result instanceof Passed)
- return failed(result.getReasons());
- else if (result instanceof Failed)
- return passed(result.getReasons());
- else
- return result;
- }
-
- @Override
- public boolean onAccountDelete(String accountName) {
- return gateKeeper.onAccountDelete(accountName);
- }
-
- @Override
- public boolean onDepotDelete(Depot depot) {
- return gateKeeper.onDepotDelete(depot);
- }
-
- @Override
- public void onDepotRename(Depot renamedDepot, String oldName) {
- gateKeeper.onDepotRename(renamedDepot, oldName);
- }
-
- @Override
- public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
- Account origninalAccount) {
- return gateKeeper.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, origninalAccount);
- }
-
- @Override
- public void onAccountRename(String oldName, String newName) {
- gateKeeper.onAccountRename(oldName, newName);
- }
-
- @Override
- public void onTeamRename(String oldName, String newName) {
- gateKeeper.onTeamRename(oldName, newName);
- }
-
- @Override
- public boolean onTeamDelete(String teamName) {
- return gateKeeper.onTeamDelete(teamName);
- }
-
- @Override
- public boolean onRefDelete(String refName) {
- return gateKeeper.onRefDelete(refName);
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import javax.validation.Valid;
+import javax.validation.constraints.NotNull;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Horizontal;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
+
+@Editable(name="Not Composition", order=400, icon="fa-object-group", category=GateKeeper.CATEGORY_COMPOSITION,
+ description="This gate keeper will be passed if contained gate keeper is not passed")
+@Horizontal
+public class NotGateKeeper extends CompositeGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ private GateKeeper gateKeeper = new DefaultGateKeeper();
+
+ @Valid
+ @NotNull
+ public GateKeeper getGateKeeper() {
+ return gateKeeper;
+ }
+
+ public void setGateKeeper(GateKeeper gateKeeper) {
+ this.gateKeeper = gateKeeper;
+ }
+
+ @Override
+ protected GateCheckResult aggregate(Checker checker) {
+ GateCheckResult result = checker.check(getGateKeeper());
+
+ if (result instanceof Passed)
+ return failed(result.getReasons());
+ else if (result instanceof Failed)
+ return passed(result.getReasons());
+ else
+ return result;
+ }
+
+ @Override
+ public boolean onAccountDelete(String accountName) {
+ return gateKeeper.onAccountDelete(accountName);
+ }
+
+ @Override
+ public boolean onDepotDelete(Depot depot) {
+ return gateKeeper.onDepotDelete(depot);
+ }
+
+ @Override
+ public void onDepotRename(Depot renamedDepot, String oldName) {
+ gateKeeper.onDepotRename(renamedDepot, oldName);
+ }
+
+ @Override
+ public boolean onDepotTransfer(Depot depotDefiningGateKeeper, Depot transferredDepot,
+ Account origninalAccount) {
+ return gateKeeper.onDepotTransfer(depotDefiningGateKeeper, transferredDepot, origninalAccount);
+ }
+
+ @Override
+ public void onAccountRename(String oldName, String newName) {
+ gateKeeper.onAccountRename(oldName, newName);
+ }
+
+ @Override
+ public void onTeamRename(String oldName, String newName) {
+ gateKeeper.onTeamRename(oldName, newName);
+ }
+
+ @Override
+ public boolean onTeamDelete(String teamName) {
+ return gateKeeper.onTeamDelete(teamName);
+ }
+
+ @Override
+ public boolean onRefDelete(String refName) {
+ return gateKeeper.onRefDelete(refName);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/OrGateKeeper.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/OrGateKeeper.java
index 8497964f98..f0cfe51433 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/OrGateKeeper.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/OrGateKeeper.java
@@ -1,46 +1,46 @@
-package com.pmease.gitplex.core.gatekeeper;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.pmease.commons.wicket.editable.annotation.Editable;
-import com.pmease.commons.wicket.editable.annotation.Horizontal;
-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.Passed;
-import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
-
-@Editable(name="Or Composition", order=200, icon="fa-object-group", category=GateKeeper.CATEGORY_COMPOSITION,
- description="This gate keeper will be passed if any of the contained gate keepers is passed")
-@Horizontal
-public class OrGateKeeper extends AndOrGateKeeper {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected CheckResult aggregate(Checker checker) {
- List<String> pendingReasons = new ArrayList<String>();
- List<String> rejectReasons = new ArrayList<String>();
-
- for (GateKeeper each: getGateKeepers()) {
- CheckResult result = checker.check(each);
- if (result instanceof Failed) {
- rejectReasons.addAll(result.getReasons());
- } else if (result instanceof Passed) {
- return result;
- } else if (result instanceof Blocking) {
- result.getReasons().addAll(pendingReasons);
- return result;
- } else if (result instanceof Pending) {
- pendingReasons.addAll(result.getReasons());
- }
- }
-
- if (!pendingReasons.isEmpty())
- return pending(pendingReasons);
- else
- return failed(rejectReasons);
- }
-
-}
+package com.pmease.gitplex.core.gatekeeper;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import com.pmease.commons.wicket.editable.annotation.Editable;
+import com.pmease.commons.wicket.editable.annotation.Horizontal;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Blocking;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
+import com.pmease.gitplex.core.gatekeeper.checkresult.Pending;
+
+@Editable(name="Or Composition", order=200, icon="fa-object-group", category=GateKeeper.CATEGORY_COMPOSITION,
+ description="This gate keeper will be passed if any of the contained gate keepers is passed")
+@Horizontal
+public class OrGateKeeper extends AndOrGateKeeper {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ protected GateCheckResult aggregate(Checker checker) {
+ List<String> pendingReasons = new ArrayList<String>();
+ List<String> rejectReasons = new ArrayList<String>();
+
+ for (GateKeeper each: getGateKeepers()) {
+ GateCheckResult result = checker.check(each);
+ if (result instanceof Failed) {
+ rejectReasons.addAll(result.getReasons());
+ } else if (result instanceof Passed) {
+ return result;
+ } else if (result instanceof Blocking) {
+ result.getReasons().addAll(pendingReasons);
+ return result;
+ } else if (result instanceof Pending) {
+ pendingReasons.addAll(result.getReasons());
+ }
+ }
+
+ if (!pendingReasons.isEmpty())
+ return pending(pendingReasons);
+ else
+ return failed(rejectReasons);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Blocking.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Blocking.java
index d966644e38..a4f87bc59d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Blocking.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Blocking.java
@@ -7,7 +7,7 @@ import java.util.List;
* of this gate keeper has been determined.
*/
@SuppressWarnings("serial")
-public class Blocking extends CheckResult {
+public class Blocking extends GateCheckResult {
public Blocking(List<String> reasons) {
super(reasons);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Failed.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Failed.java
index de86063ba0..cee6979970 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Failed.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Failed.java
@@ -4,7 +4,7 @@ import java.util.List;
/* Reject the merge request. */
@SuppressWarnings("serial")
-public class Failed extends CheckResult {
+public class Failed extends GateCheckResult {
public Failed(List<String> reasons) {
super(reasons);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/CheckResult.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/GateCheckResult.java
similarity index 86%
rename from gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/CheckResult.java
rename to gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/GateCheckResult.java
index 7f54dab686..1988338eef 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/CheckResult.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/GateCheckResult.java
@@ -4,11 +4,11 @@ import java.io.Serializable;
import java.util.List;
@SuppressWarnings("serial")
-public abstract class CheckResult implements Serializable {
+public abstract class GateCheckResult implements Serializable {
private final List<String> reasons;
- public CheckResult(List<String> reasons) {
+ public GateCheckResult(List<String> reasons) {
this.reasons = reasons;
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Ignored.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Ignored.java
index b18b2a4f92..be07aa32f0 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Ignored.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Ignored.java
@@ -11,7 +11,7 @@ import java.util.ArrayList;
*
*/
@SuppressWarnings("serial")
-public class Ignored extends CheckResult {
+public class Ignored extends GateCheckResult {
public Ignored() {
super(new ArrayList<String>());
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Passed.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Passed.java
index 962ff61484..6c8308358d 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Passed.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Passed.java
@@ -3,7 +3,7 @@ package com.pmease.gitplex.core.gatekeeper.checkresult;
import java.util.List;
@SuppressWarnings("serial")
-public class Passed extends CheckResult {
+public class Passed extends GateCheckResult {
public Passed(List<String> reasons) {
super(reasons);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Pending.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Pending.java
index a103fb6b49..ae1ed76cbf 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Pending.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/gatekeeper/checkresult/Pending.java
@@ -4,7 +4,7 @@ import java.util.List;
/* merge request acceptance check is pending and result is unknown yet */
@SuppressWarnings("serial")
-public class Pending extends CheckResult {
+public class Pending extends GateCheckResult {
public Pending(List<String> reasons) {
super(reasons);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPostReceiveCallback.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPostReceiveCallback.java
index b47e63dc17..767975f34e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPostReceiveCallback.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPostReceiveCallback.java
@@ -1,133 +1,133 @@
-package com.pmease.gitplex.core.hookcallback;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.shiro.util.ThreadContext;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.RefUpdate;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.util.StringUtils;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.manager.DepotManager;
-
-@SuppressWarnings("serial")
-@Singleton
-public class GitPostReceiveCallback extends HttpServlet {
-
- private static final Logger logger = LoggerFactory.getLogger(GitPostReceiveCallback.class);
-
- public static final String PATH = "/git-postreceive-callback";
-
- private final DepotManager depotManager;
-
- private final ListenerRegistry listenerRegistry;
-
- private final UnitOfWork unitOfWork;
-
- @Inject
- public GitPostReceiveCallback(DepotManager depotManager, UnitOfWork unitOfWork, ListenerRegistry listenerRegistry) {
- this.depotManager = depotManager;
- this.unitOfWork = unitOfWork;
- this.listenerRegistry = listenerRegistry;
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- String clientIp = request.getHeader("X-Forwarded-For");
- if (clientIp == null) clientIp = request.getRemoteAddr();
-
- if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
- response.sendError(HttpServletResponse.SC_FORBIDDEN,
- "Git hook callbacks can only be accessed from localhost.");
- return;
- }
-
- List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/");
- Preconditions.checkState(fields.size() == 2);
-
- Long depotId = Long.valueOf(fields.get(0));
- Long userId = Long.valueOf(fields.get(1));
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- IOUtils.copy(request.getInputStream(), baos);
-
- /*
- * If multiple refs are updated, the hook stdin will put each ref update info into
- * a separate line, however the line breaks is omitted when forward the hook stdin
- * to curl via "@-", below logic is used to parse these info correctly even
- * without line breaks.
- */
- String callbackData = new String(baos.toByteArray());
- callbackData = StringUtils.reverse(StringUtils.remove(callbackData, '\n'));
-
- fields.clear();
- fields.addAll(StringUtils.splitAndTrim(callbackData, " "));
-
- unitOfWork.doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(Account.asSubject(userId));
- try {
- Depot depot = depotManager.load(depotId);
-
- int pos = 0;
- while (true) {
- String refName = StringUtils.reverse(fields.get(pos));
- pos++;
- ObjectId newCommit = ObjectId.fromString(StringUtils.reverse(fields.get(pos)));
- pos++;
- String field = fields.get(pos);
- ObjectId oldCommit = ObjectId.fromString(StringUtils.reverse(field.substring(0, 40)));
-
- if (!newCommit.equals(ObjectId.zeroId())) {
- depot.cacheObjectId(refName, newCommit);
- } else {
- newCommit = ObjectId.zeroId();
- depot.cacheObjectId(refName, null);
- }
-
- String branch = GitUtils.ref2branch(refName);
- if (branch != null && depot.getDefaultBranch() == null) {
- RefUpdate refUpdate = depot.updateRef("HEAD");
- GitUtils.linkRef(refUpdate, refName);
- }
-
- listenerRegistry.notify(new RefUpdated(depot, refName, oldCommit, newCommit));
-
- field = field.substring(40);
- if (field.length() == 0)
- break;
- else
- fields.set(pos, field);
- }
- } catch (Exception e) {
- logger.error("Error executing post-receive callback", e);
- } finally {
- ThreadContext.unbindSubject();
- }
- }
-
- });
- }
-
-}
+package com.pmease.gitplex.core.hookcallback;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServlet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.shiro.util.ThreadContext;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.RefUpdate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.util.StringUtils;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.manager.DepotManager;
+
+@SuppressWarnings("serial")
+@Singleton
+public class GitPostReceiveCallback extends HttpServlet {
+
+ private static final Logger logger = LoggerFactory.getLogger(GitPostReceiveCallback.class);
+
+ public static final String PATH = "/git-postreceive-callback";
+
+ private final DepotManager depotManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final UnitOfWork unitOfWork;
+
+ @Inject
+ public GitPostReceiveCallback(DepotManager depotManager, UnitOfWork unitOfWork, ListenerRegistry listenerRegistry) {
+ this.depotManager = depotManager;
+ this.unitOfWork = unitOfWork;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Override
+ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ String clientIp = request.getHeader("X-Forwarded-For");
+ if (clientIp == null) clientIp = request.getRemoteAddr();
+
+ if (!InetAddress.getByName(clientIp).isLoopbackAddress()) {
+ response.sendError(HttpServletResponse.SC_FORBIDDEN,
+ "Git hook callbacks can only be accessed from localhost.");
+ return;
+ }
+
+ List<String> fields = StringUtils.splitAndTrim(request.getPathInfo(), "/");
+ Preconditions.checkState(fields.size() == 2);
+
+ Long depotId = Long.valueOf(fields.get(0));
+ Long userId = Long.valueOf(fields.get(1));
+
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ IOUtils.copy(request.getInputStream(), baos);
+
+ /*
+ * If multiple refs are updated, the hook stdin will put each ref update info into
+ * a separate line, however the line breaks is omitted when forward the hook stdin
+ * to curl via "@-", below logic is used to parse these info correctly even
+ * without line breaks.
+ */
+ String callbackData = new String(baos.toByteArray());
+ callbackData = StringUtils.reverse(StringUtils.remove(callbackData, '\n'));
+
+ fields.clear();
+ fields.addAll(StringUtils.splitAndTrim(callbackData, " "));
+
+ unitOfWork.doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(Account.asSubject(userId));
+ try {
+ Depot depot = depotManager.load(depotId);
+
+ int pos = 0;
+ while (true) {
+ String refName = StringUtils.reverse(fields.get(pos));
+ pos++;
+ ObjectId newCommit = ObjectId.fromString(StringUtils.reverse(fields.get(pos)));
+ pos++;
+ String field = fields.get(pos);
+ ObjectId oldCommit = ObjectId.fromString(StringUtils.reverse(field.substring(0, 40)));
+
+ if (!newCommit.equals(ObjectId.zeroId())) {
+ depot.cacheObjectId(refName, newCommit);
+ } else {
+ newCommit = ObjectId.zeroId();
+ depot.cacheObjectId(refName, null);
+ }
+
+ String branch = GitUtils.ref2branch(refName);
+ if (branch != null && depot.getDefaultBranch() == null) {
+ RefUpdate refUpdate = depot.updateRef("HEAD");
+ GitUtils.linkRef(refUpdate, refName);
+ }
+
+ listenerRegistry.post(new RefUpdated(depot, refName, oldCommit, newCommit));
+
+ field = field.substring(40);
+ if (field.length() == 0)
+ break;
+ else
+ fields.set(pos, field);
+ }
+ } catch (Exception e) {
+ logger.error("Error executing post-receive callback", e);
+ } finally {
+ ThreadContext.unbindSubject();
+ }
+ }
+
+ });
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPreReceiveCallback.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPreReceiveCallback.java
index 8d502cc41c..293e9fe315 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPreReceiveCallback.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/hookcallback/GitPreReceiveCallback.java
@@ -24,7 +24,7 @@ import com.pmease.commons.util.StringUtils;
import com.pmease.gitplex.core.entity.Account;
import com.pmease.gitplex.core.entity.Depot;
import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
import com.pmease.gitplex.core.gatekeeper.checkresult.Failed;
import com.pmease.gitplex.core.gatekeeper.checkresult.Passed;
import com.pmease.gitplex.core.manager.AccountManager;
@@ -114,7 +114,7 @@ public class GitPreReceiveCallback extends HttpServlet {
}
} else {
GateKeeper gateKeeper = depot.getGateKeeper();
- CheckResult checkResult = gateKeeper.checkPush(user, depot, refName, oldCommit, newCommit);
+ GateCheckResult checkResult = gateKeeper.checkPush(user, depot, refName, oldCommit, newCommit);
if (!(checkResult instanceof Passed)) {
List<String> messages = new ArrayList<>();
for (String each: checkResult.getReasons())
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/BranchWatchManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/BranchWatchManager.java
index 21e349abe3..deeb0528e8 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/BranchWatchManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/BranchWatchManager.java
@@ -12,5 +12,5 @@ public interface BranchWatchManager extends EntityManager<BranchWatch> {
Collection<BranchWatch> find(Account user, Depot depot);
Collection<BranchWatch> find(Depot depot, String branch);
-
+
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentReplyManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentReplyManager.java
index e315e58177..1bc3497a5a 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentReplyManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/CodeCommentReplyManager.java
@@ -5,6 +5,6 @@ import com.pmease.gitplex.core.entity.CodeCommentReply;
public interface CodeCommentReplyManager extends EntityManager<CodeCommentReply> {
- void save(CodeCommentReply reply, boolean notifyListeners);
+ void save(CodeCommentReply reply, boolean callListeners);
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/MailManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/MailManager.java
index af4f17af56..8ed9b527cc 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/MailManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/MailManager.java
@@ -1,16 +1,16 @@
-package com.pmease.gitplex.core.manager;
-
-import java.util.Collection;
-
-import javax.annotation.Nullable;
-
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.setting.MailSetting;
-
-public interface MailManager {
-
- void sendMailNow(@Nullable MailSetting mailSetting, Collection<Account> toList, String subject, String body);
-
- void sendMail(Collection<Account> toList, String subject, String body);
-
-}
+package com.pmease.gitplex.core.manager;
+
+import java.util.Collection;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.setting.MailSetting;
+
+public interface MailManager {
+
+ void sendMail(Collection<Account> toList, String subject, String body);
+
+ void sendMail(MailSetting mailSetting, Collection<Account> toList, String subject, String body);
+
+ void sendMailAsync(Collection<Account> toList, String subject, String body);
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/NotificationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestNotificationManager.java
similarity index 62%
rename from gitplex.core/src/main/java/com/pmease/gitplex/core/manager/NotificationManager.java
rename to gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestNotificationManager.java
index 187e0fe512..7b6423cf35 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/NotificationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestNotificationManager.java
@@ -3,6 +3,6 @@ package com.pmease.gitplex.core.manager;
import com.pmease.commons.hibernate.dao.EntityManager;
import com.pmease.gitplex.core.entity.PullRequestNotification;
-public interface NotificationManager extends EntityManager<PullRequestNotification> {
+public interface PullRequestNotificationManager extends EntityManager<PullRequestNotification> {
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
index 128e7ab84f..7b004670c7 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestUpdateManager.java
@@ -10,7 +10,7 @@ import com.pmease.gitplex.core.entity.PullRequestUpdate;
public interface PullRequestUpdateManager extends EntityManager<PullRequestUpdate> {
- void save(PullRequestUpdate update, boolean notifyListeners);
+ void save(PullRequestUpdate update, boolean callListeners);
@Nullable
PullRequestUpdate find(String uuid);
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestWatchManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestWatchManager.java
new file mode 100644
index 0000000000..e5a80a95a7
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/PullRequestWatchManager.java
@@ -0,0 +1,8 @@
+package com.pmease.gitplex.core.manager;
+
+import com.pmease.commons.hibernate.dao.EntityManager;
+import com.pmease.gitplex.core.entity.PullRequestWatch;
+
+public interface PullRequestWatchManager extends EntityManager<PullRequestWatch> {
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/UrlManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/UrlManager.java
index 506b2c23a3..e79133e3b0 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/UrlManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/UrlManager.java
@@ -1,17 +1,18 @@
-package com.pmease.gitplex.core.manager;
-
-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.PullRequestComment;
-
-public interface UrlManager {
-
- String urlFor(Account user);
-
- String urlFor(Depot depot);
-
- String urlFor(PullRequest request);
-
- String urlFor(PullRequestComment comment);
-}
+package com.pmease.gitplex.core.manager;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+
+public interface UrlManager {
+
+ String urlFor(Account user);
+
+ String urlFor(Depot depot);
+
+ String urlFor(PullRequest request);
+
+ String urlFor(CodeComment comment);
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentManager.java
index 7ebd26a5c5..78b2417430 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentManager.java
@@ -21,32 +21,41 @@ 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.wicket.editable.EditableUtils;
import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentRelation;
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.LastEvent;
-import com.pmease.gitplex.core.event.codecomment.CodeCommentCreated;
+import com.pmease.gitplex.core.event.codecomment.CodeCommentEvent;
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.codecomment.CodeCommentCreated;
+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.manager.CodeCommentManager;
import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
@Singleton
public class DefaultCodeCommentManager extends AbstractEntityManager<CodeComment> implements CodeCommentManager {
private final ListenerRegistry listenerRegistry;
- private final CodeCommentStatusChangeManager codeCommentActivityManager;
+ private final CodeCommentStatusChangeManager codeCommentStatusChangeManager;
+
+ private final PullRequestManager pullRequestManager;
@Inject
public DefaultCodeCommentManager(Dao dao, ListenerRegistry listenerRegistry,
- CodeCommentStatusChangeManager codeCommentActivityManager) {
+ CodeCommentStatusChangeManager codeCommentStatusChangeManager, PullRequestManager pullRequestManager) {
super(dao);
this.listenerRegistry = listenerRegistry;
- this.codeCommentActivityManager = codeCommentActivityManager;
+ this.codeCommentStatusChangeManager = codeCommentStatusChangeManager;
+ this.pullRequestManager = pullRequestManager;
}
@Sessional
@@ -86,7 +95,7 @@ public class DefaultCodeCommentManager extends AbstractEntityManager<CodeComment
}
dao.persist(comment);
if (event != null) {
- listenerRegistry.notify(event);
+ listenerRegistry.post(event);
}
}
@@ -123,39 +132,47 @@ public class DefaultCodeCommentManager extends AbstractEntityManager<CodeComment
@Override
public void changeStatus(CodeCommentStatusChange statusChange) {
statusChange.getComment().setResolved(statusChange.isResolved());
- save(statusChange.getComment());
- codeCommentActivityManager.save(statusChange);
+ codeCommentStatusChangeManager.save(statusChange);
- if (statusChange.isResolved())
- listenerRegistry.notify(new CodeCommentResolved(statusChange.getComment(), statusChange.getUser()));
- else
- listenerRegistry.notify(new CodeCommentUnresolved(statusChange.getComment(), statusChange.getUser()));
+ CodeCommentEvent event;
+ if (statusChange.isResolved()) {
+ event = new CodeCommentResolved(statusChange);
+ } else {
+ event = new CodeCommentUnresolved(statusChange);
+ }
+ listenerRegistry.post(event);
+ statusChange.getComment().setLastEvent(event);
+ save(statusChange.getComment());
}
@Transactional
@Listen
public void on(CodeCommentReplied event) {
CodeCommentReply reply = event.getReply();
- CodeComment comment = reply.getComment();
- LastEvent lastEvent = new LastEvent();
- lastEvent.setDate(reply.getDate());
- lastEvent.setDescription(EditableUtils.getName(event.getClass()));
- lastEvent.setUser(reply.getUser());
- comment.setLastEvent(lastEvent);
- save(comment);
+
+ for (CodeCommentRelation relation: reply.getComment().getRelations()) {
+ PullRequest request = relation.getRequest();
+ PullRequestCodeCommentReplied pullRequestCodeCommentReplied =
+ new PullRequestCodeCommentReplied(request, reply);
+ listenerRegistry.post(pullRequestCodeCommentReplied);
+ request.setLastEvent(pullRequestCodeCommentReplied);
+ pullRequestManager.save(request);
+ }
+
}
@Transactional
@Listen
public void on(CodeCommentResolved event) {
- CodeComment comment = event.getComment();
- LastEvent lastEvent = new LastEvent();
- lastEvent.setDate(new Date());
- lastEvent.setDescription(EditableUtils.getName(event.getClass()));
- lastEvent.setUser(event.getUser());
- comment.setLastEvent(lastEvent);
- save(comment);
+ for (CodeCommentRelation relation: event.getComment().getRelations()) {
+ PullRequest request = relation.getRequest();
+ PullRequestCodeCommentResolved pullRequestCodeCommentResolved =
+ new PullRequestCodeCommentResolved(request, event.getStatusChange());
+ listenerRegistry.post(pullRequestCodeCommentResolved);
+ request.setLastEvent(pullRequestCodeCommentResolved);
+ pullRequestManager.save(request);
+ }
}
@Transactional
@@ -164,10 +181,19 @@ public class DefaultCodeCommentManager extends AbstractEntityManager<CodeComment
CodeComment comment = event.getComment();
LastEvent lastEvent = new LastEvent();
lastEvent.setDate(new Date());
- lastEvent.setDescription(EditableUtils.getName(event.getClass()));
+ lastEvent.setType(event.getClass());
lastEvent.setUser(event.getUser());
comment.setLastEvent(lastEvent);
save(comment);
+
+ for (CodeCommentRelation relation: event.getComment().getRelations()) {
+ PullRequest request = relation.getRequest();
+ PullRequestCodeCommentUnresolved pullRequestCodeCommentUnresolved =
+ new PullRequestCodeCommentUnresolved(request, event.getStatusChange());
+ listenerRegistry.post(pullRequestCodeCommentUnresolved);
+ request.setLastEvent(pullRequestCodeCommentUnresolved);
+ pullRequestManager.save(request);
+ }
}
}
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.java
index 015aef54ff..74c97708cf 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,173 +1,171 @@
-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);
- }
- }
- }
-
-}
+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.loader.ListenerRegistry;
+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.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;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultCodeCommentRelationManager(Dao dao, PullRequestInfoManager pullRequestInfoManager,
+ CodeCommentInfoManager codeCommentInfoManager, CodeCommentManager codeCommentManager,
+ PullRequestManager pullRequestManager, VisitInfoManager visitInfoManager,
+ ListenerRegistry listenerRegistry) {
+ super(dao);
+ this.pullRequestInfoManager = pullRequestInfoManager;
+ this.codeCommentInfoManager = codeCommentInfoManager;
+ this.codeCommentManager = codeCommentManager;
+ this.pullRequestManager = pullRequestManager;
+ this.visitInfoManager = visitInfoManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ /*
+ * 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())) {
+ PullRequestCodeCommented event = new PullRequestCodeCommented(request, comment);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ 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) {
+ PullRequestCodeCommented pullRequestCodeCommented = new PullRequestCodeCommented(request, comment);
+ listenerRegistry.post(pullRequestCodeCommented);
+ request.setLastEvent(pullRequestCodeCommented);
+ 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/DefaultCodeCommentReplyManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentReplyManager.java
index bae73dafcb..b0b5561ab3 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentReplyManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultCodeCommentReplyManager.java
@@ -9,6 +9,7 @@ import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.loader.ListenerRegistry;
import com.pmease.gitplex.core.entity.CodeCommentReply;
import com.pmease.gitplex.core.event.codecomment.CodeCommentReplied;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
import com.pmease.gitplex.core.manager.CodeCommentReplyManager;
@Singleton
@@ -17,19 +18,25 @@ public class DefaultCodeCommentReplyManager extends AbstractEntityManager<CodeCo
private final ListenerRegistry listenerRegistry;
+ private final CodeCommentManager codeCommentManager;
+
@Inject
- public DefaultCodeCommentReplyManager(Dao dao, ListenerRegistry listenerRegistry) {
+ public DefaultCodeCommentReplyManager(Dao dao, ListenerRegistry listenerRegistry, CodeCommentManager codeCommentManager) {
super(dao);
this.listenerRegistry = listenerRegistry;
+ this.codeCommentManager = codeCommentManager;
}
@Transactional
@Override
- public void save(CodeCommentReply reply, boolean notifyListeners) {
+ public void save(CodeCommentReply reply, boolean callListeners) {
boolean isNew = reply.isNew();
dao.persist(reply);
- if (isNew && notifyListeners) {
- listenerRegistry.notify(new CodeCommentReplied(reply));
+ if (isNew && callListeners) {
+ CodeCommentReplied event = new CodeCommentReplied(reply);
+ listenerRegistry.post(event);
+ reply.getComment().setLastEvent(event);
+ codeCommentManager.save(reply.getComment());
}
}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
index 3f13ad565b..a4342eef77 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultDepotManager.java
@@ -1,460 +1,460 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.stream.Collectors;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.io.IOUtils;
-import org.eclipse.jgit.api.Git;
-import org.eclipse.jgit.internal.storage.file.FileRepository;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.hibernate.Query;
-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.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.git.command.CloneCommand;
-import com.pmease.commons.hibernate.Sessional;
-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.loader.ListenerRegistry;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.Pair;
-import com.pmease.commons.util.StringUtils;
-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.Team;
-import com.pmease.gitplex.core.entity.TeamAuthorization;
-import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.event.depot.DepotDeleted;
-import com.pmease.gitplex.core.event.depot.DepotRenamed;
-import com.pmease.gitplex.core.event.depot.DepotTransferred;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
-import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
-import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
-import com.pmease.gitplex.core.gatekeeper.GateKeeper;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.CodeCommentInfoManager;
-import com.pmease.gitplex.core.manager.CommitInfoManager;
-import com.pmease.gitplex.core.manager.DepotManager;
-import com.pmease.gitplex.core.manager.PullRequestInfoManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.TeamAuthorizationManager;
-import com.pmease.gitplex.core.security.privilege.DepotPrivilege;
-
-@Singleton
-public class DefaultDepotManager extends AbstractEntityManager<Depot> implements DepotManager {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultDepotManager.class);
-
- private final ListenerRegistry listenerRegistry;
-
- private final StorageManager storageManager;
-
- private final AccountManager userManager;
-
- private final CommitInfoManager commitInfoManager;
-
- private final PullRequestInfoManager pullRequestInfoManager;
-
- private final CodeCommentInfoManager codeCommentInfoManager;
-
- private final PullRequestManager pullRequestManager;
-
- private final TeamAuthorizationManager teamAuthorizationManager;
-
- private final String gitReceiveHook;
-
- private final BiMap<Pair<Long, String>, Long> nameToId = HashBiMap.create();
-
- private final ReadWriteLock idLock = new ReentrantReadWriteLock();
-
- private final Map<Long, Repository> repositoryCache = new ConcurrentHashMap<>();
-
- @Inject
- public DefaultDepotManager(Dao dao, AccountManager userManager, CodeCommentInfoManager codeCommentInfoManager,
- TeamAuthorizationManager teamAuthorizationManager, PullRequestInfoManager pullRequestInfoManager,
- StorageManager storageManager, CommitInfoManager commitInfoManager,
- PullRequestManager pullRequestManager, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.storageManager = storageManager;
- this.userManager = userManager;
- this.pullRequestInfoManager = pullRequestInfoManager;
- this.teamAuthorizationManager = teamAuthorizationManager;
- this.commitInfoManager = commitInfoManager;
- this.codeCommentInfoManager = codeCommentInfoManager;
- this.pullRequestManager = pullRequestManager;
- this.listenerRegistry = listenerRegistry;
-
- try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-receive-hook")) {
- Preconditions.checkNotNull(is);
- gitReceiveHook = StringUtils.join(IOUtils.readLines(is), "\n");
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- }
-
- @Override
- public Repository getRepository(Depot depot) {
- Repository repository = repositoryCache.get(depot.getId());
- if (repository == null) {
- synchronized (repositoryCache) {
- repository = repositoryCache.get(depot.getId());
- if (repository == null) {
- try {
- repository = new FileRepository(depot.getDirectory());
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- repositoryCache.put(depot.getId(), repository);
- }
- }
- }
- return repository;
- }
-
- @Transactional
- @Override
- public void save(Depot depot, Long oldAccountId, String oldName) {
- Preconditions.checkArgument(oldAccountId==null || oldName==null,
- "Can not rename and transfer depot in the same time");
-
- boolean isNew = depot.isNew();
-
- dao.persist(depot);
-
- if (oldAccountId != null && !depot.getAccount().getId().equals(oldAccountId)) {
- Account oldAccount = userManager.load(oldAccountId);
- listenerRegistry.notify(new DepotTransferred(depot, oldAccount));
-
- for (Depot each: findAll()) {
- for (IntegrationPolicy policy: each.getIntegrationPolicies()) {
- policy.onDepotTransfer(depot, oldAccount);
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onDepotTransfer(each, depot, oldAccount))
- it.remove();
- }
- }
- }
- if (oldName != null && !depot.getName().equals(oldName)) {
- listenerRegistry.notify(new DepotRenamed(depot, oldName));
-
- for (Depot each: findAll()) {
- for (IntegrationPolicy integrationPolicy: each.getIntegrationPolicies()) {
- integrationPolicy.onDepotRename(depot.getAccount(), oldName, depot.getName());
- }
- for (GateKeeper gateKeeper: each.getGateKeepers()) {
- gateKeeper.onDepotRename(depot, oldName);
- }
- }
- }
-
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- idLock.writeLock().lock();
- try {
- nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
- } finally {
- idLock.writeLock().unlock();
- }
- if (isNew) {
- checkSanity(depot);
- commitInfoManager.collect(depot);
- }
- }
-
- });
- }
-
- @Transactional
- @Override
- public void delete(Depot depot) {
- Query query = getSession().createQuery("update Depot set forkedFrom=null where forkedFrom=:forkedFrom");
- query.setParameter("forkedFrom", depot);
- query.executeUpdate();
-
- dao.remove(depot);
-
- for (Depot each: findAll()) {
- for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
- if (it.next().onDepotDelete(depot))
- it.remove();
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onDepotDelete(depot))
- it.remove();
- }
- }
-
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- idLock.writeLock().lock();
- try {
- nameToId.inverse().remove(depot.getId());
- } finally {
- idLock.writeLock().unlock();
- }
- getRepository(depot).close();
- repositoryCache.remove(depot.getId());
-
- FileUtils.deleteDir(storageManager.getGitDir(depot));
- }
-
- });
-
- listenerRegistry.notify(new DepotDeleted(depot));
- }
-
- @Sessional
- @Override
- public Depot find(String accountName, String depotName) {
- Account user = userManager.find(accountName);
- if (user != null)
- return find(user, depotName);
- else
- return null;
- }
-
- @Sessional
- @Override
- public Depot find(Account account, String depotName) {
- idLock.readLock().lock();
- try {
- Long id = nameToId.get(new Pair<>(account.getId(), depotName));
- if (id != null)
- return load(id);
- else
- return null;
- } finally {
- idLock.readLock().unlock();
- }
- }
-
- @Sessional
- @Override
- public Depot find(String depotFQN) {
- String userName = StringUtils.substringBefore(depotFQN, Depot.FQN_SEPARATOR);
- Account user = userManager.find(userName);
- if (user != null)
- return find(user, StringUtils.substringAfter(depotFQN, Depot.FQN_SEPARATOR));
- else
- return null;
- }
-
- @Transactional
- @Override
- public Depot fork(Depot depot, Account user) {
- if (depot.getAccount().equals(user))
- return depot;
-
- Depot forked = null;
- for (Depot each: user.getDepots()) {
- if (depot.equals(each.getForkedFrom())) {
- forked = each;
- break;
- }
- }
- if (forked == null) {
- Set<String> existingNames = new HashSet<>();
- for (Depot each: user.getDepots())
- existingNames.add(each.getName());
-
- forked = new Depot();
- forked.setAccount(user);
- forked.setForkedFrom(depot);
- if (existingNames.contains(depot.getName())) {
- int suffix = 1;
- while (existingNames.contains(depot.getName() + "_" + suffix))
- suffix++;
- forked.setName(depot.getName() + "_" + suffix);
- } else {
- forked.setName(depot.getName());
- }
-
- dao.persist(forked);
-
- FileUtils.cleanDir(forked.getDirectory());
- new CloneCommand(forked.getDirectory()).bare(true).from(depot.getDirectory().getAbsolutePath()).call();
- }
-
- return forked;
- }
-
- private void checkSanity(Depot depot) {
- logger.info("Checking sanity of repository '{}'...", depot);
-
- File gitDir = depot.getDirectory();
- if (depot.getDirectory().exists() && !GitUtils.isValid(gitDir)) {
- logger.warn("Directory '" + gitDir + "' is not a valid git repository, removing...");
- FileUtils.deleteDir(gitDir);
- }
-
- if (!gitDir.exists()) {
- logger.warn("Initializing git repository in '" + gitDir + "'...");
- FileUtils.createDir(gitDir);
- try {
- Git.init().setDirectory(gitDir).setBare(true).call();
- } catch (Exception e) {
- Throwables.propagate(e);
- }
- }
-
- if (!depot.isValid()) {
- File hooksDir = new File(gitDir, "hooks");
-
- File gitPreReceiveHookFile = new File(hooksDir, "pre-receive");
- FileUtils.writeFile(gitPreReceiveHookFile, String.format(gitReceiveHook, "git-prereceive-callback"));
- gitPreReceiveHookFile.setExecutable(true);
-
- File gitPostReceiveHookFile = new File(hooksDir, "post-receive");
- FileUtils.writeFile(gitPostReceiveHookFile, String.format(gitReceiveHook, "git-postreceive-callback"));
- gitPostReceiveHookFile.setExecutable(true);
- }
- }
-
- @Sessional
- @Listen
- public void on(SystemStarting event) {
- for (Depot depot: findAll())
- nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
- }
-
- @Transactional
- @Listen
- public void on(SystemStarted event) {
- for (Depot depot: findAll()) {
- checkSanity(depot);
- commitInfoManager.collect(depot);
- pullRequestInfoManager.collect(depot);
- codeCommentInfoManager.collect(depot);
- }
-
- pullRequestManager.checkSanity();
- }
-
- @Listen
- public void on(SystemStopping event) {
- synchronized(repositoryCache) {
- for (Repository repository: repositoryCache.values()) {
- repository.close();
- }
- }
- }
-
- @Transactional
- @Listen
- public void on(RefUpdated event) {
- if (event.getNewCommit().equals(ObjectId.zeroId())) {
- String branch = GitUtils.ref2branch(event.getRefName());
- for (Depot each: findAll()) {
- if (branch != null) {
- for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
- if (it.next().onBranchDelete(each, event.getDepot(), branch))
- it.remove();
- }
- }
- for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
- if (it.next().onRefDelete(event.getRefName()))
- it.remove();
- }
- }
- }
- }
-
- @Sessional
- @Override
- public Collection<Depot> findAllAccessible(Account account, Account user) {
- Collection<Depot> depots;
- if (account == null)
- depots = GitPlex.getInstance(DepotManager.class).findAll();
- else
- depots = account.getDepots();
-
- if (user == null) {
- return depots.stream().filter((depot)->depot.isPublicRead()).collect(Collectors.toSet());
- } else if (user.isAdministrator() || user.equals(account)) {
- return depots;
- } else {
- Collection<Account> adminOrganizations = user.getOrganizations()
- .stream()
- .filter((membership)->membership.isAdmin())
- .map((membership)->membership.getOrganization())
- .collect(Collectors.toSet());
-
- // return fast in special cases
- if (adminOrganizations.contains(account)) {
- return depots;
- }
-
- Collection<Account> memberOrganizations = user.getOrganizations()
- .stream()
- .filter((membership)->!membership.isAdmin())
- .map((membership)->membership.getOrganization())
- .collect(Collectors.toSet());
-
- // return fast in special cases
- if (memberOrganizations.contains(account) && account.getDefaultPrivilege() != DepotPrivilege.NONE) {
- return depots;
- }
-
- Collection<Depot> authorizedDepots = user.getAuthorizedDepots()
- .stream()
- .map((authorization)->authorization.getDepot())
- .collect(Collectors.toSet());
- Collection<Team> joinedTeams = user.getJoinedTeams()
- .stream()
- .map((membership)->membership.getTeam())
- .collect(Collectors.toSet());
-
- Collection<TeamAuthorization> authorizations;
- if (account != null)
- authorizations = account.getAllTeamAuthorizationsInOrganization();
- else
- authorizations = teamAuthorizationManager.findAll();
-
- for (TeamAuthorization authorization: authorizations) {
- if (joinedTeams.contains(authorization.getTeam()))
- authorizedDepots.add(authorization.getDepot());
- }
-
- return depots.stream()
- .filter((depot->depot.isPublicRead()
- || depot.getAccount().equals(user)
- || authorizedDepots.contains(depot)
- || adminOrganizations.contains(depot.getAccount())
- || memberOrganizations.contains(depot.getAccount())
- && depot.getAccount().getDefaultPrivilege() != DepotPrivilege.NONE))
- .collect(Collectors.toSet());
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+import java.util.stream.Collectors;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.io.IOUtils;
+import org.eclipse.jgit.api.Git;
+import org.eclipse.jgit.internal.storage.file.FileRepository;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.hibernate.Query;
+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.BiMap;
+import com.google.common.collect.HashBiMap;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.git.command.CloneCommand;
+import com.pmease.commons.hibernate.Sessional;
+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.loader.ListenerRegistry;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.Pair;
+import com.pmease.commons.util.StringUtils;
+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.Team;
+import com.pmease.gitplex.core.entity.TeamAuthorization;
+import com.pmease.gitplex.core.entity.support.IntegrationPolicy;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.event.depot.DepotDeleted;
+import com.pmease.gitplex.core.event.depot.DepotRenamed;
+import com.pmease.gitplex.core.event.depot.DepotTransferred;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarted;
+import com.pmease.gitplex.core.event.lifecycle.SystemStarting;
+import com.pmease.gitplex.core.event.lifecycle.SystemStopping;
+import com.pmease.gitplex.core.gatekeeper.GateKeeper;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.CodeCommentInfoManager;
+import com.pmease.gitplex.core.manager.CommitInfoManager;
+import com.pmease.gitplex.core.manager.DepotManager;
+import com.pmease.gitplex.core.manager.PullRequestInfoManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.TeamAuthorizationManager;
+import com.pmease.gitplex.core.security.privilege.DepotPrivilege;
+
+@Singleton
+public class DefaultDepotManager extends AbstractEntityManager<Depot> implements DepotManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultDepotManager.class);
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final StorageManager storageManager;
+
+ private final AccountManager userManager;
+
+ private final CommitInfoManager commitInfoManager;
+
+ private final PullRequestInfoManager pullRequestInfoManager;
+
+ private final CodeCommentInfoManager codeCommentInfoManager;
+
+ private final PullRequestManager pullRequestManager;
+
+ private final TeamAuthorizationManager teamAuthorizationManager;
+
+ private final String gitReceiveHook;
+
+ private final BiMap<Pair<Long, String>, Long> nameToId = HashBiMap.create();
+
+ private final ReadWriteLock idLock = new ReentrantReadWriteLock();
+
+ private final Map<Long, Repository> repositoryCache = new ConcurrentHashMap<>();
+
+ @Inject
+ public DefaultDepotManager(Dao dao, AccountManager userManager, CodeCommentInfoManager codeCommentInfoManager,
+ TeamAuthorizationManager teamAuthorizationManager, PullRequestInfoManager pullRequestInfoManager,
+ StorageManager storageManager, CommitInfoManager commitInfoManager,
+ PullRequestManager pullRequestManager, ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.storageManager = storageManager;
+ this.userManager = userManager;
+ this.pullRequestInfoManager = pullRequestInfoManager;
+ this.teamAuthorizationManager = teamAuthorizationManager;
+ this.commitInfoManager = commitInfoManager;
+ this.codeCommentInfoManager = codeCommentInfoManager;
+ this.pullRequestManager = pullRequestManager;
+ this.listenerRegistry = listenerRegistry;
+
+ try (InputStream is = getClass().getClassLoader().getResourceAsStream("git-receive-hook")) {
+ Preconditions.checkNotNull(is);
+ gitReceiveHook = StringUtils.join(IOUtils.readLines(is), "\n");
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ }
+
+ @Override
+ public Repository getRepository(Depot depot) {
+ Repository repository = repositoryCache.get(depot.getId());
+ if (repository == null) {
+ synchronized (repositoryCache) {
+ repository = repositoryCache.get(depot.getId());
+ if (repository == null) {
+ try {
+ repository = new FileRepository(depot.getDirectory());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ repositoryCache.put(depot.getId(), repository);
+ }
+ }
+ }
+ return repository;
+ }
+
+ @Transactional
+ @Override
+ public void save(Depot depot, Long oldAccountId, String oldName) {
+ Preconditions.checkArgument(oldAccountId==null || oldName==null,
+ "Can not rename and transfer depot in the same time");
+
+ boolean isNew = depot.isNew();
+
+ dao.persist(depot);
+
+ if (oldAccountId != null && !depot.getAccount().getId().equals(oldAccountId)) {
+ Account oldAccount = userManager.load(oldAccountId);
+ listenerRegistry.post(new DepotTransferred(depot, oldAccount));
+
+ for (Depot each: findAll()) {
+ for (IntegrationPolicy policy: each.getIntegrationPolicies()) {
+ policy.onDepotTransfer(depot, oldAccount);
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onDepotTransfer(each, depot, oldAccount))
+ it.remove();
+ }
+ }
+ }
+ if (oldName != null && !depot.getName().equals(oldName)) {
+ listenerRegistry.post(new DepotRenamed(depot, oldName));
+
+ for (Depot each: findAll()) {
+ for (IntegrationPolicy integrationPolicy: each.getIntegrationPolicies()) {
+ integrationPolicy.onDepotRename(depot.getAccount(), oldName, depot.getName());
+ }
+ for (GateKeeper gateKeeper: each.getGateKeepers()) {
+ gateKeeper.onDepotRename(depot, oldName);
+ }
+ }
+ }
+
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ idLock.writeLock().lock();
+ try {
+ nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
+ } finally {
+ idLock.writeLock().unlock();
+ }
+ if (isNew) {
+ checkSanity(depot);
+ commitInfoManager.collect(depot);
+ }
+ }
+
+ });
+ }
+
+ @Transactional
+ @Override
+ public void delete(Depot depot) {
+ Query query = getSession().createQuery("update Depot set forkedFrom=null where forkedFrom=:forkedFrom");
+ query.setParameter("forkedFrom", depot);
+ query.executeUpdate();
+
+ dao.remove(depot);
+
+ for (Depot each: findAll()) {
+ for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
+ if (it.next().onDepotDelete(depot))
+ it.remove();
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onDepotDelete(depot))
+ it.remove();
+ }
+ }
+
+ doAfterCommit(new Runnable() {
+
+ @Override
+ public void run() {
+ idLock.writeLock().lock();
+ try {
+ nameToId.inverse().remove(depot.getId());
+ } finally {
+ idLock.writeLock().unlock();
+ }
+ getRepository(depot).close();
+ repositoryCache.remove(depot.getId());
+
+ FileUtils.deleteDir(storageManager.getGitDir(depot));
+ }
+
+ });
+
+ listenerRegistry.post(new DepotDeleted(depot));
+ }
+
+ @Sessional
+ @Override
+ public Depot find(String accountName, String depotName) {
+ Account user = userManager.find(accountName);
+ if (user != null)
+ return find(user, depotName);
+ else
+ return null;
+ }
+
+ @Sessional
+ @Override
+ public Depot find(Account account, String depotName) {
+ idLock.readLock().lock();
+ try {
+ Long id = nameToId.get(new Pair<>(account.getId(), depotName));
+ if (id != null)
+ return load(id);
+ else
+ return null;
+ } finally {
+ idLock.readLock().unlock();
+ }
+ }
+
+ @Sessional
+ @Override
+ public Depot find(String depotFQN) {
+ String userName = StringUtils.substringBefore(depotFQN, Depot.FQN_SEPARATOR);
+ Account user = userManager.find(userName);
+ if (user != null)
+ return find(user, StringUtils.substringAfter(depotFQN, Depot.FQN_SEPARATOR));
+ else
+ return null;
+ }
+
+ @Transactional
+ @Override
+ public Depot fork(Depot depot, Account user) {
+ if (depot.getAccount().equals(user))
+ return depot;
+
+ Depot forked = null;
+ for (Depot each: user.getDepots()) {
+ if (depot.equals(each.getForkedFrom())) {
+ forked = each;
+ break;
+ }
+ }
+ if (forked == null) {
+ Set<String> existingNames = new HashSet<>();
+ for (Depot each: user.getDepots())
+ existingNames.add(each.getName());
+
+ forked = new Depot();
+ forked.setAccount(user);
+ forked.setForkedFrom(depot);
+ if (existingNames.contains(depot.getName())) {
+ int suffix = 1;
+ while (existingNames.contains(depot.getName() + "_" + suffix))
+ suffix++;
+ forked.setName(depot.getName() + "_" + suffix);
+ } else {
+ forked.setName(depot.getName());
+ }
+
+ dao.persist(forked);
+
+ FileUtils.cleanDir(forked.getDirectory());
+ new CloneCommand(forked.getDirectory()).bare(true).from(depot.getDirectory().getAbsolutePath()).call();
+ }
+
+ return forked;
+ }
+
+ private void checkSanity(Depot depot) {
+ logger.info("Checking sanity of repository '{}'...", depot);
+
+ File gitDir = depot.getDirectory();
+ if (depot.getDirectory().exists() && !GitUtils.isValid(gitDir)) {
+ logger.warn("Directory '" + gitDir + "' is not a valid git repository, removing...");
+ FileUtils.deleteDir(gitDir);
+ }
+
+ if (!gitDir.exists()) {
+ logger.warn("Initializing git repository in '" + gitDir + "'...");
+ FileUtils.createDir(gitDir);
+ try {
+ Git.init().setDirectory(gitDir).setBare(true).call();
+ } catch (Exception e) {
+ Throwables.propagate(e);
+ }
+ }
+
+ if (!depot.isValid()) {
+ File hooksDir = new File(gitDir, "hooks");
+
+ File gitPreReceiveHookFile = new File(hooksDir, "pre-receive");
+ FileUtils.writeFile(gitPreReceiveHookFile, String.format(gitReceiveHook, "git-prereceive-callback"));
+ gitPreReceiveHookFile.setExecutable(true);
+
+ File gitPostReceiveHookFile = new File(hooksDir, "post-receive");
+ FileUtils.writeFile(gitPostReceiveHookFile, String.format(gitReceiveHook, "git-postreceive-callback"));
+ gitPostReceiveHookFile.setExecutable(true);
+ }
+ }
+
+ @Sessional
+ @Listen
+ public void on(SystemStarting event) {
+ for (Depot depot: findAll())
+ nameToId.inverse().put(depot.getId(), new Pair<>(depot.getAccount().getId(), depot.getName()));
+ }
+
+ @Transactional
+ @Listen
+ public void on(SystemStarted event) {
+ for (Depot depot: findAll()) {
+ checkSanity(depot);
+ commitInfoManager.collect(depot);
+ pullRequestInfoManager.collect(depot);
+ codeCommentInfoManager.collect(depot);
+ }
+
+ pullRequestManager.checkSanity();
+ }
+
+ @Listen
+ public void on(SystemStopping event) {
+ synchronized(repositoryCache) {
+ for (Repository repository: repositoryCache.values()) {
+ repository.close();
+ }
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(RefUpdated event) {
+ if (event.getNewCommit().equals(ObjectId.zeroId())) {
+ String branch = GitUtils.ref2branch(event.getRefName());
+ for (Depot each: findAll()) {
+ if (branch != null) {
+ for (Iterator<IntegrationPolicy> it = each.getIntegrationPolicies().iterator(); it.hasNext();) {
+ if (it.next().onBranchDelete(each, event.getDepot(), branch))
+ it.remove();
+ }
+ }
+ for (Iterator<GateKeeper> it = each.getGateKeepers().iterator(); it.hasNext();) {
+ if (it.next().onRefDelete(event.getRefName()))
+ it.remove();
+ }
+ }
+ }
+ }
+
+ @Sessional
+ @Override
+ public Collection<Depot> findAllAccessible(Account account, Account user) {
+ Collection<Depot> depots;
+ if (account == null)
+ depots = GitPlex.getInstance(DepotManager.class).findAll();
+ else
+ depots = account.getDepots();
+
+ if (user == null) {
+ return depots.stream().filter((depot)->depot.isPublicRead()).collect(Collectors.toSet());
+ } else if (user.isAdministrator() || user.equals(account)) {
+ return depots;
+ } else {
+ Collection<Account> adminOrganizations = user.getOrganizations()
+ .stream()
+ .filter((membership)->membership.isAdmin())
+ .map((membership)->membership.getOrganization())
+ .collect(Collectors.toSet());
+
+ // return fast in special cases
+ if (adminOrganizations.contains(account)) {
+ return depots;
+ }
+
+ Collection<Account> memberOrganizations = user.getOrganizations()
+ .stream()
+ .filter((membership)->!membership.isAdmin())
+ .map((membership)->membership.getOrganization())
+ .collect(Collectors.toSet());
+
+ // return fast in special cases
+ if (memberOrganizations.contains(account) && account.getDefaultPrivilege() != DepotPrivilege.NONE) {
+ return depots;
+ }
+
+ Collection<Depot> authorizedDepots = user.getAuthorizedDepots()
+ .stream()
+ .map((authorization)->authorization.getDepot())
+ .collect(Collectors.toSet());
+ Collection<Team> joinedTeams = user.getJoinedTeams()
+ .stream()
+ .map((membership)->membership.getTeam())
+ .collect(Collectors.toSet());
+
+ Collection<TeamAuthorization> authorizations;
+ if (account != null)
+ authorizations = account.getAllTeamAuthorizationsInOrganization();
+ else
+ authorizations = teamAuthorizationManager.findAll();
+
+ for (TeamAuthorization authorization: authorizations) {
+ if (joinedTeams.contains(authorization.getTeam()))
+ authorizedDepots.add(authorization.getDepot());
+ }
+
+ return depots.stream()
+ .filter((depot->depot.isPublicRead()
+ || depot.getAccount().equals(user)
+ || authorizedDepots.contains(depot)
+ || adminOrganizations.contains(depot.getAccount())
+ || memberOrganizations.contains(depot.getAccount())
+ && depot.getAccount().getDefaultPrivilege() != DepotPrivilege.NONE))
+ .collect(Collectors.toSet());
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
index bd5ae9a1f8..35d42ec903 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultMailManager.java
@@ -1,120 +1,176 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.concurrent.ExecutorService;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.codec.CharEncoding;
-import org.apache.commons.mail.EmailException;
-import org.apache.commons.mail.HtmlEmail;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.pmease.commons.bootstrap.Bootstrap;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.setting.MailSetting;
-
-@Singleton
-public class DefaultMailManager implements MailManager {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultMailManager.class);
-
- private final ConfigManager configManager;
-
- private final ExecutorService executorService;
-
- @Inject
- public DefaultMailManager(ConfigManager configManager, ExecutorService executorService) {
- this.configManager = configManager;
- this.executorService = executorService;
- }
-
- @Override
- public void sendMail(final Collection<Account> toList, final String subject, final String body) {
- executorService.execute(new Runnable() {
-
- @Override
- public void run() {
- try {
- sendMailNow(null, toList, subject, body);
- } catch (Exception e) {
- logger.error("Error sending email (to: " + toList + ", subject: " + subject + ")", e);
- }
- }
-
- });
- }
-
- @Override
- public void sendMailNow(MailSetting mailSetting, Collection<Account> toList, String subject, String body) {
- Collection<String> toAddresses = new ArrayList<>();
- for (Account user: toList) {
- if (user.getEmail() != null)
- toAddresses.add(user.getEmail());
- }
-
- if (toAddresses.isEmpty())
- return;
-
- if (mailSetting == null)
- mailSetting = configManager.getMailSetting();
-
- if (mailSetting == null)
- throw new RuntimeException("Mail setting is not defined.");
-
- HtmlEmail email = new HtmlEmail();
- email.setSocketConnectionTimeout(Bootstrap.SOCKET_CONNECT_TIMEOUT);
-
- if (mailSetting.getTimeout() != 0)
- email.setSocketTimeout(mailSetting.getTimeout()*1000);
-
- if (mailSetting.isEnableStartTLS())
- email.setStartTLSEnabled(true);
-
- email.setSSLCheckServerIdentity(false);
-
- String senderEmail = mailSetting.getSenderAddress();
- if (senderEmail == null) {
- String hostName;
- try {
- hostName = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException e) {
- throw new RuntimeException(e);
- }
- senderEmail = "gitplex@" + hostName;
- }
- try {
- email.setFrom(senderEmail);
- if (mailSetting.getReplyAddress() != null)
- email.addReplyTo(mailSetting.getReplyAddress());
-
- for (String address: toAddresses)
- email.addTo(address);
-
- email.setHostName(mailSetting.getSmtpHost());
- email.setSmtpPort(mailSetting.getSmtpPort());
- email.setSslSmtpPort(String.valueOf(mailSetting.getSslSmtpPort()));
- email.setSSLOnConnect(mailSetting.isSmtpOverSSL());
- String smtpUser = mailSetting.getSmtpUser();
- if (smtpUser != null)
- email.setAuthentication(smtpUser, mailSetting.getSmtpPassword());
- email.setCharset(CharEncoding.UTF_8);
-
- email.setSubject(subject);
- email.setHtmlMsg(body);
-
- logger.debug("Sending email (to: {}, subject: {})... " + toAddresses, subject);
- email.send();
- } catch (EmailException e) {
- throw new RuntimeException(e);
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.concurrent.ExecutorService;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.codec.CharEncoding;
+import org.apache.commons.mail.EmailException;
+import org.apache.commons.mail.HtmlEmail;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.bootstrap.Bootstrap;
+import com.pmease.commons.loader.Listen;
+import com.pmease.commons.markdown.MarkdownManager;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.event.mention.AccountMentionedInCodeComment;
+import com.pmease.gitplex.core.event.mention.AccountMentionedInPullRequest;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+import com.pmease.gitplex.core.setting.MailSetting;
+
+@Singleton
+public class DefaultMailManager implements MailManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultMailManager.class);
+
+ private final ConfigManager configManager;
+
+ private final MarkdownManager markdownManager;
+
+ private final ExecutorService executorService;
+
+ private final UrlManager urlManager;
+
+ @Inject
+ public DefaultMailManager(ConfigManager configManager, ExecutorService executorService,
+ MarkdownManager markdownManager, UrlManager urlManager) {
+ this.configManager = configManager;
+ this.executorService = executorService;
+ this.markdownManager = markdownManager;
+ this.urlManager = urlManager;
+ }
+
+ @Override
+ public void sendMailAsync(Collection<Account> toList, String subject, String body) {
+ executorService.execute(new Runnable() {
+
+ @Override
+ public void run() {
+ try {
+ sendMail(toList, subject, body);
+ } catch (Exception e) {
+ logger.error("Error sending email (to: " + toList + ", subject: " + subject + ")", e);
+ }
+ }
+
+ });
+ }
+
+ @Override
+ public void sendMail(MailSetting mailSetting, Collection<Account> toList, String subject, String body) {
+ Collection<String> toAddresses = new ArrayList<>();
+ for (Account user: toList) {
+ if (user.getEmail() != null)
+ toAddresses.add(user.getEmail());
+ }
+
+ if (toAddresses.isEmpty())
+ return;
+
+ if (mailSetting == null)
+ mailSetting = configManager.getMailSetting();
+
+ if (mailSetting == null)
+ throw new RuntimeException("Mail setting is not defined.");
+
+ HtmlEmail email = new HtmlEmail();
+ email.setSocketConnectionTimeout(Bootstrap.SOCKET_CONNECT_TIMEOUT);
+
+ if (mailSetting.getTimeout() != 0)
+ email.setSocketTimeout(mailSetting.getTimeout()*1000);
+
+ email.setStartTLSEnabled(true);
+
+ email.setSSLCheckServerIdentity(false);
+
+ String senderEmail = mailSetting.getSenderAddress();
+ if (senderEmail == null) {
+ String hostName;
+ try {
+ hostName = InetAddress.getLocalHost().getHostName();
+ } catch (UnknownHostException e) {
+ throw new RuntimeException(e);
+ }
+ senderEmail = "gitplex@" + hostName;
+ }
+ try {
+ email.setFrom(senderEmail);
+ for (String address: toAddresses)
+ email.addTo(address);
+
+ email.setHostName(mailSetting.getSmtpHost());
+ email.setSmtpPort(mailSetting.getSmtpPort());
+ email.setSslSmtpPort(String.valueOf(mailSetting.getSmtpPort()));
+ String smtpUser = mailSetting.getSmtpUser();
+ if (smtpUser != null)
+ email.setAuthentication(smtpUser, mailSetting.getSmtpPassword());
+ email.setCharset(CharEncoding.UTF_8);
+
+ email.setSubject(subject);
+ email.setHtmlMsg(body);
+
+ logger.debug("Sending email (to: {}, subject: {})... ", toAddresses, subject);
+ email.send();
+ } catch (EmailException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Override
+ public void sendMail(Collection<Account> toList, String subject, String body) {
+ sendMail(configManager.getMailSetting(), toList, subject, body);
+ }
+
+ @Listen
+ public void on(AccountMentionedInPullRequest event) {
+ PullRequest request = event.getRequest();
+ Account user = event.getUser();
+ String subject = String.format("You are mentioned in pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("%s."
+ + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
+ + "<p style='margin: 16px 0;'>"
+ + "For details, please visit <a href='%s'>%s</a>",
+ subject, markdownManager.escape(event.getMarkdown()), url, url);
+
+ sendMailAsync(Sets.newHashSet(user), subject, decorate(user, body));
+ }
+
+ @Listen
+ public void on(AccountMentionedInCodeComment event) {
+ Account user = event.getUser();
+ CodeComment comment = event.getComment();
+ String subject = String.format("You are mentioned in code comment #%d (%s)",
+ comment.getId(), comment.getTitle());
+ String url = urlManager.urlFor(comment);
+ String body = String.format("%s."
+ + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
+ + "<p style='margin: 16px 0;'>"
+ + "For details, please visit <a href='%s'>%s</a>",
+ subject, markdownManager.escape(event.getMarkdown()), url, url);
+
+ sendMailAsync(Sets.newHashSet(user), subject, decorate(user, body));
+ }
+
+ private String decorate(Account user, String body) {
+ return String.format("Dear %s, "
+ + "<p style='margin: 16px 0;'>"
+ + "%s"
+ + "<p style='margin: 16px 0;'>"
+ + "-- Sent by GitPlex",
+ user.getDisplayName(), body);
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestCommentManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestCommentManager.java
index 471a0db5ce..d10fb50a15 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestCommentManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestCommentManager.java
@@ -1,43 +1,51 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-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.ListenerRegistry;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestCommented;
-import com.pmease.gitplex.core.manager.PullRequestCommentManager;
-
-@Singleton
-public class DefaultPullRequestCommentManager extends AbstractEntityManager<PullRequestComment>
- implements PullRequestCommentManager {
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultPullRequestCommentManager(Dao dao, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.listenerRegistry = listenerRegistry;
- }
-
- @Transactional
- @Override
- public void save(PullRequestComment comment) {
- save(comment, true);
- }
-
- @Transactional
- @Override
- public void save(PullRequestComment comment, boolean notifyListeners) {
- boolean isNew = comment.isNew();
- dao.persist(comment);
- if (notifyListeners && isNew) {
- listenerRegistry.notify(new PullRequestCommented(comment));
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+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.ListenerRegistry;
+import com.pmease.gitplex.core.entity.PullRequestComment;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestCommented;
+import com.pmease.gitplex.core.manager.PullRequestCommentManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+
+@Singleton
+public class DefaultPullRequestCommentManager extends AbstractEntityManager<PullRequestComment>
+ implements PullRequestCommentManager {
+
+ private final ListenerRegistry listenerRegistry;
+
+ private final PullRequestManager pullRequestManager;
+
+ @Inject
+ public DefaultPullRequestCommentManager(Dao dao, PullRequestManager pullRequestManager,
+ ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.listenerRegistry = listenerRegistry;
+ this.pullRequestManager = pullRequestManager;
+ }
+
+ @Transactional
+ @Override
+ public void save(PullRequestComment comment) {
+ save(comment, true);
+ }
+
+ @Transactional
+ @Override
+ public void save(PullRequestComment comment, boolean notifyListeners) {
+ boolean isNew = comment.isNew();
+ dao.persist(comment);
+ if (notifyListeners && isNew) {
+ PullRequestCommented event = new PullRequestCommented(comment);
+ listenerRegistry.post(event);
+ comment.getRequest().setLastEvent(event);
+ pullRequestManager.save(event.getRequest());
+ }
+ }
+
+}
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.java
index 1d2d48fdf7..a28282ac44 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
@@ -57,10 +57,7 @@ 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;
@@ -70,19 +67,11 @@ 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;
@@ -92,8 +81,6 @@ 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;
@@ -101,8 +88,8 @@ 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.PullRequestNotificationManager;
import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
import com.pmease.gitplex.core.manager.support.BatchWorker;
@@ -141,7 +128,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
@Inject
public DefaultPullRequestManager(Dao dao, PullRequestUpdateManager pullRequestUpdateManager,
PullRequestReviewInvitationManager reviewInvitationManager, AccountManager accountManager,
- NotificationManager notificationManager, MarkdownManager markdownManager,
+ PullRequestNotificationManager notificationManager, MarkdownManager markdownManager,
BatchWorkManager batchWorkManager, ListenerRegistry listenerRegistry,
ExecutorService executorService, UnitOfWork unitOfWork) {
super(dao);
@@ -154,7 +141,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
this.executorService = executorService;
this.listenerRegistry = listenerRegistry;
}
-
+
@Transactional
@Override
public void delete(PullRequest request) {
@@ -183,7 +170,10 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
Throwables.propagate(e);
}
request.getSourceDepot().cacheObjectId(request.getSourceBranch(), latestCommit.copy());
- listenerRegistry.notify(new SourceBranchRestored(request, accountManager.getCurrent(), note));
+ SourceBranchRestored event = new SourceBranchRestored(request, accountManager.getCurrent(), note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ save(request);
}
}
@@ -194,7 +184,10 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
if (request.getSource().getObjectName(false) != null) {
request.getSource().delete();
- listenerRegistry.notify(new SourceBranchDeleted(request, accountManager.getCurrent(), note));
+ SourceBranchDeleted event = new SourceBranchDeleted(request, accountManager.getCurrent(), note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ save(request);
}
}
@@ -208,11 +201,11 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
closeAsIntegrated(request, true, null);
} else {
request.setCloseInfo(null);
-
+ PullRequestReopened event = new PullRequestReopened(request, user, note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
save(request);
checkAsync(request);
-
- listenerRegistry.notify(new PullRequestReopened(request, user, note));
}
}
@@ -227,9 +220,10 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
closeInfo.setCloseStatus(CloseInfo.Status.DISCARDED);
request.setCloseInfo(closeInfo);
- dao.persist(request);
-
- listenerRegistry.notify(new PullRequestDiscarded(request, user, note));
+ PullRequestDiscarded event = new PullRequestDiscarded(request, user, note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ save(request);
}
@Transactional
@@ -297,7 +291,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
try {
PullRequest request = load(requestId);
request.getSourceDepot().cacheObjectId(request.getSourceRef(), newCommitId);
- listenerRegistry.notify(new RefUpdated(
+ listenerRegistry.post(new RefUpdated(
request.getSourceDepot(), request.getSourceRef(), requestHeadId, newCommitId));
} finally {
ThreadContext.unbindSubject();
@@ -327,7 +321,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
try {
PullRequest request = load(requestId);
request.getTargetDepot().cacheObjectId(request.getTargetRef(), newCommitId);
- listenerRegistry.notify(new RefUpdated(request.getTargetDepot(), targetRef,
+ listenerRegistry.post(new RefUpdated(request.getTargetDepot(), targetRef,
ObjectId.fromString(preview.getTargetHead()), newCommitId));
} finally {
ThreadContext.unbindSubject();
@@ -385,16 +379,9 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
for (PullRequestReviewInvitation invitation: request.getReviewInvitations())
reviewInvitationManager.save(invitation);
- doAfterCommit(new Runnable() {
-
- @Override
- public void run() {
- batchWorkManager.submit(getIntegrationPreviewer(request), new Prioritized(UI_PREVIEW_PRIORITY));
- }
-
- });
+ checkAsync(request);
- listenerRegistry.notify(new PullRequestOpened(request));
+ listenerRegistry.post(new PullRequestOpened(request));
}
@Override
@@ -415,12 +402,13 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
@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));
+ PullRequestAssigned event = new PullRequestAssigned(request, accountManager.getCurrent(), note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
}
+ save(request);
}
private void onTargetBranchUpdate(PullRequest request) {
@@ -447,11 +435,12 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
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));
+ PullRequestIntegrated event = new PullRequestIntegrated(request, user, note);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ save(request);
}
private void updateIfNecessary(PullRequest request, boolean notifyListeners) {
@@ -480,7 +469,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
} else {
Date timeBeforeCheck = new Date();
if (request.getStatus() == PENDING_UPDATE) {
- listenerRegistry.notify(new PullRequestPendingUpdate(request));
+ listenerRegistry.post(new PullRequestPendingUpdate(request));
} else if (request.getStatus() == PENDING_INTEGRATE) {
IntegrationPreview integrationPreview = request.getIntegrationPreview();
if (integrationPreview != null
@@ -488,14 +477,14 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
&& request.getAssignee() == null) {
integrate(request, "Integrated automatically by system");
} else {
- listenerRegistry.notify(new PullRequestPendingIntegration(request));
+ listenerRegistry.post(new PullRequestPendingIntegration(request));
}
} else if (request.getStatus() == PENDING_APPROVAL) {
for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
if (invitation.getDate().getTime()>=timeBeforeCheck.getTime())
reviewInvitationManager.save(invitation);
}
- listenerRegistry.notify(new PullRequestPendingApproval(request));
+ listenerRegistry.post(new PullRequestPendingApproval(request));
}
}
}
@@ -586,7 +575,7 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
integrate(request, "Integrated automatically by GitPlex");
}
- listenerRegistry.notify(new IntegrationPreviewCalculated(request));
+ listenerRegistry.post(new IntegrationPreviewCalculated(request));
logger.info("Integration preview of pull request #{} in repository '{}' is calculated.",
request.getNumber(), request.getTargetDepot());
}
@@ -781,74 +770,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
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());
@@ -883,17 +804,6 @@ public class DefaultPullRequestManager extends AbstractEntityManager<PullRequest
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();
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
index 420e360d4b..e2466ecbab 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestNotificationManager.java
@@ -1,278 +1,253 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.INTEGRATE;
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.REVIEW;
-import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.UPDATE;
-import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.Query;
-import org.hibernate.criterion.Restrictions;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Sets;
-import com.pmease.commons.hibernate.Transactional;
-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.markdown.MarkdownManager;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequestNotification;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestComment;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentioned;
-import com.pmease.gitplex.core.event.pullrequest.AccountMentionedInComment;
-import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;
-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.PullRequestPendingApproval;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
-import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.manager.NotificationManager;
-import com.pmease.gitplex.core.manager.UrlManager;
-
-/**
- * This class manages pull request task notifications and send email to relevant users. This
- * notification does not correlate with pull request watch notifications and can not be
- * suppressed.
- *
- * @author robin
- *
- */
-@Singleton
-public class DefaultPullRequestNotificationManager extends AbstractEntityManager<PullRequestNotification>
- implements NotificationManager {
-
- private final MailManager mailManager;
-
- private final UrlManager urlManager;
-
- private final MarkdownManager markdownManager;
-
- @Inject
- public DefaultPullRequestNotificationManager(Dao dao, MailManager mailManager,
- UrlManager urlManager, MarkdownManager markdownManager) {
- super(dao);
-
- this.mailManager = mailManager;
- this.urlManager = urlManager;
- this.markdownManager = markdownManager;
- }
-
- @Transactional
- @Listen
- public void on(PullRequestUpdated event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and task=:task");
- query.setParameter("request", event.getRequest());
- query.setParameter("task", UPDATE);
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(PullRequestAssigned event) {
- PullRequest request = event.getRequest();
- Preconditions.checkNotNull(request.getAssignee());
-
- if (request.getStatus() == PENDING_INTEGRATE) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and task=:task and user!=:user");
- query.setParameter("request", request);
- query.setParameter("task", INTEGRATE);
- query.setParameter("user", request.getAssignee());
- query.executeUpdate();
-
- requestIntegration(request);
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestIntegrated event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request");
- query.setParameter("request", event.getRequest());
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(PullRequestDiscarded event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request");
- query.setParameter("request", event.getRequest());
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(InvitingPullRequestReview event) {
- PullRequestReviewInvitation invitation = event.getInvitation();
- PullRequest request = invitation.getRequest();
- Account user = invitation.getUser();
- if (invitation.isExcluded()) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and user=:user and task=:task");
- query.setParameter("request", request);
- query.setParameter("user", user);
- query.setParameter("task", REVIEW);
- query.executeUpdate();
- } else {
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(user);
- notification.setTask(REVIEW);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", request))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null) {
- dao.persist(notification);
- String subject = String.format("Please review pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are invited to review pull request #%d (%s). Please visit "
- + "<a href='%s'>%s</a> to add your comments.",
- request.getId(), request.getTitle(), url, url);
- mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
- }
- }
-
- }
-
- private String decorateMail(Account user, String body) {
- return String.format("Dear %s, "
- + "<p style='margin: 16px 0;'>"
- + "%s"
- + "<p style='margin: 16px 0;'>"
- + "-- Sent by GitPlex",
- user.getDisplayName(), body);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingApproval event) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and (task=:update or task=:integrate)");
- query.setParameter("request", event.getRequest());
- query.setParameter("update", UPDATE);
- query.setParameter("integrate", INTEGRATE);
- query.executeUpdate();
- }
-
- @Transactional
- @Listen
- public void on(AccountMentioned event) {
- PullRequest request = event.getRequest();
- Account user = event.getUser();
- String subject = String.format("You are mentioned in pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("%s."
- + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
- + "<p style='margin: 16px 0;'>"
- + "For details, please visit <a href='%s'>%s</a>",
- subject, markdownManager.escape(request.getDescription()), url, url);
-
- mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
- }
-
- @Transactional
- @Listen
- public void on(AccountMentionedInComment event) {
- PullRequestComment comment = event.getComment();
- Account user = event.getUser();
- String subject = String.format("You are mentioned in comment of pull request #%d (%s)",
- comment.getRequest().getId(), comment.getRequest().getTitle());
- String url = urlManager.urlFor(comment);
- String body = String.format("%s."
- + "<p style='margin: 16px 0; padding-left: 16px; border-left: 4px solid #CCC;'>%s"
- + "<p style='margin: 16px 0;'>"
- + "For details, please visit <a href='%s'>%s</a>",
- subject, markdownManager.escape(comment.getContent()), url, url);
-
- mailManager.sendMail(Sets.newHashSet(user), subject, decorateMail(user, body));
- }
-
- private void requestIntegration(PullRequest request) {
- Account user = request.getAssignee();
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(user);
- notification.setTask(INTEGRATE);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", notification.getRequest()))
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null) {
- dao.persist(notification);
- String subject = String.format("Please integrate pull request #%d (%s)",
- request.getId(), request.getTitle());
- String url = urlManager.urlFor(request);
- String body = String.format("You are assignee of pull request #%d (%s). "
- + "Please visit <a href='%s'>%s</a> to integrate it into target branch.",
- request.getId(), request.getTitle(), url, url);
-
- mailManager.sendMail(Sets.newHashSet(notification.getUser()), subject, decorateMail(user, body));
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingIntegration event) {
- PullRequest request = event.getRequest();
- if (request.getAssignee() != null)
- requestIntegration(request);
- }
-
- @Transactional
- @Listen
- public void on(PullRequestPendingUpdate event) {
- PullRequest request = event.getRequest();
- if (request.getSubmitter() != null) {
- PullRequestNotification notification = new PullRequestNotification();
- notification.setRequest(request);
- notification.setUser(request.getSubmitter());
- notification.setTask(UPDATE);
- EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
- criteria.add(Restrictions.eq("request", notification.getRequest()))
- .add(Restrictions.eq("user", notification.getUser()))
- .add(Restrictions.eq("task", notification.getTask()));
- if (find(criteria) == null)
- dao.persist(notification);
- }
- }
-
- @Transactional
- @Listen
- public void on(PullRequestApproved event) {
- onReviewed(event.getReview());
- }
-
- @Transactional
- @Listen
- public void on(PullRequestDisapproved event) {
- onReviewed(event.getReview());
- }
-
- private void onReviewed(PullRequestReview review) {
- Query query = getSession().createQuery("delete from PullRequestNotification "
- + "where request=:request and user=:user and task=:task");
- query.setParameter("request", review.getUpdate().getRequest());
- query.setParameter("user", review.getUser());
- query.setParameter("task", REVIEW);
- query.executeUpdate();
- }
-
+package com.pmease.gitplex.core.manager.impl;
+
+import static com.pmease.gitplex.core.entity.PullRequest.Status.PENDING_INTEGRATE;
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.INTEGRATE;
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.REVIEW;
+import static com.pmease.gitplex.core.entity.PullRequestNotification.Task.UPDATE;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.Query;
+import org.hibernate.criterion.Restrictions;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+import com.pmease.commons.hibernate.Transactional;
+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.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.PullRequestNotification;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;
+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.PullRequestPendingApproval;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingIntegration;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestPendingUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewInvitationChanged;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.manager.PullRequestNotificationManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+
+/**
+ * This class manages pull request tasks and send task notifications if necessary.
+ * Unlike watch based notifications, task notifications can not be suppressed.
+ *
+ * @author robin
+ *
+ */
+@Singleton
+public class DefaultPullRequestNotificationManager extends AbstractEntityManager<PullRequestNotification>
+ implements PullRequestNotificationManager {
+
+ private final MailManager mailManager;
+
+ private final UrlManager urlManager;
+
+ @Inject
+ public DefaultPullRequestNotificationManager(Dao dao, MailManager mailManager, UrlManager urlManager) {
+ super(dao);
+
+ this.mailManager = mailManager;
+ this.urlManager = urlManager;
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestUpdated event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and task=:task");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("task", UPDATE);
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestAssigned event) {
+ PullRequest request = event.getRequest();
+ Preconditions.checkNotNull(request.getAssignee());
+
+ if (request.getStatus() == PENDING_INTEGRATE) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and task=:task and user!=:user");
+ query.setParameter("request", request);
+ query.setParameter("task", INTEGRATE);
+ query.setParameter("user", request.getAssignee());
+ query.executeUpdate();
+
+ requestIntegration(request);
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestIntegrated event) {
+ onClosed(event.getRequest());
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestDiscarded event) {
+ onClosed(event.getRequest());
+ }
+
+ private void onClosed(PullRequest request) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request");
+ query.setParameter("request", request);
+ query.executeUpdate();
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestReviewInvitationChanged event) {
+ PullRequestReviewInvitation invitation = event.getInvitation();
+ PullRequest request = invitation.getRequest();
+ Account user = invitation.getUser();
+ if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and user=:user and task=:task");
+ query.setParameter("request", request);
+ query.setParameter("user", user);
+ query.setParameter("task", REVIEW);
+ query.executeUpdate();
+ } else if (invitation.getStatus() == PullRequestReviewInvitation.Status.ADDED_BY_RULE) {
+ PullRequestNotification task = new PullRequestNotification();
+ task.setRequest(request);
+ task.setUser(user);
+ task.setTask(REVIEW);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", request))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("task", task.getTask()));
+ if (find(criteria) == null) {
+ save(task);
+
+ String subject = String.format("Please review pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are designated to review pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> to do the review.",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
+ }
+ } else {
+ String subject = String.format("You are invited to review pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are invited to review pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> to do the review.",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(invitation.getUser()), subject, decorate(user, body));
+ }
+ }
+
+ private String decorate(Account user, String body) {
+ return String.format("Dear %s, "
+ + "<p style='margin: 16px 0;'>"
+ + "%s"
+ + "<p style='margin: 16px 0;'>"
+ + "-- Sent by GitPlex",
+ user.getDisplayName(), body);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingApproval event) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and (task=:update or task=:integrate)");
+ query.setParameter("request", event.getRequest());
+ query.setParameter("update", UPDATE);
+ query.setParameter("integrate", INTEGRATE);
+ query.executeUpdate();
+ }
+
+ private void requestIntegration(PullRequest request) {
+ Account user = request.getAssignee();
+ PullRequestNotification task = new PullRequestNotification();
+ task.setRequest(request);
+ task.setUser(user);
+ task.setTask(INTEGRATE);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", task.getRequest()))
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("task", task.getTask()));
+ if (find(criteria) == null) {
+ save(task);
+ String subject = String.format("Please integrate pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("Pull request #%d (%s) is pending integration.<br>"
+ + "Please visit <a href='%s'>%s</a> to check and integrate.",
+ request.getNumber(), request.getTitle(), url, url);
+
+ mailManager.sendMailAsync(Sets.newHashSet(task.getUser()), subject, decorate(user, body));
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingIntegration event) {
+ PullRequest request = event.getRequest();
+ if (request.getAssignee() != null)
+ requestIntegration(request);
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestPendingUpdate event) {
+ PullRequest request = event.getRequest();
+ if (request.getSubmitter() != null) {
+ PullRequestNotification task = new PullRequestNotification();
+ task.setRequest(request);
+ task.setUser(request.getSubmitter());
+ task.setTask(UPDATE);
+ EntityCriteria<PullRequestNotification> criteria = EntityCriteria.of(PullRequestNotification.class);
+ criteria.add(Restrictions.eq("request", task.getRequest()))
+ .add(Restrictions.eq("user", task.getUser()))
+ .add(Restrictions.eq("task", task.getTask()));
+ if (find(criteria) == null) {
+ save(task);
+ String subject = String.format("New commits are expected in pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("Next commits are expected for next round of review in pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> for details",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(request.getSubmitter()), subject,
+ decorate(request.getSubmitter(), body));
+ }
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestApproved event) {
+ onReviewed(event.getReview());
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestDisapproved event) {
+ onReviewed(event.getReview());
+ }
+
+ private void onReviewed(PullRequestReview review) {
+ Query query = getSession().createQuery("delete from PullRequestNotification "
+ + "where request=:request and user=:user and task=:task");
+ query.setParameter("request", review.getUpdate().getRequest());
+ query.setParameter("user", review.getUser());
+ query.setParameter("task", REVIEW);
+ query.executeUpdate();
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
index 171bc3320d..6bc165776e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewInvitationManager.java
@@ -1,68 +1,68 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.util.Collection;
-import java.util.Date;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.criterion.Restrictions;
-
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-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.ListenerRegistry;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.event.pullrequest.InvitingPullRequestReview;
-import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-
-@Singleton
-public class DefaultPullRequestReviewInvitationManager extends AbstractEntityManager<PullRequestReviewInvitation>
- implements PullRequestReviewInvitationManager {
-
- private final PullRequestReviewManager reviewManager;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultPullRequestReviewInvitationManager(Dao dao, PullRequestReviewManager reviewManager,
- ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.reviewManager = reviewManager;
- this.listenerRegistry = listenerRegistry;
- }
-
- @Sessional
- @Override
- public PullRequestReviewInvitation find(Account reviewer, PullRequest request) {
- return find(EntityCriteria.of(PullRequestReviewInvitation.class)
- .add(Restrictions.eq("reviewer", reviewer))
- .add(Restrictions.eq("request", request)));
- }
-
- @Transactional
- @Override
- public void save(PullRequestReviewInvitation invitation) {
- dao.persist(invitation);
-
- listenerRegistry.notify(new InvitingPullRequestReview(invitation));
- }
-
- @Transactional
- @Override
- public void update(Collection<PullRequestReviewInvitation> invitations, Date since) {
- for (PullRequestReviewInvitation invitation: invitations) {
- if (invitation.getDate().getTime()>=since.getTime()) {
- save(invitation);
- if (invitation.isExcluded())
- reviewManager.deleteAll(invitation.getUser(), invitation.getRequest());
- }
- }
- }
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.util.Collection;
+import java.util.Date;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.criterion.Restrictions;
+
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+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.ListenerRegistry;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewInvitationChanged;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+
+@Singleton
+public class DefaultPullRequestReviewInvitationManager extends AbstractEntityManager<PullRequestReviewInvitation>
+ implements PullRequestReviewInvitationManager {
+
+ private final PullRequestReviewManager reviewManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultPullRequestReviewInvitationManager(Dao dao, PullRequestReviewManager reviewManager,
+ ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.reviewManager = reviewManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Sessional
+ @Override
+ public PullRequestReviewInvitation find(Account reviewer, PullRequest request) {
+ return find(EntityCriteria.of(PullRequestReviewInvitation.class)
+ .add(Restrictions.eq("reviewer", reviewer))
+ .add(Restrictions.eq("request", request)));
+ }
+
+ @Transactional
+ @Override
+ public void save(PullRequestReviewInvitation invitation) {
+ dao.persist(invitation);
+
+ listenerRegistry.post(new PullRequestReviewInvitationChanged(invitation));
+ }
+
+ @Transactional
+ @Override
+ public void update(Collection<PullRequestReviewInvitation> invitations, Date since) {
+ for (PullRequestReviewInvitation invitation: invitations) {
+ if (invitation.getDate().getTime()>=since.getTime()) {
+ save(invitation);
+ if (invitation.getStatus() == PullRequestReviewInvitation.Status.EXCLUDED)
+ reviewManager.deleteAll(invitation.getUser(), invitation.getRequest());
+ }
+ }
+ }
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
index 75b9c93f0c..b1451fec2e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestReviewManager.java
@@ -1,96 +1,110 @@
-package com.pmease.gitplex.core.manager.impl;
-
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
-
-import com.pmease.commons.hibernate.Sessional;
-import com.pmease.commons.hibernate.Transactional;
-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.ListenerRegistry;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
-import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-
-@Singleton
-public class DefaultPullRequestReviewManager extends AbstractEntityManager<PullRequestReview> implements PullRequestReviewManager {
-
- private final AccountManager accountManager;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultPullRequestReviewManager(Dao dao, AccountManager accountManager, ListenerRegistry listenerRegistry) {
- super(dao);
-
- this.accountManager = accountManager;
- this.listenerRegistry = listenerRegistry;
- }
-
- @Sessional
- @Override
- public PullRequestReview find(Account user, PullRequestUpdate update) {
- return find(EntityCriteria.of(PullRequestReview.class)
- .add(Restrictions.eq("user", user))
- .add(Restrictions.eq("update", update)));
- }
-
- @Transactional
- @Override
- public void review(PullRequest request, PullRequestReview.Result result, String note) {
- PullRequestReview review = new PullRequestReview();
- review.setUpdate(request.getLatestUpdate());
- review.setResult(result);
- review.setUser(accountManager.getCurrent());
- review.setDate(new Date());
- save(review);
-
- if (result == PullRequestReview.Result.APPROVE)
- listenerRegistry.notify(new PullRequestApproved(review, note));
- else
- listenerRegistry.notify(new PullRequestDisapproved(review, note));
- }
-
- @Transactional
- @Override
- public void delete(PullRequestReview entity) {
- super.delete(entity);
- listenerRegistry.notify(new PullRequestReviewDeleted(entity, accountManager.getCurrent(), null));
- }
-
- @Sessional
- @Override
- public List<PullRequestReview> findAll(PullRequest request) {
- EntityCriteria<PullRequestReview> criteria = EntityCriteria.of(PullRequestReview.class);
- criteria.createCriteria("update").add(Restrictions.eq("request", request));
- criteria.addOrder(Order.asc("date"));
- return findAll(criteria);
- }
-
- @Transactional
- @Override
- public void deleteAll(Account user, PullRequest request) {
- for (Iterator<PullRequestReview> it = request.getReviews().iterator(); it.hasNext();) {
- PullRequestReview review = it.next();
- if (review.getUser().equals(user)) {
- delete(review);
- it.remove();
- }
- }
- }
-
-}
+package com.pmease.gitplex.core.manager.impl;
+
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
+
+import com.pmease.commons.hibernate.Sessional;
+import com.pmease.commons.hibernate.Transactional;
+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.ListenerRegistry;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestApproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestChangeEvent;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestDisapproved;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewDeleted;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+
+@Singleton
+public class DefaultPullRequestReviewManager extends AbstractEntityManager<PullRequestReview> implements PullRequestReviewManager {
+
+ private final AccountManager accountManager;
+
+ private final PullRequestManager pullRequestManager;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultPullRequestReviewManager(Dao dao, AccountManager accountManager, PullRequestManager pullRequestManager,
+ ListenerRegistry listenerRegistry) {
+ super(dao);
+
+ this.accountManager = accountManager;
+ this.pullRequestManager = pullRequestManager;
+ this.listenerRegistry = listenerRegistry;
+ }
+
+ @Sessional
+ @Override
+ public PullRequestReview find(Account user, PullRequestUpdate update) {
+ return find(EntityCriteria.of(PullRequestReview.class)
+ .add(Restrictions.eq("user", user))
+ .add(Restrictions.eq("update", update)));
+ }
+
+ @Transactional
+ @Override
+ public void review(PullRequest request, PullRequestReview.Result result, String note) {
+ PullRequestReview review = new PullRequestReview();
+ review.setUpdate(request.getLatestUpdate());
+ review.setResult(result);
+ review.setUser(accountManager.getCurrent());
+ review.setDate(new Date());
+ save(review);
+
+ PullRequestChangeEvent event;
+ if (result == PullRequestReview.Result.APPROVE) {
+ event = new PullRequestApproved(review, note);
+ } else {
+ event = new PullRequestDisapproved(review, note);
+ }
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ pullRequestManager.save(request);
+ }
+
+ @Transactional
+ @Override
+ public void delete(PullRequestReview entity) {
+ super.delete(entity);
+ PullRequestReviewDeleted event = new PullRequestReviewDeleted(entity, accountManager.getCurrent(), null);
+ listenerRegistry.post(event);
+ event.getRequest().setLastEvent(event);
+ pullRequestManager.save(event.getRequest());
+ }
+
+ @Sessional
+ @Override
+ public List<PullRequestReview> findAll(PullRequest request) {
+ EntityCriteria<PullRequestReview> criteria = EntityCriteria.of(PullRequestReview.class);
+ criteria.createCriteria("update").add(Restrictions.eq("request", request));
+ criteria.addOrder(Order.asc("date"));
+ return findAll(criteria);
+ }
+
+ @Transactional
+ @Override
+ public void deleteAll(Account user, PullRequest request) {
+ for (Iterator<PullRequestReview> it = request.getReviews().iterator(); it.hasNext();) {
+ PullRequestReview review = it.next();
+ if (review.getUser().equals(user)) {
+ delete(review);
+ it.remove();
+ }
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestStatusChangeManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestStatusChangeManager.java
index a07889782a..d655b4b78e 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestStatusChangeManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestStatusChangeManager.java
@@ -1,7 +1,5 @@
package com.pmease.gitplex.core.manager.impl;
-import java.util.Date;
-
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -27,7 +25,7 @@ public class DefaultPullRequestStatusChangeManager extends AbstractEntityManager
public void on(PullRequestStatusChangeEvent event) {
PullRequestStatusChange statusChange = new PullRequestStatusChange();
statusChange.setRequest(event.getRequest());
- statusChange.setDate(new Date());
+ statusChange.setDate(event.getDate());
statusChange.setEventType(event.getClass());
statusChange.setUser(event.getUser());
statusChange.setNote(event.getNote());
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
index 9c06bfc3f2..59c8a88b16 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestUpdateManager.java
@@ -24,6 +24,7 @@ import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.PullRequestUpdate;
import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
import com.pmease.gitplex.core.manager.PullRequestCommentManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.core.manager.PullRequestUpdateManager;
@Singleton
@@ -32,12 +33,15 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
private final ListenerRegistry listenerRegistry;
+ private final PullRequestManager pullRequestManager;
+
@Inject
public DefaultPullRequestUpdateManager(Dao dao, ListenerRegistry listenerRegistry,
- PullRequestCommentManager commentManager) {
+ PullRequestCommentManager commentManager, PullRequestManager pullRequestManager) {
super(dao);
this.listenerRegistry = listenerRegistry;
+ this.pullRequestManager = pullRequestManager;
}
@Transactional
@@ -48,7 +52,7 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
@Transactional
@Override
- public void save(PullRequestUpdate update, boolean notifyListeners) {
+ public void save(PullRequestUpdate update, boolean callListeners) {
PullRequest request = update.getRequest();
String sourceHead = request.getSource().getObjectName();
@@ -70,8 +74,12 @@ public class DefaultPullRequestUpdateManager extends AbstractEntityManager<PullR
GitUtils.updateRef(refUpdate);
}
- if (notifyListeners)
- listenerRegistry.notify(new PullRequestUpdated(update));
+ if (callListeners) {
+ PullRequestUpdated event = new PullRequestUpdated(update);
+ listenerRegistry.post(event);
+ request.setLastEvent(event);
+ pullRequestManager.save(request);
+ }
}
@Sessional
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestVerificationManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestVerificationManager.java
index 710dafc296..7d6de41b65 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestVerificationManager.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestVerificationManager.java
@@ -16,11 +16,13 @@ import com.pmease.commons.loader.ListenerRegistry;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.entity.PullRequestVerification;
import com.pmease.gitplex.core.entity.PullRequestVerification.Status;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestChangeEvent;
import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationDeleted;
import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationFailed;
import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationRunning;
import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationSucceeded;
import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.core.manager.PullRequestVerificationManager;
@Singleton
@@ -31,11 +33,15 @@ public class DefaultPullRequestVerificationManager extends AbstractEntityManager
private final ListenerRegistry listenerRegistry;
+ private final PullRequestManager pullRequestManager;
+
@Inject
- public DefaultPullRequestVerificationManager(Dao dao, AccountManager accountManager, ListenerRegistry listenerRegistry) {
+ public DefaultPullRequestVerificationManager(Dao dao, AccountManager accountManager,
+ ListenerRegistry listenerRegistry, PullRequestManager pullRequestManager) {
super(dao);
this.accountManager = accountManager;
this.listenerRegistry = listenerRegistry;
+ this.pullRequestManager = pullRequestManager;
}
@Transactional
@@ -43,19 +49,28 @@ public class DefaultPullRequestVerificationManager extends AbstractEntityManager
public void save(PullRequestVerification entity) {
super.save(entity);
+ PullRequestChangeEvent event;
if (entity.getStatus() == PullRequestVerification.Status.FAILED)
- listenerRegistry.notify(new PullRequestVerificationFailed(entity));
+ event = new PullRequestVerificationFailed(entity);
else if (entity.getStatus() == PullRequestVerification.Status.RUNNING)
- listenerRegistry.notify(new PullRequestVerificationRunning(entity));
+ event = new PullRequestVerificationRunning(entity);
else
- listenerRegistry.notify(new PullRequestVerificationSucceeded(entity));
+ event = new PullRequestVerificationSucceeded(entity);
+ if (entity.getStatus() != PullRequestVerification.Status.RUNNING) {
+ listenerRegistry.post(event);
+ event.getRequest().setLastEvent(event);
+ pullRequestManager.save(event.getRequest());
+ }
}
@Transactional
@Override
public void delete(PullRequestVerification entity) {
super.delete(entity);
- listenerRegistry.notify(new PullRequestVerificationDeleted(entity, accountManager.getCurrent()));
+ PullRequestVerificationDeleted event = new PullRequestVerificationDeleted(entity, accountManager.getCurrent());
+ listenerRegistry.post(event);
+ event.getRequest().setLastEvent(event);
+ pullRequestManager.save(event.getRequest());
}
@Sessional
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java
new file mode 100644
index 0000000000..318cf4d47e
--- /dev/null
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/manager/impl/DefaultPullRequestWatchManager.java
@@ -0,0 +1,234 @@
+package com.pmease.gitplex.core.manager.impl;
+
+import java.util.Collection;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.eclipse.jgit.lib.PersonIdent;
+import org.eclipse.jgit.revwalk.RevCommit;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.git.NameAndEmail;
+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.markdown.MarkdownManager;
+import com.pmease.commons.wicket.editable.EditableUtils;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.BranchWatch;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.PullRequestWatch;
+import com.pmease.gitplex.core.event.pullrequest.IntegrationPreviewCalculated;
+import com.pmease.gitplex.core.event.pullrequest.MarkdownAware;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestAssigned;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestChangeEvent;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestOpened;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestReviewInvitationChanged;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestUpdated;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationFailed;
+import com.pmease.gitplex.core.event.pullrequest.PullRequestVerificationRunning;
+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.BranchWatchManager;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.manager.PullRequestWatchManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+import com.pmease.gitplex.core.manager.VisitInfoManager;
+import com.pmease.gitplex.core.util.markdown.MentionParser;
+
+@Singleton
+public class DefaultPullRequestWatchManager extends AbstractEntityManager<PullRequestWatch>
+ implements PullRequestWatchManager {
+
+ private final AccountManager userManager;
+
+ private final BranchWatchManager branchWatchManager;
+
+ private final MailManager mailManager;
+
+ private final UrlManager urlManager;
+
+ private final VisitInfoManager visitInfoManager;
+
+ private final MarkdownManager markdownManager;
+
+ @Inject
+ public DefaultPullRequestWatchManager(Dao dao, AccountManager userManager, MarkdownManager markdownManager,
+ BranchWatchManager branchWatchManager, MailManager mailManager, UrlManager urlManager,
+ VisitInfoManager visitInfoManager) {
+ super(dao);
+ this.userManager = userManager;
+ this.branchWatchManager = branchWatchManager;
+ this.mailManager = mailManager;
+ this.urlManager = urlManager;
+ this.visitInfoManager = visitInfoManager;
+ this.markdownManager = markdownManager;
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestChangeEvent event) {
+ if (event instanceof IntegrationPreviewCalculated || event instanceof SourceBranchDeleted
+ || event instanceof SourceBranchRestored || event instanceof PullRequestVerificationRunning) {
+ return;
+ }
+
+ PullRequest request = event.getRequest();
+ Account user = event.getUser();
+
+ Collection<Account> mentionUsers = new HashSet<>();
+
+ /*
+ * verification is often performed automatically by robots (such as CI system), and it does not make
+ * sense to make them watching the pull request
+ */
+ if (user != null && !(event instanceof PullRequestVerificationSucceeded) && !(event instanceof PullRequestVerificationFailed)) {
+ watch(request, user,
+ "You've set to watch this pull request as you've " + EditableUtils.getName(event.getClass()));
+ }
+ if (event instanceof PullRequestOpened) {
+ if (request.getAssignee() != null)
+ watch(request, request.getAssignee(), "You are set to watch this pull request as you are assigned to integrate it.");
+ for (BranchWatch branchWatch: branchWatchManager.find(request.getTargetDepot(), request.getTargetBranch())) {
+ watch(request, branchWatch.getUser(),
+ "You are set to watch this pull request as you are watching the target branch.");
+ }
+ makeContributorsWatching(request.getLatestUpdate());
+ } else if (event instanceof PullRequestAssigned) {
+ watch(request, request.getAssignee(), "You are set to watch this pull request as you are assigned to integrate it.");
+ } else if (event instanceof MarkdownAware) {
+ MarkdownAware markdownAware = (MarkdownAware) event;
+ String markdown = markdownAware.getMarkdown();
+ if (markdown != null) {
+ String html = markdownManager.parse(markdown);
+ mentionUsers.addAll(new MentionParser().parseMentions(html));
+ for (Account mention: mentionUsers) {
+ watch(request, mention, "You are set to watch this pull request as you are mentioned in code comment.");
+ }
+ }
+ } else if (event instanceof PullRequestUpdated) {
+ PullRequestUpdated updated = (PullRequestUpdated) event;
+ makeContributorsWatching(updated.getUpdate());
+ }
+
+ Collection<Account> watchUsers = new HashSet<>();
+
+ for (PullRequestWatch watch: request.getWatches()) {
+ if (!watch.isIgnore() && !watch.getUser().equals(event.getUser())) {
+ if (request.getLastEvent() == null) {
+ watchUsers.add(watch.getUser());
+ } else {
+ Date visitDate = visitInfoManager.getVisitDate(watch.getUser(), request);
+ if (visitDate == null || visitDate.getTime()<request.getLastEvent().getDate().getTime()) {
+ if (request.getLastEvent().getType() != event.getClass()) {
+ watchUsers.add(watch.getUser());
+ }
+ } else {
+ watchUsers.add(watch.getUser());
+ }
+ }
+ }
+ }
+
+ watchUsers.removeAll(mentionUsers);
+
+ if ((event instanceof PullRequestOpened || event instanceof PullRequestAssigned)
+ && request.getAssignee() != null
+ && !request.getAssignee().equals(event.getUser())) {
+ watchUsers.remove(request.getAssignee());
+ String subject = String.format("You are assigned with pull request #%d (%s)",
+ request.getNumber(), request.getTitle());
+ String url = urlManager.urlFor(request);
+ String body = String.format("You are assigned with pull request #%d (%s).<br>"
+ + "Please visit <a href='%s'>%s</a> for details.",
+ request.getNumber(), request.getTitle(), url, url);
+ mailManager.sendMailAsync(Sets.newHashSet(request.getAssignee()), subject, decorate(user, body));
+ }
+
+ if (!watchUsers.isEmpty()) {
+ String subject, body;
+ String url = urlManager.urlFor(request);
+ if (event instanceof PullRequestOpened) {
+ subject = String.format("Newly opened pull request - #%d (%s)",
+ request.getNumber(), request.getTitle());
+ body = String.format("Dear Users,"
+ + "<p style='margin: 16px 0;'>A new pull request is opened - #%d (%s)"
+ + "<p style='margin: 16px 0;'>Visit <a href='%s'>%s</a> for details."
+ + "<p style='margin: 16px 0;'>-- Sent by GitPlex"
+ + "<p style='margin: 16px 0; font-size: 12px; color: #888;'>"
+ + "You receive this email as you are watching target branch.",
+ request.getNumber(), request.getTitle(), url, url);
+ } else {
+ subject = String.format("New activity in pull request #%d (%s) - %s",
+ request.getNumber(), request.getTitle(), EditableUtils.getName(event.getClass()));
+ body = String.format("Dear Users,"
+ + "<p style='margin: 16px 0;'>There is new activity in pull request #%d (%s) - %s "
+ + "<p style='margin: 16px 0;'>Visit <a href='%s'>%s</a> for details."
+ + "<p style='margin: 16px 0;'>-- Sent by GitPlex"
+ + "<p style='margin: 16px 0; font-size: 12px; color: #888;'>"
+ + "You receive this email as you are watching the pull request.",
+ request.getNumber(), request.getTitle(), EditableUtils.getName(event.getClass()), url, url);
+ }
+ mailManager.sendMailAsync(watchUsers, subject, body);
+ }
+
+ }
+
+ private String decorate(Account user, String body) {
+ return String.format("Dear %s, "
+ + "<p style='margin: 16px 0;'>"
+ + "%s"
+ + "<p style='margin: 16px 0;'>"
+ + "-- Sent by GitPlex",
+ user.getDisplayName(), body);
+ }
+
+ @Transactional
+ private void makeContributorsWatching(PullRequestUpdate update) {
+ // we use a name-email pair to filter off duplicate person as equals method of PersonIdent also takes
+ // "when" field into account
+ Set<NameAndEmail> nameAndEmails = new HashSet<>();
+ for (RevCommit commit: update.getCommits()) {
+ nameAndEmails.add(new NameAndEmail(commit.getCommitterIdent()));
+ nameAndEmails.add(new NameAndEmail(commit.getAuthorIdent()));
+ }
+ for (NameAndEmail nameAndEmail: nameAndEmails) {
+ PersonIdent person = new PersonIdent(nameAndEmail.getName(), nameAndEmail.getEmailAddress());
+ Account user = userManager.find(person);
+ if (user != null)
+ watch(update.getRequest(), user, "You are set to watch this pull request as it contains your commits.");
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(PullRequestReviewInvitationChanged event) {
+ PullRequestReviewInvitation invitation = event.getInvitation();
+ if (invitation.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED) {
+ watch(invitation.getRequest(), invitation.getUser(),
+ "You are set to watch this pull request as you are invited to review it.");
+ }
+ }
+
+ private void watch(PullRequest request, Account user, String reason) {
+ PullRequestWatch watch = request.getWatch(user);
+ if (watch == null) {
+ watch = new PullRequestWatch();
+ watch.setRequest(request);
+ watch.setUser(user);
+ watch.setReason(reason);
+ request.getWatches().add(watch);
+ save(watch);
+ }
+ }
+
+}
diff --git a/gitplex.core/src/main/java/com/pmease/gitplex/core/setting/MailSetting.java b/gitplex.core/src/main/java/com/pmease/gitplex/core/setting/MailSetting.java
index 347806d32f..023dc7d3d5 100644
--- a/gitplex.core/src/main/java/com/pmease/gitplex/core/setting/MailSetting.java
+++ b/gitplex.core/src/main/java/com/pmease/gitplex/core/setting/MailSetting.java
@@ -14,22 +14,14 @@ public class MailSetting implements Serializable {
private String smtpHost;
- private int smtpPort = 25;
-
- private int sslSmtpPort = 465;
-
- private boolean smtpOverSSL;
+ private int smtpPort = 587;
private String smtpUser;
private String smtpPassword;
- private boolean enableStartTLS;
-
private String senderAddress;
- private String replyAddress;
-
private int timeout = 300;
@Editable(order=100, name="SMTP Host", description=
@@ -56,32 +48,6 @@ public class MailSetting implements Serializable {
this.smtpPort = smtpPort;
}
- @Editable(order=210, name="SSL SMTP Port", description=
- "Specify SSL port number for the above SMTP host. This port number "
- + "will be used if the option 'Use SMTP over SSL' is checked."
- )
- public int getSslSmtpPort() {
- return sslSmtpPort;
- }
-
- public void setSslSmtpPort(int sslSmtpPort) {
- this.sslSmtpPort = sslSmtpPort;
- }
-
- @Editable(order=250, name="Use SMTP over SSL?", description=
- "Whether or not send email using SMTP over SSL. If SSL is enabled, and a " +
- "<b>SSLHandshakeException</b> is thrown with message <b>unable to find " +
- "valid certification path to requested target</b> while sending the email, " +
- "please make sure public key of your SMTP server is trusted by GitPlex."
- )
- public boolean isSmtpOverSSL() {
- return smtpOverSSL;
- }
-
- public void setSmtpOverSSL(boolean smtpOverSSL) {
- this.smtpOverSSL = smtpOverSSL;
- }
-
@Editable(order=300, name="SMTP User", description=
"Optionally specify user name here if the SMTP host needs authentication"
)
@@ -105,17 +71,6 @@ public class MailSetting implements Serializable {
this.smtpPassword = smtpPassword;
}
- @Editable(order=450, name="Enable Start TLS?", description=
- "Whether the STARTTLS command used to switch to an encrypted connection for authentication."
- )
- public boolean isEnableStartTLS() {
- return enableStartTLS;
- }
-
- public void setEnableStartTLS(boolean enableStartTLS) {
- this.enableStartTLS = enableStartTLS;
- }
-
@Editable(order=500, description=
"This property is optional. If specified, GitPlex will use this email " +
"as the sender address when sending out emails. Otherwise, the sender " +
@@ -130,19 +85,6 @@ public class MailSetting implements Serializable {
this.senderAddress = senderAddress;
}
- @Editable(order=500, description=
- "This property is optional. If specified, GitPlex will use this email " +
- "as the reply-to address when user replies to the notification email. Otherwise, " +
- "the sender address will be used."
- )
- public String getReplyAddress() {
- return replyAddress;
- }
-
- public void setReplyAddress(String replyAddress) {
- this.replyAddress = replyAddress;
- }
-
@Editable(order=600, description="Specify timeout in seconds when communicating with the SMTP server. " +
"Use 0 to set an infinite timeout.")
public int getTimeout() {
diff --git a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
index 1534f591f6..1d21f57bdf 100644
--- a/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
+++ b/gitplex.search/src/main/java/com/pmease/gitplex/search/DefaultIndexManager.java
@@ -1,450 +1,450 @@
-package com.pmease.gitplex.search;
-
-import static com.pmease.gitplex.search.FieldConstants.BLOB_HASH;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_PATH;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
-import static com.pmease.gitplex.search.FieldConstants.BLOB_TEXT;
-import static com.pmease.gitplex.search.FieldConstants.COMMIT_HASH;
-import static com.pmease.gitplex.search.FieldConstants.COMMIT_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_HASH;
-import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_INDEX_VERSION;
-import static com.pmease.gitplex.search.FieldConstants.META;
-import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
-import static com.pmease.gitplex.search.IndexConstants.NGRAM_SIZE;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.concurrent.Callable;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.lucene.document.Document;
-import org.apache.lucene.document.Field.Store;
-import org.apache.lucene.document.StoredField;
-import org.apache.lucene.document.StringField;
-import org.apache.lucene.document.TextField;
-import org.apache.lucene.index.AtomicReaderContext;
-import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
-import org.apache.lucene.search.BooleanClause.Occur;
-import org.apache.lucene.search.BooleanQuery;
-import org.apache.lucene.search.Collector;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.search.Scorer;
-import org.apache.lucene.search.TopDocs;
-import org.apache.lucene.store.Directory;
-import org.apache.lucene.store.FSDirectory;
-import org.apache.lucene.util.Version;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.eclipse.jgit.lib.AnyObjectId;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.FileMode;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.ObjectLoader;
-import org.eclipse.jgit.lib.Repository;
-import org.eclipse.jgit.revwalk.RevWalk;
-import org.eclipse.jgit.treewalk.TreeWalk;
-import org.eclipse.jgit.treewalk.filter.TreeFilter;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Throwables;
-import com.pmease.commons.hibernate.Transactional;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.lang.extractors.ExtractException;
-import com.pmease.commons.lang.extractors.Extractor;
-import com.pmease.commons.lang.extractors.Extractors;
-import com.pmease.commons.lang.extractors.Symbol;
-import com.pmease.commons.loader.Listen;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.util.ContentDetector;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.concurrent.Prioritized;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.event.RefUpdated;
-import com.pmease.gitplex.core.event.depot.DepotDeleted;
-import com.pmease.gitplex.core.manager.BatchWorkManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.support.BatchWorker;
-import com.pmease.gitplex.core.manager.support.IndexResult;
-
-@Singleton
-public class DefaultIndexManager implements IndexManager {
-
- private static final Logger logger = LoggerFactory.getLogger(DefaultIndexManager.class);
-
- private static final int UI_INDEXING_PRIORITY = 10;
-
- private static final int BACKEND_INDEXING_PRIORITY = 50;
-
- private static final int INDEX_VERSION = 1;
-
- private final StorageManager storageManager;
-
- private final BatchWorkManager batchWorkManager;
-
- private final SearchManager searchManager;
-
- private final Extractors extractors;
-
- private final UnitOfWork unitOfWork;
-
- private final Dao dao;
-
- private final ListenerRegistry listenerRegistry;
-
- @Inject
- public DefaultIndexManager(ListenerRegistry listenerRegistry, StorageManager storageManager,
- BatchWorkManager batchWorkManager, Extractors extractors,
- UnitOfWork unitOfWork, Dao dao, SearchManager searchManager) {
- this.listenerRegistry = listenerRegistry;
- this.storageManager = storageManager;
- this.batchWorkManager = batchWorkManager;
- this.extractors = extractors;
- this.unitOfWork = unitOfWork;
- this.dao = dao;
- this.searchManager = searchManager;
- }
-
- private String getCommitIndexVersion(final IndexSearcher searcher, AnyObjectId commitId) throws IOException {
- final AtomicReference<String> indexVersion = new AtomicReference<>(null);
-
- searcher.search(COMMIT_HASH.query(commitId.getName()), new Collector() {
-
- private int docBase;
-
- @Override
- public void setScorer(Scorer scorer) throws IOException {
- }
-
- @Override
- public void collect(int doc) throws IOException {
- indexVersion.set(searcher.doc(docBase+doc).get(COMMIT_INDEX_VERSION.name()));
- }
-
- @Override
- public void setNextReader(AtomicReaderContext context) throws IOException {
- docBase = context.docBase;
- }
-
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return true;
- }
-
- });
- return indexVersion.get();
- }
-
- private IndexResult index(Repository repository, AnyObjectId commitId,
- IndexWriter writer, final IndexSearcher searcher) throws Exception {
- try ( RevWalk revWalk = new RevWalk(repository);
- TreeWalk treeWalk = new TreeWalk(repository)) {
- treeWalk.addTree(revWalk.parseCommit(commitId).getTree());
- treeWalk.setRecursive(true);
-
- if (searcher != null) {
- TopDocs topDocs = searcher.search(META.query(LAST_COMMIT.name()), 1);
- if (topDocs.scoreDocs.length != 0) {
- Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
- String lastCommitAnalyzersVersion = doc.get(LAST_COMMIT_INDEX_VERSION.name());
- if (lastCommitAnalyzersVersion.equals(extractors.getVersion())) {
- String lastCommitHash = doc.get(LAST_COMMIT_HASH.name());
- ObjectId lastCommitId = repository.resolve(lastCommitHash);
- if (repository.hasObject(lastCommitId)) {
- treeWalk.addTree(revWalk.parseCommit(lastCommitId).getTree());
- treeWalk.setFilter(TreeFilter.ANY_DIFF);
- }
- }
- }
- }
-
- int indexed = 0;
- int checked = 0;
- while (treeWalk.next()) {
- if ((treeWalk.getRawMode(0) & FileMode.TYPE_MASK) == FileMode.TYPE_FILE
- && (treeWalk.getTreeCount() == 1 || !treeWalk.idEqual(0, 1))) {
- ObjectId blobId = treeWalk.getObjectId(0);
- String blobPath = treeWalk.getPathString();
-
- BooleanQuery query = new BooleanQuery();
- query.add(BLOB_HASH.query(blobId.name()), Occur.MUST);
- query.add(BLOB_PATH.query(blobPath), Occur.MUST);
-
- final AtomicReference<String> blobIndexVersionRef = new AtomicReference<>(null);
- if (searcher != null) {
- searcher.search(query, new Collector() {
-
- private AtomicReaderContext context;
-
- @Override
- public void setScorer(Scorer scorer) throws IOException {
- }
-
- @Override
- public void collect(int doc) throws IOException {
- blobIndexVersionRef.set(searcher.doc(context.docBase+doc).get(BLOB_INDEX_VERSION.name()));
- }
-
- @Override
- public void setNextReader(AtomicReaderContext context) throws IOException {
- this.context = context;
- }
-
- @Override
- public boolean acceptsDocsOutOfOrder() {
- return true;
- }
-
- });
- checked++;
- }
-
- Extractor extractor = extractors.getExtractor(blobPath);
- String currentBlobIndexVersion = getCurrentBlobIndexVersion(extractor);
- String blobIndexVersion = blobIndexVersionRef.get();
- if (blobIndexVersion != null) {
- if (currentBlobIndexVersion != null) {
- if (!blobIndexVersion.equals(currentBlobIndexVersion)) {
- writer.deleteDocuments(query);
- indexBlob(writer, repository, extractor, blobId, blobPath);
- indexed++;
- }
- } else {
- writer.deleteDocuments(query);
- }
- } else if (currentBlobIndexVersion != null) {
- indexBlob(writer, repository, extractor, blobId, blobPath);
- indexed++;
- }
- }
- }
-
- // record current commit so that we know which commit has been indexed
- Document document = new Document();
- document.add(new StringField(COMMIT_HASH.name(), commitId.getName(), Store.NO));
- document.add(new StoredField(COMMIT_INDEX_VERSION.name(), getCurrentCommitIndexVersion()));
- writer.updateDocument(COMMIT_HASH.term(commitId.getName()), document);
-
- // record last commit so that we only need to indexing changed files for subsequent commits
- document = new Document();
- document.add(new StringField(META.name(), LAST_COMMIT.name(), Store.NO));
- document.add(new StoredField(LAST_COMMIT_INDEX_VERSION.name(), extractors.getVersion()));
- document.add(new StoredField(LAST_COMMIT_HASH.name(), commitId.getName()));
- writer.updateDocument(META.term(LAST_COMMIT.name()), document);
-
- return new IndexResult(checked, indexed);
- }
- }
-
- private void indexBlob(IndexWriter writer, Repository repository,
- Extractor extractor, ObjectId blobId, String blobPath) throws IOException {
- Document document = new Document();
-
- document.add(new StoredField(BLOB_INDEX_VERSION.name(), getCurrentBlobIndexVersion(extractor)));
- document.add(new StringField(BLOB_HASH.name(), blobId.name(), Store.NO));
- document.add(new StringField(BLOB_PATH.name(), blobPath, Store.YES));
-
- String blobName = blobPath;
- if (blobPath.indexOf('/') != -1)
- blobName = StringUtils.substringAfterLast(blobPath, "/");
-
- document.add(new StringField(BLOB_NAME.name(), blobName.toLowerCase(), Store.NO));
-
- ObjectLoader objectLoader = repository.open(blobId);
- if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
- byte[] bytes = objectLoader.getCachedBytes();
- String content = ContentDetector.convertToText(bytes, blobName);
- if (content != null) {
- document.add(new TextField(BLOB_TEXT.name(), content, Store.NO));
-
- if (extractor != null) {
- try {
- for (Symbol symbol: extractor.extract(content)) {
- String fieldValue = symbol.getName();
- if (fieldValue != null) {
- fieldValue = fieldValue.toLowerCase();
-
- String fieldName;
- if (symbol.isPrimary())
- fieldName = BLOB_PRIMARY_SYMBOLS.name();
- else
- fieldName = BLOB_SECONDARY_SYMBOLS.name();
- document.add(new StringField(fieldName, fieldValue, Store.NO));
- }
- }
- } catch (ExtractException e) {
- logger.error("Error extracting symbols from blob (hash:" + blobId.name() + ", path:" + blobPath + ")", e);
- }
- }
- } else {
- logger.debug("Ignore content of binary file '{}'.", blobPath);
- }
- } else {
- logger.debug("Ignore content of large file '{}'.", blobPath);
- }
-
- writer.addDocument(document);
- }
-
- private IndexWriterConfig newIndexWriterConfig() {
- IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new NGramAnalyzer(NGRAM_SIZE, NGRAM_SIZE));
- config.setOpenMode(OpenMode.CREATE_OR_APPEND);
- return config;
- }
-
- private BatchWorker getBatchWorker(Depot depot) {
- Long depotId = depot.getId();
- return new BatchWorker("depot-" + depotId + "-indexBlob", 1) {
-
- @Override
- public void doWork(Collection<Prioritized> works) {
- Preconditions.checkState(works.size() == 1);
- unitOfWork.call(new Callable<Void>() {
-
- @Override
- public Void call() throws Exception {
- Depot depot = dao.load(Depot.class, depotId);
- IndexWork indexWork = (IndexWork) works.iterator().next();
- index(depot, indexWork.getCommitId());
- return null;
- }
-
- });
- }
-
- };
- }
-
- @Override
- public IndexResult index(Depot depot, ObjectId commit) {
- IndexResult indexResult;
- File indexDir = storageManager.getIndexDir(depot);
- try (Directory directory = FSDirectory.open(indexDir)) {
- if (DirectoryReader.indexExists(directory)) {
- try (IndexReader reader = DirectoryReader.open(directory)) {
- IndexSearcher searcher = new IndexSearcher(reader);
- if (getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit))) {
- return new IndexResult(0, 0);
- } else {
- try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
- logger.debug("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
- try {
- indexResult = index(depot.getRepository(), commit, writer, searcher);
- writer.commit();
- } catch (Exception e) {
- writer.rollback();
- throw Throwables.propagate(e);
- }
- }
- }
- }
- } else {
- try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
- try {
- logger.debug("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
- indexResult = index(depot.getRepository(), commit, writer, null);
- writer.commit();
- } catch (Exception e) {
- writer.rollback();
- throw Throwables.propagate(e);
- }
- }
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- listenerRegistry.notify(new CommitIndexed(depot, commit.copy()));
-
- logger.debug("Commit indexed (repository: {}, commit: {}, checked blobs: {}, indexed blobs: {})",
- depot.getFQN(), commit.name(), indexResult.getChecked(), indexResult.getIndexed());
-
- return indexResult;
- }
-
- private String getCurrentCommitIndexVersion() {
- return INDEX_VERSION + ";" + extractors.getVersion();
- }
-
- private String getCurrentBlobIndexVersion(Extractor extractor) {
- if (extractor != null)
- return INDEX_VERSION + ";" + extractor.getVersion();
- else
- return String.valueOf(INDEX_VERSION);
- }
-
- @Override
- public boolean isIndexed(Depot depot, ObjectId commit) {
- File indexDir = storageManager.getIndexDir(depot);
- try (Directory directory = FSDirectory.open(indexDir)) {
- if (DirectoryReader.indexExists(directory)) {
- try (IndexReader reader = DirectoryReader.open(directory)) {
- IndexSearcher searcher = new IndexSearcher(reader);
- return getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit));
- }
- } else {
- return false;
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Transactional
- @Listen
- public void on(DepotDeleted event) {
- searchManager.closeSearcher(event.getDepot());
- FileUtils.deleteDir(storageManager.getIndexDir(event.getDepot()));
- }
-
- @Listen
- public void on(RefUpdated event) {
- // only index branches at back end, tags will be indexed on demand from GUI
- // as many tags might be pushed all at once when the repository is imported
- if (event.getRefName().startsWith(Constants.R_HEADS) && !event.getNewCommit().equals(ObjectId.zeroId())) {
- IndexWork work = new IndexWork(BACKEND_INDEXING_PRIORITY, event.getNewCommit());
- batchWorkManager.submit(getBatchWorker(event.getDepot()), work);
- }
- }
-
- @Override
- public void indexAsync(Depot depot, ObjectId commit) {
- int priority;
- if (RequestCycle.get() != null)
- priority = UI_INDEXING_PRIORITY;
- else
- priority = BACKEND_INDEXING_PRIORITY;
- IndexWork work = new IndexWork(priority, commit);
- batchWorkManager.submit(getBatchWorker(depot), work);
- }
-
- private static class IndexWork extends Prioritized {
-
- private final ObjectId commitId;
-
- public IndexWork(int priority, ObjectId commitId) {
- super(priority);
- this.commitId = commitId;
- }
-
- public ObjectId getCommitId() {
- return commitId;
- }
-
- }
-
-}
+package com.pmease.gitplex.search;
+
+import static com.pmease.gitplex.search.FieldConstants.BLOB_HASH;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_NAME;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_PATH;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_PRIMARY_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_SECONDARY_SYMBOLS;
+import static com.pmease.gitplex.search.FieldConstants.BLOB_TEXT;
+import static com.pmease.gitplex.search.FieldConstants.COMMIT_HASH;
+import static com.pmease.gitplex.search.FieldConstants.COMMIT_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_HASH;
+import static com.pmease.gitplex.search.FieldConstants.LAST_COMMIT_INDEX_VERSION;
+import static com.pmease.gitplex.search.FieldConstants.META;
+import static com.pmease.gitplex.search.IndexConstants.MAX_INDEXABLE_SIZE;
+import static com.pmease.gitplex.search.IndexConstants.NGRAM_SIZE;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.concurrent.Callable;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field.Store;
+import org.apache.lucene.document.StoredField;
+import org.apache.lucene.document.StringField;
+import org.apache.lucene.document.TextField;
+import org.apache.lucene.index.AtomicReaderContext;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.IndexWriterConfig.OpenMode;
+import org.apache.lucene.search.BooleanClause.Occur;
+import org.apache.lucene.search.BooleanQuery;
+import org.apache.lucene.search.Collector;
+import org.apache.lucene.search.IndexSearcher;
+import org.apache.lucene.search.Scorer;
+import org.apache.lucene.search.TopDocs;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.util.Version;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.eclipse.jgit.lib.AnyObjectId;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.FileMode;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.ObjectLoader;
+import org.eclipse.jgit.lib.Repository;
+import org.eclipse.jgit.revwalk.RevWalk;
+import org.eclipse.jgit.treewalk.TreeWalk;
+import org.eclipse.jgit.treewalk.filter.TreeFilter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.pmease.commons.hibernate.Transactional;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.lang.extractors.ExtractException;
+import com.pmease.commons.lang.extractors.Extractor;
+import com.pmease.commons.lang.extractors.Extractors;
+import com.pmease.commons.lang.extractors.Symbol;
+import com.pmease.commons.loader.Listen;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.util.ContentDetector;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.concurrent.Prioritized;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.event.RefUpdated;
+import com.pmease.gitplex.core.event.depot.DepotDeleted;
+import com.pmease.gitplex.core.manager.BatchWorkManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.support.BatchWorker;
+import com.pmease.gitplex.core.manager.support.IndexResult;
+
+@Singleton
+public class DefaultIndexManager implements IndexManager {
+
+ private static final Logger logger = LoggerFactory.getLogger(DefaultIndexManager.class);
+
+ private static final int UI_INDEXING_PRIORITY = 10;
+
+ private static final int BACKEND_INDEXING_PRIORITY = 50;
+
+ private static final int INDEX_VERSION = 1;
+
+ private final StorageManager storageManager;
+
+ private final BatchWorkManager batchWorkManager;
+
+ private final SearchManager searchManager;
+
+ private final Extractors extractors;
+
+ private final UnitOfWork unitOfWork;
+
+ private final Dao dao;
+
+ private final ListenerRegistry listenerRegistry;
+
+ @Inject
+ public DefaultIndexManager(ListenerRegistry listenerRegistry, StorageManager storageManager,
+ BatchWorkManager batchWorkManager, Extractors extractors,
+ UnitOfWork unitOfWork, Dao dao, SearchManager searchManager) {
+ this.listenerRegistry = listenerRegistry;
+ this.storageManager = storageManager;
+ this.batchWorkManager = batchWorkManager;
+ this.extractors = extractors;
+ this.unitOfWork = unitOfWork;
+ this.dao = dao;
+ this.searchManager = searchManager;
+ }
+
+ private String getCommitIndexVersion(final IndexSearcher searcher, AnyObjectId commitId) throws IOException {
+ final AtomicReference<String> indexVersion = new AtomicReference<>(null);
+
+ searcher.search(COMMIT_HASH.query(commitId.getName()), new Collector() {
+
+ private int docBase;
+
+ @Override
+ public void setScorer(Scorer scorer) throws IOException {
+ }
+
+ @Override
+ public void collect(int doc) throws IOException {
+ indexVersion.set(searcher.doc(docBase+doc).get(COMMIT_INDEX_VERSION.name()));
+ }
+
+ @Override
+ public void setNextReader(AtomicReaderContext context) throws IOException {
+ docBase = context.docBase;
+ }
+
+ @Override
+ public boolean acceptsDocsOutOfOrder() {
+ return true;
+ }
+
+ });
+ return indexVersion.get();
+ }
+
+ private IndexResult index(Repository repository, AnyObjectId commitId,
+ IndexWriter writer, final IndexSearcher searcher) throws Exception {
+ try ( RevWalk revWalk = new RevWalk(repository);
+ TreeWalk treeWalk = new TreeWalk(repository)) {
+ treeWalk.addTree(revWalk.parseCommit(commitId).getTree());
+ treeWalk.setRecursive(true);
+
+ if (searcher != null) {
+ TopDocs topDocs = searcher.search(META.query(LAST_COMMIT.name()), 1);
+ if (topDocs.scoreDocs.length != 0) {
+ Document doc = searcher.doc(topDocs.scoreDocs[0].doc);
+ String lastCommitAnalyzersVersion = doc.get(LAST_COMMIT_INDEX_VERSION.name());
+ if (lastCommitAnalyzersVersion.equals(extractors.getVersion())) {
+ String lastCommitHash = doc.get(LAST_COMMIT_HASH.name());
+ ObjectId lastCommitId = repository.resolve(lastCommitHash);
+ if (repository.hasObject(lastCommitId)) {
+ treeWalk.addTree(revWalk.parseCommit(lastCommitId).getTree());
+ treeWalk.setFilter(TreeFilter.ANY_DIFF);
+ }
+ }
+ }
+ }
+
+ int indexed = 0;
+ int checked = 0;
+ while (treeWalk.next()) {
+ if ((treeWalk.getRawMode(0) & FileMode.TYPE_MASK) == FileMode.TYPE_FILE
+ && (treeWalk.getTreeCount() == 1 || !treeWalk.idEqual(0, 1))) {
+ ObjectId blobId = treeWalk.getObjectId(0);
+ String blobPath = treeWalk.getPathString();
+
+ BooleanQuery query = new BooleanQuery();
+ query.add(BLOB_HASH.query(blobId.name()), Occur.MUST);
+ query.add(BLOB_PATH.query(blobPath), Occur.MUST);
+
+ final AtomicReference<String> blobIndexVersionRef = new AtomicReference<>(null);
+ if (searcher != null) {
+ searcher.search(query, new Collector() {
+
+ private AtomicReaderContext context;
+
+ @Override
+ public void setScorer(Scorer scorer) throws IOException {
+ }
+
+ @Override
+ public void collect(int doc) throws IOException {
+ blobIndexVersionRef.set(searcher.doc(context.docBase+doc).get(BLOB_INDEX_VERSION.name()));
+ }
+
+ @Override
+ public void setNextReader(AtomicReaderContext context) throws IOException {
+ this.context = context;
+ }
+
+ @Override
+ public boolean acceptsDocsOutOfOrder() {
+ return true;
+ }
+
+ });
+ checked++;
+ }
+
+ Extractor extractor = extractors.getExtractor(blobPath);
+ String currentBlobIndexVersion = getCurrentBlobIndexVersion(extractor);
+ String blobIndexVersion = blobIndexVersionRef.get();
+ if (blobIndexVersion != null) {
+ if (currentBlobIndexVersion != null) {
+ if (!blobIndexVersion.equals(currentBlobIndexVersion)) {
+ writer.deleteDocuments(query);
+ indexBlob(writer, repository, extractor, blobId, blobPath);
+ indexed++;
+ }
+ } else {
+ writer.deleteDocuments(query);
+ }
+ } else if (currentBlobIndexVersion != null) {
+ indexBlob(writer, repository, extractor, blobId, blobPath);
+ indexed++;
+ }
+ }
+ }
+
+ // record current commit so that we know which commit has been indexed
+ Document document = new Document();
+ document.add(new StringField(COMMIT_HASH.name(), commitId.getName(), Store.NO));
+ document.add(new StoredField(COMMIT_INDEX_VERSION.name(), getCurrentCommitIndexVersion()));
+ writer.updateDocument(COMMIT_HASH.term(commitId.getName()), document);
+
+ // record last commit so that we only need to indexing changed files for subsequent commits
+ document = new Document();
+ document.add(new StringField(META.name(), LAST_COMMIT.name(), Store.NO));
+ document.add(new StoredField(LAST_COMMIT_INDEX_VERSION.name(), extractors.getVersion()));
+ document.add(new StoredField(LAST_COMMIT_HASH.name(), commitId.getName()));
+ writer.updateDocument(META.term(LAST_COMMIT.name()), document);
+
+ return new IndexResult(checked, indexed);
+ }
+ }
+
+ private void indexBlob(IndexWriter writer, Repository repository,
+ Extractor extractor, ObjectId blobId, String blobPath) throws IOException {
+ Document document = new Document();
+
+ document.add(new StoredField(BLOB_INDEX_VERSION.name(), getCurrentBlobIndexVersion(extractor)));
+ document.add(new StringField(BLOB_HASH.name(), blobId.name(), Store.NO));
+ document.add(new StringField(BLOB_PATH.name(), blobPath, Store.YES));
+
+ String blobName = blobPath;
+ if (blobPath.indexOf('/') != -1)
+ blobName = StringUtils.substringAfterLast(blobPath, "/");
+
+ document.add(new StringField(BLOB_NAME.name(), blobName.toLowerCase(), Store.NO));
+
+ ObjectLoader objectLoader = repository.open(blobId);
+ if (objectLoader.getSize() <= MAX_INDEXABLE_SIZE) {
+ byte[] bytes = objectLoader.getCachedBytes();
+ String content = ContentDetector.convertToText(bytes, blobName);
+ if (content != null) {
+ document.add(new TextField(BLOB_TEXT.name(), content, Store.NO));
+
+ if (extractor != null) {
+ try {
+ for (Symbol symbol: extractor.extract(content)) {
+ String fieldValue = symbol.getName();
+ if (fieldValue != null) {
+ fieldValue = fieldValue.toLowerCase();
+
+ String fieldName;
+ if (symbol.isPrimary())
+ fieldName = BLOB_PRIMARY_SYMBOLS.name();
+ else
+ fieldName = BLOB_SECONDARY_SYMBOLS.name();
+ document.add(new StringField(fieldName, fieldValue, Store.NO));
+ }
+ }
+ } catch (ExtractException e) {
+ logger.error("Error extracting symbols from blob (hash:" + blobId.name() + ", path:" + blobPath + ")", e);
+ }
+ }
+ } else {
+ logger.debug("Ignore content of binary file '{}'.", blobPath);
+ }
+ } else {
+ logger.debug("Ignore content of large file '{}'.", blobPath);
+ }
+
+ writer.addDocument(document);
+ }
+
+ private IndexWriterConfig newIndexWriterConfig() {
+ IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, new NGramAnalyzer(NGRAM_SIZE, NGRAM_SIZE));
+ config.setOpenMode(OpenMode.CREATE_OR_APPEND);
+ return config;
+ }
+
+ private BatchWorker getBatchWorker(Depot depot) {
+ Long depotId = depot.getId();
+ return new BatchWorker("depot-" + depotId + "-indexBlob", 1) {
+
+ @Override
+ public void doWork(Collection<Prioritized> works) {
+ Preconditions.checkState(works.size() == 1);
+ unitOfWork.call(new Callable<Void>() {
+
+ @Override
+ public Void call() throws Exception {
+ Depot depot = dao.load(Depot.class, depotId);
+ IndexWork indexWork = (IndexWork) works.iterator().next();
+ index(depot, indexWork.getCommitId());
+ return null;
+ }
+
+ });
+ }
+
+ };
+ }
+
+ @Override
+ public IndexResult index(Depot depot, ObjectId commit) {
+ IndexResult indexResult;
+ File indexDir = storageManager.getIndexDir(depot);
+ try (Directory directory = FSDirectory.open(indexDir)) {
+ if (DirectoryReader.indexExists(directory)) {
+ try (IndexReader reader = DirectoryReader.open(directory)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ if (getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit))) {
+ return new IndexResult(0, 0);
+ } else {
+ try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
+ logger.debug("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
+ try {
+ indexResult = index(depot.getRepository(), commit, writer, searcher);
+ writer.commit();
+ } catch (Exception e) {
+ writer.rollback();
+ throw Throwables.propagate(e);
+ }
+ }
+ }
+ }
+ } else {
+ try (IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig())) {
+ try {
+ logger.debug("Indexing commit (repository: {}, commit: {})", depot.getFQN(), commit.getName());
+ indexResult = index(depot.getRepository(), commit, writer, null);
+ writer.commit();
+ } catch (Exception e) {
+ writer.rollback();
+ throw Throwables.propagate(e);
+ }
+ }
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ listenerRegistry.post(new CommitIndexed(depot, commit.copy()));
+
+ logger.debug("Commit indexed (repository: {}, commit: {}, checked blobs: {}, indexed blobs: {})",
+ depot.getFQN(), commit.name(), indexResult.getChecked(), indexResult.getIndexed());
+
+ return indexResult;
+ }
+
+ private String getCurrentCommitIndexVersion() {
+ return INDEX_VERSION + ";" + extractors.getVersion();
+ }
+
+ private String getCurrentBlobIndexVersion(Extractor extractor) {
+ if (extractor != null)
+ return INDEX_VERSION + ";" + extractor.getVersion();
+ else
+ return String.valueOf(INDEX_VERSION);
+ }
+
+ @Override
+ public boolean isIndexed(Depot depot, ObjectId commit) {
+ File indexDir = storageManager.getIndexDir(depot);
+ try (Directory directory = FSDirectory.open(indexDir)) {
+ if (DirectoryReader.indexExists(directory)) {
+ try (IndexReader reader = DirectoryReader.open(directory)) {
+ IndexSearcher searcher = new IndexSearcher(reader);
+ return getCurrentCommitIndexVersion().equals(getCommitIndexVersion(searcher, commit));
+ }
+ } else {
+ return false;
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @Transactional
+ @Listen
+ public void on(DepotDeleted event) {
+ searchManager.closeSearcher(event.getDepot());
+ FileUtils.deleteDir(storageManager.getIndexDir(event.getDepot()));
+ }
+
+ @Listen
+ public void on(RefUpdated event) {
+ // only index branches at back end, tags will be indexed on demand from GUI
+ // as many tags might be pushed all at once when the repository is imported
+ if (event.getRefName().startsWith(Constants.R_HEADS) && !event.getNewCommit().equals(ObjectId.zeroId())) {
+ IndexWork work = new IndexWork(BACKEND_INDEXING_PRIORITY, event.getNewCommit());
+ batchWorkManager.submit(getBatchWorker(event.getDepot()), work);
+ }
+ }
+
+ @Override
+ public void indexAsync(Depot depot, ObjectId commit) {
+ int priority;
+ if (RequestCycle.get() != null)
+ priority = UI_INDEXING_PRIORITY;
+ else
+ priority = BACKEND_INDEXING_PRIORITY;
+ IndexWork work = new IndexWork(priority, commit);
+ batchWorkManager.submit(getBatchWorker(depot), work);
+ }
+
+ private static class IndexWork extends Prioritized {
+
+ private final ObjectId commitId;
+
+ public IndexWork(int priority, ObjectId commitId) {
+ super(priority);
+ this.commitId = commitId;
+ }
+
+ public ObjectId getCommitId() {
+ return commitId;
+ }
+
+ }
+
+}
diff --git a/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java b/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
index 322ba83da5..d8a6c6e08a 100644
--- a/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
+++ b/gitplex.search/src/test/java/com/pmease/gitplex/search/IndexAndSearchTest.java
@@ -1,312 +1,312 @@
-package com.pmease.gitplex.search;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.File;
-import java.util.List;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.request.resource.ResourceReference;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-import org.junit.Test;
-import org.mockito.Mockito;
-
-import com.google.common.collect.Lists;
-import com.pmease.commons.git.AbstractGitTest;
-import com.pmease.commons.hibernate.UnitOfWork;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.lang.extractors.ExtractException;
-import com.pmease.commons.lang.extractors.Extractor;
-import com.pmease.commons.lang.extractors.Extractors;
-import com.pmease.commons.lang.extractors.Symbol;
-import com.pmease.commons.lang.extractors.TokenPosition;
-import com.pmease.commons.lang.extractors.java.JavaExtractor;
-import com.pmease.commons.loader.AppLoader;
-import com.pmease.commons.loader.ListenerRegistry;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.util.Range;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.event.depot.DepotDeleted;
-import com.pmease.gitplex.core.manager.BatchWorkManager;
-import com.pmease.gitplex.core.manager.StorageManager;
-import com.pmease.gitplex.core.manager.support.IndexResult;
-import com.pmease.gitplex.search.hit.QueryHit;
-import com.pmease.gitplex.search.query.BlobQuery;
-import com.pmease.gitplex.search.query.SymbolQuery;
-import com.pmease.gitplex.search.query.TextQuery;
-
-public class IndexAndSearchTest extends AbstractGitTest {
-
- private File indexDir;
-
- private Depot depot;
-
- private StorageManager storageManager;
-
- private Extractors extractors;
-
- private DefaultIndexManager indexManager;
-
- private DefaultSearchManager searchManager;
-
- @Override
- protected void setup() {
- super.setup();
-
- indexDir = FileUtils.createTempDir();
-
- depot = new Depot() {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public File getDirectory() {
- return git.getRepository().getDirectory();
- }
-
- @Override
- public Repository getRepository() {
- return git.getRepository();
- }
-
- };
- depot.setId(1L);
- depot.setName("test");
- depot.setAccount(new Account());
- depot.getAccount().setName("test");
-
- storageManager = mock(StorageManager.class);
- when(storageManager.getIndexDir(Mockito.any(Depot.class))).thenReturn(indexDir);
-
- when(AppLoader.getInstance(StorageManager.class)).thenReturn(storageManager);
-
- extractors = mock(Extractors.class);
- when(extractors.getVersion()).thenReturn("java:1");
- when(extractors.getExtractor(anyString())).thenReturn(new JavaExtractor());
-
- when(AppLoader.getInstance(Extractors.class)).thenReturn(extractors);
-
- searchManager = new DefaultSearchManager(storageManager);
-
- ListenerRegistry listenerRegistry = new ListenerRegistry() {
-
- @Override
- public void notify(Object event) {
- searchManager.on((CommitIndexed) event);
- }
-
- };
-
- indexManager = new DefaultIndexManager(listenerRegistry, storageManager,
- mock(BatchWorkManager.class), extractors,
- mock(UnitOfWork.class), mock(Dao.class), searchManager);
- }
-
- @Test
- public void testBasic() throws Exception {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat");
-
- ObjectId commit = git.getRepository().resolve("master");
- assertEquals(2, indexManager.index(depot, commit).getIndexed());
-
- BlobQuery query = new TextQuery("public", false, false, false, null, null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(4, hits.size());
-
- query = new SymbolQuery("nam*", null, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("nam", null, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(0, hits.size());
-
- query = new SymbolQuery("name", null, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("cat", null, true, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + " public int age;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog age");
-
- commit = git.getRepository().resolve("master");
- assertEquals(1, indexManager.index(depot, commit).getIndexed());
-
- query = new TextQuery("strin", false, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
-
- query = new SymbolQuery("Age", null, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "remove dog age");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + " public int age;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat age");
-
- commit = git.getRepository().resolve("master");
-
- IndexResult indexResult = indexManager.index(depot, commit);
- assertEquals(2, indexResult.getChecked());
- assertEquals(1, indexResult.getIndexed());
-
- commit = git.getRepository().resolve("master~2");
- assertEquals(0, indexManager.index(depot, commit).getChecked());
-
- when(extractors.getVersion()).thenReturn("java:2");
- when(extractors.getExtractor(anyString())).thenReturn(new Extractor() {
-
- @Override
- public List<Symbol> extract(String text) throws ExtractException {
- return Lists.<Symbol>newArrayList(new Symbol(null, "tiger", new TokenPosition(0, null)) {
-
- private static final long serialVersionUID = 1L;
-
- @Override
- public Component render(String componentId, Range matchRange) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String describe(List<Symbol> symbols) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public ResourceReference getIcon() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public String getScope() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public boolean isPrimary() {
- return false;
- }
-
- });
- }
-
- @Override
- public boolean accept(String fileName) {
- return true;
- }
-
- @Override
- public int getVersion() {
- return 2;
- }
-
- });
-
- assertEquals(2, indexManager.index(depot, commit).getIndexed());
-
- query = new SymbolQuery("tiger", null, false, true, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
- }
-
- @Test
- public void testRegex() throws Exception {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + " public String nam;\n"
- + "}";
- addFileAndCommit("Dog.java", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("Cat.java", code, "add cat");
-
- ObjectId commit = git.getRepository().resolve("master");
- indexManager.index(depot, commit);
-
- BlobQuery query = new TextQuery("public|}", true, false, false, null, null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(7, hits.size());
-
- query = new TextQuery("nam", true, false, false, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(3, hits.size());
-
- query = new TextQuery("nam", true, false, true, null, null, Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
- }
-
- @Test
- public void testPath() throws Exception {
- String code = ""
- + "public class Dog {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("animals/Dog.c", code, "add dog");
-
- code = ""
- + "public class Cat {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("aminals/Cat.c", code, "add cat");
-
- code = ""
- + "public class Pine {\n"
- + " public String name;\n"
- + "}";
- addFileAndCommit("plants/Pine.java", code, "add pine");
-
- ObjectId commit = git.getRepository().resolve("master");
- indexManager.index(depot, commit);
-
- BlobQuery query = new TextQuery("name", false, true, false, "plants/", null, Integer.MAX_VALUE);
- List<QueryHit> hits = searchManager.search(depot, commit, query);
- assertEquals(1, hits.size());
-
- query = new TextQuery("name", false, true, false, null, "*.c", Integer.MAX_VALUE);
- hits = searchManager.search(depot, commit, query);
- assertEquals(2, hits.size());
- }
-
- @Override
- protected void teardown() {
- indexManager.on(new DepotDeleted(depot));
- super.teardown();
- }
-
-}
+package com.pmease.gitplex.search;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.File;
+import java.util.List;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.request.resource.ResourceReference;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import com.google.common.collect.Lists;
+import com.pmease.commons.git.AbstractGitTest;
+import com.pmease.commons.hibernate.UnitOfWork;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.lang.extractors.ExtractException;
+import com.pmease.commons.lang.extractors.Extractor;
+import com.pmease.commons.lang.extractors.Extractors;
+import com.pmease.commons.lang.extractors.Symbol;
+import com.pmease.commons.lang.extractors.TokenPosition;
+import com.pmease.commons.lang.extractors.java.JavaExtractor;
+import com.pmease.commons.loader.AppLoader;
+import com.pmease.commons.loader.ListenerRegistry;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.util.Range;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.event.depot.DepotDeleted;
+import com.pmease.gitplex.core.manager.BatchWorkManager;
+import com.pmease.gitplex.core.manager.StorageManager;
+import com.pmease.gitplex.core.manager.support.IndexResult;
+import com.pmease.gitplex.search.hit.QueryHit;
+import com.pmease.gitplex.search.query.BlobQuery;
+import com.pmease.gitplex.search.query.SymbolQuery;
+import com.pmease.gitplex.search.query.TextQuery;
+
+public class IndexAndSearchTest extends AbstractGitTest {
+
+ private File indexDir;
+
+ private Depot depot;
+
+ private StorageManager storageManager;
+
+ private Extractors extractors;
+
+ private DefaultIndexManager indexManager;
+
+ private DefaultSearchManager searchManager;
+
+ @Override
+ protected void setup() {
+ super.setup();
+
+ indexDir = FileUtils.createTempDir();
+
+ depot = new Depot() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public File getDirectory() {
+ return git.getRepository().getDirectory();
+ }
+
+ @Override
+ public Repository getRepository() {
+ return git.getRepository();
+ }
+
+ };
+ depot.setId(1L);
+ depot.setName("test");
+ depot.setAccount(new Account());
+ depot.getAccount().setName("test");
+
+ storageManager = mock(StorageManager.class);
+ when(storageManager.getIndexDir(Mockito.any(Depot.class))).thenReturn(indexDir);
+
+ when(AppLoader.getInstance(StorageManager.class)).thenReturn(storageManager);
+
+ extractors = mock(Extractors.class);
+ when(extractors.getVersion()).thenReturn("java:1");
+ when(extractors.getExtractor(anyString())).thenReturn(new JavaExtractor());
+
+ when(AppLoader.getInstance(Extractors.class)).thenReturn(extractors);
+
+ searchManager = new DefaultSearchManager(storageManager);
+
+ ListenerRegistry listenerRegistry = new ListenerRegistry() {
+
+ @Override
+ public void post(Object event) {
+ searchManager.on((CommitIndexed) event);
+ }
+
+ };
+
+ indexManager = new DefaultIndexManager(listenerRegistry, storageManager,
+ mock(BatchWorkManager.class), extractors,
+ mock(UnitOfWork.class), mock(Dao.class), searchManager);
+ }
+
+ @Test
+ public void testBasic() throws Exception {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat");
+
+ ObjectId commit = git.getRepository().resolve("master");
+ assertEquals(2, indexManager.index(depot, commit).getIndexed());
+
+ BlobQuery query = new TextQuery("public", false, false, false, null, null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(4, hits.size());
+
+ query = new SymbolQuery("nam*", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("nam", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(0, hits.size());
+
+ query = new SymbolQuery("name", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("cat", null, true, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + " public int age;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog age");
+
+ commit = git.getRepository().resolve("master");
+ assertEquals(1, indexManager.index(depot, commit).getIndexed());
+
+ query = new TextQuery("strin", false, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+
+ query = new SymbolQuery("Age", null, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "remove dog age");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + " public int age;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat age");
+
+ commit = git.getRepository().resolve("master");
+
+ IndexResult indexResult = indexManager.index(depot, commit);
+ assertEquals(2, indexResult.getChecked());
+ assertEquals(1, indexResult.getIndexed());
+
+ commit = git.getRepository().resolve("master~2");
+ assertEquals(0, indexManager.index(depot, commit).getChecked());
+
+ when(extractors.getVersion()).thenReturn("java:2");
+ when(extractors.getExtractor(anyString())).thenReturn(new Extractor() {
+
+ @Override
+ public List<Symbol> extract(String text) throws ExtractException {
+ return Lists.<Symbol>newArrayList(new Symbol(null, "tiger", new TokenPosition(0, null)) {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Component render(String componentId, Range matchRange) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String describe(List<Symbol> symbols) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public ResourceReference getIcon() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public String getScope() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public boolean isPrimary() {
+ return false;
+ }
+
+ });
+ }
+
+ @Override
+ public boolean accept(String fileName) {
+ return true;
+ }
+
+ @Override
+ public int getVersion() {
+ return 2;
+ }
+
+ });
+
+ assertEquals(2, indexManager.index(depot, commit).getIndexed());
+
+ query = new SymbolQuery("tiger", null, false, true, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+ }
+
+ @Test
+ public void testRegex() throws Exception {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + " public String nam;\n"
+ + "}";
+ addFileAndCommit("Dog.java", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("Cat.java", code, "add cat");
+
+ ObjectId commit = git.getRepository().resolve("master");
+ indexManager.index(depot, commit);
+
+ BlobQuery query = new TextQuery("public|}", true, false, false, null, null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(7, hits.size());
+
+ query = new TextQuery("nam", true, false, false, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(3, hits.size());
+
+ query = new TextQuery("nam", true, false, true, null, null, Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+ }
+
+ @Test
+ public void testPath() throws Exception {
+ String code = ""
+ + "public class Dog {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("animals/Dog.c", code, "add dog");
+
+ code = ""
+ + "public class Cat {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("aminals/Cat.c", code, "add cat");
+
+ code = ""
+ + "public class Pine {\n"
+ + " public String name;\n"
+ + "}";
+ addFileAndCommit("plants/Pine.java", code, "add pine");
+
+ ObjectId commit = git.getRepository().resolve("master");
+ indexManager.index(depot, commit);
+
+ BlobQuery query = new TextQuery("name", false, true, false, "plants/", null, Integer.MAX_VALUE);
+ List<QueryHit> hits = searchManager.search(depot, commit, query);
+ assertEquals(1, hits.size());
+
+ query = new TextQuery("name", false, true, false, null, "*.c", Integer.MAX_VALUE);
+ hits = searchManager.search(depot, commit, query);
+ assertEquals(2, hits.size());
+ }
+
+ @Override
+ protected void teardown() {
+ indexManager.on(new DepotDeleted(depot));
+ super.teardown();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebUrlManager.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebUrlManager.java
index f78ac7db37..01b09add30 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/WebUrlManager.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/WebUrlManager.java
@@ -1,43 +1,43 @@
-package com.pmease.gitplex.web;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-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.PullRequestComment;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.UrlManager;
-
-@Singleton
-public class WebUrlManager implements UrlManager {
-
- private final ConfigManager configManager;
-
- @Inject
- public WebUrlManager(ConfigManager configManager) {
- this.configManager = configManager;
- }
-
- @Override
- public String urlFor(PullRequest request) {
- return urlFor(request.getTarget().getDepot()) + "/pulls/" + request.getId() + "/overview";
- }
-
- @Override
- public String urlFor(Account user) {
- return configManager.getSystemSetting().getServerUrl() + "/" + user.getName();
- }
-
- @Override
- public String urlFor(Depot depot) {
- return urlFor(depot.getAccount()) + "/" + depot.getName();
- }
-
- @Override
- public String urlFor(PullRequestComment comment) {
- return urlFor(comment.getRequest()) + "#comment" + comment.getId();
- }
-
-}
+package com.pmease.gitplex.web;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.UrlManager;
+
+@Singleton
+public class WebUrlManager implements UrlManager {
+
+ private final ConfigManager configManager;
+
+ @Inject
+ public WebUrlManager(ConfigManager configManager) {
+ this.configManager = configManager;
+ }
+
+ @Override
+ public String urlFor(PullRequest request) {
+ return urlFor(request.getTarget().getDepot()) + "/pulls/" + request.getNumber() + "/overview";
+ }
+
+ @Override
+ public String urlFor(Account user) {
+ return configManager.getSystemSetting().getServerUrl() + "/" + user.getName();
+ }
+
+ @Override
+ public String urlFor(Depot depot) {
+ return urlFor(depot.getAccount()) + "/" + depot.getName();
+ }
+
+ @Override
+ public String urlFor(CodeComment comment) {
+ return urlFor(comment.getDepot()) + "/comments/" + comment.getId();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentListPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentListPanel.java
index adeb8fbddd..7725d8b4f6 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentListPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/comment/CodeCommentListPanel.java
@@ -1,348 +1,292 @@
-package com.pmease.gitplex.web.component.comment;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigationToolbar;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar;
-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.link.Link;
-import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.markup.repeater.Item;
-import org.apache.wicket.markup.repeater.data.IDataProvider;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.eclipse.jgit.lib.FileMode;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
-
-import com.google.common.base.Preconditions;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.wicket.editable.BeanContext;
-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.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.security.SecurityUtils;
-import com.pmease.gitplex.web.Constants;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;
-import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.navigation.BootstrapPagingNavigator;
-
-@SuppressWarnings("serial")
-public abstract class CodeCommentListPanel extends Panel {
-
- private final IModel<CodeCommentFilter> filterOptionModel;
-
- public CodeCommentListPanel(String id, IModel<CodeCommentFilter> filterOptionModel) {
- super(id);
-
- this.filterOptionModel = filterOptionModel;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Link<Void>("myComments") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(SecurityUtils.getAccount() != null);
- }
-
- @Override
- public void onClick() {
- CodeCommentFilter filterOption = new CodeCommentFilter();
- filterOption.setUserName(SecurityUtils.getAccount().getName());
- filterOptionModel.setObject(filterOption);
- }
-
- });
- add(new Link<Void>("myUnresolvedComments") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(SecurityUtils.getAccount() != null);
- }
-
- @Override
- public void onClick() {
- CodeCommentFilter filterOption = new CodeCommentFilter();
- filterOption.setUserName(SecurityUtils.getAccount().getName());
- filterOption.setUnresolved(true);
- filterOptionModel.setObject(filterOption);
- }
-
- });
- add(new Link<Void>("unresolvedComments") {
-
- @Override
- public void onClick() {
- CodeCommentFilter filterOption = new CodeCommentFilter();
- filterOption.setUnresolved(true);
- filterOptionModel.setObject(filterOption);
- }
-
- });
- add(new Link<Void>("allComments") {
-
- @Override
- public void onClick() {
- filterOptionModel.setObject(new CodeCommentFilter());
- }
-
- });
- Form<?> filterForm = new Form<Void>("filterForm") {
-
- @Override
- protected void onSubmit() {
- super.onSubmit();
- }
-
- };
- filterForm.add(BeanContext.editModel("editor", filterOptionModel));
- add(filterForm);
-
- List<IColumn<CodeComment, Void>> columns = new ArrayList<>();
- columns.add(new AbstractColumn<CodeComment, Void>(Model.of("Code Comment")) {
-
- private void openComment(CodeComment comment) {
- Depot depot = ((DepotPage) getPage()).getDepot();
-
- PullRequest request = getPullRequest();
- List<CodeCommentActivity> activities= new ArrayList<>();
- activities.addAll(comment.getReplies());
- activities.addAll(comment.getStatusChanges());
- activities.sort((o1, o2)->o1.getDate().compareTo(o2.getDate()));
- if (request != null) {
- PullRequest.ComparingInfo comparingInfo = null;
- for (int i=activities.size()-1; i>=0; i--) {
- CodeCommentActivity activity = activities.get(i);
- comparingInfo = request.getRequestComparingInfo(activity.getComparingInfo());
- if (comparingInfo != null)
- break;
- }
- if (comparingInfo == null) {
- comparingInfo = Preconditions.checkNotNull(request.getRequestComparingInfo(comment.getComparingInfo()));
- }
- RequestChangesPage.State state = new RequestChangesPage.State();
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- state.oldCommit = comparingInfo.getOldCommit();
- state.newCommit = comparingInfo.getNewCommit();
- state.pathFilter = comparingInfo.getPathFilter();
- state.whitespaceOption = comparingInfo.getWhitespaceOption();
- setResponsePage(RequestChangesPage.class, RequestChangesPage.paramsOf(request, state));
- } else {
- CompareContext compareContext;
- if (!activities.isEmpty()) {
- CodeCommentActivity lastActivity = activities.get(activities.size()-1);
- compareContext = lastActivity.getCompareContext();
- } else {
- compareContext = comment.getCompareContext();
- }
- if (!compareContext.getCompareCommit().equals(comment.getCommentPos().getCommit())) {
- RevisionComparePage.State state = new RevisionComparePage.State();
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- state.compareWithMergeBase = false;
- if (compareContext.isLeftSide()) {
- state.leftSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
- state.rightSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
- } else {
- state.leftSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
- state.rightSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
- }
- state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
- state.whitespaceOption = compareContext.getWhitespaceOption();
- state.pathFilter = compareContext.getPathFilter();
- setResponsePage(RevisionComparePage.class, RevisionComparePage.paramsOf(depot, state));
- } else {
- DepotFilePage.State state = new DepotFilePage.State();
- state.blobIdent.revision = comment.getCommentPos().getCommit();
- state.blobIdent.path = comment.getCommentPos().getPath();
- state.blobIdent.mode = FileMode.TYPE_FILE;
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos().getRange();
- setResponsePage(DepotFilePage.class, DepotFilePage.paramsOf(depot, state));
- }
- }
- }
-
- @Override
- public void populateItem(Item<ICellPopulator<CodeComment>> cellItem,
- String componentId, IModel<CodeComment> rowModel) {
- CodeComment comment = rowModel.getObject();
- Fragment fragment = new Fragment(componentId, "commentFrag", CodeCommentListPanel.this);
- Link<Void> titleLink = new Link<Void>("title") {
-
- @Override
- public void onClick() {
- openComment(rowModel.getObject());
- }
-
- };
- titleLink.add(new Label("label", comment.getTitle()));
- fragment.add(titleLink);
- fragment.add(new WebMarkupContainer("resolved").setVisible(comment.isResolved()));
- fragment.add(new AccountLink("user", comment.getUser()));
-
- Link<Void> fileLink = new Link<Void>("file") {
-
- @Override
- public void onClick() {
- openComment(rowModel.getObject());
- }
-
- };
- fileLink.add(new Label("label", comment.getCommentPos().getPath()));
- fragment.add(fileLink);
-
- fragment.add(new Label("date", DateUtils.formatAge(comment.getDate())));
-
- WebMarkupContainer lastEventContainer = new WebMarkupContainer("lastEvent");
- if (comment.getLastEvent() != null) {
- lastEventContainer.add(new Label("description", comment.getLastEvent().getDescription()));
- lastEventContainer.add(new AccountLink("user", comment.getLastEvent().getUser())
- .setVisible(comment.getLastEvent().getUser()!=null));
- lastEventContainer.add(new Label("date", DateUtils.formatAge(comment.getLastEvent().getDate())));
- } else {
- lastEventContainer.add(new Label("description"));
- lastEventContainer.add(new AccountLink("user", (Account)null));
- lastEventContainer.add(new Label("date"));
- lastEventContainer.setVisible(false);
- }
- fragment.add(lastEventContainer);
-
- cellItem.add(fragment);
-
- Date lastUpdateDate;
- if (comment.getLastEvent() != null)
- lastUpdateDate = comment.getLastEvent().getDate();
- else
- lastUpdateDate = comment.getDate();
- cellItem.add(AttributeAppender.append("class",
- comment.isVisitedAfter(lastUpdateDate)?"comment":"comment new"));
- }
-
- });
-
- IDataProvider<CodeComment> dataProvider = new IDataProvider<CodeComment>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public Iterator<? extends CodeComment> iterator(long first, long count) {
- DepotPage page = (DepotPage) getPage();
-
- if (getPullRequest() != null) {
- List<CodeComment> comments = new ArrayList<>(getPullRequest().getCodeComments());
- filterOptionModel.getObject().filter(comments);
- return comments.iterator();
- } else {
- EntityCriteria<CodeComment> criteria = EntityCriteria.of(CodeComment.class);
- criteria.add(Restrictions.eq("depot", page.getDepot()));
- filterOptionModel.getObject().fill(criteria);
- criteria.addOrder(Order.desc("id"));
- return GitPlex.getInstance(Dao.class).findRange(criteria, (int)first, (int)count).iterator();
- }
- }
-
- @Override
- public long size() {
- DepotPage page = (DepotPage) getPage();
-
- if (getPullRequest() != null) {
- return getPullRequest().getCodeComments().size();
- } else {
- EntityCriteria<CodeComment> criteria = EntityCriteria.of(CodeComment.class);
- criteria.add(Restrictions.eq("depot", page.getDepot()));
- filterOptionModel.getObject().fill(criteria);
- return GitPlex.getInstance(Dao.class).count(criteria);
- }
- }
-
- @Override
- public IModel<CodeComment> model(CodeComment object) {
- Long commentId = object.getId();
- return new LoadableDetachableModel<CodeComment>() {
-
- @Override
- protected CodeComment load() {
- return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
- }
-
- };
- }
-
- };
- DataTable<CodeComment, Void> dataTable = new DataTable<>("comments", columns,
- dataProvider, getPullRequest()!=null?Integer.MAX_VALUE:Constants.DEFAULT_PAGE_SIZE);
- dataTable.addBottomToolbar(new NoRecordsToolbar(dataTable));
- dataTable.addBottomToolbar(new NavigationToolbar(dataTable) {
-
- @Override
- protected PagingNavigator newPagingNavigator(String navigatorId, DataTable<?, ?> table) {
- return new BootstrapPagingNavigator(navigatorId, dataTable);
- }
-
- });
- add(dataTable);
-
- if (getPullRequest() != null && dataTable.getItemCount() > PullRequest.MAX_CODE_COMMENTS) {
- add(new Label("alert", "Too many code comments, only displaying " + PullRequest.MAX_CODE_COMMENTS));
- } else {
- add(new WebMarkupContainer("alert").setVisible(false));
- }
- }
-
- @Override
- protected void onDetach() {
- filterOptionModel.detach();
- super.onDetach();
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(new CssResourceReference(
- CodeCommentListPanel.class, "code-comment-list.css")));
- }
-
- @Nullable
- protected abstract PullRequest getPullRequest();
-
-}
+package com.pmease.gitplex.web.component.comment;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigationToolbar;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar;
+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.link.Link;
+import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.markup.repeater.Item;
+import org.apache.wicket.markup.repeater.data.IDataProvider;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
+
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.wicket.editable.BeanContext;
+import com.pmease.commons.wicket.editable.EditableUtils;
+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.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.Constants;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.comments.CodeCommentPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.navigation.BootstrapPagingNavigator;
+
+@SuppressWarnings("serial")
+public abstract class CodeCommentListPanel extends Panel {
+
+ private final IModel<CodeCommentFilter> filterOptionModel;
+
+ public CodeCommentListPanel(String id, IModel<CodeCommentFilter> filterOptionModel) {
+ super(id);
+
+ this.filterOptionModel = filterOptionModel;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Link<Void>("myComments") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(SecurityUtils.getAccount() != null);
+ }
+
+ @Override
+ public void onClick() {
+ CodeCommentFilter filterOption = new CodeCommentFilter();
+ filterOption.setUserName(SecurityUtils.getAccount().getName());
+ filterOptionModel.setObject(filterOption);
+ }
+
+ });
+ add(new Link<Void>("myUnresolvedComments") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(SecurityUtils.getAccount() != null);
+ }
+
+ @Override
+ public void onClick() {
+ CodeCommentFilter filterOption = new CodeCommentFilter();
+ filterOption.setUserName(SecurityUtils.getAccount().getName());
+ filterOption.setUnresolved(true);
+ filterOptionModel.setObject(filterOption);
+ }
+
+ });
+ add(new Link<Void>("unresolvedComments") {
+
+ @Override
+ public void onClick() {
+ CodeCommentFilter filterOption = new CodeCommentFilter();
+ filterOption.setUnresolved(true);
+ filterOptionModel.setObject(filterOption);
+ }
+
+ });
+ add(new Link<Void>("allComments") {
+
+ @Override
+ public void onClick() {
+ filterOptionModel.setObject(new CodeCommentFilter());
+ }
+
+ });
+ Form<?> filterForm = new Form<Void>("filterForm") {
+
+ @Override
+ protected void onSubmit() {
+ super.onSubmit();
+ }
+
+ };
+ filterForm.add(BeanContext.editModel("editor", filterOptionModel));
+ add(filterForm);
+
+ List<IColumn<CodeComment, Void>> columns = new ArrayList<>();
+ columns.add(new AbstractColumn<CodeComment, Void>(Model.of("Code Comment")) {
+
+ private void openComment(CodeComment comment) {
+ Depot depot = ((DepotPage) getPage()).getDepot();
+
+ PullRequest request = getPullRequest();
+ if (request != null) {
+ setResponsePage(RequestChangesPage.class, RequestChangesPage.paramsOf(request, comment));
+ } else {
+ setResponsePage(CodeCommentPage.class, CodeCommentPage.paramsOf(depot, comment));
+ }
+ }
+
+ @Override
+ public void populateItem(Item<ICellPopulator<CodeComment>> cellItem,
+ String componentId, IModel<CodeComment> rowModel) {
+ CodeComment comment = rowModel.getObject();
+ Fragment fragment = new Fragment(componentId, "commentFrag", CodeCommentListPanel.this);
+ Link<Void> titleLink = new Link<Void>("title") {
+
+ @Override
+ public void onClick() {
+ openComment(rowModel.getObject());
+ }
+
+ };
+ titleLink.add(new Label("label", comment.getTitle()));
+ fragment.add(titleLink);
+ fragment.add(new WebMarkupContainer("resolved").setVisible(comment.isResolved()));
+ fragment.add(new AccountLink("user", comment.getUser()));
+
+ Link<Void> fileLink = new Link<Void>("file") {
+
+ @Override
+ public void onClick() {
+ openComment(rowModel.getObject());
+ }
+
+ };
+ fileLink.add(new Label("label", comment.getCommentPos().getPath()));
+ fragment.add(fileLink);
+
+ fragment.add(new Label("date", DateUtils.formatAge(comment.getDate())));
+
+ WebMarkupContainer lastEventContainer = new WebMarkupContainer("lastEvent");
+ if (comment.getLastEvent() != null) {
+ String description = EditableUtils.getName(comment.getLastEvent().getType());
+ lastEventContainer.add(new Label("description", description));
+ lastEventContainer.add(new AccountLink("user", comment.getLastEvent().getUser())
+ .setVisible(comment.getLastEvent().getUser()!=null));
+ lastEventContainer.add(new Label("date", DateUtils.formatAge(comment.getLastEvent().getDate())));
+ } else {
+ lastEventContainer.add(new Label("description"));
+ lastEventContainer.add(new AccountLink("user", (Account)null));
+ lastEventContainer.add(new Label("date"));
+ lastEventContainer.setVisible(false);
+ }
+ fragment.add(lastEventContainer);
+
+ cellItem.add(fragment);
+
+ Date lastUpdateDate;
+ if (comment.getLastEvent() != null)
+ lastUpdateDate = comment.getLastEvent().getDate();
+ else
+ lastUpdateDate = comment.getDate();
+ cellItem.add(AttributeAppender.append("class",
+ comment.isVisitedAfter(lastUpdateDate)?"comment":"comment new"));
+ }
+
+ });
+
+ IDataProvider<CodeComment> dataProvider = new IDataProvider<CodeComment>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public Iterator<? extends CodeComment> iterator(long first, long count) {
+ DepotPage page = (DepotPage) getPage();
+
+ if (getPullRequest() != null) {
+ List<CodeComment> comments = new ArrayList<>(getPullRequest().getCodeComments());
+ filterOptionModel.getObject().filter(comments);
+ return comments.iterator();
+ } else {
+ EntityCriteria<CodeComment> criteria = EntityCriteria.of(CodeComment.class);
+ criteria.add(Restrictions.eq("depot", page.getDepot()));
+ filterOptionModel.getObject().fill(criteria);
+ criteria.addOrder(Order.desc("id"));
+ return GitPlex.getInstance(Dao.class).findRange(criteria, (int)first, (int)count).iterator();
+ }
+ }
+
+ @Override
+ public long size() {
+ DepotPage page = (DepotPage) getPage();
+
+ if (getPullRequest() != null) {
+ return getPullRequest().getCodeComments().size();
+ } else {
+ EntityCriteria<CodeComment> criteria = EntityCriteria.of(CodeComment.class);
+ criteria.add(Restrictions.eq("depot", page.getDepot()));
+ filterOptionModel.getObject().fill(criteria);
+ return GitPlex.getInstance(Dao.class).count(criteria);
+ }
+ }
+
+ @Override
+ public IModel<CodeComment> model(CodeComment object) {
+ Long commentId = object.getId();
+ return new LoadableDetachableModel<CodeComment>() {
+
+ @Override
+ protected CodeComment load() {
+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
+ }
+
+ };
+ }
+
+ };
+ DataTable<CodeComment, Void> dataTable = new DataTable<>("comments", columns,
+ dataProvider, getPullRequest()!=null?Integer.MAX_VALUE:Constants.DEFAULT_PAGE_SIZE);
+ dataTable.addBottomToolbar(new NoRecordsToolbar(dataTable));
+ dataTable.addBottomToolbar(new NavigationToolbar(dataTable) {
+
+ @Override
+ protected PagingNavigator newPagingNavigator(String navigatorId, DataTable<?, ?> table) {
+ return new BootstrapPagingNavigator(navigatorId, dataTable);
+ }
+
+ });
+ add(dataTable);
+
+ if (getPullRequest() != null && dataTable.getItemCount() > PullRequest.MAX_CODE_COMMENTS) {
+ add(new Label("alert", "Too many code comments, only displaying " + PullRequest.MAX_CODE_COMMENTS));
+ } else {
+ add(new WebMarkupContainer("alert").setVisible(false));
+ }
+ }
+
+ @Override
+ protected void onDetach() {
+ filterOptionModel.detach();
+ super.onDetach();
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(
+ CodeCommentListPanel.class, "code-comment-list.css")));
+ }
+
+ @Nullable
+ protected abstract PullRequest getPullRequest();
+
+}
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.java
index 4aecbf2178..89585c8c8f 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
@@ -49,7 +49,6 @@ 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.AccountManager;
import com.pmease.gitplex.core.manager.CodeCommentManager;
import com.pmease.gitplex.core.manager.CodeCommentReplyManager;
import com.pmease.gitplex.core.manager.CodeCommentStatusChangeManager;
@@ -88,14 +87,6 @@ public abstract class CodeCommentPanel extends Panel {
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());
- }
private WebMarkupContainer newCommentContainer() {
WebMarkupContainer commentContainer = new Fragment("comment", "viewFrag", this);
@@ -635,10 +626,14 @@ public abstract class CodeCommentPanel extends Panel {
handler.add(newActivityContainer);
prevActivityMarkupId = newActivityContainer.getMarkupId();
}
-
- Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
- if (user != null)
- GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());
+ }
+
+ @Override
+ protected void onInitialRenderDetach() {
+ Account user = SecurityUtils.getAccount();
+ if (user != null)
+ GitPlex.getInstance(VisitInfoManager.class).visit(user, getComment());
+ super.onInitialRenderDetach();
}
});
@@ -714,6 +709,7 @@ public abstract class CodeCommentPanel extends Panel {
statusChange.setCompareContext(compareContext);
statusChange.setResolved(!comment.isResolved());
statusChange.setDate(date);
+ statusChange.setNote(contentInput.getModelObject());
GitPlex.getInstance(CodeCommentManager.class).changeStatus(statusChange);
onStatusChanged(target, fragment, statusChange);
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createbranch/CreateBranchPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createbranch/CreateBranchPanel.java
index d565702003..1e0b71925c 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createbranch/CreateBranchPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createbranch/CreateBranchPanel.java
@@ -1,125 +1,125 @@
-package com.pmease.gitplex.web.component.createbranch;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.model.IModel;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-abstract class CreateBranchPanel extends Panel {
-
- private final IModel<Depot> depotModel;
-
- private final String revision;
-
- private String branchName;
-
- public CreateBranchPanel(String id, IModel<Depot> depotModel, String revision) {
- super(id);
- this.depotModel = depotModel;
- this.revision = revision;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
- form.add(new NotificationPanel("feedback", form));
-
- final TextField<String> nameInput;
- form.add(nameInput = new TextField<String>("name", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return branchName;
- }
-
- @Override
- public void setObject(String object) {
- branchName = object;
- }
-
- }));
- nameInput.setOutputMarkupId(true);
-
- form.add(new AjaxButton("create") {
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- if (branchName == null) {
- form.error("Branch name is required.");
- target.focusComponent(nameInput);
- target.add(form);
- } else if (!Repository.isValidRefName(Constants.R_HEADS + branchName)) {
- form.error("Invalid branch name.");
- target.focusComponent(nameInput);
- target.add(form);
- } else if (depotModel.getObject().getObjectId(GitUtils.branch2ref(branchName), false) != null) {
- form.error("Branch '" + branchName + "' already exists, please choose a different name.");
- target.focusComponent(nameInput);
- target.add(form);
- } else {
- Depot depot = depotModel.getObject();
- ObjectId commitId = depot.getRevCommit(revision);
- Account user = Preconditions.checkNotNull(SecurityUtils.getAccount());
- CheckResult checkResult = depot.getGateKeeper().checkPush(user,
- depot, Constants.R_HEADS + branchName, ObjectId.zeroId(), commitId);
- if (!checkResult.isPassed()) {
- form.error(Joiner.on(", ").join(checkResult.getReasons()));
- target.focusComponent(nameInput);
- target.add(form);
- } else {
- depot.createBranch(branchName, revision);
- onCreate(target, branchName);
- }
- }
- }
-
- });
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onCancel(target);
- }
-
- });
- add(form);
- }
-
- protected abstract void onCreate(AjaxRequestTarget target, String branch);
-
- protected abstract void onCancel(AjaxRequestTarget target);
-
- @Override
- protected void onDetach() {
- depotModel.detach();
-
- super.onDetach();
- }
-
-}
+package com.pmease.gitplex.web.component.createbranch;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.model.IModel;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+abstract class CreateBranchPanel extends Panel {
+
+ private final IModel<Depot> depotModel;
+
+ private final String revision;
+
+ private String branchName;
+
+ public CreateBranchPanel(String id, IModel<Depot> depotModel, String revision) {
+ super(id);
+ this.depotModel = depotModel;
+ this.revision = revision;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+ form.add(new NotificationPanel("feedback", form));
+
+ final TextField<String> nameInput;
+ form.add(nameInput = new TextField<String>("name", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return branchName;
+ }
+
+ @Override
+ public void setObject(String object) {
+ branchName = object;
+ }
+
+ }));
+ nameInput.setOutputMarkupId(true);
+
+ form.add(new AjaxButton("create") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ if (branchName == null) {
+ form.error("Branch name is required.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else if (!Repository.isValidRefName(Constants.R_HEADS + branchName)) {
+ form.error("Invalid branch name.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else if (depotModel.getObject().getObjectId(GitUtils.branch2ref(branchName), false) != null) {
+ form.error("Branch '" + branchName + "' already exists, please choose a different name.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else {
+ Depot depot = depotModel.getObject();
+ ObjectId commitId = depot.getRevCommit(revision);
+ Account user = Preconditions.checkNotNull(SecurityUtils.getAccount());
+ GateCheckResult checkResult = depot.getGateKeeper().checkPush(user,
+ depot, Constants.R_HEADS + branchName, ObjectId.zeroId(), commitId);
+ if (!checkResult.isPassed()) {
+ form.error(Joiner.on(", ").join(checkResult.getReasons()));
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else {
+ depot.createBranch(branchName, revision);
+ onCreate(target, branchName);
+ }
+ }
+ }
+
+ });
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ onCancel(target);
+ }
+
+ });
+ add(form);
+ }
+
+ protected abstract void onCreate(AjaxRequestTarget target, String branch);
+
+ protected abstract void onCancel(AjaxRequestTarget target);
+
+ @Override
+ protected void onDetach() {
+ depotModel.detach();
+
+ super.onDetach();
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createtag/CreateTagPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createtag/CreateTagPanel.java
index b309c7a9e0..0466210158 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createtag/CreateTagPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/createtag/CreateTagPanel.java
@@ -1,145 +1,145 @@
-package com.pmease.gitplex.web.component.createtag;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.html.form.Form;
-import org.apache.wicket.markup.html.form.TextArea;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.panel.Panel;
-import org.apache.wicket.model.IModel;
-import org.eclipse.jgit.lib.Constants;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.lib.Repository;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.pmease.commons.git.GitUtils;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.Depot;
-import com.pmease.gitplex.core.gatekeeper.checkresult.CheckResult;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-abstract class CreateTagPanel extends Panel {
-
- private final IModel<Depot> depotModel;
-
- private final String revision;
-
- private String tagName;
-
- private String tagMessage;
-
- public CreateTagPanel(String id, IModel<Depot> depotModel, String revision) {
- super(id);
- this.depotModel = depotModel;
- this.revision = revision;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- Form<?> form = new Form<Void>("form");
- form.setOutputMarkupId(true);
- form.add(new NotificationPanel("feedback", form));
-
- final TextField<String> nameInput;
- form.add(nameInput = new TextField<String>("name", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return tagName;
- }
-
- @Override
- public void setObject(String object) {
- tagName = object;
- }
-
- }));
- nameInput.setOutputMarkupId(true);
-
- form.add(new TextArea<String>("message", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return tagMessage;
- }
-
- @Override
- public void setObject(String object) {
- tagMessage = object;
- }
-
- }));
- form.add(new AjaxButton("create") {
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- if (tagName == null) {
- form.error("Tag name is required.");
- target.focusComponent(nameInput);
- target.add(form);
- } else if (!Repository.isValidRefName(Constants.R_TAGS + tagName)) {
- form.error("Tag name is not valid.");
- target.focusComponent(nameInput);
- target.add(form);
- } else if (depotModel.getObject().getObjectId(GitUtils.tag2ref(tagName), false) != null) {
- form.error("Tag '" + tagName + "' already exists, please choose a different name.");
- target.focusComponent(nameInput);
- target.add(form);
- } else {
- Depot depot = depotModel.getObject();
- ObjectId commitId = depot.getRevCommit(revision);
- Account user = Preconditions.checkNotNull(SecurityUtils.getAccount());
- CheckResult checkResult = depot.getGateKeeper().checkPush(user,
- depot, Constants.R_TAGS + tagName, ObjectId.zeroId(), commitId);
- if (!checkResult.isPassed()) {
- form.error(Joiner.on(", ").join(checkResult.getReasons()));
- target.focusComponent(nameInput);
- target.add(form);
- } else {
- depot.tag(tagName, revision, user.asPerson(), tagMessage);
- onCreate(target, tagName);
- }
- }
- }
-
- });
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- onCancel(target);
- }
-
- });
- add(form);
- }
-
- protected abstract void onCreate(AjaxRequestTarget target, String tag);
-
- protected abstract void onCancel(AjaxRequestTarget target);
-
- @Override
- protected void onDetach() {
- depotModel.detach();
-
- super.onDetach();
- }
-
-}
+package com.pmease.gitplex.web.component.createtag;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextArea;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.panel.Panel;
+import org.apache.wicket.model.IModel;
+import org.eclipse.jgit.lib.Constants;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.lib.Repository;
+
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.gatekeeper.checkresult.GateCheckResult;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+abstract class CreateTagPanel extends Panel {
+
+ private final IModel<Depot> depotModel;
+
+ private final String revision;
+
+ private String tagName;
+
+ private String tagMessage;
+
+ public CreateTagPanel(String id, IModel<Depot> depotModel, String revision) {
+ super(id);
+ this.depotModel = depotModel;
+ this.revision = revision;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ Form<?> form = new Form<Void>("form");
+ form.setOutputMarkupId(true);
+ form.add(new NotificationPanel("feedback", form));
+
+ final TextField<String> nameInput;
+ form.add(nameInput = new TextField<String>("name", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return tagName;
+ }
+
+ @Override
+ public void setObject(String object) {
+ tagName = object;
+ }
+
+ }));
+ nameInput.setOutputMarkupId(true);
+
+ form.add(new TextArea<String>("message", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return tagMessage;
+ }
+
+ @Override
+ public void setObject(String object) {
+ tagMessage = object;
+ }
+
+ }));
+ form.add(new AjaxButton("create") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ if (tagName == null) {
+ form.error("Tag name is required.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else if (!Repository.isValidRefName(Constants.R_TAGS + tagName)) {
+ form.error("Tag name is not valid.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else if (depotModel.getObject().getObjectId(GitUtils.tag2ref(tagName), false) != null) {
+ form.error("Tag '" + tagName + "' already exists, please choose a different name.");
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else {
+ Depot depot = depotModel.getObject();
+ ObjectId commitId = depot.getRevCommit(revision);
+ Account user = Preconditions.checkNotNull(SecurityUtils.getAccount());
+ GateCheckResult checkResult = depot.getGateKeeper().checkPush(user,
+ depot, Constants.R_TAGS + tagName, ObjectId.zeroId(), commitId);
+ if (!checkResult.isPassed()) {
+ form.error(Joiner.on(", ").join(checkResult.getReasons()));
+ target.focusComponent(nameInput);
+ target.add(form);
+ } else {
+ depot.tag(tagName, revision, user.asPerson(), tagMessage);
+ onCreate(target, tagName);
+ }
+ }
+ }
+
+ });
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ onCancel(target);
+ }
+
+ });
+ add(form);
+ }
+
+ protected abstract void onCreate(AjaxRequestTarget target, String tag);
+
+ protected abstract void onCancel(AjaxRequestTarget target);
+
+ @Override
+ protected void onDetach() {
+ depotModel.detach();
+
+ super.onDetach();
+ }
+
+}
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.java
index b7659fde42..ba8cc1cb23 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
@@ -45,18 +45,18 @@ public class ReviewerAvatar extends RemoveableAvatar {
PullRequest request = requestModel.getObject();
Set<Account> prevInvited = new HashSet<>();
for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (!each.isExcluded())
+ if (each.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED)
prevInvited.add(each.getUser());
if (each.getUser().equals(invitation.getUser())) {
- each.setExcluded(true);
+ each.setStatus(PullRequestReviewInvitation.Status.EXCLUDED);
each.setDate(new Date());
}
}
- request.getTargetDepot().getGateKeeper().checkRequest(request);
+ request.checkGates(true);
Set<Account> nowInvited = new HashSet<>();
for (PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (!each.isExcluded())
+ if (each.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED)
nowInvited.add(each.getUser());
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
index 63cbbe3017..5bc2d6c704 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/component/pullrequest/requestreviewer/ReviewerChoice.java
@@ -1,87 +1,84 @@
-package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
-
-import java.util.Date;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.head.JavaScriptHeaderItem;
-import org.apache.wicket.model.IModel;
-
-import com.pmease.commons.wicket.component.select2.SelectToAddChoice;
-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.accountchoice.AccountChoiceResourceReference;
-
-@SuppressWarnings("serial")
-public abstract class ReviewerChoice extends SelectToAddChoice<Account> {
-
- private final IModel<PullRequest> requestModel;
-
- public ReviewerChoice(String id, IModel<PullRequest> requestModel) {
- super(id, new ReviewerProvider(requestModel));
-
- this.requestModel = requestModel;
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = requestModel.getObject();
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
- setVisible(request.isOpen()
- && !request.getPotentialReviewers().isEmpty()
- && (currentUser != null && currentUser.equals(request.getSubmitter()) || SecurityUtils.canManage(request.getTargetDepot())));
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- getSettings().setPlaceholder("Select user to add as reviewer...");
- getSettings().setFormatResult("gitplex.accountChoiceFormatter.formatResult");
- getSettings().setFormatSelection("gitplex.accountChoiceFormatter.formatSelection");
- getSettings().setEscapeMarkup("gitplex.accountChoiceFormatter.escapeMarkup");
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
-
- super.onDetach();
- }
-
- protected void onSelect(AjaxRequestTarget target, Account user) {
- PullRequest request = requestModel.getObject();
- PullRequestReviewInvitation invitation = null;
- for(PullRequestReviewInvitation each: request.getReviewInvitations()) {
- if (each.getUser().equals(user)) {
- invitation = each;
- break;
- }
- }
- if (invitation != null) {
- invitation.setExcluded(false);
- invitation.setDate(new Date());
- } else {
- invitation = new PullRequestReviewInvitation();
- invitation.setRequest(request);
- invitation.setUser(user);
- request.getReviewInvitations().add(invitation);
- }
- if (!request.isNew())
- GitPlex.getInstance(PullRequestReviewInvitationManager.class).save(invitation);
- };
-}
+package com.pmease.gitplex.web.component.pullrequest.requestreviewer;
+
+import java.util.Date;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.head.JavaScriptHeaderItem;
+import org.apache.wicket.model.IModel;
+
+import com.pmease.commons.wicket.component.select2.SelectToAddChoice;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.manager.PullRequestReviewInvitationManager;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.accountchoice.AccountChoiceResourceReference;
+
+@SuppressWarnings("serial")
+public abstract class ReviewerChoice extends SelectToAddChoice<Account> {
+
+ private final IModel<PullRequest> requestModel;
+
+ public ReviewerChoice(String id, IModel<PullRequest> requestModel) {
+ super(id, new ReviewerProvider(requestModel));
+
+ this.requestModel = requestModel;
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = requestModel.getObject();
+ setVisible(request.isOpen()
+ && !request.getPotentialReviewers().isEmpty()
+ && SecurityUtils.canModify(request));
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ getSettings().setPlaceholder("Select user to add as reviewer...");
+ getSettings().setFormatResult("gitplex.accountChoiceFormatter.formatResult");
+ getSettings().setFormatSelection("gitplex.accountChoiceFormatter.formatSelection");
+ getSettings().setEscapeMarkup("gitplex.accountChoiceFormatter.escapeMarkup");
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(JavaScriptHeaderItem.forReference(AccountChoiceResourceReference.INSTANCE));
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+
+ super.onDetach();
+ }
+
+ protected void onSelect(AjaxRequestTarget target, Account user) {
+ PullRequest request = requestModel.getObject();
+ PullRequestReviewInvitation invitation = null;
+ for(PullRequestReviewInvitation each: request.getReviewInvitations()) {
+ if (each.getUser().equals(user)) {
+ invitation = each;
+ break;
+ }
+ }
+ if (invitation == null) {
+ invitation = new PullRequestReviewInvitation();
+ invitation.setRequest(request);
+ invitation.setUser(user);
+ request.getReviewInvitations().add(invitation);
+ }
+ invitation.setStatus(PullRequestReviewInvitation.Status.ADDED_MANUALLY);
+ invitation.setDate(new Date());
+ if (!request.isNew())
+ GitPlex.getInstance(PullRequestReviewInvitationManager.class).save(invitation);
+ };
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/mapper/UrlMapper.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/mapper/UrlMapper.java
index 080ac4c8b9..fac6dc320a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/mapper/UrlMapper.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/mapper/UrlMapper.java
@@ -33,6 +33,7 @@ import com.pmease.gitplex.web.page.admin.account.AccountListPage;
import com.pmease.gitplex.web.page.admin.account.NewUserPage;
import com.pmease.gitplex.web.page.depot.NoBranchesPage;
import com.pmease.gitplex.web.page.depot.branches.DepotBranchesPage;
+import com.pmease.gitplex.web.page.depot.comments.CodeCommentPage;
import com.pmease.gitplex.web.page.depot.comments.DepotCommentsPage;
import com.pmease.gitplex.web.page.depot.commit.CommitDetailPage;
import com.pmease.gitplex.web.page.depot.commit.DepotCommitsPage;
@@ -41,7 +42,7 @@ import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
import com.pmease.gitplex.web.page.depot.overview.DepotOverviewPage;
import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.CodeCommentsPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.RequestCodeCommentsPage;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.integrationpreview.IntegrationPreviewPage;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
@@ -173,12 +174,13 @@ public class UrlMapper extends CompoundRequestMapper {
add(new DepotMapper(
"${account}/${depot}/pulls/${request}/overview", RequestOverviewPage.class));
add(new DepotMapper(
- "${account}/${depot}/pulls/${request}/code-comments", CodeCommentsPage.class));
+ "${account}/${depot}/pulls/${request}/code-comments", RequestCodeCommentsPage.class));
add(new DepotMapper(
"${account}/${depot}/pulls/${request}/changes", RequestChangesPage.class));
add(new DepotMapper(
"${account}/${depot}/pulls/${request}/integration-preview", IntegrationPreviewPage.class));
add(new DepotMapper("${account}/${depot}/comments", DepotCommentsPage.class));
+ add(new DepotMapper("${account}/${depot}/comments/${comment}", CodeCommentPage.class));
add(new DepotMapper("${account}/${depot}/settings/general", GeneralSettingPage.class));
add(new DepotMapper("${account}/${depot}/settings/teams", DepotTeamListPage.class));
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
index d94d2f8608..df121d5ba9 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/model/ReviewersModel.java
@@ -1,7 +1,6 @@
package com.pmease.gitplex.web.model;
import java.util.ArrayList;
-import java.util.Comparator;
import java.util.List;
import org.apache.wicket.model.IModel;
@@ -23,10 +22,22 @@ public class ReviewersModel extends LoadableDetachableModel<List<PullRequestRevi
protected List<PullRequestReviewInvitation> load() {
List<PullRequestReviewInvitation> invitations = new ArrayList<>();
for (PullRequestReviewInvitation invitation: requestModel.getObject().getReviewInvitations()) {
- if (!invitation.isExcluded())
+ if (invitation.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED)
invitations.add(invitation);
}
- invitations.sort(Comparator.comparing(PullRequestReviewInvitation::getDate));
+ invitations.sort((o1, o2)->{
+ if (o1.getId() == null) {
+ if (o2.getId() == null)
+ return o1.getDate().compareTo(o2.getDate());
+ else
+ return 1;
+ } else {
+ if (o2.getId() == null)
+ return -1;
+ else
+ return (int)(o1.getId() - o2.getId());
+ }
+ });
return invitations;
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/AccountLayoutPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/AccountLayoutPage.java
index 7a43c8aed1..129b7353d5 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/AccountLayoutPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/AccountLayoutPage.java
@@ -1,87 +1,87 @@
-package com.pmease.gitplex.web.page.account;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.wicket.markup.head.CssHeaderItem;
-import org.apache.wicket.markup.head.IHeaderResponse;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-
-import com.pmease.commons.wicket.component.tabbable.PageTab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.gitplex.core.security.SecurityUtils;
-import com.pmease.gitplex.web.component.avatar.Avatar;
-import com.pmease.gitplex.web.page.account.collaborators.AccountCollaboratorListPage;
-import com.pmease.gitplex.web.page.account.collaborators.CollaboratorPage;
-import com.pmease.gitplex.web.page.account.members.MemberListPage;
-import com.pmease.gitplex.web.page.account.members.MemberPage;
-import com.pmease.gitplex.web.page.account.members.NewMembersPage;
-import com.pmease.gitplex.web.page.account.notifications.NotificationListPage;
-import com.pmease.gitplex.web.page.account.overview.AccountOverviewPage;
-import com.pmease.gitplex.web.page.account.overview.NewDepotPage;
-import com.pmease.gitplex.web.page.account.overview.NewOrganizationPage;
-import com.pmease.gitplex.web.page.account.setting.AvatarEditPage;
-import com.pmease.gitplex.web.page.account.setting.PasswordEditPage;
-import com.pmease.gitplex.web.page.account.setting.ProfileEditPage;
-import com.pmease.gitplex.web.page.account.teams.TeamListPage;
-import com.pmease.gitplex.web.page.account.teams.TeamPage;
-
-@SuppressWarnings("serial")
-public abstract class AccountLayoutPage extends AccountPage {
-
- public AccountLayoutPage(PageParameters params) {
- super(params);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- BookmarkablePageLink<Void> avatarLink = new BookmarkablePageLink<Void>("avatar",
- AvatarEditPage.class, AvatarEditPage.paramsOf(getAccount()));
- if (!SecurityUtils.canManage(getAccount()))
- avatarLink.setEnabled(false);
- add(avatarLink);
- avatarLink.add(new Avatar("avatar", accountModel.getObject(), null));
-
- List<PageTab> tabs = new ArrayList<>();
-
- tabs.add(new AccountTab("Overview", "fa fa-fw fa-list-alt", 0,
- AccountOverviewPage.class, NewOrganizationPage.class, NewDepotPage.class));
-
- if (getAccount().isOrganization()) {
- if (SecurityUtils.canAccess(getAccount())) {
- tabs.add(new AccountTab("Members", "fa fa-fw fa-user",
- getAccount().getOrganizationMembers().size(),
- MemberListPage.class, NewMembersPage.class, MemberPage.class));
- tabs.add(new AccountTab("Teams", "fa fa-fw fa-group",
- getAccount().getDefinedTeams().size(), TeamListPage.class, TeamPage.class));
- }
- if (SecurityUtils.canManage(getAccount())) {
- tabs.add(new AccountTab("Collaborators", "fa fa-fw fa-user",
- getAccount().getAllUserAuthorizationsInOrganization().size(),
- AccountCollaboratorListPage.class, CollaboratorPage.class));
- tabs.add(new AccountTab("Setting", "fa fa-fw fa-cog", 0, ProfileEditPage.class, AvatarEditPage.class));
- }
- } else if (SecurityUtils.canManage(getAccount())) {
- tabs.add(new AccountTab("Collaborators", "fa fa-fw fa-user",
- getAccount().getAllUserAuthorizationsInOrganization().size(),
- AccountCollaboratorListPage.class, CollaboratorPage.class));
- tabs.add(new AccountTab("Notifications", "fa fa-fw fa-bell-o",
- getAccount().getRequestNotifications().size(), NotificationListPage.class));
- tabs.add(new AccountTab("Setting", "fa fa-fw fa-cog", 0,
- ProfileEditPage.class, AvatarEditPage.class, PasswordEditPage.class));
- }
- add(new Tabbable("accountTabs", tabs));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(AccountLayoutPage.class, "account.css")));
- }
-
-}
+package com.pmease.gitplex.web.page.account;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+
+import com.pmease.commons.wicket.component.tabbable.PageTab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.gitplex.core.security.SecurityUtils;
+import com.pmease.gitplex.web.component.avatar.Avatar;
+import com.pmease.gitplex.web.page.account.collaborators.AccountCollaboratorListPage;
+import com.pmease.gitplex.web.page.account.collaborators.CollaboratorPage;
+import com.pmease.gitplex.web.page.account.members.MemberListPage;
+import com.pmease.gitplex.web.page.account.members.MemberPage;
+import com.pmease.gitplex.web.page.account.members.NewMembersPage;
+import com.pmease.gitplex.web.page.account.notifications.NotificationListPage;
+import com.pmease.gitplex.web.page.account.overview.AccountOverviewPage;
+import com.pmease.gitplex.web.page.account.overview.NewDepotPage;
+import com.pmease.gitplex.web.page.account.overview.NewOrganizationPage;
+import com.pmease.gitplex.web.page.account.setting.AvatarEditPage;
+import com.pmease.gitplex.web.page.account.setting.PasswordEditPage;
+import com.pmease.gitplex.web.page.account.setting.ProfileEditPage;
+import com.pmease.gitplex.web.page.account.teams.TeamListPage;
+import com.pmease.gitplex.web.page.account.teams.TeamPage;
+
+@SuppressWarnings("serial")
+public abstract class AccountLayoutPage extends AccountPage {
+
+ public AccountLayoutPage(PageParameters params) {
+ super(params);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ BookmarkablePageLink<Void> avatarLink = new BookmarkablePageLink<Void>("avatar",
+ AvatarEditPage.class, AvatarEditPage.paramsOf(getAccount()));
+ if (!SecurityUtils.canManage(getAccount()))
+ avatarLink.setEnabled(false);
+ add(avatarLink);
+ avatarLink.add(new Avatar("avatar", accountModel.getObject(), null));
+
+ List<PageTab> tabs = new ArrayList<>();
+
+ tabs.add(new AccountTab("Overview", "fa fa-fw fa-list-alt", 0,
+ AccountOverviewPage.class, NewOrganizationPage.class, NewDepotPage.class));
+
+ if (getAccount().isOrganization()) {
+ if (SecurityUtils.canAccess(getAccount())) {
+ tabs.add(new AccountTab("Members", "fa fa-fw fa-user",
+ getAccount().getOrganizationMembers().size(),
+ MemberListPage.class, NewMembersPage.class, MemberPage.class));
+ tabs.add(new AccountTab("Teams", "fa fa-fw fa-group",
+ getAccount().getDefinedTeams().size(), TeamListPage.class, TeamPage.class));
+ }
+ if (SecurityUtils.canManage(getAccount())) {
+ tabs.add(new AccountTab("Collaborators", "fa fa-fw fa-user",
+ getAccount().getAllUserAuthorizationsInOrganization().size(),
+ AccountCollaboratorListPage.class, CollaboratorPage.class));
+ tabs.add(new AccountTab("Setting", "fa fa-fw fa-cog", 0, ProfileEditPage.class, AvatarEditPage.class));
+ }
+ } else if (SecurityUtils.canManage(getAccount())) {
+ tabs.add(new AccountTab("Collaborators", "fa fa-fw fa-user",
+ getAccount().getAllUserAuthorizationsInOrganization().size(),
+ AccountCollaboratorListPage.class, CollaboratorPage.class));
+ tabs.add(new AccountTab("Notifications", "fa fa-fw fa-bell-o",
+ getAccount().getRequestNotifications().size(), NotificationListPage.class));
+ tabs.add(new AccountTab("Setting", "fa fa-fw fa-cog", 0,
+ ProfileEditPage.class, AvatarEditPage.class, PasswordEditPage.class));
+ }
+ add(new Tabbable("accountTabs", tabs));
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(AccountLayoutPage.class, "account.css")));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.html
index 76f898661c..768e61db4d 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.html
@@ -1,10 +1,14 @@
-<wicket:extend>
- <div>
- <table wicket:id="notifications" class="table table-striped"></table>
- <wicket:enclosure child="deleteSelected">
- <div class="help-block">
- <i class="fa fa-info-circle"></i> GitPlex will remove notifications as you complete relevant tasks. However you can also <a wicket:id="deleteSelected">delete selected notifications</a> manually here.
- </div>
- </wicket:enclosure>
- </div>
+<wicket:extend>
+ <div>
+ <table wicket:id="notifications" class="table table-striped"></table>
+ <div wicket:id="noNotifications" class="alert alert-warning">No notifications found</div>
+ <wicket:enclosure child="deleteSelected">
+ <div class="help-block">
+ <i class="fa fa-info-circle"></i> GitPlex will remove notifications as you complete relevant tasks. However you can also <a wicket:id="deleteSelected">delete selected notifications</a> manually here.
+ </div>
+ </wicket:enclosure>
+ </div>
+ <wicket:fragment wicket:id="requestFrag">
+ <a wicket:id="link"></a>
+ </wicket:fragment>
</wicket:extend>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.java
index 540ead6f28..af281bca2a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/account/notifications/NotificationListPage.java
@@ -6,12 +6,15 @@ import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.markup.ComponentTag;
+import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
@@ -59,7 +62,7 @@ public class NotificationListPage extends AccountLayoutPage {
};
- final SelectionColumn<PullRequestNotification, String> selectionColumn;
+ SelectionColumn<PullRequestNotification, String> selectionColumn;
List<IColumn<PullRequestNotification, String>> columns = new ArrayList<>();
selectionColumn = new SelectionColumn<PullRequestNotification, String>();
@@ -72,7 +75,8 @@ public class NotificationListPage extends AccountLayoutPage {
Item<ICellPopulator<PullRequestNotification>> cellItem,
String componentId, IModel<PullRequestNotification> rowModel) {
PullRequestNotification notification = rowModel.getObject();
- cellItem.add(new BookmarkablePageLink<Void>(componentId, RequestOverviewPage.class,
+ Fragment fragment = new Fragment(componentId, "requestFrag", NotificationListPage.this);
+ fragment.add(new BookmarkablePageLink<Void>("link", RequestOverviewPage.class,
RequestOverviewPage.paramsOf(notification.getRequest())) {
@Override
@@ -81,6 +85,7 @@ public class NotificationListPage extends AccountLayoutPage {
}
});
+ cellItem.add(fragment);
}
});
@@ -149,8 +154,12 @@ public class NotificationListPage extends AccountLayoutPage {
});
- add(new DefaultDataTable<PullRequestNotification, String>("notifications",
- columns, dataProvider, Constants.DEFAULT_PAGE_SIZE));
+ DataTable<PullRequestNotification, String> dataTable =
+ new DefaultDataTable<PullRequestNotification, String>("notifications", columns, dataProvider, Constants.DEFAULT_PAGE_SIZE);
+ dataTable.setVisible(dataTable.getRowCount() != 0);
+ add(dataTable);
+
+ add(new WebMarkupContainer("noNotifications").setVisible(dataTable.getRowCount() == 0));
add(new Link<Void>("deleteSelected") {
@@ -168,7 +177,7 @@ public class NotificationListPage extends AccountLayoutPage {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(getAccount().equals(getLoginUser()));
+ setVisible(getAccount().equals(getLoginUser()) && dataTable.getRowCount() != 0);
}
});
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/MailSettingPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/MailSettingPage.java
index 6e877ad0c8..418584b180 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/MailSettingPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/admin/MailSettingPage.java
@@ -1,100 +1,99 @@
-package com.pmease.gitplex.web.page.admin;
-
-import java.io.Serializable;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.form.AjaxButton;
-import org.apache.wicket.markup.html.form.Form;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Sets;
-import com.pmease.commons.wicket.behavior.testform.TestFormBehavior;
-import com.pmease.commons.wicket.behavior.testform.TestResult;
-import com.pmease.commons.wicket.editable.BeanContext;
-import com.pmease.commons.wicket.editable.BeanEditor;
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.ConfigManager;
-import com.pmease.gitplex.core.manager.MailManager;
-import com.pmease.gitplex.core.setting.MailSetting;
-
-@SuppressWarnings("serial")
-public class MailSettingPage extends AdministrationPage {
-
- private static final Logger logger = LoggerFactory.getLogger(MailSettingPage.class);
-
- private MailSetting mailSetting;
-
- private BeanEditor<Serializable> editor;
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- mailSetting = GitPlex.getInstance(ConfigManager.class).getMailSetting();
- if (mailSetting == null)
- mailSetting = new MailSetting();
-
- Form<?> form = new Form<Void>("form") {
-
- @Override
- protected void onSubmit() {
- super.onSubmit();
- GitPlex.getInstance(ConfigManager.class).saveMailSetting(mailSetting);
- getSession().success("Mail setting has been updated");
- setResponsePage(MailSettingPage.class);
- }
-
- };
- form.add(editor = BeanContext.editBean("editor", mailSetting));
-
- form.add(new AjaxButton("test") {
-
- private TestFormBehavior testBehavior;
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(testBehavior = new TestFormBehavior() {
-
- @Override
- protected TestResult test() {
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
- try {
- GitPlex.getInstance(MailManager.class).sendMailNow(
- mailSetting, Sets.newHashSet(currentUser),
- "Test email from GitPlex", "Great, your mail setting is correct!");
- return new TestResult.Successful("Test mail has been sent to " +
- currentUser.getEmail() + ", please check your mail box.");
- } catch (Exception e) {
- logger.error("Error sending test email", e);
- return new TestResult.Failed("Error sending test email: " + e.getMessage() + ", check server log for details.");
- }
- }
-
- });
- }
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- target.add(editor);
- target.focusComponent(null);
- testBehavior.requestTest(target);
- }
-
- @Override
- protected void onError(AjaxRequestTarget target, Form<?> form) {
- target.add(editor);
- }
-
- });
-
- add(form);
- }
-
+package com.pmease.gitplex.web.page.admin;
+
+import java.io.Serializable;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.form.Form;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Sets;
+import com.pmease.commons.wicket.behavior.testform.TestFormBehavior;
+import com.pmease.commons.wicket.behavior.testform.TestResult;
+import com.pmease.commons.wicket.editable.BeanContext;
+import com.pmease.commons.wicket.editable.BeanEditor;
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.ConfigManager;
+import com.pmease.gitplex.core.manager.MailManager;
+import com.pmease.gitplex.core.setting.MailSetting;
+
+@SuppressWarnings("serial")
+public class MailSettingPage extends AdministrationPage {
+
+ private static final Logger logger = LoggerFactory.getLogger(MailSettingPage.class);
+
+ private MailSetting mailSetting;
+
+ private BeanEditor<Serializable> editor;
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ mailSetting = GitPlex.getInstance(ConfigManager.class).getMailSetting();
+ if (mailSetting == null)
+ mailSetting = new MailSetting();
+
+ Form<?> form = new Form<Void>("form") {
+
+ @Override
+ protected void onSubmit() {
+ super.onSubmit();
+ GitPlex.getInstance(ConfigManager.class).saveMailSetting(mailSetting);
+ getSession().success("Mail setting has been updated");
+ }
+
+ };
+ form.add(editor = BeanContext.editBean("editor", mailSetting));
+
+ form.add(new AjaxButton("test") {
+
+ private TestFormBehavior testBehavior;
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(testBehavior = new TestFormBehavior() {
+
+ @Override
+ protected TestResult test() {
+ Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
+ try {
+ GitPlex.getInstance(MailManager.class).sendMail(
+ mailSetting, Sets.newHashSet(currentUser),
+ "Test email from GitPlex", "Great, your mail setting is correct!");
+ return new TestResult.Successful("Test mail has been sent to " +
+ currentUser.getEmail() + ", please check your mail box.");
+ } catch (Exception e) {
+ logger.error("Error sending test email", e);
+ return new TestResult.Failed("Error sending test email: " + e.getMessage() + ", check server log for details.");
+ }
+ }
+
+ });
+ }
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ target.add(editor);
+ target.focusComponent(null);
+ testBehavior.requestTest(target);
+ }
+
+ @Override
+ protected void onError(AjaxRequestTarget target, Form<?> form) {
+ target.add(editor);
+ }
+
+ });
+
+ add(form);
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/branches/DepotBranchesPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/branches/DepotBranchesPage.java
index e5389c32ce..937b065d43 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/branches/DepotBranchesPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/branches/DepotBranchesPage.java
@@ -51,7 +51,6 @@ import org.eclipse.jgit.revwalk.RevWalk;
import com.google.common.base.Preconditions;
import com.pmease.commons.git.GitUtils;
import com.pmease.commons.git.RefInfo;
-import com.pmease.commons.hibernate.dao.Dao;
import com.pmease.commons.util.StringUtils;
import com.pmease.commons.wicket.ajaxlistener.ConfirmListener;
import com.pmease.commons.wicket.behavior.OnTypingDoneBehavior;
@@ -231,11 +230,11 @@ public class DepotBranchesPage extends DepotPage {
@Override
protected Map<String, BranchWatch> load() {
- Map<String, BranchWatch> requestWatches = new HashMap<>();
+ Map<String, BranchWatch> watches = new HashMap<>();
for (BranchWatch watch: GitPlex.getInstance(BranchWatchManager.class).find(
Preconditions.checkNotNull(getLoginUser()), getDepot()))
- requestWatches.put(watch.getBranch(), watch);
- return requestWatches;
+ watches.put(watch.getBranch(), watch);
+ return watches;
}
};
@@ -415,7 +414,7 @@ public class DepotBranchesPage extends DepotPage {
@Override
protected void populateItem(ListItem<RefInfo> item) {
RefInfo ref = item.getModelObject();
- final String branch = GitUtils.ref2branch(ref.getRef().getName());
+ String branch = GitUtils.ref2branch(ref.getRef().getName());
DepotFilePage.State state = new DepotFilePage.State();
state.blobIdent.revision = branch;
@@ -577,7 +576,7 @@ public class DepotBranchesPage extends DepotPage {
public void onClick(AjaxRequestTarget target) {
BranchWatch watch = branchWatchesModel.getObject().get(branch);
if (watch != null) {
- GitPlex.getInstance(Dao.class).remove(watch);
+ GitPlex.getInstance(BranchWatchManager.class).delete(watch);
branchWatchesModel.getObject().remove(branch);
}
target.add(actionsContainer);
@@ -586,8 +585,7 @@ public class DepotBranchesPage extends DepotPage {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(getLoginUser() != null
- && branchWatchesModel.getObject().containsKey(item.getModelObject()));
+ setVisible(getLoginUser() != null && branchWatchesModel.getObject().containsKey(branch));
}
});
@@ -599,15 +597,14 @@ public class DepotBranchesPage extends DepotPage {
watch.setDepot(getDepot());
watch.setBranch(branch);
watch.setUser(getLoginUser());
- GitPlex.getInstance(Dao.class).persist(watch);
+ GitPlex.getInstance(BranchWatchManager.class).save(watch);
target.add(actionsContainer);
}
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(getLoginUser() != null
- && !branchWatchesModel.getObject().containsKey(item.getModelObject()));
+ setVisible(getLoginUser() != null && !branchWatchesModel.getObject().containsKey(branch));
}
});
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.html
new file mode 100644
index 0000000000..43298b44c7
--- /dev/null
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.html
@@ -0,0 +1,15 @@
+<wicket:extend>
+ <div id="code-comment" class="well">
+ <div>
+ <i class="fa fa-hand-o-right"></i> You may open this comment in context of below pull requests
+ </div>
+ <ul>
+ <li wicket:id="requests" class="request">
+ <a wicket:id="request">
+ #<span wicket:id="number" class="number"></span> - <span wicket:id="title" class="title"></span>
+ </a>
+ </li>
+ </ul>
+ <i class="fa fa-hand-o-right"></i> <a wicket:id="link">Or open it directly without pull requests</a>
+ </div>
+</wicket:extend>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.java
new file mode 100644
index 0000000000..2fd7e2bb87
--- /dev/null
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/CodeCommentPage.java
@@ -0,0 +1,128 @@
+package com.pmease.gitplex.web.page.depot.comments;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.markup.head.CssHeaderItem;
+import org.apache.wicket.markup.head.IHeaderResponse;
+import org.apache.wicket.markup.html.basic.Label;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.list.ListItem;
+import org.apache.wicket.markup.html.list.ListView;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.CodeComment;
+import com.pmease.gitplex.core.entity.CodeCommentRelation;
+import com.pmease.gitplex.core.entity.Depot;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.support.CompareContext;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.compare.RevisionComparePage;
+import com.pmease.gitplex.web.page.depot.file.DepotFilePage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+
+@SuppressWarnings("serial")
+public class CodeCommentPage extends DepotPage {
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private final IModel<CodeComment> commentModel;
+
+ public CodeCommentPage(PageParameters params) {
+ super(params);
+
+ Long commentId = params.get(PARAM_COMMENT).toLong();
+ commentModel = new LoadableDetachableModel<CodeComment>() {
+
+ @Override
+ protected CodeComment load() {
+ return GitPlex.getInstance(CodeCommentManager.class).load(commentId);
+ }
+
+ };
+
+ CodeComment comment = commentModel.getObject();
+ if (comment.getRelations().isEmpty()) {
+ CompareContext compareContext = comment.getLastCompareContext();
+ if (!compareContext.getCompareCommit().equals(comment.getCommentPos().getCommit())) {
+ throw new RestartResponseException(
+ RevisionComparePage.class,
+ RevisionComparePage.paramsOf(getDepot(), comment));
+ } else {
+ throw new RestartResponseException(
+ DepotFilePage.class,
+ DepotFilePage.paramsOf(getDepot(), comment));
+ }
+ }
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new ListView<PullRequest>("requests", new LoadableDetachableModel<List<PullRequest>>() {
+
+ @Override
+ protected List<PullRequest> load() {
+ return commentModel.getObject().getRelations()
+ .stream()
+ .map(CodeCommentRelation::getRequest)
+ .sorted((o1, o2)->(int)(o2.getId()-o1.getId()))
+ .collect(Collectors.toList());
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<PullRequest> item) {
+ PullRequest request = item.getModelObject();
+ CodeComment comment = commentModel.getObject();
+ PageParameters params = RequestChangesPage.paramsOf(request, comment);
+ Link<Void> link = new BookmarkablePageLink<Void>("request",
+ RequestChangesPage.class, params);
+ link.add(new Label("number", request.getNumber()));
+ link.add(new Label("title", request.getTitle()));
+ item.add(link);
+ }
+
+ });
+
+ CodeComment comment = commentModel.getObject();
+ CompareContext compareContext = comment.getLastCompareContext();
+ if (!compareContext.getCompareCommit().equals(comment.getCommentPos().getCommit())) {
+ add(new BookmarkablePageLink<Void>("link",
+ RevisionComparePage.class,
+ RevisionComparePage.paramsOf(getDepot(), comment)));
+ } else {
+ add(new BookmarkablePageLink<Void>("link",
+ DepotFilePage.class,
+ DepotFilePage.paramsOf(getDepot(), comment)));
+ }
+ }
+
+ public static PageParameters paramsOf(Depot depot, CodeComment comment) {
+ PageParameters params = paramsOf(depot);
+ params.add(PARAM_COMMENT, comment.getId());
+ return params;
+ }
+
+ @Override
+ protected void onDetach() {
+ commentModel.detach();
+ super.onDetach();
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(new CssResourceReference(CodeCommentPage.class, "depot-comments.css")));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/depot-comments.css b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/depot-comments.css
index 609c4bfd63..f92b3e2ef3 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/depot-comments.css
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/comments/depot-comments.css
@@ -1,3 +1,7 @@
-#depot-comments {
- padding: 20px;
+#depot-comments {
+ padding: 20px;
+}
+#code-comment {
+ margin: 20px;
+ font-size: 16px;
}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
index 252339fb90..9e4c68b070 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/compare/RevisionComparePage.java
@@ -1,735 +1,755 @@
-package com.pmease.gitplex.web.page.depot.compare;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
-import org.apache.wicket.behavior.AttributeAppender;
-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.CheckBox;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.eclipse.jgit.lib.ObjectId;
-import org.eclipse.jgit.revwalk.RevCommit;
-import org.eclipse.jgit.revwalk.RevWalk;
-
-import com.pmease.commons.git.command.CalcMergeBaseCommand;
-import com.pmease.commons.git.command.CloneCommand;
-import com.pmease.commons.git.command.FetchCommand;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.commons.util.FileUtils;
-import com.pmease.commons.wicket.behavior.TooltipBehavior;
-import com.pmease.commons.wicket.component.backtotop.BackToTop;
-import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
-import com.pmease.commons.wicket.component.tabbable.Tab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-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.PullRequest;
-import com.pmease.gitplex.core.entity.support.CommentPos;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.DepotAndRevision;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
-import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.component.revisionpicker.AffinalRevisionPicker;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.NoBranchesPage;
-import com.pmease.gitplex.web.page.depot.commit.CommitDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-
-@SuppressWarnings("serial")
-public class RevisionComparePage extends DepotPage implements CommentSupport {
-
- public enum TabPanel {
- COMMITS,
- CHANGES;
-
- public static TabPanel of(@Nullable String name) {
- if (name != null) {
- return valueOf(name.toUpperCase());
- } else {
- return COMMITS;
- }
- }
-
- };
-
- private static final String PARAM_LEFT = "left";
-
- private static final String PARAM_RIGHT = "right";
-
- private static final String PARAM_COMPARE_WITH_MERGE_BASE = "compare-with-merge-base";
-
- private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
-
- private static final String PARAM_COMMENT = "comment";
-
- private static final String PARAM_MARK = "mark";
-
- private static final String PARAM_PATH_FILTER = "path-filter";
-
- private static final String PARAM_BLAME_FILE = "blame-file";
-
- private static final String PARAM_TAB = "tab-panel";
-
- private static final String TAB_PANEL_ID = "tabPanel";
-
- private IModel<List<RevCommit>> commitsModel;
-
- private IModel<PullRequest> requestModel;
-
- private IModel<ObjectId> mergeBaseModel;
-
- private State state = new State();
-
- private ObjectId leftCommitId;
-
- private ObjectId rightCommitId;
-
- private Tabbable tabbable;
-
- public static PageParameters paramsOf(Depot depot, State state) {
- PageParameters params = paramsOf(depot);
- params.set(PARAM_LEFT, state.leftSide.toString());
- params.set(PARAM_RIGHT, state.rightSide.toString());
- params.set(PARAM_COMPARE_WITH_MERGE_BASE, state.compareWithMergeBase);
- if (state.whitespaceOption != WhitespaceOption.DEFAULT)
- params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
- if (state.pathFilter != null)
- params.set(PARAM_PATH_FILTER, state.pathFilter);
- if (state.blameFile != null)
- params.set(PARAM_BLAME_FILE, state.blameFile);
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mark != null)
- params.set(PARAM_MARK, state.mark.toString());
- if (state.tabPanel != null)
- params.set(PARAM_TAB, state.tabPanel.name());
- return params;
- }
-
- public RevisionComparePage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- String str = params.get(PARAM_LEFT).toString();
- if (str != null) {
- state.leftSide = new DepotAndRevision(str);
- } else {
- state.leftSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
- }
- leftCommitId = state.leftSide.getCommit().copy();
-
- str = params.get(PARAM_RIGHT).toString();
- if (str != null) {
- state.rightSide = new DepotAndRevision(str);
- } else {
- state.rightSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
- }
- rightCommitId = state.rightSide.getCommit().copy();
-
- state.compareWithMergeBase = params.get(PARAM_COMPARE_WITH_MERGE_BASE).toBoolean(true);
-
- /*
- * When compare across different repositories, left revision and right revision might not
- * exist in same repository and this cause many difficulties such as calculating changes,
- * recording comment revisions, or get permanent mark urls. So we add below constraint as
- * merge base commit and right side revision are guaranteed to be both in right side
- * repository
- */
- if (!state.compareWithMergeBase && !state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
- throw new IllegalArgumentException("Can only compare with merge base when compare across repositories");
- }
-
- state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
- state.blameFile = params.get(PARAM_BLAME_FILE).toString();
- state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
-
- state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
- state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
-
- state.tabPanel = TabPanel.of(params.get(PARAM_TAB).toString());
-
- requestModel = new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
- DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
- return GitPlex.getInstance(PullRequestManager.class).findOpen(left, right);
- }
-
- };
-
- mergeBaseModel = new LoadableDetachableModel<ObjectId>() {
-
- @Override
- protected ObjectId load() {
- Depot leftDepot = state.leftSide.getDepot();
- Depot rightDepot = state.rightSide.getDepot();
- if (!leftDepot.equals(rightDepot)) {
- File tempDir = FileUtils.createTempDir();
- try {
- new CloneCommand(tempDir).from(leftDepot.getDirectory().getAbsolutePath()).bare(true).shared(true).call();
- new FetchCommand(tempDir).from(rightDepot.getDirectory().getAbsolutePath()).refspec(state.rightSide.getRevision()).call();
- return ObjectId.fromString(new CalcMergeBaseCommand(tempDir).rev1(leftCommitId.name()).rev2(rightCommitId.name()).call());
- } finally {
- FileUtils.deleteDir(tempDir);
- }
- } else {
- return leftDepot.getMergeBase(state.leftSide.getRevision(), state.rightSide.getRevision());
- }
- }
-
- };
-
- commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
-
- @Override
- protected List<RevCommit> load() {
- List<RevCommit> commits = new ArrayList<>();
- Depot rightDepot = state.rightSide.getDepot();
-
- try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
- ObjectId mergeBase = mergeBaseModel.getObject();
- if (rightDepot.equals(state.leftSide.getDepot())
- && !state.compareWithMergeBase
- && !mergeBase.equals(leftCommitId)) {
- revWalk.markStart(revWalk.parseCommit(rightCommitId));
- revWalk.markStart(revWalk.parseCommit(leftCommitId));
- revWalk.markUninteresting(revWalk.parseCommit(mergeBase));
- revWalk.forEach(c->commits.add(c));
- /*
- * Add the merge base commit to make the revision graph understandable,
- * note that we can not get merge commit object by calling parseCommit
- * in current revWalk as it has been marked as uninteresting and this
- * will make the commit object incomplete
- */
- commits.add(getDepot().getRevCommit(mergeBase));
- } else {
- revWalk.markStart(revWalk.parseCommit(rightCommitId));
- revWalk.markUninteresting(revWalk.parseCommit(leftCommitId));
- revWalk.forEach(c->commits.add(c));
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
-
- return commits;
- }
-
- };
-
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- setOutputMarkupId(true);
-
- add(new AffinalRevisionPicker("leftRevSelector", state.leftSide.getDepotId(), state.leftSide.getRevision()) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
- State newState = new State();
- newState.leftSide = new DepotAndRevision(depot, revision);
- newState.rightSide = state.rightSide;
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.mark = state.mark;
- newState.commentId = state.commentId;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = paramsOf(depot, newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
-
- CheckBox checkBox = new CheckBox("compareWithMergeBase", Model.of(state.compareWithMergeBase)) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!mergeBaseModel.equals(leftCommitId));
- }
-
- };
- checkBox.add(new OnChangeAjaxBehavior() {
-
- @Override
- protected void onUpdate(AjaxRequestTarget target) {
- State newState = new State();
- newState.leftSide = state.leftSide;
- newState.rightSide = state.rightSide;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = !state.compareWithMergeBase;
- newState.commentId = state.commentId;
- newState.mark = state.mark;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = RevisionComparePage.paramsOf(depotModel.getObject(), newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
- add(checkBox);
-
- String tooltip;
- if (!state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
- checkBox.add(AttributeAppender.append("disabled", "disabled"));
- tooltip = "Can only compare with common ancestor when compare across different repositories";
- } else {
- tooltip = "Check this to compare \"right side\" with common ancestor of left and right";
- }
-
- add(new WebMarkupContainer("mergeBaseTooltip").add(new TooltipBehavior(Model.of(tooltip))));
-
- PageParameters params = CommitDetailPage.paramsOf(state.leftSide.getDepot(), state.leftSide.getCommit().name());
- Link<Void> leftCommitLink = new BookmarkablePageLink<Void>("leftCommitLink", CommitDetailPage.class, params);
- leftCommitLink.add(new Label("message", state.leftSide.getCommit().getShortMessage()));
- add(leftCommitLink);
-
- params = CommitDetailPage.paramsOf(state.rightSide.getDepot(), state.rightSide.getCommit().name());
- Link<Void> rightCommitLink = new BookmarkablePageLink<Void>("rightCommitLink", CommitDetailPage.class, params);
- rightCommitLink.add(new Label("message", state.rightSide.getCommit().getShortMessage()));
- add(rightCommitLink);
-
- add(new AffinalRevisionPicker("rightRevSelector",
- state.rightSide.getDepotId(), state.rightSide.getRevision()) {
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
- State newState = new State();
- newState.leftSide = state.leftSide;
- newState.rightSide = new DepotAndRevision(depot, revision);
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.commentId = state.commentId;
- newState.mark = state.mark;
- newState.tabPanel = state.tabPanel;
-
- PageParameters params = paramsOf(getDepot(), newState);
- setResponsePage(RevisionComparePage.class, params);
- }
-
- });
-
- add(new Link<Void>("swap") {
-
- @Override
- public void onClick() {
- State newState = new State();
- newState.leftSide = state.rightSide;
- newState.rightSide = state.leftSide;
- newState.pathFilter = state.pathFilter;
- newState.tabPanel = state.tabPanel;
- newState.whitespaceOption = state.whitespaceOption;
- newState.compareWithMergeBase = state.compareWithMergeBase;
- newState.mark = state.mark;
- newState.commentId = state.commentId;
-
- setResponsePage(RevisionComparePage.class,paramsOf(getDepot(), newState));
- }
-
- });
-
- add(new Link<Void>("createRequest") {
-
- @Override
- public void onClick() {
- DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
- DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
- setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(left.getDepot(), left, right));
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- if (state.leftSide.getBranch()!=null && state.rightSide.getBranch()!=null) {
- PullRequest request = requestModel.getObject();
- setVisible(request == null && !mergeBaseModel.getObject().equals(rightCommitId));
- } else {
- setVisible(false);
- }
- }
-
- });
-
- add(new WebMarkupContainer("openedRequest") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- setVisible(requestModel.getObject() != null);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new Label("no", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return String.valueOf(requestModel.getObject().getNumber());
- }
-
- }));
- add(new Link<Void>("link") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
- add(new Label("label", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return requestModel.getObject().getTitle();
- }
- }));
- }
-
- @Override
- public void onClick() {
- PageParameters params = RequestDetailPage.paramsOf(requestModel.getObject());
- setResponsePage(RequestOverviewPage.class, params);
- }
-
- });
-
- }
-
- });
-
- List<Tab> tabs = new ArrayList<>();
-
- tabs.add(new AjaxActionTab(Model.of("Commits")) {
-
- @Override
- public boolean isSelected() {
- return state.tabPanel == null || state.tabPanel == TabPanel.COMMITS;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- state.tabPanel = TabPanel.COMMITS;
- newTabPanel(target);
- pushState(target);
- }
-
- });
-
- tabs.add(new AjaxActionTab(Model.of("Changes")) {
-
- @Override
- public boolean isSelected() {
- return state.tabPanel == TabPanel.CHANGES;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Component tabLink) {
- state.tabPanel = TabPanel.CHANGES;
- newTabPanel(target);
- pushState(target);
- }
-
- });
-
- add(tabbable = new Tabbable("tabs", tabs));
-
- newTabPanel(null);
-
- add(new BackToTop("backToTop"));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RevisionComparePage.class, "revision-compare.css")));
- }
-
- private void newTabPanel(@Nullable AjaxRequestTarget target) {
- IModel<Depot> depotModel = new LoadableDetachableModel<Depot>() {
-
- @Override
- protected Depot load() {
- Depot depot = state.rightSide.getDepot();
- if (state.leftSide.getDepot().equals(state.rightSide.getDepot()))
- depot.cacheObjectId(state.leftSide.getRevision(), leftCommitId);
- depot.cacheObjectId(state.rightSide.getRevision(), rightCommitId);
- return depot;
- }
-
- };
- WebMarkupContainer tabPanel;
- switch (state.tabPanel) {
- case CHANGES:
- IModel<String> blameModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.blameFile;
- }
-
- @Override
- public void setObject(String object) {
- state.blameFile = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- IModel<String> pathFilterModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.pathFilter;
- }
-
- @Override
- public void setObject(String object) {
- state.pathFilter = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public WhitespaceOption getObject() {
- return state.whitespaceOption;
- }
-
- @Override
- public void setObject(WhitespaceOption object) {
- state.whitespaceOption = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- tabPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
- new Model<PullRequest>(null),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():state.leftSide.getRevision(),
- state.rightSide.getRevision(), pathFilterModel, whitespaceOptionModel, blameModel, this);
- break;
- default:
- tabPanel = new CommitListPanel(TAB_PANEL_ID, depotModel, commitsModel);
-
- if (!mergeBaseModel.equals(leftCommitId) && !state.compareWithMergeBase) {
- tabPanel.add(AttributeAppender.append("class", "with-merge-base"));
- }
- break;
- }
- tabPanel.setOutputMarkupId(true);
- if (target != null) {
- replace(tabPanel);
- target.add(tabPanel);
- } else {
- add(tabPanel);
- }
- }
-
- private void pushState(AjaxRequestTarget target) {
- PageParameters params = paramsOf(getDepot(), state);
- CharSequence url = RequestCycle.get().urlFor(RevisionComparePage.class, params);
- pushState(target, url.toString(), state);
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- state = (State) data;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newTabPanel(target);
- target.add(tabbable);
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
- mergeBaseModel.detach();
- commitsModel.detach();
-
- super.onDetach();
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(RevisionComparePage.class, paramsOf(depot));
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public DepotAndRevision leftSide;
-
- public DepotAndRevision rightSide;
-
- public boolean compareWithMergeBase = true;
-
- public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
-
- @Nullable
- public TabPanel tabPanel;
-
- @Nullable
- public String pathFilter;
-
- @Nullable
- public String blameFile;
-
- @Nullable
- public Long commentId;
-
- @Nullable
- public CommentPos mark;
-
- public State() {
- }
-
- public State(State state) {
- leftSide = state.leftSide;
- rightSide = state.rightSide;
- compareWithMergeBase = state.compareWithMergeBase;
- whitespaceOption = state.whitespaceOption;
- pathFilter = state.pathFilter;
- blameFile = state.blameFile;
- commentId = state.commentId;
- mark = state.mark;
- tabPanel = state.tabPanel;
- }
-
- }
-
- @Override
- public CommentPos getMark() {
- return state.mark;
- }
-
- @Override
- public String getMarkUrl(CommentPos mark) {
- State markState = new State();
- markState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
- markState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
- markState.mark = mark;
- markState.pathFilter = state.pathFilter;
- markState.tabPanel = TabPanel.CHANGES;
- markState.whitespaceOption = state.whitespaceOption;
- markState.compareWithMergeBase = false;
- return urlFor(RevisionComparePage.class, paramsOf(markState.rightSide.getDepot(), markState)).toString();
- }
-
- @Override
- public String getCommentUrl(CodeComment comment) {
- State commentState = new State();
- commentState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
- state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
- commentState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
- commentState.mark = comment.getCommentPos();
- commentState.commentId = comment.getId();
- commentState.tabPanel = TabPanel.CHANGES;
- commentState.pathFilter = state.pathFilter;
- commentState.whitespaceOption = state.whitespaceOption;
- commentState.compareWithMergeBase = false;
- return urlFor(RevisionComparePage.class, paramsOf(commentState.rightSide.getDepot(), commentState)).toString();
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (state.commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
- else
- return null;
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- state.mark = comment.getCommentPos();
- state.commentId = comment.getId();
- } else {
- state.commentId = null;
- }
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, CommentPos mark) {
- state.mark = mark;
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
- state.commentId = null;
- state.mark = mark;
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- Collection<WebSocketRegion> regions = new ArrayList<>();
- if (state.commentId != null)
- regions.add(new CodeCommentChangedRegion(state.commentId));
- return regions;
- }
-
-}
+package com.pmease.gitplex.web.page.depot.compare;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.form.OnChangeAjaxBehavior;
+import org.apache.wicket.behavior.AttributeAppender;
+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.CheckBox;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.eclipse.jgit.lib.ObjectId;
+import org.eclipse.jgit.revwalk.RevCommit;
+import org.eclipse.jgit.revwalk.RevWalk;
+
+import com.pmease.commons.git.command.CalcMergeBaseCommand;
+import com.pmease.commons.git.command.CloneCommand;
+import com.pmease.commons.git.command.FetchCommand;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.commons.util.FileUtils;
+import com.pmease.commons.wicket.behavior.TooltipBehavior;
+import com.pmease.commons.wicket.component.backtotop.BackToTop;
+import com.pmease.commons.wicket.component.tabbable.AjaxActionTab;
+import com.pmease.commons.wicket.component.tabbable.Tab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+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.PullRequest;
+import com.pmease.gitplex.core.entity.support.CommentPos;
+import com.pmease.gitplex.core.entity.support.CompareContext;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.DepotAndRevision;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.web.component.commitlist.CommitListPanel;
+import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.component.revisionpicker.AffinalRevisionPicker;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.NoBranchesPage;
+import com.pmease.gitplex.web.page.depot.commit.CommitDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+
+@SuppressWarnings("serial")
+public class RevisionComparePage extends DepotPage implements CommentSupport {
+
+ public enum TabPanel {
+ COMMITS,
+ CHANGES;
+
+ public static TabPanel of(@Nullable String name) {
+ if (name != null) {
+ return valueOf(name.toUpperCase());
+ } else {
+ return COMMITS;
+ }
+ }
+
+ };
+
+ private static final String PARAM_LEFT = "left";
+
+ private static final String PARAM_RIGHT = "right";
+
+ private static final String PARAM_COMPARE_WITH_MERGE_BASE = "compare-with-merge-base";
+
+ private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private static final String PARAM_MARK = "mark";
+
+ private static final String PARAM_PATH_FILTER = "path-filter";
+
+ private static final String PARAM_BLAME_FILE = "blame-file";
+
+ private static final String PARAM_TAB = "tab-panel";
+
+ private static final String TAB_PANEL_ID = "tabPanel";
+
+ private IModel<List<RevCommit>> commitsModel;
+
+ private IModel<PullRequest> requestModel;
+
+ private IModel<ObjectId> mergeBaseModel;
+
+ private State state = new State();
+
+ private ObjectId leftCommitId;
+
+ private ObjectId rightCommitId;
+
+ private Tabbable tabbable;
+
+ public static PageParameters paramsOf(Depot depot, CodeComment comment) {
+ RevisionComparePage.State state = new RevisionComparePage.State();
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ state.compareWithMergeBase = false;
+ CompareContext compareContext = comment.getLastCompareContext();
+ if (compareContext.isLeftSide()) {
+ state.leftSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
+ state.rightSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
+ } else {
+ state.leftSide = new DepotAndRevision(depot, comment.getCommentPos().getCommit());
+ state.rightSide = new DepotAndRevision(depot, compareContext.getCompareCommit());
+ }
+ state.tabPanel = RevisionComparePage.TabPanel.CHANGES;
+ state.whitespaceOption = compareContext.getWhitespaceOption();
+ state.pathFilter = compareContext.getPathFilter();
+ return paramsOf(depot, state);
+ }
+
+ public static PageParameters paramsOf(Depot depot, State state) {
+ PageParameters params = paramsOf(depot);
+ params.set(PARAM_LEFT, state.leftSide.toString());
+ params.set(PARAM_RIGHT, state.rightSide.toString());
+ params.set(PARAM_COMPARE_WITH_MERGE_BASE, state.compareWithMergeBase);
+ if (state.whitespaceOption != WhitespaceOption.DEFAULT)
+ params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
+ if (state.pathFilter != null)
+ params.set(PARAM_PATH_FILTER, state.pathFilter);
+ if (state.blameFile != null)
+ params.set(PARAM_BLAME_FILE, state.blameFile);
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark.toString());
+ if (state.tabPanel != null)
+ params.set(PARAM_TAB, state.tabPanel.name());
+ return params;
+ }
+
+ public RevisionComparePage(final PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ String str = params.get(PARAM_LEFT).toString();
+ if (str != null) {
+ state.leftSide = new DepotAndRevision(str);
+ } else {
+ state.leftSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
+ }
+ leftCommitId = state.leftSide.getCommit().copy();
+
+ str = params.get(PARAM_RIGHT).toString();
+ if (str != null) {
+ state.rightSide = new DepotAndRevision(str);
+ } else {
+ state.rightSide = new DepotAndRevision(getDepot(), getDepot().getDefaultBranch());
+ }
+ rightCommitId = state.rightSide.getCommit().copy();
+
+ state.compareWithMergeBase = params.get(PARAM_COMPARE_WITH_MERGE_BASE).toBoolean(true);
+
+ /*
+ * When compare across different repositories, left revision and right revision might not
+ * exist in same repository and this cause many difficulties such as calculating changes,
+ * recording comment revisions, or get permanent mark urls. So we add below constraint as
+ * merge base commit and right side revision are guaranteed to be both in right side
+ * repository
+ */
+ if (!state.compareWithMergeBase && !state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
+ throw new IllegalArgumentException("Can only compare with merge base when compare across repositories");
+ }
+
+ state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
+ state.blameFile = params.get(PARAM_BLAME_FILE).toString();
+ state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
+
+ state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
+
+ state.tabPanel = TabPanel.of(params.get(PARAM_TAB).toString());
+
+ requestModel = new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
+ DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
+ return GitPlex.getInstance(PullRequestManager.class).findOpen(left, right);
+ }
+
+ };
+
+ mergeBaseModel = new LoadableDetachableModel<ObjectId>() {
+
+ @Override
+ protected ObjectId load() {
+ Depot leftDepot = state.leftSide.getDepot();
+ Depot rightDepot = state.rightSide.getDepot();
+ if (!leftDepot.equals(rightDepot)) {
+ File tempDir = FileUtils.createTempDir();
+ try {
+ new CloneCommand(tempDir).from(leftDepot.getDirectory().getAbsolutePath()).bare(true).shared(true).call();
+ new FetchCommand(tempDir).from(rightDepot.getDirectory().getAbsolutePath()).refspec(state.rightSide.getRevision()).call();
+ return ObjectId.fromString(new CalcMergeBaseCommand(tempDir).rev1(leftCommitId.name()).rev2(rightCommitId.name()).call());
+ } finally {
+ FileUtils.deleteDir(tempDir);
+ }
+ } else {
+ return leftDepot.getMergeBase(state.leftSide.getRevision(), state.rightSide.getRevision());
+ }
+ }
+
+ };
+
+ commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
+
+ @Override
+ protected List<RevCommit> load() {
+ List<RevCommit> commits = new ArrayList<>();
+ Depot rightDepot = state.rightSide.getDepot();
+
+ try (RevWalk revWalk = new RevWalk(getDepot().getRepository())) {
+ ObjectId mergeBase = mergeBaseModel.getObject();
+ if (rightDepot.equals(state.leftSide.getDepot())
+ && !state.compareWithMergeBase
+ && !mergeBase.equals(leftCommitId)) {
+ revWalk.markStart(revWalk.parseCommit(rightCommitId));
+ revWalk.markStart(revWalk.parseCommit(leftCommitId));
+ revWalk.markUninteresting(revWalk.parseCommit(mergeBase));
+ revWalk.forEach(c->commits.add(c));
+ /*
+ * Add the merge base commit to make the revision graph understandable,
+ * note that we can not get merge commit object by calling parseCommit
+ * in current revWalk as it has been marked as uninteresting and this
+ * will make the commit object incomplete
+ */
+ commits.add(getDepot().getRevCommit(mergeBase));
+ } else {
+ revWalk.markStart(revWalk.parseCommit(rightCommitId));
+ revWalk.markUninteresting(revWalk.parseCommit(leftCommitId));
+ revWalk.forEach(c->commits.add(c));
+ }
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+
+ return commits;
+ }
+
+ };
+
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ setOutputMarkupId(true);
+
+ add(new AffinalRevisionPicker("leftRevSelector", state.leftSide.getDepotId(), state.leftSide.getRevision()) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
+ State newState = new State();
+ newState.leftSide = new DepotAndRevision(depot, revision);
+ newState.rightSide = state.rightSide;
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.mark = state.mark;
+ newState.commentId = state.commentId;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = paramsOf(depot, newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+
+ CheckBox checkBox = new CheckBox("compareWithMergeBase", Model.of(state.compareWithMergeBase)) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!mergeBaseModel.equals(leftCommitId));
+ }
+
+ };
+ checkBox.add(new OnChangeAjaxBehavior() {
+
+ @Override
+ protected void onUpdate(AjaxRequestTarget target) {
+ State newState = new State();
+ newState.leftSide = state.leftSide;
+ newState.rightSide = state.rightSide;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = !state.compareWithMergeBase;
+ newState.commentId = state.commentId;
+ newState.mark = state.mark;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = RevisionComparePage.paramsOf(depotModel.getObject(), newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+ add(checkBox);
+
+ String tooltip;
+ if (!state.leftSide.getDepot().equals(state.rightSide.getDepot())) {
+ checkBox.add(AttributeAppender.append("disabled", "disabled"));
+ tooltip = "Can only compare with common ancestor when compare across different repositories";
+ } else {
+ tooltip = "Check this to compare \"right side\" with common ancestor of left and right";
+ }
+
+ add(new WebMarkupContainer("mergeBaseTooltip").add(new TooltipBehavior(Model.of(tooltip))));
+
+ PageParameters params = CommitDetailPage.paramsOf(state.leftSide.getDepot(), state.leftSide.getCommit().name());
+ Link<Void> leftCommitLink = new BookmarkablePageLink<Void>("leftCommitLink", CommitDetailPage.class, params);
+ leftCommitLink.add(new Label("message", state.leftSide.getCommit().getShortMessage()));
+ add(leftCommitLink);
+
+ params = CommitDetailPage.paramsOf(state.rightSide.getDepot(), state.rightSide.getCommit().name());
+ Link<Void> rightCommitLink = new BookmarkablePageLink<Void>("rightCommitLink", CommitDetailPage.class, params);
+ rightCommitLink.add(new Label("message", state.rightSide.getCommit().getShortMessage()));
+ add(rightCommitLink);
+
+ add(new AffinalRevisionPicker("rightRevSelector",
+ state.rightSide.getDepotId(), state.rightSide.getRevision()) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot, String revision) {
+ State newState = new State();
+ newState.leftSide = state.leftSide;
+ newState.rightSide = new DepotAndRevision(depot, revision);
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.commentId = state.commentId;
+ newState.mark = state.mark;
+ newState.tabPanel = state.tabPanel;
+
+ PageParameters params = paramsOf(getDepot(), newState);
+ setResponsePage(RevisionComparePage.class, params);
+ }
+
+ });
+
+ add(new Link<Void>("swap") {
+
+ @Override
+ public void onClick() {
+ State newState = new State();
+ newState.leftSide = state.rightSide;
+ newState.rightSide = state.leftSide;
+ newState.pathFilter = state.pathFilter;
+ newState.tabPanel = state.tabPanel;
+ newState.whitespaceOption = state.whitespaceOption;
+ newState.compareWithMergeBase = state.compareWithMergeBase;
+ newState.mark = state.mark;
+ newState.commentId = state.commentId;
+
+ setResponsePage(RevisionComparePage.class,paramsOf(getDepot(), newState));
+ }
+
+ });
+
+ add(new Link<Void>("createRequest") {
+
+ @Override
+ public void onClick() {
+ DepotAndBranch left = new DepotAndBranch(state.leftSide.toString());
+ DepotAndBranch right = new DepotAndBranch(state.rightSide.toString());
+ setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(left.getDepot(), left, right));
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ if (state.leftSide.getBranch()!=null && state.rightSide.getBranch()!=null) {
+ PullRequest request = requestModel.getObject();
+ setVisible(request == null && !mergeBaseModel.getObject().equals(rightCommitId));
+ } else {
+ setVisible(false);
+ }
+ }
+
+ });
+
+ add(new WebMarkupContainer("openedRequest") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ setVisible(requestModel.getObject() != null);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new Label("no", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return String.valueOf(requestModel.getObject().getNumber());
+ }
+
+ }));
+ add(new Link<Void>("link") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+ add(new Label("label", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return requestModel.getObject().getTitle();
+ }
+ }));
+ }
+
+ @Override
+ public void onClick() {
+ PageParameters params = RequestDetailPage.paramsOf(requestModel.getObject());
+ setResponsePage(RequestOverviewPage.class, params);
+ }
+
+ });
+
+ }
+
+ });
+
+ List<Tab> tabs = new ArrayList<>();
+
+ tabs.add(new AjaxActionTab(Model.of("Commits")) {
+
+ @Override
+ public boolean isSelected() {
+ return state.tabPanel == null || state.tabPanel == TabPanel.COMMITS;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ state.tabPanel = TabPanel.COMMITS;
+ newTabPanel(target);
+ pushState(target);
+ }
+
+ });
+
+ tabs.add(new AjaxActionTab(Model.of("Changes")) {
+
+ @Override
+ public boolean isSelected() {
+ return state.tabPanel == TabPanel.CHANGES;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Component tabLink) {
+ state.tabPanel = TabPanel.CHANGES;
+ newTabPanel(target);
+ pushState(target);
+ }
+
+ });
+
+ add(tabbable = new Tabbable("tabs", tabs));
+
+ newTabPanel(null);
+
+ add(new BackToTop("backToTop"));
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RevisionComparePage.class, "revision-compare.css")));
+ }
+
+ private void newTabPanel(@Nullable AjaxRequestTarget target) {
+ IModel<Depot> depotModel = new LoadableDetachableModel<Depot>() {
+
+ @Override
+ protected Depot load() {
+ Depot depot = state.rightSide.getDepot();
+ if (state.leftSide.getDepot().equals(state.rightSide.getDepot()))
+ depot.cacheObjectId(state.leftSide.getRevision(), leftCommitId);
+ depot.cacheObjectId(state.rightSide.getRevision(), rightCommitId);
+ return depot;
+ }
+
+ };
+ WebMarkupContainer tabPanel;
+ switch (state.tabPanel) {
+ case CHANGES:
+ IModel<String> blameModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.blameFile;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.blameFile = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ IModel<String> pathFilterModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.pathFilter;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.pathFilter = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public WhitespaceOption getObject() {
+ return state.whitespaceOption;
+ }
+
+ @Override
+ public void setObject(WhitespaceOption object) {
+ state.whitespaceOption = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ tabPanel = new RevisionDiffPanel(TAB_PANEL_ID, depotModel,
+ new Model<PullRequest>(null),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():state.leftSide.getRevision(),
+ state.rightSide.getRevision(), pathFilterModel, whitespaceOptionModel, blameModel, this);
+ break;
+ default:
+ tabPanel = new CommitListPanel(TAB_PANEL_ID, depotModel, commitsModel);
+
+ if (!mergeBaseModel.equals(leftCommitId) && !state.compareWithMergeBase) {
+ tabPanel.add(AttributeAppender.append("class", "with-merge-base"));
+ }
+ break;
+ }
+ tabPanel.setOutputMarkupId(true);
+ if (target != null) {
+ replace(tabPanel);
+ target.add(tabPanel);
+ } else {
+ add(tabPanel);
+ }
+ }
+
+ private void pushState(AjaxRequestTarget target) {
+ PageParameters params = paramsOf(getDepot(), state);
+ CharSequence url = RequestCycle.get().urlFor(RevisionComparePage.class, params);
+ pushState(target, url.toString(), state);
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ state = (State) data;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newTabPanel(target);
+ target.add(tabbable);
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+ mergeBaseModel.detach();
+ commitsModel.detach();
+
+ super.onDetach();
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(RevisionComparePage.class, paramsOf(depot));
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public DepotAndRevision leftSide;
+
+ public DepotAndRevision rightSide;
+
+ public boolean compareWithMergeBase = true;
+
+ public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
+
+ @Nullable
+ public TabPanel tabPanel;
+
+ @Nullable
+ public String pathFilter;
+
+ @Nullable
+ public String blameFile;
+
+ @Nullable
+ public Long commentId;
+
+ @Nullable
+ public CommentPos mark;
+
+ public State() {
+ }
+
+ public State(State state) {
+ leftSide = state.leftSide;
+ rightSide = state.rightSide;
+ compareWithMergeBase = state.compareWithMergeBase;
+ whitespaceOption = state.whitespaceOption;
+ pathFilter = state.pathFilter;
+ blameFile = state.blameFile;
+ commentId = state.commentId;
+ mark = state.mark;
+ tabPanel = state.tabPanel;
+ }
+
+ }
+
+ @Override
+ public CommentPos getMark() {
+ return state.mark;
+ }
+
+ @Override
+ public String getMarkUrl(CommentPos mark) {
+ State markState = new State();
+ markState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
+ markState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
+ markState.mark = mark;
+ markState.pathFilter = state.pathFilter;
+ markState.tabPanel = TabPanel.CHANGES;
+ markState.whitespaceOption = state.whitespaceOption;
+ markState.compareWithMergeBase = false;
+ return urlFor(RevisionComparePage.class, paramsOf(markState.rightSide.getDepot(), markState)).toString();
+ }
+
+ @Override
+ public String getCommentUrl(CodeComment comment) {
+ State commentState = new State();
+ commentState.leftSide = new DepotAndRevision(state.rightSide.getDepot(),
+ state.compareWithMergeBase?mergeBaseModel.getObject().name():leftCommitId.name());
+ commentState.rightSide = new DepotAndRevision(state.rightSide.getDepot(), rightCommitId.name());
+ commentState.mark = comment.getCommentPos();
+ commentState.commentId = comment.getId();
+ commentState.tabPanel = TabPanel.CHANGES;
+ commentState.pathFilter = state.pathFilter;
+ commentState.whitespaceOption = state.whitespaceOption;
+ commentState.compareWithMergeBase = false;
+ return urlFor(RevisionComparePage.class, paramsOf(commentState.rightSide.getDepot(), commentState)).toString();
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (state.commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
+ else
+ return null;
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ state.mark = comment.getCommentPos();
+ state.commentId = comment.getId();
+ } else {
+ state.commentId = null;
+ }
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, CommentPos mark) {
+ state.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
+ state.commentId = null;
+ state.mark = mark;
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ Collection<WebSocketRegion> regions = new ArrayList<>();
+ if (state.commentId != null)
+ regions.add(new CodeCommentChangedRegion(state.commentId));
+ return regions;
+ }
+
+}
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.java
index 31159e86c3..6f6c0cf7fd 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,975 +1,985 @@
-package com.pmease.gitplex.web.page.depot.file;
-
-import java.io.IOException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-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.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
-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.manager.DepotManager;
-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;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
-
-@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 ObjectId commitId;
-
- private transient List<QueryHit> queryHits;
-
- public DepotFilePage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- 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);
- 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(), 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(), commitId)) {
- GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
- setVisible(true);
- } else {
- setVisible(false);
- }
- }
-
- });
-
- newContributionPanel(null);
- newFileViewer(null);
-
- add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
-
- newSearchResult(null, queryHits);
-
- add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- 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();
-
- Long depotId = depot.getId();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, newCommit.copy());
- RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
- GitPlex.getInstance(ListenerRegistry.class).notify(event);
- } 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;
- }
- }
-
- Long depotId = depot.getId();
- Subject subject = SecurityUtils.getSubject();
- GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
-
- @Override
- public void run() {
- ThreadContext.bind(subject);
- try {
- Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
- depot.cacheObjectId(branch, newCommit.copy());
- RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
- GitPlex.getInstance(ListenerRegistry.class).notify(event);
- } 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;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- 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);
- commitId = getDepot().getRevCommit(blobIdent.revision).copy();
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- 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));
- }
-
- @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;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- 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;
- }
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, TextRange mark) {
- commentId = null;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- 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<>();
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- List<WebSocketRegion> regions = new ArrayList<>();
- if (commentId != null)
- regions.add(new CodeCommentChangedRegion(commentId));
- regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
- return regions;
- }
-
- 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.Collection;
+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.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
+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.manager.DepotManager;
+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;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+import com.pmease.gitplex.web.websocket.CommitIndexedRegion;
+
+@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 ObjectId commitId;
+
+ private transient List<QueryHit> queryHits;
+
+ public DepotFilePage(final PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ 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);
+ 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(), 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(), commitId)) {
+ GitPlex.getInstance(IndexManager.class).indexAsync(getDepot(), commitId);
+ setVisible(true);
+ } else {
+ setVisible(false);
+ }
+ }
+
+ });
+
+ newContributionPanel(null);
+ newFileViewer(null);
+
+ add(searchResultContainer = new WebMarkupContainer("searchResultContainer"));
+
+ newSearchResult(null, queryHits);
+
+ add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ 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();
+
+ Long depotId = depot.getId();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, newCommit.copy());
+ RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } 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;
+ }
+ }
+
+ Long depotId = depot.getId();
+ Subject subject = SecurityUtils.getSubject();
+ GitPlex.getInstance(UnitOfWork.class).doAsync(new Runnable() {
+
+ @Override
+ public void run() {
+ ThreadContext.bind(subject);
+ try {
+ Depot depot = GitPlex.getInstance(DepotManager.class).load(depotId);
+ depot.cacheObjectId(branch, newCommit.copy());
+ RefUpdated event = new RefUpdated(depot, refName, oldCommit.copy(), newCommit.copy());
+ GitPlex.getInstance(ListenerRegistry.class).post(event);
+ } 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;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ 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);
+ commitId = getDepot().getRevCommit(blobIdent.revision).copy();
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ 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, CodeComment comment) {
+ DepotFilePage.State state = new DepotFilePage.State();
+ state.blobIdent.revision = comment.getCommentPos().getCommit();
+ state.blobIdent.path = comment.getCommentPos().getPath();
+ state.blobIdent.mode = FileMode.TYPE_FILE;
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos().getRange();
+ return paramsOf(depot, state);
+ }
+
+ 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));
+ }
+
+ @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;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ 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;
+ }
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, TextRange mark) {
+ commentId = null;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ 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<>();
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ List<WebSocketRegion> regions = new ArrayList<>();
+ if (commentId != null)
+ regions.add(new CodeCommentChangedRegion(commentId));
+ regions.add(new CommitIndexedRegion(getDepot().getId(), commitId));
+ return regions;
+ }
+
+ 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/newrequest/NewRequestPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
index e9cb6ccb9a..1811e251a5 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/newrequest/NewRequestPage.java
@@ -56,11 +56,11 @@ 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.PullRequest.Status;
+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.CommentPos;
import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
import com.pmease.gitplex.core.manager.CodeCommentManager;
import com.pmease.gitplex.core.manager.PullRequestManager;
import com.pmease.gitplex.core.security.ObjectPermission;
@@ -489,7 +489,7 @@ public class NewRequestPage extends PullRequestPage implements CommentSupport {
@Override
protected List<String> load() {
- return getPullRequest().getCheckResult().getReasons();
+ return getPullRequest().checkGates(false).getReasons();
}
}) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/ApprovalHintPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/ApprovalHintPanel.java
index c8f3ce9976..381e66a295 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/ApprovalHintPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/ApprovalHintPanel.java
@@ -13,7 +13,7 @@ import com.pmease.gitplex.core.entity.CodeComment;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.core.manager.AccountManager;
import com.pmease.gitplex.web.component.comment.CodeCommentFilter;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.CodeCommentsPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.RequestCodeCommentsPage;
@SuppressWarnings("serial")
public class ApprovalHintPanel extends GenericPanel<PullRequest> {
@@ -28,9 +28,9 @@ public class ApprovalHintPanel extends GenericPanel<PullRequest> {
PullRequest request = getModelObject();
- PageParameters params = CodeCommentsPage.paramsOf(request);
+ PageParameters params = RequestCodeCommentsPage.paramsOf(request);
getFilter().fillPageParams(params);
- add(new BookmarkablePageLink<Void>("link", CodeCommentsPage.class, params));
+ add(new BookmarkablePageLink<Void>("link", RequestCodeCommentsPage.class, params));
}
private CodeCommentFilter getFilter() {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/IntegrationHintPanel.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/IntegrationHintPanel.java
index 74e7401b12..5842370fe3 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/IntegrationHintPanel.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/IntegrationHintPanel.java
@@ -10,7 +10,7 @@ import org.apache.wicket.request.mapper.parameter.PageParameters;
import com.pmease.gitplex.core.entity.CodeComment;
import com.pmease.gitplex.core.entity.PullRequest;
import com.pmease.gitplex.web.component.comment.CodeCommentFilter;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.CodeCommentsPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.RequestCodeCommentsPage;
@SuppressWarnings("serial")
public class IntegrationHintPanel extends GenericPanel<PullRequest> {
@@ -25,9 +25,9 @@ public class IntegrationHintPanel extends GenericPanel<PullRequest> {
PullRequest request = getModelObject();
- PageParameters params = CodeCommentsPage.paramsOf(request);
+ PageParameters params = RequestCodeCommentsPage.paramsOf(request);
getFilter().fillPageParams(params);
- add(new BookmarkablePageLink<Void>("link", CodeCommentsPage.class, params));
+ add(new BookmarkablePageLink<Void>("link", RequestCodeCommentsPage.class, params));
}
private CodeCommentFilter getFilter() {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
index bcb6936efc..8d864d4c57 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/PullRequestOperation.java
@@ -1,205 +1,205 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.eclipse.jgit.lib.ObjectId;
-
-import com.pmease.gitplex.core.GitPlex;
-import com.pmease.gitplex.core.entity.Account;
-import com.pmease.gitplex.core.entity.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequest.Status;
-import com.pmease.gitplex.core.entity.PullRequestReview;
-import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.manager.AccountManager;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.PullRequestReviewManager;
-import com.pmease.gitplex.core.security.ObjectPermission;
-import com.pmease.gitplex.core.security.SecurityUtils;
-
-@SuppressWarnings("serial")
-public enum PullRequestOperation {
- INTEGRATE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.getSubject().isPermitted(
- ObjectPermission.ofDepotWrite(request.getTargetDepot()))) {
- return false;
- } else {
- return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
- }
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
- }
-
- @Override
- public Component newHinter(String id, PullRequest request) {
- Long requestId = request.getId();
- return new IntegrationHintPanel(id, new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(PullRequestManager.class).load(requestId);
- }
-
- });
- }
-
- },
- DISCARD {
-
- @Override
- public boolean canOperate(PullRequest request) {
- if (!SecurityUtils.canModify(request))
- return false;
- else
- return request.isOpen();
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
- }
-
- },
- APPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.APPROVE, comment);
- }
-
- @Override
- public Component newHinter(String id, PullRequest request) {
- Long requestId = request.getId();
- return new ApprovalHintPanel(id, new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(PullRequestManager.class).load(requestId);
- }
-
- });
- }
-
- },
- DISAPPROVE {
-
- @Override
- public boolean canOperate(PullRequest request) {
- return canReview(request);
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.DISAPPROVE, comment);
- }
-
- },
- REOPEN {
-
- @Override
- public boolean canOperate(PullRequest request) {
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- if (request.isOpen()
- || !SecurityUtils.canModify(request)
- || request.getTarget().getObjectName(false) == null
- || request.getSourceDepot() == null
- || request.getSource().getObjectName(false) == null
- || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
- return false;
- }
-
- // now check if source branch is integrated into target branch
- String sourceHead = request.getSource().getObjectName();
- return request.getTargetDepot().getObjectId(sourceHead, false) == null
- || !request.getTargetDepot().isMergedInto(sourceHead, request.getTarget().getObjectName());
- }
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
- }
-
- },
- DELETE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request, comment);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- IntegrationPreview preview = request.getLastIntegrationPreview();
- PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
- return request.getStatus() == Status.INTEGRATED
- && request.getSourceDepot() != null
- && request.getSource().getObjectName(false) != null
- && !request.getSource().isDefault()
- && preview != null
- && (request.getSource().getObjectName().equals(preview.getRequestHead())
- || request.getSource().getObjectName().equals(preview.getIntegrated()))
- && SecurityUtils.canModify(request)
- && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), request.getSource().getObjectId(), ObjectId.zeroId())
- && pullRequestManager.findAllOpenTo(request.getSource(), null).isEmpty();
- }
-
- },
- RESTORE_SOURCE_BRANCH {
-
- @Override
- public void operate(PullRequest request, String comment) {
- GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request, comment);
- }
-
- @Override
- public boolean canOperate(PullRequest request) {
- return request.getSourceDepot() != null
- && request.getSource().getObjectName(false) == null
- && SecurityUtils.canModify(request)
- && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash()));
- }
-
- };
-
- private static boolean canReview(PullRequest request) {
- Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
-
- // call request.getStatus() in order to trigger generation of review
- // integrations which will be used in else condition
- if (user == null
- || request.getStatus() == PullRequest.Status.INTEGRATED
- || request.getStatus() == PullRequest.Status.DISCARDED
- || request.isReviewEffective(user)) {
- return false;
- } else {
- for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
- if (!invitation.isExcluded() && invitation.getUser().equals(user))
- return true;
- }
- return false;
- }
- }
-
- public abstract void operate(PullRequest request, @Nullable String comment);
-
- public abstract boolean canOperate(PullRequest request);
-
- public Component newHinter(String id, PullRequest request) {
- return new WebMarkupContainer(id).setVisible(false);
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.eclipse.jgit.lib.ObjectId;
+
+import com.pmease.gitplex.core.GitPlex;
+import com.pmease.gitplex.core.entity.Account;
+import com.pmease.gitplex.core.entity.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequest.Status;
+import com.pmease.gitplex.core.entity.PullRequestReview;
+import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+import com.pmease.gitplex.core.manager.AccountManager;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+import com.pmease.gitplex.core.manager.PullRequestReviewManager;
+import com.pmease.gitplex.core.security.ObjectPermission;
+import com.pmease.gitplex.core.security.SecurityUtils;
+
+@SuppressWarnings("serial")
+public enum PullRequestOperation {
+ INTEGRATE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.getSubject().isPermitted(
+ ObjectPermission.ofDepotWrite(request.getTargetDepot()))) {
+ return false;
+ } else {
+ return GitPlex.getInstance(PullRequestManager.class).canIntegrate(request);
+ }
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).integrate(request, comment);
+ }
+
+ @Override
+ public Component newHinter(String id, PullRequest request) {
+ Long requestId = request.getId();
+ return new IntegrationHintPanel(id, new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(PullRequestManager.class).load(requestId);
+ }
+
+ });
+ }
+
+ },
+ DISCARD {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ if (!SecurityUtils.canModify(request))
+ return false;
+ else
+ return request.isOpen();
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).discard(request, comment);
+ }
+
+ },
+ APPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.APPROVE, comment);
+ }
+
+ @Override
+ public Component newHinter(String id, PullRequest request) {
+ Long requestId = request.getId();
+ return new ApprovalHintPanel(id, new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(PullRequestManager.class).load(requestId);
+ }
+
+ });
+ }
+
+ },
+ DISAPPROVE {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return canReview(request);
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestReviewManager.class).review(request, PullRequestReview.Result.DISAPPROVE, comment);
+ }
+
+ },
+ REOPEN {
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ if (request.isOpen()
+ || !SecurityUtils.canModify(request)
+ || request.getTarget().getObjectName(false) == null
+ || request.getSourceDepot() == null
+ || request.getSource().getObjectName(false) == null
+ || pullRequestManager.findOpen(request.getTarget(), request.getSource()) != null) {
+ return false;
+ }
+
+ // now check if source branch is integrated into target branch
+ String sourceHead = request.getSource().getObjectName();
+ return request.getTargetDepot().getObjectId(sourceHead, false) == null
+ || !request.getTargetDepot().isMergedInto(sourceHead, request.getTarget().getObjectName());
+ }
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).reopen(request, comment);
+ }
+
+ },
+ DELETE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).deleteSourceBranch(request, comment);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ PullRequestManager pullRequestManager = GitPlex.getInstance(PullRequestManager.class);
+ return request.getStatus() == Status.INTEGRATED
+ && request.getSourceDepot() != null
+ && request.getSource().getObjectName(false) != null
+ && !request.getSource().isDefault()
+ && preview != null
+ && (request.getSource().getObjectName().equals(preview.getRequestHead())
+ || request.getSource().getObjectName().equals(preview.getIntegrated()))
+ && SecurityUtils.canModify(request)
+ && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), request.getSource().getObjectId(), ObjectId.zeroId())
+ && pullRequestManager.findAllOpenTo(request.getSource(), null).isEmpty();
+ }
+
+ },
+ RESTORE_SOURCE_BRANCH {
+
+ @Override
+ public void operate(PullRequest request, String comment) {
+ GitPlex.getInstance(PullRequestManager.class).restoreSourceBranch(request, comment);
+ }
+
+ @Override
+ public boolean canOperate(PullRequest request) {
+ return request.getSourceDepot() != null
+ && request.getSource().getObjectName(false) == null
+ && SecurityUtils.canModify(request)
+ && SecurityUtils.canPushRef(request.getSourceDepot(), request.getSourceRef(), ObjectId.zeroId(), ObjectId.fromString(request.getLatestUpdate().getHeadCommitHash()));
+ }
+
+ };
+
+ private static boolean canReview(PullRequest request) {
+ Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
+
+ // call request.getStatus() in order to trigger generation of review
+ // integrations which will be used in else condition
+ if (user == null
+ || request.getStatus() == PullRequest.Status.INTEGRATED
+ || request.getStatus() == PullRequest.Status.DISCARDED
+ || request.isReviewEffective(user)) {
+ return false;
+ } else {
+ for (PullRequestReviewInvitation invitation: request.getReviewInvitations()) {
+ if (invitation.getStatus() != PullRequestReviewInvitation.Status.EXCLUDED && invitation.getUser().equals(user))
+ return true;
+ }
+ return false;
+ }
+ }
+
+ public abstract void operate(PullRequest request, @Nullable String comment);
+
+ public abstract boolean canOperate(PullRequest request);
+
+ public Component newHinter(String id, PullRequest request) {
+ return new WebMarkupContainer(id).setVisible(false);
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
index cba66531f6..8317189ba1 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/RequestDetailPage.java
@@ -1,974 +1,993 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
-
-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.web.page.depot.pullrequest.requestdetail.PullRequestOperation.APPROVE;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DELETE_SOURCE_BRANCH;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DISAPPROVE;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DISCARD;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.INTEGRATE;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.REOPEN;
-import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.RESTORE_SOURCE_BRANCH;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.text.WordUtils;
-import org.apache.wicket.AttributeModifier;
-import org.apache.wicket.Component;
-import org.apache.wicket.Page;
-import org.apache.wicket.RestartResponseException;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-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.event.Broadcast;
-import org.apache.wicket.event.IEvent;
-import org.apache.wicket.markup.ComponentTag;
-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.FormComponent;
-import org.apache.wicket.markup.html.form.TextField;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-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.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.model.Model;
-import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.util.visit.IVisit;
-import org.apache.wicket.util.visit.IVisitor;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
-import com.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
-import com.pmease.commons.wicket.component.DropdownLink;
-import com.pmease.commons.wicket.component.backtotop.BackToTop;
-import com.pmease.commons.wicket.component.tabbable.PageTab;
-import com.pmease.commons.wicket.component.tabbable.PageTabLink;
-import com.pmease.commons.wicket.component.tabbable.Tab;
-import com.pmease.commons.wicket.component.tabbable.Tabbable;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
-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.Status;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.PullRequestVerification;
-import com.pmease.gitplex.core.entity.support.DepotAndBranch;
-import com.pmease.gitplex.core.entity.support.IntegrationPreview;
-import com.pmease.gitplex.core.manager.PullRequestManager;
-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.BranchLink;
-import com.pmease.gitplex.web.component.comment.CommentInput;
-import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
-import com.pmease.gitplex.web.component.pullrequest.verificationstatus.VerificationStatusPanel;
-import com.pmease.gitplex.web.model.EntityModel;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.NoBranchesPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.PullRequestPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.CodeCommentsPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.integrationpreview.IntegrationPreviewPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
-import com.pmease.gitplex.web.util.DateUtils;
-import com.pmease.gitplex.web.websocket.PullRequestChanged;
-import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
-
-@SuppressWarnings("serial")
-public abstract class RequestDetailPage extends PullRequestPage {
-
- private static final Logger logger = LoggerFactory.getLogger(RequestDetailPage.class);
-
- protected IModel<PullRequest> requestModel;
-
- private boolean editingTitle;
-
- public RequestDetailPage(final PageParameters params) {
- super(params);
-
- if (getDepot().getDefaultBranch() == null)
- throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
-
- requestModel = new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return Preconditions.checkNotNull(GitPlex.getInstance(PullRequestManager.class).find(getDepot(), params.get("request").toLong()));
- }
-
- };
-
- }
-
- @Override
- protected void onAfterRender() {
- super.onAfterRender();
- Account user = SecurityUtils.getAccount();
- if (user != null)
- GitPlex.getInstance(VisitInfoManager.class).visit(user, getPullRequest());
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- PullRequest request = getPullRequest();
-
- WebMarkupContainer requestTitle = new WebMarkupContainer("requestHead");
- requestTitle.setOutputMarkupId(true);
- add(requestTitle);
-
- requestTitle.add(new Label("title", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getPullRequest().getTitle();
- }
-
- }) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!editingTitle);
- }
-
- });
-
- requestTitle.add(new Label("number", "#" + request.getNumber()) {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!editingTitle);
- }
-
- });
-
- requestTitle.add(new AjaxLink<Void>("editLink") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- editingTitle = true;
-
- target.add(requestTitle);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- setVisible(!editingTitle && SecurityUtils.canModify(getPullRequest()));
- }
-
- });
-
- Form<?> form = new Form<Void>("editForm") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(editingTitle);
- }
-
- };
- requestTitle.add(form);
-
- form.add(new TextField<String>("title", new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- if (StringUtils.isNotBlank(getPullRequest().getTitle()))
- return getPullRequest().getTitle();
- else
- return "";
- }
-
- @Override
- public void setObject(String object) {
- getPullRequest().setTitle(object);
- }
-
- }));
-
- form.add(new AjaxButton("save") {
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- if (StringUtils.isNotBlank(getPullRequest().getTitle())) {
- GitPlex.getInstance(Dao.class).persist(getPullRequest());
- editingTitle = false;
- }
-
- target.add(requestTitle);
- }
-
- });
-
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- editingTitle = false;
-
- target.add(requestTitle);
- }
-
- });
-
- add(newStatusAndBranchesContainer());
-
- WebMarkupContainer summaryContainer = new WebMarkupContainer("requestSummary") {
-
- @Override
- public void onEvent(IEvent<?> event) {
- super.onEvent(event);
-
- if (event.getPayload() instanceof PullRequestChanged) {
- Form<?> form = visitChildren(Form.class, new IVisitor<Form<?>, Form<?>>() {
-
- @Override
- public void component(Form<?> object, IVisit<Form<?>> visit) {
- visit.stop(object);
- }
-
- });
- if (form == null) {
- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
- pullRequestChanged.getPartialPageRequestHandler().add(this);
- }
- }
- }
-
- };
- summaryContainer.setOutputMarkupPlaceholderTag(true);
- add(summaryContainer);
-
- summaryContainer.add(newDiscardedNoteContainer());
- summaryContainer.add(newPendingUpdateNoteContainer());
- summaryContainer.add(newPendingApprovalNoteContainer());
- summaryContainer.add(newIntegratedNoteContainer());
- summaryContainer.add(newStatusReasonsContainer());
- summaryContainer.add(newIntegrationPreviewContainer());
- summaryContainer.add(newOperationsContainer());
-
- List<Tab> tabs = new ArrayList<>();
-
- tabs.add(new RequestTab("Overview", RequestOverviewPage.class));
- tabs.add(new RequestTab("File Changes", RequestChangesPage.class));
- tabs.add(new RequestTab("Code Comments", CodeCommentsPage.class));
- tabs.add(new RequestTab("Integration Preview", IntegrationPreviewPage.class));
-
- add(new Tabbable("requestTabs", tabs).setOutputMarkupId(true));
-
- add(new BackToTop("backToTop"));
-
- add(new WebSocketRenderBehavior() {
-
- @Override
- protected void onRender(WebSocketRequestHandler handler) {
- send(getPage(), Broadcast.BREADTH, new PullRequestChanged(handler));
- }
-
- });
- }
-
- private WebMarkupContainer newStatusAndBranchesContainer() {
- WebMarkupContainer statusAndBranchesContainer = new WebMarkupContainer("statusAndBranches");
-
- PullRequest request = getPullRequest();
-
- statusAndBranchesContainer.add(new Label("status", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return getPullRequest().getStatus().toString();
- }
-
- }) {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- setOutputMarkupId(true);
-
- add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- PullRequest.Status status = getPullRequest().getStatus();
- if (status == Status.DISCARDED)
- return " label-danger";
- else if (status == Status.INTEGRATED)
- return " label-success";
- else
- return " label-warning";
- }
-
- }));
- }
-
- @Override
- public void onEvent(IEvent<?> event) {
- super.onEvent(event);
-
- if (event.getPayload() instanceof PullRequestChanged) {
- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
- pullRequestChanged.getPartialPageRequestHandler().add(this);
- }
- }
-
- });
-
- if (request.getStatus() == Status.INTEGRATED) {
- statusAndBranchesContainer.add(new AccountLink("user", request.getCloseInfo().getClosedBy()));
-
- int commitCount = 0;
- for (PullRequestUpdate update: request.getUpdates())
- commitCount += update.getCommits().size();
-
- statusAndBranchesContainer.add(new Label("action", "integrated " + commitCount + " commits"));
- statusAndBranchesContainer.add(new Label("date", DateUtils.formatAge(request.getCloseInfo().getCloseDate())));
- } else {
- statusAndBranchesContainer.add(new AccountLink("user", request.getSubmitter()));
- statusAndBranchesContainer.add(new Label("action", "wants to integrate"));
- statusAndBranchesContainer.add(new Label("date", DateUtils.formatAge(request.getSubmitDate())));
- }
-
- statusAndBranchesContainer.add(new BranchLink("target", request.getTarget()));
- if (request.getSourceDepot() != null) {
- statusAndBranchesContainer.add(new BranchLink("source", request.getSource()));
- } else {
- statusAndBranchesContainer.add(new Label("source", "unknown") {
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- tag.setName("span");
- }
-
- });
- }
- return statusAndBranchesContainer;
- }
-
- private WebMarkupContainer newIntegrationPreviewContainer() {
- WebMarkupContainer integrationPreviewContainer = new WebMarkupContainer("integrationPreview") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().isOpen());
- }
-
- };
- integrationPreviewContainer.setOutputMarkupId(true);
-
- integrationPreviewContainer.add(new WebMarkupContainer("calculating") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getIntegrationPreview() == null);
- }
-
- });
- integrationPreviewContainer.add(new WebMarkupContainer("conflict") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new DropdownLink("resolveInstructionsTrigger") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getSource() != null);
- }
-
- @Override
- protected Component newContent(String id) {
- return new ResolveConflictInstructionPanel(id, new EntityModel<PullRequest>(getPullRequest()));
- }
-
- });
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- IntegrationPreview preview = getPullRequest().getIntegrationPreview();
- setVisible(preview != null && preview.getIntegrated() == null);
- }
-
- });
- integrationPreviewContainer.add(new WebMarkupContainer("noConflict") {
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- Link<Void> link = new Link<Void>("preview") {
-
- @Override
- public void onClick() {
- PullRequest request = getPullRequest();
- PageParameters params = IntegrationPreviewPage.paramsOf(request);
- setResponsePage(IntegrationPreviewPage.class, params);
- }
-
- };
- add(link);
-
- add(new VerificationStatusPanel("verification", requestModel, new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getIntegrationPreview();
- if (preview != null)
- return preview.getIntegrated();
- else
- return null;
- }
-
- }) {
-
- @Override
- protected Component newStatusComponent(String id, final IModel<PullRequestVerification.Status> statusModel) {
- return new Label(id, new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- if (statusModel.getObject() == PullRequestVerification.Status.SUCCESSFUL)
- return "successful <i class='caret'></i>";
- else if (statusModel.getObject() == PullRequestVerification.Status.RUNNING)
- return "running <i class='caret'></i>";
- else if (statusModel.getObject() == PullRequestVerification.Status.FAILED)
- return "failed <i class='caret'></i>";
- else
- return "";
- }
-
- }) {
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- if (statusModel.getObject() == PullRequestVerification.Status.SUCCESSFUL)
- tag.put("class", "label label-success");
- else if (statusModel.getObject() == PullRequestVerification.Status.RUNNING)
- tag.put("class", "label label-warning");
- else if (statusModel.getObject() == PullRequestVerification.Status.FAILED)
- tag.put("class", "label label-danger");
- }
-
- @Override
- protected void onDetach() {
- statusModel.detach();
-
- super.onDetach();
- }
-
- }.setEscapeModelStrings(false);
- }
-
- });
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- IntegrationPreview preview = getPullRequest().getIntegrationPreview();
- setVisible(preview != null && preview.getIntegrated() != null);
- }
-
- });
-
- return integrationPreviewContainer;
- }
-
- private WebMarkupContainer newOperationsContainer() {
- final WebMarkupContainer operationsContainer = new WebMarkupContainer("operations") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- boolean hasVisibleChildren = false;
- for (int i=0; i<size(); i++) {
- @SuppressWarnings("deprecation")
- Component child = get(i);
- child.configure();
- if (child.isVisible()) {
- hasVisibleChildren = true;
- break;
- }
- }
-
- setVisible(hasVisibleChildren);
- }
-
- };
- operationsContainer.setOutputMarkupId(true);
-
- String confirmId = "confirm";
-
- operationsContainer.add(new AjaxLink<Void>("approve") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, APPROVE, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(APPROVE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
-
- operationsContainer.add(new AjaxLink<Void>("disapprove") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, DISAPPROVE, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(DISAPPROVE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
-
- operationsContainer.add(new AjaxLink<Void>("integrate") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, INTEGRATE, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(INTEGRATE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
-
- operationsContainer.add(new AjaxLink<Void>("discard") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, DISCARD, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(DISCARD.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
- operationsContainer.add(new AjaxLink<Void>("reopen") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, REOPEN, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(REOPEN.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
- operationsContainer.add(new AjaxLink<Void>("deleteSourceBranch") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, DELETE_SOURCE_BRANCH, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(DELETE_SOURCE_BRANCH.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
- operationsContainer.add(new AjaxLink<Void>("restoreSourceBranch") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- operationsContainer.replace(newOperationConfirm(confirmId, RESTORE_SOURCE_BRANCH, operationsContainer));
- target.add(operationsContainer);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(RESTORE_SOURCE_BRANCH.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
- }
-
- });
-
- operationsContainer.add(new WebMarkupContainer(confirmId).setVisible(false));
-
- return operationsContainer;
- }
-
- private Component newOperationConfirm(String id, PullRequestOperation operation,
- WebMarkupContainer operationsContainer) {
- PullRequest request = getPullRequest();
-
- Fragment fragment = new Fragment(id, "operationConfirmFrag", this);
- Form<?> form = new Form<Void>("form");
- fragment.add(form);
-
- DepotAndBranch source = request.getSource();
- Preconditions.checkNotNull(source);
-
- FormComponent<String> noteInput;
- form.add(noteInput = new CommentInput("note", Model.of("")) {
-
- @Override
- protected AttachmentSupport getAttachmentSupport() {
- return new DepotAttachmentSupport(requestModel.getObject().getTargetDepot(),
- requestModel.getObject().getUUID());
- }
-
- @Override
- protected Depot getDepot() {
- return requestModel.getObject().getTargetDepot();
- }
-
- });
- noteInput.add(AttributeModifier.replace("placeholder", "Leave a note"));
- form.add(operation.newHinter("hint", request));
- form.add(new NotificationPanel("feedback", form));
- form.add(new AjaxButton("submit") {
-
- @Override
- protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
- super.onSubmit(target, form);
-
- String actionName = operation.name().toLowerCase();
-
- PullRequest request = getPullRequest();
- try {
- operation.operate(request, noteInput.getModelObject());
- setResponsePage(getPage().getClass(), paramsOf(getPullRequest()));
- } catch (Exception e) {
- if (e.getMessage() != null) {
- error("Unable to " + actionName + ": " + e.getMessage());
- logger.error("Error " + actionName, e);
- } else {
- error("Unable to " + actionName + ": check log for details");
- }
- target.add(operationsContainer);
- }
- }
-
- }.add(AttributeModifier.replace("value", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- return "Confirm " + WordUtils.capitalizeFully(operation.name()).replace("_", " ").toLowerCase();
- }
-
- })).add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- if (operation == INTEGRATE)
- return "btn-success";
- else if (operation == DISCARD)
- return "btn-danger";
- else
- return "btn-primary";
- }
-
- })));
- form.add(new AjaxLink<Void>("cancel") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- fragment.replaceWith(new WebMarkupContainer(id).setVisible(false));
- target.add(operationsContainer);
- }
-
- });
-
- return fragment;
- }
-
- private WebMarkupContainer newDiscardedNoteContainer() {
- WebMarkupContainer discardedNoteContainer = new WebMarkupContainer("discardedNote") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getStatus() == Status.DISCARDED);
- }
-
- };
- return discardedNoteContainer;
- }
-
- private WebMarkupContainer newPendingUpdateNoteContainer() {
- WebMarkupContainer pendingUpdateNoteContainer = new WebMarkupContainer("pendingUpdateNote") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getStatus() == Status.PENDING_UPDATE);
- }
-
- };
- return pendingUpdateNoteContainer;
- }
-
- private WebMarkupContainer newPendingApprovalNoteContainer() {
- WebMarkupContainer pendingApprovalNoteContainer = new WebMarkupContainer("pendingApprovalNote") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getStatus() == Status.PENDING_APPROVAL);
- }
-
- };
- return pendingApprovalNoteContainer;
- }
-
- private WebMarkupContainer newIntegratedNoteContainer() {
- WebMarkupContainer integratedNoteContainer = new WebMarkupContainer("integratedNote") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getPullRequest().getStatus() == Status.INTEGRATED);
- }
-
- };
- integratedNoteContainer.setOutputMarkupId(true);
-
- integratedNoteContainer.add(new WebMarkupContainer("fastForwarded") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getLastIntegrationPreview();
- setVisible(preview != null && preview.getRequestHead().equals(preview.getIntegrated()));
- }
-
- });
- integratedNoteContainer.add(new WebMarkupContainer("merged") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getLastIntegrationPreview();
- setVisible(preview != null
- && !preview.getRequestHead().equals(preview.getIntegrated())
- && (preview.getIntegrationStrategy() == MERGE_ALWAYS || preview.getIntegrationStrategy() == MERGE_IF_NECESSARY));
- }
-
- });
- integratedNoteContainer.add(new WebMarkupContainer("mergedOutside") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- setVisible(getPullRequest().getLastIntegrationPreview() == null);
- }
-
- });
- integratedNoteContainer.add(new WebMarkupContainer("squashed") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getLastIntegrationPreview();
- setVisible(preview != null
- && !preview.getRequestHead().equals(preview.getIntegrated())
- && preview.getIntegrationStrategy() == MERGE_WITH_SQUASH);
- }
-
- });
-
- integratedNoteContainer.add(new WebMarkupContainer("sourceRebased") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getLastIntegrationPreview();
- setVisible(preview != null
- && !preview.getRequestHead().equals(preview.getIntegrated())
- && preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET);
- }
-
- });
-
- integratedNoteContainer.add(new WebMarkupContainer("targetRebased") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- PullRequest request = getPullRequest();
- IntegrationPreview preview = request.getLastIntegrationPreview();
- setVisible(preview != null
- && !preview.getRequestHead().equals(preview.getIntegrated())
- && preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE);
- }
-
- });
-
- return integratedNoteContainer;
- }
-
- private WebMarkupContainer newStatusReasonsContainer() {
- WebMarkupContainer statusReasonsContainer = new WebMarkupContainer("statusReasons") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- PullRequest.Status status = getPullRequest().getStatus();
- setVisible(status == Status.PENDING_APPROVAL || status == Status.PENDING_UPDATE);
- }
-
- };
- statusReasonsContainer.setOutputMarkupId(true);
-
- statusReasonsContainer.add(new ListView<String>("reasons", new AbstractReadOnlyModel<List<String>>() {
-
- @Override
- public List<String> getObject() {
- return getPullRequest().getCheckResult().getReasons();
- }
-
- }) {
-
- @Override
- protected void populateItem(ListItem<String> item) {
- item.add(new Label("reason", item.getModelObject()));
- }
-
- });
-
- return statusReasonsContainer;
- }
-
- @Override
- protected void onDetach() {
- requestModel.detach();
- super.onDetach();
- }
-
- public static PageParameters paramsOf(PullRequest request) {
- PageParameters params = DepotPage.paramsOf(request.getTarget().getDepot());
- params.set("request", request.getNumber());
- return params;
- }
-
- public PullRequest getPullRequest() {
- return requestModel.getObject();
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- return Lists.newArrayList(new PullRequestChangedRegion(getPullRequest().getId()));
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RequestDetailPage.class, "request-detail.css")));
- }
-
- private class RequestTab extends PageTab {
-
- public RequestTab(String title, Class<? extends Page> pageClass) {
- super(Model.of(title), pageClass);
- }
-
- @Override
- public Component render(String componentId) {
- if (getMainPageClass() == CodeCommentsPage.class) {
- Fragment fragment = new Fragment(componentId, "codeCommentsTabLinkFrag", RequestDetailPage.this);
- PullRequest request = getPullRequest();
- Link<Void> link = new BookmarkablePageLink<Void>("link", CodeCommentsPage.class, paramsOf(request));
- if (request.getLastCodeCommentEventDate() != null && !request.isVisitedAfter(request.getLastCodeCommentEventDate()))
- link.add(AttributeAppender.append("class", "new"));
- fragment.add(link);
- return fragment;
- } else {
- return new PageTabLink(componentId, this) {
-
- @Override
- protected Link<?> newLink(String linkId, Class<? extends Page> pageClass) {
- return new BookmarkablePageLink<Void>(linkId, pageClass, paramsOf(getPullRequest()));
- }
-
- };
- }
- }
-
- }
-
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail;
+
+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.web.page.depot.pullrequest.requestdetail.PullRequestOperation.APPROVE;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DELETE_SOURCE_BRANCH;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DISAPPROVE;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.DISCARD;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.INTEGRATE;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.REOPEN;
+import static com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.PullRequestOperation.RESTORE_SOURCE_BRANCH;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.text.WordUtils;
+import org.apache.wicket.AttributeModifier;
+import org.apache.wicket.Component;
+import org.apache.wicket.Page;
+import org.apache.wicket.RestartResponseException;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+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.event.Broadcast;
+import org.apache.wicket.event.IEvent;
+import org.apache.wicket.markup.ComponentTag;
+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.FormComponent;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+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.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.model.Model;
+import org.apache.wicket.protocol.ws.api.WebSocketRequestHandler;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.util.visit.IVisit;
+import org.apache.wicket.util.visit.IVisitor;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.wicket.behavior.markdown.AttachmentSupport;
+import com.pmease.commons.wicket.component.DropdownLink;
+import com.pmease.commons.wicket.component.backtotop.BackToTop;
+import com.pmease.commons.wicket.component.tabbable.PageTab;
+import com.pmease.commons.wicket.component.tabbable.PageTabLink;
+import com.pmease.commons.wicket.component.tabbable.Tab;
+import com.pmease.commons.wicket.component.tabbable.Tabbable;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+import com.pmease.commons.wicket.websocket.WebSocketRenderBehavior;
+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.Status;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.PullRequestVerification;
+import com.pmease.gitplex.core.entity.support.DepotAndBranch;
+import com.pmease.gitplex.core.entity.support.IntegrationPreview;
+import com.pmease.gitplex.core.manager.PullRequestManager;
+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.BranchLink;
+import com.pmease.gitplex.web.component.comment.CommentInput;
+import com.pmease.gitplex.web.component.comment.DepotAttachmentSupport;
+import com.pmease.gitplex.web.component.pullrequest.verificationstatus.VerificationStatusPanel;
+import com.pmease.gitplex.web.model.EntityModel;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.NoBranchesPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.PullRequestPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes.RequestChangesPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.codecomments.RequestCodeCommentsPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.integrationpreview.IntegrationPreviewPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
+import com.pmease.gitplex.web.util.DateUtils;
+import com.pmease.gitplex.web.websocket.PullRequestChanged;
+import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.common.NotificationPanel;
+
+@SuppressWarnings("serial")
+public abstract class RequestDetailPage extends PullRequestPage {
+
+ private static final Logger logger = LoggerFactory.getLogger(RequestDetailPage.class);
+
+ protected IModel<PullRequest> requestModel;
+
+ private boolean editingTitle;
+
+ public RequestDetailPage(PageParameters params) {
+ super(params);
+
+ if (getDepot().getDefaultBranch() == null)
+ throw new RestartResponseException(NoBranchesPage.class, paramsOf(getDepot()));
+
+ requestModel = new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return Preconditions.checkNotNull(GitPlex.getInstance(PullRequestManager.class).find(getDepot(), params.get("request").toLong()));
+ }
+
+ };
+
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ PullRequest request = getPullRequest();
+
+ WebMarkupContainer requestTitle = new WebMarkupContainer("requestHead");
+ requestTitle.setOutputMarkupId(true);
+ add(requestTitle);
+
+ requestTitle.add(new Label("title", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getTitle();
+ }
+
+ }) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!editingTitle);
+ }
+
+ });
+
+ requestTitle.add(new Label("number", "#" + request.getNumber()) {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!editingTitle);
+ }
+
+ });
+
+ requestTitle.add(new AjaxLink<Void>("editLink") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ editingTitle = true;
+
+ target.add(requestTitle);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ setVisible(!editingTitle && SecurityUtils.canModify(getPullRequest()));
+ }
+
+ });
+
+ Form<?> form = new Form<Void>("editForm") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(editingTitle);
+ }
+
+ };
+ requestTitle.add(form);
+
+ form.add(new TextField<String>("title", new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ if (StringUtils.isNotBlank(getPullRequest().getTitle()))
+ return getPullRequest().getTitle();
+ else
+ return "";
+ }
+
+ @Override
+ public void setObject(String object) {
+ getPullRequest().setTitle(object);
+ }
+
+ }));
+
+ form.add(new AjaxButton("save") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ if (StringUtils.isNotBlank(getPullRequest().getTitle())) {
+ GitPlex.getInstance(Dao.class).persist(getPullRequest());
+ editingTitle = false;
+ }
+
+ target.add(requestTitle);
+ }
+
+ });
+
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ editingTitle = false;
+
+ target.add(requestTitle);
+ }
+
+ });
+
+ add(newStatusAndBranchesContainer());
+
+ WebMarkupContainer summaryContainer = new WebMarkupContainer("requestSummary") {
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+
+ if (event.getPayload() instanceof PullRequestChanged) {
+ Form<?> form = visitChildren(Form.class, new IVisitor<Form<?>, Form<?>>() {
+
+ @Override
+ public void component(Form<?> object, IVisit<Form<?>> visit) {
+ visit.stop(object);
+ }
+
+ });
+ if (form == null) {
+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
+ pullRequestChanged.getPartialPageRequestHandler().add(this);
+ }
+ }
+ }
+
+ };
+ summaryContainer.setOutputMarkupPlaceholderTag(true);
+ add(summaryContainer);
+
+ summaryContainer.add(newDiscardedNoteContainer());
+ summaryContainer.add(newPendingUpdateNoteContainer());
+ summaryContainer.add(newPendingApprovalNoteContainer());
+ summaryContainer.add(newIntegratedNoteContainer());
+ summaryContainer.add(newStatusReasonsContainer());
+ summaryContainer.add(newIntegrationPreviewContainer());
+ summaryContainer.add(newOperationsContainer());
+
+ List<Tab> tabs = new ArrayList<>();
+
+ tabs.add(new RequestTab("Overview", RequestOverviewPage.class));
+ tabs.add(new RequestTab("File Changes", RequestChangesPage.class));
+ tabs.add(new RequestTab("Code Comments", RequestCodeCommentsPage.class));
+ tabs.add(new RequestTab("Integration Preview", IntegrationPreviewPage.class));
+
+ add(new Tabbable("requestTabs", tabs).setOutputMarkupId(true));
+
+ add(new BackToTop("backToTop"));
+
+ add(new WebSocketRenderBehavior() {
+
+ @Override
+ protected void onRender(WebSocketRequestHandler handler) {
+ send(getPage(), Broadcast.BREADTH, new PullRequestChanged(handler));
+ }
+
+ @Override
+ protected void onInitialRenderDetach() {
+ Account user = SecurityUtils.getAccount();
+ if (user != null)
+ GitPlex.getInstance(VisitInfoManager.class).visit(user, getPullRequest());
+ }
+
+ });
+ }
+
+ private WebMarkupContainer newStatusAndBranchesContainer() {
+ WebMarkupContainer statusAndBranchesContainer = new WebMarkupContainer("statusAndBranches");
+
+ PullRequest request = getPullRequest();
+
+ statusAndBranchesContainer.add(new Label("status", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return getPullRequest().getStatus().toString();
+ }
+
+ }) {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ setOutputMarkupId(true);
+
+ add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ PullRequest.Status status = getPullRequest().getStatus();
+ if (status == Status.DISCARDED)
+ return " label-danger";
+ else if (status == Status.INTEGRATED)
+ return " label-success";
+ else
+ return " label-warning";
+ }
+
+ }));
+ }
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+
+ if (event.getPayload() instanceof PullRequestChanged) {
+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
+ pullRequestChanged.getPartialPageRequestHandler().add(this);
+ }
+ }
+
+ });
+
+ if (request.getStatus() == Status.INTEGRATED) {
+ statusAndBranchesContainer.add(new AccountLink("user", request.getCloseInfo().getClosedBy()));
+
+ int commitCount = 0;
+ for (PullRequestUpdate update: request.getUpdates())
+ commitCount += update.getCommits().size();
+
+ statusAndBranchesContainer.add(new Label("action", "integrated " + commitCount + " commits"));
+ statusAndBranchesContainer.add(new Label("date", DateUtils.formatAge(request.getCloseInfo().getCloseDate())));
+ } else {
+ statusAndBranchesContainer.add(new AccountLink("user", request.getSubmitter()));
+ statusAndBranchesContainer.add(new Label("action", "wants to integrate"));
+ statusAndBranchesContainer.add(new Label("date", DateUtils.formatAge(request.getSubmitDate())));
+ }
+
+ statusAndBranchesContainer.add(new BranchLink("target", request.getTarget()));
+ if (request.getSourceDepot() != null) {
+ statusAndBranchesContainer.add(new BranchLink("source", request.getSource()));
+ } else {
+ statusAndBranchesContainer.add(new Label("source", "unknown") {
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ tag.setName("span");
+ }
+
+ });
+ }
+ return statusAndBranchesContainer;
+ }
+
+ private WebMarkupContainer newIntegrationPreviewContainer() {
+ WebMarkupContainer integrationPreviewContainer = new WebMarkupContainer("integrationPreview") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().isOpen());
+ }
+
+ };
+ integrationPreviewContainer.setOutputMarkupId(true);
+
+ integrationPreviewContainer.add(new WebMarkupContainer("calculating") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getIntegrationPreview() == null);
+ }
+
+ });
+ integrationPreviewContainer.add(new WebMarkupContainer("conflict") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new DropdownLink("resolveInstructionsTrigger") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getSource() != null);
+ }
+
+ @Override
+ protected Component newContent(String id) {
+ return new ResolveConflictInstructionPanel(id, new EntityModel<PullRequest>(getPullRequest()));
+ }
+
+ });
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ IntegrationPreview preview = getPullRequest().getIntegrationPreview();
+ setVisible(preview != null && preview.getIntegrated() == null);
+ }
+
+ });
+ integrationPreviewContainer.add(new WebMarkupContainer("noConflict") {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ Link<Void> link = new Link<Void>("preview") {
+
+ @Override
+ public void onClick() {
+ PullRequest request = getPullRequest();
+ PageParameters params = IntegrationPreviewPage.paramsOf(request);
+ setResponsePage(IntegrationPreviewPage.class, params);
+ }
+
+ };
+ add(link);
+
+ add(new VerificationStatusPanel("verification", requestModel, new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getIntegrationPreview();
+ if (preview != null)
+ return preview.getIntegrated();
+ else
+ return null;
+ }
+
+ }) {
+
+ @Override
+ protected Component newStatusComponent(String id, final IModel<PullRequestVerification.Status> statusModel) {
+ return new Label(id, new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ if (statusModel.getObject() == PullRequestVerification.Status.SUCCESSFUL)
+ return "successful <i class='caret'></i>";
+ else if (statusModel.getObject() == PullRequestVerification.Status.RUNNING)
+ return "running <i class='caret'></i>";
+ else if (statusModel.getObject() == PullRequestVerification.Status.FAILED)
+ return "failed <i class='caret'></i>";
+ else
+ return "";
+ }
+
+ }) {
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ if (statusModel.getObject() == PullRequestVerification.Status.SUCCESSFUL)
+ tag.put("class", "label label-success");
+ else if (statusModel.getObject() == PullRequestVerification.Status.RUNNING)
+ tag.put("class", "label label-warning");
+ else if (statusModel.getObject() == PullRequestVerification.Status.FAILED)
+ tag.put("class", "label label-danger");
+ }
+
+ @Override
+ protected void onDetach() {
+ statusModel.detach();
+
+ super.onDetach();
+ }
+
+ }.setEscapeModelStrings(false);
+ }
+
+ });
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ IntegrationPreview preview = getPullRequest().getIntegrationPreview();
+ setVisible(preview != null && preview.getIntegrated() != null);
+ }
+
+ });
+
+ return integrationPreviewContainer;
+ }
+
+ private WebMarkupContainer newOperationsContainer() {
+ final WebMarkupContainer operationsContainer = new WebMarkupContainer("operations") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ boolean hasVisibleChildren = false;
+ for (int i=0; i<size(); i++) {
+ @SuppressWarnings("deprecation")
+ Component child = get(i);
+ child.configure();
+ if (child.isVisible()) {
+ hasVisibleChildren = true;
+ break;
+ }
+ }
+
+ setVisible(hasVisibleChildren);
+ }
+
+ };
+ operationsContainer.setOutputMarkupId(true);
+
+ String confirmId = "confirm";
+
+ operationsContainer.add(new AjaxLink<Void>("approve") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, APPROVE, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(APPROVE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+
+ operationsContainer.add(new AjaxLink<Void>("disapprove") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, DISAPPROVE, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(DISAPPROVE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+
+ operationsContainer.add(new AjaxLink<Void>("integrate") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, INTEGRATE, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(INTEGRATE.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+
+ operationsContainer.add(new AjaxLink<Void>("discard") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, DISCARD, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(DISCARD.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+ operationsContainer.add(new AjaxLink<Void>("reopen") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, REOPEN, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(REOPEN.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+ operationsContainer.add(new AjaxLink<Void>("deleteSourceBranch") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, DELETE_SOURCE_BRANCH, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(DELETE_SOURCE_BRANCH.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+ operationsContainer.add(new AjaxLink<Void>("restoreSourceBranch") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ operationsContainer.replace(newOperationConfirm(confirmId, RESTORE_SOURCE_BRANCH, operationsContainer));
+ target.add(operationsContainer);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(RESTORE_SOURCE_BRANCH.canOperate(getPullRequest()) && !operationsContainer.get(confirmId).isVisible());
+ }
+
+ });
+
+ operationsContainer.add(new WebMarkupContainer(confirmId).setVisible(false));
+
+ return operationsContainer;
+ }
+
+ private Component newOperationConfirm(String id, PullRequestOperation operation,
+ WebMarkupContainer operationsContainer) {
+ PullRequest request = getPullRequest();
+
+ Fragment fragment = new Fragment(id, "operationConfirmFrag", this);
+ Form<?> form = new Form<Void>("form");
+ fragment.add(form);
+
+ DepotAndBranch source = request.getSource();
+ Preconditions.checkNotNull(source);
+
+ FormComponent<String> noteInput;
+ form.add(noteInput = new CommentInput("note", Model.of("")) {
+
+ @Override
+ protected AttachmentSupport getAttachmentSupport() {
+ return new DepotAttachmentSupport(requestModel.getObject().getTargetDepot(),
+ requestModel.getObject().getUUID());
+ }
+
+ @Override
+ protected Depot getDepot() {
+ return requestModel.getObject().getTargetDepot();
+ }
+
+ });
+ noteInput.add(AttributeModifier.replace("placeholder", "Leave a note"));
+ form.add(operation.newHinter("hint", request));
+ form.add(new NotificationPanel("feedback", form));
+ form.add(new AjaxButton("submit") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+
+ String actionName = operation.name().toLowerCase();
+
+ PullRequest request = getPullRequest();
+ try {
+ operation.operate(request, noteInput.getModelObject());
+ setResponsePage(getPage().getClass(), paramsOf(getPullRequest()));
+ } catch (Exception e) {
+ if (e.getMessage() != null) {
+ error("Unable to " + actionName + ": " + e.getMessage());
+ logger.error("Error " + actionName, e);
+ } else {
+ error("Unable to " + actionName + ": check log for details");
+ }
+ target.add(operationsContainer);
+ }
+ }
+
+ }.add(AttributeModifier.replace("value", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ return "Confirm " + WordUtils.capitalizeFully(operation.name()).replace("_", " ").toLowerCase();
+ }
+
+ })).add(AttributeAppender.append("class", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ if (operation == INTEGRATE)
+ return "btn-success";
+ else if (operation == DISCARD)
+ return "btn-danger";
+ else
+ return "btn-primary";
+ }
+
+ })));
+ form.add(new AjaxLink<Void>("cancel") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ fragment.replaceWith(new WebMarkupContainer(id).setVisible(false));
+ target.add(operationsContainer);
+ }
+
+ });
+
+ return fragment;
+ }
+
+ private WebMarkupContainer newDiscardedNoteContainer() {
+ WebMarkupContainer discardedNoteContainer = new WebMarkupContainer("discardedNote") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getStatus() == Status.DISCARDED);
+ }
+
+ };
+ return discardedNoteContainer;
+ }
+
+ private WebMarkupContainer newPendingUpdateNoteContainer() {
+ WebMarkupContainer pendingUpdateNoteContainer = new WebMarkupContainer("pendingUpdateNote") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getStatus() == Status.PENDING_UPDATE);
+ }
+
+ };
+ return pendingUpdateNoteContainer;
+ }
+
+ private WebMarkupContainer newPendingApprovalNoteContainer() {
+ WebMarkupContainer pendingApprovalNoteContainer = new WebMarkupContainer("pendingApprovalNote") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getStatus() == Status.PENDING_APPROVAL);
+ }
+
+ };
+ return pendingApprovalNoteContainer;
+ }
+
+ private WebMarkupContainer newIntegratedNoteContainer() {
+ WebMarkupContainer integratedNoteContainer = new WebMarkupContainer("integratedNote") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getPullRequest().getStatus() == Status.INTEGRATED);
+ }
+
+ };
+ integratedNoteContainer.setOutputMarkupId(true);
+
+ integratedNoteContainer.add(new WebMarkupContainer("fastForwarded") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ setVisible(preview != null && preview.getRequestHead().equals(preview.getIntegrated()));
+ }
+
+ });
+ integratedNoteContainer.add(new WebMarkupContainer("merged") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ setVisible(preview != null
+ && !preview.getRequestHead().equals(preview.getIntegrated())
+ && (preview.getIntegrationStrategy() == MERGE_ALWAYS || preview.getIntegrationStrategy() == MERGE_IF_NECESSARY));
+ }
+
+ });
+ integratedNoteContainer.add(new WebMarkupContainer("mergedOutside") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ setVisible(getPullRequest().getLastIntegrationPreview() == null);
+ }
+
+ });
+ integratedNoteContainer.add(new WebMarkupContainer("squashed") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ setVisible(preview != null
+ && !preview.getRequestHead().equals(preview.getIntegrated())
+ && preview.getIntegrationStrategy() == MERGE_WITH_SQUASH);
+ }
+
+ });
+
+ integratedNoteContainer.add(new WebMarkupContainer("sourceRebased") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ setVisible(preview != null
+ && !preview.getRequestHead().equals(preview.getIntegrated())
+ && preview.getIntegrationStrategy() == REBASE_SOURCE_ONTO_TARGET);
+ }
+
+ });
+
+ integratedNoteContainer.add(new WebMarkupContainer("targetRebased") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ PullRequest request = getPullRequest();
+ IntegrationPreview preview = request.getLastIntegrationPreview();
+ setVisible(preview != null
+ && !preview.getRequestHead().equals(preview.getIntegrated())
+ && preview.getIntegrationStrategy() == REBASE_TARGET_ONTO_SOURCE);
+ }
+
+ });
+
+ return integratedNoteContainer;
+ }
+
+ private WebMarkupContainer newStatusReasonsContainer() {
+ WebMarkupContainer statusReasonsContainer = new WebMarkupContainer("statusReasons") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ PullRequest.Status status = getPullRequest().getStatus();
+ setVisible(status == Status.PENDING_APPROVAL || status == Status.PENDING_UPDATE);
+ }
+
+ };
+ statusReasonsContainer.setOutputMarkupId(true);
+
+ statusReasonsContainer.add(new ListView<String>("reasons", new AbstractReadOnlyModel<List<String>>() {
+
+ @Override
+ public List<String> getObject() {
+ return getPullRequest().checkGates(false).getReasons();
+ }
+
+ }) {
+
+ @Override
+ protected void populateItem(ListItem<String> item) {
+ item.add(new Label("reason", item.getModelObject()));
+ }
+
+ });
+
+ return statusReasonsContainer;
+ }
+
+ @Override
+ protected void onDetach() {
+ requestModel.detach();
+ super.onDetach();
+ }
+
+ public static PageParameters paramsOf(PullRequest request) {
+ PageParameters params = DepotPage.paramsOf(request.getTarget().getDepot());
+ params.set("request", request.getNumber());
+ return params;
+ }
+
+ public PullRequest getPullRequest() {
+ return requestModel.getObject();
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ return Lists.newArrayList(new PullRequestChangedRegion(getPullRequest().getId()));
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RequestDetailPage.class, "request-detail.css")));
+ }
+
+ private class RequestTab extends PageTab {
+
+ public RequestTab(String title, Class<? extends Page> pageClass) {
+ super(Model.of(title), pageClass);
+ }
+
+ @Override
+ public Component render(String componentId) {
+ if (getMainPageClass() == RequestCodeCommentsPage.class) {
+ Fragment fragment = new Fragment(componentId, "codeCommentsTabLinkFrag", RequestDetailPage.this);
+ Link<Void> link = new BookmarkablePageLink<Void>("link", RequestCodeCommentsPage.class, paramsOf(getPullRequest())) {
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+ if (event.getPayload() instanceof PullRequestChanged) {
+ ((PullRequestChanged)event.getPayload()).getPartialPageRequestHandler().add(this);
+ }
+ }
+
+ };
+ link.add(AttributeAppender.append("class", new LoadableDetachableModel<String>() {
+
+ @Override
+ protected String load() {
+ PullRequest request = getPullRequest();
+ if (request.getLastCodeCommentEventDate() != null && !request.isVisitedAfter(request.getLastCodeCommentEventDate()))
+ return "new";
+ else
+ return "";
+ }
+
+ }));
+ link.setOutputMarkupId(true);
+ fragment.add(link);
+ return fragment;
+ } else {
+ return new PageTabLink(componentId, this) {
+
+ @Override
+ protected Link<?> newLink(String linkId, Class<? extends Page> pageClass) {
+ return new BookmarkablePageLink<Void>(linkId, pageClass, paramsOf(getPullRequest()));
+ }
+
+ };
+ }
+ }
+
+ }
+
}
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
index 26ca2ed497..fc97bf3bce 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/changes/RequestChangesPage.java
@@ -1,551 +1,574 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes;
-
-import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.annotation.Nullable;
-
-import org.apache.wicket.Component;
-import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.ajax.markup.html.AjaxLink;
-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.ComponentTag;
-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.head.OnDomReadyHeaderItem;
-import org.apache.wicket.markup.html.WebMarkupContainer;
-import org.apache.wicket.markup.html.basic.Label;
-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.model.AbstractReadOnlyModel;
-import org.apache.wicket.model.IModel;
-import org.apache.wicket.model.LoadableDetachableModel;
-import org.apache.wicket.request.IRequestParameters;
-import org.apache.wicket.request.cycle.RequestCycle;
-import org.apache.wicket.request.mapper.parameter.PageParameters;
-import org.apache.wicket.request.resource.CssResourceReference;
-import org.apache.wicket.request.resource.JavaScriptResourceReference;
-import org.eclipse.jgit.revwalk.RevCommit;
-
-import com.pmease.commons.git.GitUtils;
-import com.pmease.commons.lang.diff.WhitespaceOption;
-import com.pmease.commons.wicket.component.DropdownLink;
-import com.pmease.commons.wicket.websocket.WebSocketManager;
-import com.pmease.commons.wicket.websocket.WebSocketRegion;
-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.PullRequest;
-import com.pmease.gitplex.core.entity.PullRequestUpdate;
-import com.pmease.gitplex.core.entity.support.CommentPos;
-import com.pmease.gitplex.core.manager.CodeCommentManager;
-import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
-import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
-import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
-import com.pmease.gitplex.web.websocket.PullRequestChanged;
-import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
-
-@SuppressWarnings("serial")
-public class RequestChangesPage extends RequestDetailPage implements CommentSupport {
-
- private static final String PARAM_OLD_COMMIT = "old-commit";
-
- private static final String PARAM_NEW_COMMIT = "new-commit";
-
- private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
-
- private static final String PARAM_PATH_FILTER = "path-filter";
-
- private static final String PARAM_BLAME_FILE = "blame-file";
-
- private static final String PARAM_COMMENT = "comment";
-
- private static final String PARAM_MARK = "mark";
-
- private State state = new State();
-
- private WebMarkupContainer head;
-
- private final IModel<List<RevCommit>> commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
-
- @Override
- protected List<RevCommit> load() {
- List<RevCommit> commits = new ArrayList<>();
- for (PullRequestUpdate update: getPullRequest().getSortedUpdates()) {
- commits.addAll(update.getCommits());
- }
- return commits;
- }
-
- };
-
- public RequestChangesPage(PageParameters params) {
- super(params);
-
- state.oldCommit = params.get(PARAM_OLD_COMMIT).toString();
- if (state.oldCommit == null)
- state.oldCommit = getPullRequest().getBaseCommitHash();
- state.newCommit = params.get(PARAM_NEW_COMMIT).toString();
- if (state.newCommit == null)
- state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
- state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
- state.blameFile = params.get(PARAM_BLAME_FILE).toString();
- state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
- state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
- state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
- }
-
- private int getCommitIndex(String commitHash) {
- int index = -1;
- for (int i=0; i<commitsModel.getObject().size(); i++) {
- RevCommit commit = commitsModel.getObject().get(i);
- if (commit.name().equals(commitHash)) {
- index = i;
- break;
- }
- }
- return index;
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(head = new WebMarkupContainer("changesHead") {
-
- @Override
- public void onEvent(IEvent<?> event) {
- super.onEvent(event);
-
- if (event.getPayload() instanceof PullRequestChanged) {
- PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
- pullRequestChanged.getPartialPageRequestHandler().add(this);
- }
- }
-
- });
- head.setOutputMarkupId(true);
-
- head.add(new AjaxLink<Void>("prevCommitLink") {
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- }
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(getCommitIndex(state.oldCommit) != -1 && getCommitIndex(state.newCommit) != -1);
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- int index = getCommitIndex(state.oldCommit);
- if (index != -1) {
- state.newCommit = commitsModel.getObject().get(index).name();
- index--;
- if (index == -1) {
- state.oldCommit = getPullRequest().getBaseCommitHash();
- } else {
- state.oldCommit = commitsModel.getObject().get(index).name();
- }
- newRevisionDiff(target);
- }
- target.add(head);
- pushState(target);
- }
-
- });
- head.add(new AjaxLink<Void>("nextCommitLink") {
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
-
- int oldIndex = getCommitIndex(state.oldCommit);
- int newIndex = getCommitIndex(state.newCommit);
- if (!state.oldCommit.equals(getPullRequest().getBaseCommitHash()) && oldIndex == -1
- || newIndex == -1 || newIndex == commitsModel.getObject().size()-1) {
- setEnabled(false);
- } else {
- setEnabled(true);
- }
-
- }
-
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
-
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- }
- }
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- int index = getCommitIndex(state.newCommit);
- if (index != -1 && index != commitsModel.getObject().size()-1) {
- CodeComment comment = getOpenComment();
-
- // we will not move old commit if an opened comment points to it
- if (comment == null || comment.getCommentPos().getCommit().equals(state.newCommit)) {
- state.oldCommit = state.newCommit;
- }
- index++;
- state.newCommit = commitsModel.getObject().get(index).name();
- newRevisionDiff(target);
- }
- target.add(head);
- pushState(target);
- }
-
- });
-
- DropdownLink selectedCommitsLink = new DropdownLink("comparingCommits") {
-
- @Override
- protected Component newContent(String id) {
- AbstractDefaultAjaxBehavior callbackBehavior = new AbstractDefaultAjaxBehavior() {
-
- @Override
- protected void respond(AjaxRequestTarget target) {
- IRequestParameters params = RequestCycle.get().getRequest().getRequestParameters();
- state.oldCommit = params.getParameterValue("oldCommit").toString();
- state.newCommit = params.getParameterValue("newCommit").toString();
- target.add(head);
- newRevisionDiff(target);
- pushState(target);
- close();
- }
-
- };
- Fragment fragment = new Fragment(id, "commitsFrag", RequestChangesPage.this) {
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- String callback = callbackBehavior.getCallbackFunction(explicit("oldCommit"), explicit("newCommit")).toString();
- String script;
- int oldIndex = getCommitIndex(state.oldCommit);
- int newIndex = getCommitIndex(state.newCommit);
- if ((state.oldCommit.equals(getPullRequest().getBaseCommitHash()) || oldIndex != -1)
- && newIndex != -1) {
- script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s', %d, %d);",
- callback, getPullRequest().getBaseCommitHash(), oldIndex+1, newIndex);
- } else {
- script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s');",
- callback, getPullRequest().getBaseCommitHash());
- }
- response.render(OnDomReadyHeaderItem.forScript(script));
- }
-
- };
- fragment.add(callbackBehavior);
- fragment.add(new ListView<RevCommit>("commits", commitsModel) {
-
- @Override
- protected void populateItem(ListItem<RevCommit> item) {
- RevCommit commit = item.getModelObject();
- item.add(AttributeAppender.append("data-hash", commit.name()));
- item.add(new Label("hash", GitUtils.abbreviateSHA(commit.name())));
- item.add(new Label("subject", commit.getShortMessage()));
- }
-
- });
- return fragment;
- }
- };
- selectedCommitsLink.add(new Label("label", new AbstractReadOnlyModel<String>() {
-
- @Override
- public String getObject() {
- String oldName;
- if (state.oldCommit.equals(getPullRequest().getBaseCommitHash()))
- oldName = "base";
- else
- oldName = GitUtils.abbreviateSHA(state.oldCommit);
-
- String newName;
- if (state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash())) {
- newName = "head";
- } else {
- newName = GitUtils.abbreviateSHA(state.newCommit);
- }
-
- return oldName + " ... " + newName;
- }
-
- }));
-
- head.add(selectedCommitsLink);
-
- head.add(new AjaxLink<Void>("fullChanges") {
-
- @Override
- public void onClick(AjaxRequestTarget target) {
- state.oldCommit = getPullRequest().getBaseCommitHash();
- state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
- target.add(head);
- newRevisionDiff(target);
- pushState(target);
- }
-
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(!state.oldCommit.equals(getPullRequest().getBaseCommitHash())
- || !state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash()));
- }
-
- });
-
- newRevisionDiff(null);
- }
-
- @Override
- public void onDetach() {
- commitsModel.detach();
- super.onDetach();
- }
-
- public static PageParameters paramsOf(PullRequest request, String oldCommit, String newCommit) {
- State state = new State();
- state.oldCommit = oldCommit;
- state.newCommit = newCommit;
- return paramsOf(request, state);
- }
-
- public static PageParameters paramsOf(PullRequest request, State state) {
- PageParameters params = RequestDetailPage.paramsOf(request);
-
- if (state.oldCommit != null)
- params.set(PARAM_OLD_COMMIT, state.oldCommit);
- if (state.newCommit != null)
- params.set(PARAM_NEW_COMMIT, state.newCommit);
- if (state.whitespaceOption != WhitespaceOption.DEFAULT)
- params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
- if (state.pathFilter != null)
- params.set(PARAM_PATH_FILTER, state.pathFilter);
- if (state.blameFile != null)
- params.set(PARAM_BLAME_FILE, state.blameFile);
- if (state.commentId != null)
- params.set(PARAM_COMMENT, state.commentId);
- if (state.mark != null)
- params.set(PARAM_MARK, state.mark.toString());
- return params;
- }
-
- @Override
- protected void onPopState(AjaxRequestTarget target, Serializable data) {
- super.onPopState(target, data);
-
- state = (State) data;
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
-
- newRevisionDiff(target);
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(RequestListPage.class, paramsOf(depot));
- }
-
- private void pushState(IPartialPageRequestHandler partialPageRequestHandler) {
- PageParameters params = paramsOf(getPullRequest(), state);
- CharSequence url = RequestCycle.get().urlFor(RequestChangesPage.class, params);
- pushState(partialPageRequestHandler, url.toString(), state);
- }
-
- private void newRevisionDiff(@Nullable AjaxRequestTarget target) {
- IModel<String> blameModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.blameFile;
- }
-
- @Override
- public void setObject(String object) {
- state.blameFile = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<String> pathFilterModel = new IModel<String>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public String getObject() {
- return state.pathFilter;
- }
-
- @Override
- public void setObject(String object) {
- state.pathFilter = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
- IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public WhitespaceOption getObject() {
- return state.whitespaceOption;
- }
-
- @Override
- public void setObject(WhitespaceOption object) {
- state.whitespaceOption = object;
- pushState(RequestCycle.get().find(AjaxRequestTarget.class));
- }
-
- };
-
- Component revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
- requestModel, state.oldCommit, state.newCommit, pathFilterModel,
- whitespaceOptionModel, blameModel, this);
- revisionDiff.setOutputMarkupId(true);
- if (target != null) {
- replace(revisionDiff);
- target.add(revisionDiff);
- } else {
- add(revisionDiff);
- }
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
- response.render(JavaScriptHeaderItem.forReference(
- new JavaScriptResourceReference(RequestChangesPage.class, "request-changes.js")));
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RequestChangesPage.class, "request-changes.css")));
- }
-
- @Override
- public CommentPos getMark() {
- return state.mark;
- }
-
- @Override
- public String getMarkUrl(CommentPos mark) {
- State markState = new State();
- markState.mark = mark;
- markState.oldCommit = state.oldCommit;
- markState.newCommit = state.newCommit;
- markState.pathFilter = state.pathFilter;
- markState.whitespaceOption = state.whitespaceOption;
- return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), markState)).toString();
- }
-
- @Override
- public String getCommentUrl(CodeComment comment) {
- State commentState = new State();
- commentState.mark = comment.getCommentPos();
- commentState.commentId = comment.getId();
- commentState.oldCommit = state.oldCommit;
- commentState.newCommit = state.newCommit;
- commentState.pathFilter = state.pathFilter;
- commentState.whitespaceOption = state.whitespaceOption;
- return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), commentState)).toString();
- }
-
- @Override
- public CodeComment getOpenComment() {
- if (state.commentId != null)
- return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
- else
- return null;
- }
-
- @Override
- public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
- if (comment != null) {
- state.commentId = comment.getId();
- state.mark = comment.getCommentPos();
- } else {
- state.commentId = null;
- }
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- pushState(target);
- }
-
- @Override
- public void onMark(AjaxRequestTarget target, CommentPos mark) {
- state.mark = mark;
- pushState(target);
- }
-
- @Override
- public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
- state.commentId = null;
- state.mark = mark;
- pushState(target);
- GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
- }
-
- @Override
- public Collection<WebSocketRegion> getWebSocketRegions() {
- Collection<WebSocketRegion> regions = new ArrayList<>();
- if (state.commentId != null)
- regions.add(new CodeCommentChangedRegion(state.commentId));
- regions.add(new PullRequestChangedRegion(getPullRequest().getId()));
- return regions;
- }
-
- public static class State implements Serializable {
-
- private static final long serialVersionUID = 1L;
-
- public String oldCommit;
-
- public String newCommit;
-
- public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
-
- @Nullable
- public String pathFilter;
-
- @Nullable
- public String blameFile;
-
- @Nullable
- public Long commentId;
-
- @Nullable
- public CommentPos mark;
-
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.changes;
+
+import static org.apache.wicket.ajax.attributes.CallbackParameter.explicit;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.annotation.Nullable;
+
+import org.apache.wicket.Component;
+import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.AjaxLink;
+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.ComponentTag;
+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.head.OnDomReadyHeaderItem;
+import org.apache.wicket.markup.html.WebMarkupContainer;
+import org.apache.wicket.markup.html.basic.Label;
+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.model.AbstractReadOnlyModel;
+import org.apache.wicket.model.IModel;
+import org.apache.wicket.model.LoadableDetachableModel;
+import org.apache.wicket.request.IRequestParameters;
+import org.apache.wicket.request.cycle.RequestCycle;
+import org.apache.wicket.request.mapper.parameter.PageParameters;
+import org.apache.wicket.request.resource.CssResourceReference;
+import org.apache.wicket.request.resource.JavaScriptResourceReference;
+import org.eclipse.jgit.revwalk.RevCommit;
+
+import com.google.common.base.Preconditions;
+import com.pmease.commons.git.GitUtils;
+import com.pmease.commons.lang.diff.WhitespaceOption;
+import com.pmease.commons.wicket.component.DropdownLink;
+import com.pmease.commons.wicket.websocket.WebSocketManager;
+import com.pmease.commons.wicket.websocket.WebSocketRegion;
+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.PullRequest;
+import com.pmease.gitplex.core.entity.PullRequestUpdate;
+import com.pmease.gitplex.core.entity.support.CodeCommentActivity;
+import com.pmease.gitplex.core.entity.support.CommentPos;
+import com.pmease.gitplex.core.manager.CodeCommentManager;
+import com.pmease.gitplex.web.component.diff.revision.CommentSupport;
+import com.pmease.gitplex.web.component.diff.revision.RevisionDiffPanel;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.RequestListPage;
+import com.pmease.gitplex.web.websocket.CodeCommentChangedRegion;
+import com.pmease.gitplex.web.websocket.PullRequestChanged;
+import com.pmease.gitplex.web.websocket.PullRequestChangedRegion;
+
+@SuppressWarnings("serial")
+public class RequestChangesPage extends RequestDetailPage implements CommentSupport {
+
+ private static final String PARAM_OLD_COMMIT = "old-commit";
+
+ private static final String PARAM_NEW_COMMIT = "new-commit";
+
+ private static final String PARAM_WHITESPACE_OPTION = "whitespace-option";
+
+ private static final String PARAM_PATH_FILTER = "path-filter";
+
+ private static final String PARAM_BLAME_FILE = "blame-file";
+
+ private static final String PARAM_COMMENT = "comment";
+
+ private static final String PARAM_MARK = "mark";
+
+ private State state = new State();
+
+ private WebMarkupContainer head;
+
+ private final IModel<List<RevCommit>> commitsModel = new LoadableDetachableModel<List<RevCommit>>() {
+
+ @Override
+ protected List<RevCommit> load() {
+ List<RevCommit> commits = new ArrayList<>();
+ for (PullRequestUpdate update: getPullRequest().getSortedUpdates()) {
+ commits.addAll(update.getCommits());
+ }
+ return commits;
+ }
+
+ };
+
+ public RequestChangesPage(PageParameters params) {
+ super(params);
+
+ state.oldCommit = params.get(PARAM_OLD_COMMIT).toString();
+ if (state.oldCommit == null)
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ state.newCommit = params.get(PARAM_NEW_COMMIT).toString();
+ if (state.newCommit == null)
+ state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
+ state.pathFilter = params.get(PARAM_PATH_FILTER).toString();
+ state.blameFile = params.get(PARAM_BLAME_FILE).toString();
+ state.whitespaceOption = WhitespaceOption.of(params.get(PARAM_WHITESPACE_OPTION).toString());
+ state.commentId = params.get(PARAM_COMMENT).toOptionalLong();
+ state.mark = CommentPos.of(params.get(PARAM_MARK).toString());
+ }
+
+ private int getCommitIndex(String commitHash) {
+ int index = -1;
+ for (int i=0; i<commitsModel.getObject().size(); i++) {
+ RevCommit commit = commitsModel.getObject().get(i);
+ if (commit.name().equals(commitHash)) {
+ index = i;
+ break;
+ }
+ }
+ return index;
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(head = new WebMarkupContainer("changesHead") {
+
+ @Override
+ public void onEvent(IEvent<?> event) {
+ super.onEvent(event);
+
+ if (event.getPayload() instanceof PullRequestChanged) {
+ PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
+ pullRequestChanged.getPartialPageRequestHandler().add(this);
+ }
+ }
+
+ });
+ head.setOutputMarkupId(true);
+
+ head.add(new AjaxLink<Void>("prevCommitLink") {
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ }
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(getCommitIndex(state.oldCommit) != -1 && getCommitIndex(state.newCommit) != -1);
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ int index = getCommitIndex(state.oldCommit);
+ if (index != -1) {
+ state.newCommit = commitsModel.getObject().get(index).name();
+ index--;
+ if (index == -1) {
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ } else {
+ state.oldCommit = commitsModel.getObject().get(index).name();
+ }
+ newRevisionDiff(target);
+ }
+ target.add(head);
+ pushState(target);
+ }
+
+ });
+ head.add(new AjaxLink<Void>("nextCommitLink") {
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+
+ int oldIndex = getCommitIndex(state.oldCommit);
+ int newIndex = getCommitIndex(state.newCommit);
+ if (!state.oldCommit.equals(getPullRequest().getBaseCommitHash()) && oldIndex == -1
+ || newIndex == -1 || newIndex == commitsModel.getObject().size()-1) {
+ setEnabled(false);
+ } else {
+ setEnabled(true);
+ }
+
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ }
+ }
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ int index = getCommitIndex(state.newCommit);
+ if (index != -1 && index != commitsModel.getObject().size()-1) {
+ CodeComment comment = getOpenComment();
+
+ // we will not move old commit if an opened comment points to it
+ if (comment == null || comment.getCommentPos().getCommit().equals(state.newCommit)) {
+ state.oldCommit = state.newCommit;
+ }
+ index++;
+ state.newCommit = commitsModel.getObject().get(index).name();
+ newRevisionDiff(target);
+ }
+ target.add(head);
+ pushState(target);
+ }
+
+ });
+
+ DropdownLink selectedCommitsLink = new DropdownLink("comparingCommits") {
+
+ @Override
+ protected Component newContent(String id) {
+ AbstractDefaultAjaxBehavior callbackBehavior = new AbstractDefaultAjaxBehavior() {
+
+ @Override
+ protected void respond(AjaxRequestTarget target) {
+ IRequestParameters params = RequestCycle.get().getRequest().getRequestParameters();
+ state.oldCommit = params.getParameterValue("oldCommit").toString();
+ state.newCommit = params.getParameterValue("newCommit").toString();
+ target.add(head);
+ newRevisionDiff(target);
+ pushState(target);
+ close();
+ }
+
+ };
+ Fragment fragment = new Fragment(id, "commitsFrag", RequestChangesPage.this) {
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ String callback = callbackBehavior.getCallbackFunction(explicit("oldCommit"), explicit("newCommit")).toString();
+ String script;
+ int oldIndex = getCommitIndex(state.oldCommit);
+ int newIndex = getCommitIndex(state.newCommit);
+ if ((state.oldCommit.equals(getPullRequest().getBaseCommitHash()) || oldIndex != -1)
+ && newIndex != -1) {
+ script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s', %d, %d);",
+ callback, getPullRequest().getBaseCommitHash(), oldIndex+1, newIndex);
+ } else {
+ script = String.format("gitplex.requestChanges.initCommitSelector(%s, '%s');",
+ callback, getPullRequest().getBaseCommitHash());
+ }
+ response.render(OnDomReadyHeaderItem.forScript(script));
+ }
+
+ };
+ fragment.add(callbackBehavior);
+ fragment.add(new ListView<RevCommit>("commits", commitsModel) {
+
+ @Override
+ protected void populateItem(ListItem<RevCommit> item) {
+ RevCommit commit = item.getModelObject();
+ item.add(AttributeAppender.append("data-hash", commit.name()));
+ item.add(new Label("hash", GitUtils.abbreviateSHA(commit.name())));
+ item.add(new Label("subject", commit.getShortMessage()));
+ }
+
+ });
+ return fragment;
+ }
+ };
+ selectedCommitsLink.add(new Label("label", new AbstractReadOnlyModel<String>() {
+
+ @Override
+ public String getObject() {
+ String oldName;
+ if (state.oldCommit.equals(getPullRequest().getBaseCommitHash()))
+ oldName = "base";
+ else
+ oldName = GitUtils.abbreviateSHA(state.oldCommit);
+
+ String newName;
+ if (state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash())) {
+ newName = "head";
+ } else {
+ newName = GitUtils.abbreviateSHA(state.newCommit);
+ }
+
+ return oldName + " ... " + newName;
+ }
+
+ }));
+
+ head.add(selectedCommitsLink);
+
+ head.add(new AjaxLink<Void>("fullChanges") {
+
+ @Override
+ public void onClick(AjaxRequestTarget target) {
+ state.oldCommit = getPullRequest().getBaseCommitHash();
+ state.newCommit = getPullRequest().getLatestUpdate().getHeadCommitHash();
+ target.add(head);
+ newRevisionDiff(target);
+ pushState(target);
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(!state.oldCommit.equals(getPullRequest().getBaseCommitHash())
+ || !state.newCommit.equals(getPullRequest().getLatestUpdate().getHeadCommitHash()));
+ }
+
+ });
+
+ newRevisionDiff(null);
+ }
+
+ @Override
+ public void onDetach() {
+ commitsModel.detach();
+ super.onDetach();
+ }
+
+ public static PageParameters paramsOf(PullRequest request, String oldCommit, String newCommit) {
+ State state = new State();
+ state.oldCommit = oldCommit;
+ state.newCommit = newCommit;
+ return paramsOf(request, state);
+ }
+
+ public static PageParameters paramsOf(PullRequest request, CodeComment comment) {
+ PullRequest.ComparingInfo comparingInfo = null;
+ for (int i=comment.getActivities().size()-1; i>=0; i--) {
+ CodeCommentActivity activity = comment.getActivities().get(i);
+ comparingInfo = request.getRequestComparingInfo(activity.getComparingInfo());
+ if (comparingInfo != null)
+ break;
+ }
+ if (comparingInfo == null) {
+ comparingInfo = Preconditions.checkNotNull(request.getRequestComparingInfo(comment.getComparingInfo()));
+ }
+ RequestChangesPage.State state = new RequestChangesPage.State();
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ state.oldCommit = comparingInfo.getOldCommit();
+ state.newCommit = comparingInfo.getNewCommit();
+ state.pathFilter = comparingInfo.getPathFilter();
+ state.whitespaceOption = comparingInfo.getWhitespaceOption();
+ return paramsOf(request, state);
+ }
+
+ public static PageParameters paramsOf(PullRequest request, State state) {
+ PageParameters params = RequestDetailPage.paramsOf(request);
+
+ if (state.oldCommit != null)
+ params.set(PARAM_OLD_COMMIT, state.oldCommit);
+ if (state.newCommit != null)
+ params.set(PARAM_NEW_COMMIT, state.newCommit);
+ if (state.whitespaceOption != WhitespaceOption.DEFAULT)
+ params.set(PARAM_WHITESPACE_OPTION, state.whitespaceOption.name());
+ if (state.pathFilter != null)
+ params.set(PARAM_PATH_FILTER, state.pathFilter);
+ if (state.blameFile != null)
+ params.set(PARAM_BLAME_FILE, state.blameFile);
+ if (state.commentId != null)
+ params.set(PARAM_COMMENT, state.commentId);
+ if (state.mark != null)
+ params.set(PARAM_MARK, state.mark.toString());
+ return params;
+ }
+
+ @Override
+ protected void onPopState(AjaxRequestTarget target, Serializable data) {
+ super.onPopState(target, data);
+
+ state = (State) data;
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+
+ newRevisionDiff(target);
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(RequestListPage.class, paramsOf(depot));
+ }
+
+ private void pushState(IPartialPageRequestHandler partialPageRequestHandler) {
+ PageParameters params = paramsOf(getPullRequest(), state);
+ CharSequence url = RequestCycle.get().urlFor(RequestChangesPage.class, params);
+ pushState(partialPageRequestHandler, url.toString(), state);
+ }
+
+ private void newRevisionDiff(@Nullable AjaxRequestTarget target) {
+ IModel<String> blameModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.blameFile;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.blameFile = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<String> pathFilterModel = new IModel<String>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public String getObject() {
+ return state.pathFilter;
+ }
+
+ @Override
+ public void setObject(String object) {
+ state.pathFilter = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+ IModel<WhitespaceOption> whitespaceOptionModel = new IModel<WhitespaceOption>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public WhitespaceOption getObject() {
+ return state.whitespaceOption;
+ }
+
+ @Override
+ public void setObject(WhitespaceOption object) {
+ state.whitespaceOption = object;
+ pushState(RequestCycle.get().find(AjaxRequestTarget.class));
+ }
+
+ };
+
+ Component revisionDiff = new RevisionDiffPanel("revisionDiff", depotModel,
+ requestModel, state.oldCommit, state.newCommit, pathFilterModel,
+ whitespaceOptionModel, blameModel, this);
+ revisionDiff.setOutputMarkupId(true);
+ if (target != null) {
+ replace(revisionDiff);
+ target.add(revisionDiff);
+ } else {
+ add(revisionDiff);
+ }
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+ response.render(JavaScriptHeaderItem.forReference(
+ new JavaScriptResourceReference(RequestChangesPage.class, "request-changes.js")));
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RequestChangesPage.class, "request-changes.css")));
+ }
+
+ @Override
+ public CommentPos getMark() {
+ return state.mark;
+ }
+
+ @Override
+ public String getMarkUrl(CommentPos mark) {
+ State markState = new State();
+ markState.mark = mark;
+ markState.oldCommit = state.oldCommit;
+ markState.newCommit = state.newCommit;
+ markState.pathFilter = state.pathFilter;
+ markState.whitespaceOption = state.whitespaceOption;
+ return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), markState)).toString();
+ }
+
+ @Override
+ public String getCommentUrl(CodeComment comment) {
+ State commentState = new State();
+ commentState.mark = comment.getCommentPos();
+ commentState.commentId = comment.getId();
+ commentState.oldCommit = state.oldCommit;
+ commentState.newCommit = state.newCommit;
+ commentState.pathFilter = state.pathFilter;
+ commentState.whitespaceOption = state.whitespaceOption;
+ return urlFor(RequestChangesPage.class, paramsOf(getPullRequest(), commentState)).toString();
+ }
+
+ @Override
+ public CodeComment getOpenComment() {
+ if (state.commentId != null)
+ return GitPlex.getInstance(CodeCommentManager.class).load(state.commentId);
+ else
+ return null;
+ }
+
+ @Override
+ public void onCommentOpened(AjaxRequestTarget target, CodeComment comment) {
+ if (comment != null) {
+ state.commentId = comment.getId();
+ state.mark = comment.getCommentPos();
+ } else {
+ state.commentId = null;
+ }
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ pushState(target);
+ }
+
+ @Override
+ public void onMark(AjaxRequestTarget target, CommentPos mark) {
+ state.mark = mark;
+ pushState(target);
+ }
+
+ @Override
+ public void onAddComment(AjaxRequestTarget target, CommentPos mark) {
+ state.commentId = null;
+ state.mark = mark;
+ pushState(target);
+ GitPlex.getInstance(WebSocketManager.class).onRegionChange(this);
+ }
+
+ @Override
+ public Collection<WebSocketRegion> getWebSocketRegions() {
+ Collection<WebSocketRegion> regions = new ArrayList<>();
+ if (state.commentId != null)
+ regions.add(new CodeCommentChangedRegion(state.commentId));
+ regions.add(new PullRequestChangedRegion(getPullRequest().getId()));
+ return regions;
+ }
+
+ public static class State implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ public String oldCommit;
+
+ public String newCommit;
+
+ public WhitespaceOption whitespaceOption = WhitespaceOption.DEFAULT;
+
+ @Nullable
+ public String pathFilter;
+
+ @Nullable
+ public String blameFile;
+
+ @Nullable
+ public Long commentId;
+
+ @Nullable
+ public CommentPos mark;
+
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/CodeCommentsPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/RequestCodeCommentsPage.html
similarity index 100%
rename from gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/CodeCommentsPage.html
rename to gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/RequestCodeCommentsPage.html
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/CodeCommentsPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/RequestCodeCommentsPage.java
similarity index 86%
rename from gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/CodeCommentsPage.java
rename to gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/RequestCodeCommentsPage.java
index 2e7af57b21..7c33759cee 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/CodeCommentsPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/codecomments/RequestCodeCommentsPage.java
@@ -15,13 +15,13 @@ import com.pmease.gitplex.web.component.comment.CodeCommentListPanel;
import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.RequestDetailPage;
@SuppressWarnings("serial")
-public class CodeCommentsPage extends RequestDetailPage implements CodeCommentAware {
+public class RequestCodeCommentsPage extends RequestDetailPage implements CodeCommentAware {
private final CodeCommentFilter filterOption;
private final List<String> commentedFiles = new ArrayList<>();
- public CodeCommentsPage(PageParameters params) {
+ public RequestCodeCommentsPage(PageParameters params) {
super(params);
filterOption = new CodeCommentFilter(params);
@@ -52,14 +52,14 @@ public class CodeCommentsPage extends RequestDetailPage implements CodeCommentAw
public void setObject(CodeCommentFilter object) {
PageParameters params = paramsOf(getPullRequest());
object.fillPageParams(params);
- setResponsePage(CodeCommentsPage.class, params);
+ setResponsePage(RequestCodeCommentsPage.class, params);
}
}) {
@Override
protected PullRequest getPullRequest() {
- return CodeCommentsPage.this.getPullRequest();
+ return RequestCodeCommentsPage.this.getPullRequest();
}
});
diff --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.java
index 0996c6f4f0..ebe6b00073 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
@@ -48,10 +48,8 @@ import com.pmease.gitplex.core.entity.PullRequestReviewInvitation;
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.manager.AccountManager;
import com.pmease.gitplex.core.manager.PullRequestCommentManager;
import com.pmease.gitplex.core.manager.PullRequestManager;
-import com.pmease.gitplex.core.manager.VisitInfoManager;
import com.pmease.gitplex.core.security.ObjectPermission;
import com.pmease.gitplex.core.security.SecurityUtils;
import com.pmease.gitplex.web.component.avatar.Avatar;
@@ -195,7 +193,6 @@ public class RequestOverviewPage extends RequestDetailPage {
PullRequestChanged pullRequestChanged = (PullRequestChanged) event.getPayload();
IPartialPageRequestHandler partialPageRequestHandler = pullRequestChanged.getPartialPageRequestHandler();
- PullRequest request = getPullRequest();
@SuppressWarnings("deprecation")
Component prevActivityRow = activitiesView.get(activitiesView.size()-1);
PullRequestActivity lastActivity = (PullRequestActivity) prevActivityRow.getDefaultModelObject();
@@ -239,10 +236,6 @@ public class RequestOverviewPage extends RequestDetailPage {
}
prevActivityRow = newActivityRow;
}
-
- Account user = GitPlex.getInstance(AccountManager.class).getCurrent();
- if (user != null)
- GitPlex.getInstance(VisitInfoManager.class).visit(user, request);
}
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangeActivity.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangeActivity.java
index 8265a00961..48bf78f44c 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangeActivity.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestdetail/overview/activity/StatusChangeActivity.java
@@ -31,7 +31,7 @@ public class StatusChangeActivity implements PullRequestActivity {
});
}
- private PullRequestStatusChange getStatusChange() {
+ public PullRequestStatusChange getStatusChange() {
return GitPlex.getInstance(PullRequestStatusChangeManager.class).load(statusChangeId);
}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestlist/RequestListPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestlist/RequestListPage.java
index bca12493a2..08dba17b02 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestlist/RequestListPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/depot/pullrequest/requestlist/RequestListPage.java
@@ -1,403 +1,405 @@
-package com.pmease.gitplex.web.page.depot.pullrequest.requestlist;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.wicket.ajax.AjaxRequestTarget;
-import org.apache.wicket.behavior.AttributeAppender;
-import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigationToolbar;
-import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar;
-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.link.AbstractLink;
-import org.apache.wicket.markup.html.link.BookmarkablePageLink;
-import org.apache.wicket.markup.html.link.Link;
-import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
-import org.apache.wicket.markup.html.panel.Fragment;
-import org.apache.wicket.markup.repeater.Item;
-import org.apache.wicket.markup.repeater.data.IDataProvider;
-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.pmease.commons.hibernate.dao.Dao;
-import com.pmease.commons.hibernate.dao.EntityCriteria;
-import com.pmease.commons.wicket.component.menu.MenuItem;
-import com.pmease.commons.wicket.component.menu.MenuLink;
-import com.pmease.commons.wicket.editable.BeanContext;
-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.manager.AccountManager;
-import com.pmease.gitplex.web.Constants;
-import com.pmease.gitplex.web.component.AccountLink;
-import com.pmease.gitplex.web.component.BranchLink;
-import com.pmease.gitplex.web.component.pullrequest.requeststatus.RequestStatusPanel;
-import com.pmease.gitplex.web.page.depot.DepotPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.PullRequestPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
-import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.SearchOption.Status;
-import com.pmease.gitplex.web.util.DateUtils;
-
-import de.agilecoders.wicket.core.markup.html.bootstrap.navigation.BootstrapPagingNavigator;
-
-@SuppressWarnings("serial")
-public class RequestListPage extends PullRequestPage {
-
- private static final Map<SortOption, String> sortNames = new LinkedHashMap<>();
-
- static {
- sortNames.put(new SortOption("submitDate", false), "Newest");
- sortNames.put(new SortOption("submitDate", true), "Oldest");
- sortNames.put(new SortOption("lastEventDate", false), "Recently updated");
- sortNames.put(new SortOption("lastEventDate", true), "Least recently updated");
- }
-
- private SearchOption searchOption;
-
- private SortOption sortOption;
-
- public RequestListPage(PageParameters params) {
- super(params);
-
- searchOption = new SearchOption(params);
- sortOption = new SortOption(params);
- }
-
- @Override
- protected void onInitialize() {
- super.onInitialize();
-
- add(new MenuLink("filters") {
-
- @Override
- protected List<MenuItem> getMenuItems() {
- List<MenuItem> menuItems = new ArrayList<>();
-
- Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
- if (currentUser != null) {
- final String userName = currentUser.getName();
- menuItems.add(new MenuItem() {
-
- @Override
- public String getIconClass() {
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Open requests assigned to me";
- }
-
- @Override
- public AbstractLink newLink(String id) {
- return new Link<Void>(id) {
-
- @Override
- public void onClick() {
- searchOption = new SearchOption();
- searchOption.setStatus(Status.OPEN);
- searchOption.setAssigneeName(userName);
-
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- }
-
- });
- menuItems.add(new MenuItem() {
-
- @Override
- public String getIconClass() {
- return null;
- }
-
- @Override
- public String getLabel() {
- return "Open requests submitted by me";
- }
-
- @Override
- public AbstractLink newLink(String id) {
- return new Link<Void>(id) {
-
- @Override
- public void onClick() {
- searchOption = new SearchOption();
- searchOption.setStatus(Status.OPEN);
- searchOption.setSubmitterName(userName);
-
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- }
-
- });
- }
- menuItems.add(new MenuItem() {
-
- @Override
- public String getIconClass() {
- return null;
- }
-
- @Override
- public String getLabel() {
- return "All open requests";
- }
-
- @Override
- public AbstractLink newLink(String id) {
- return new Link<Void>(id) {
-
- @Override
- public void onClick() {
- searchOption = new SearchOption();
- searchOption.setStatus(Status.OPEN);
-
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- }
-
- });
- menuItems.add(new MenuItem() {
-
- @Override
- public String getIconClass() {
- return null;
- }
-
- @Override
- public String getLabel() {
- return "All closed requests";
- }
-
- @Override
- public AbstractLink newLink(String id) {
- return new Link<Void>(id) {
-
- @Override
- public void onClick() {
- searchOption = new SearchOption();
- searchOption.setStatus(Status.CLOSED);
-
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- }
-
- });
- return menuItems;
- }
-
- });
-
- add(new MenuLink("sortBy") {
-
- @Override
- protected List<MenuItem> getMenuItems() {
- List<MenuItem> menuItems = new ArrayList<>();
-
- for (Map.Entry<SortOption, String> entry: sortNames.entrySet()) {
- final SortOption sortOption = entry.getKey();
- final String displayName = entry.getValue();
- menuItems.add(new MenuItem() {
-
- @Override
- public String getLabel() {
- return displayName;
- }
-
- @Override
- public String getIconClass() {
- if (RequestListPage.this.sortOption.equals(sortOption))
- return "fa fa-check";
- else
- return null;
- }
-
- @Override
- public AbstractLink newLink(String id) {
- return new Link<Void>(id) {
-
- @Override
- public void onClick() {
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- }
-
- });
- }
-
- return menuItems;
- }
-
- });
-
- add(new Link<Void>("newRequest") {
-
- @Override
- public void onClick() {
- DepotPage page = (DepotPage) getPage();
- setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(page.getDepot()));
- }
-
- });
-
- Form<?> form = new Form<Void>("filterForm") {
-
- @Override
- protected void onSubmit() {
- super.onSubmit();
-
- setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
- }
-
- };
- form.add(BeanContext.editBean("editor", searchOption));
- add(form);
-
- List<IColumn<PullRequest, Void>> columns = new ArrayList<>();
- columns.add(new AbstractColumn<PullRequest, Void>(Model.of("Pull Request")) {
-
- @Override
- public void populateItem(Item<ICellPopulator<PullRequest>> cellItem,
- String componentId, final IModel<PullRequest> rowModel) {
- PullRequest request = rowModel.getObject();
- Fragment fragment = new Fragment(componentId, "requestFrag", RequestListPage.this);
- fragment.add(new Label("number", "#" + request.getNumber()));
- fragment.add(new BookmarkablePageLink<Void>("title", RequestOverviewPage.class,
- RequestOverviewPage.paramsOf(request)) {
-
- @Override
- public IModel<?> getBody() {
- return Model.of(rowModel.getObject().getTitle());
- }
-
- });
-
- fragment.add(new RequestStatusPanel("status", rowModel, false));
- fragment.add(new AccountLink("submitter", rowModel.getObject().getSubmitter()));
- fragment.add(new BranchLink("target", request.getTarget()));
- fragment.add(new BranchLink("source", request.getSource()));
- fragment.add(new Label("date", DateUtils.formatAge(request.getSubmitDate())));
-
- WebMarkupContainer lastEventContainer = new WebMarkupContainer("lastEvent");
- if (request.getLastEvent() != null) {
- lastEventContainer.add(new AccountLink("user", request.getLastEvent().getUser())
- .setVisible(request.getLastEvent().getUser()!=null));
- lastEventContainer.add(new Label("description", request.getLastEvent().getDescription()));
- lastEventContainer.add(new Label("date", DateUtils.formatAge(request.getLastEvent().getDate())));
- } else {
- lastEventContainer.add(new AccountLink("user", (Account)null));
- lastEventContainer.add(new Label("description"));
- lastEventContainer.add(new Label("date"));
- lastEventContainer.setVisible(false);
- }
- fragment.add(lastEventContainer);
-
- cellItem.add(fragment);
-
- Date lastActivityDate;
- if (request.getLastEvent() != null)
- lastActivityDate = request.getLastEvent().getDate();
- else
- lastActivityDate = request.getSubmitDate();
- cellItem.add(AttributeAppender.append("class",
- request.isVisitedAfter(lastActivityDate)?"request":"request new"));
- }
-
- });
-
- IDataProvider<PullRequest> dataProvider = new IDataProvider<PullRequest>() {
-
- @Override
- public void detach() {
- }
-
- @Override
- public Iterator<? extends PullRequest> iterator(long first, long count) {
- DepotPage page = (DepotPage) getPage();
-
- EntityCriteria<PullRequest> criteria = searchOption.getCriteria(page.getDepot());
- criteria.addOrder(sortOption.getOrder());
- return GitPlex.getInstance(Dao.class).findRange(criteria, (int)first, (int)count).iterator();
- }
-
- @Override
- public long size() {
- DepotPage page = (DepotPage) getPage();
- return GitPlex.getInstance(Dao.class).count(searchOption.getCriteria(page.getDepot()));
- }
-
- @Override
- public IModel<PullRequest> model(PullRequest object) {
- final Long pullRequestId = object.getId();
- return new LoadableDetachableModel<PullRequest>() {
-
- @Override
- protected PullRequest load() {
- return GitPlex.getInstance(Dao.class).load(PullRequest.class, pullRequestId);
- }
-
- };
- }
-
- };
- DataTable<PullRequest, Void> dataTable = new DataTable<>("requests", columns,
- dataProvider, Constants.DEFAULT_PAGE_SIZE);
- dataTable.addBottomToolbar(new NoRecordsToolbar(dataTable));
- dataTable.addBottomToolbar(new NavigationToolbar(dataTable) {
-
- @Override
- protected PagingNavigator newPagingNavigator(String navigatorId, DataTable<?, ?> table) {
- return new BootstrapPagingNavigator(navigatorId, dataTable);
- }
-
- });
- add(dataTable);
- }
-
- @Override
- public void renderHead(IHeaderResponse response) {
- super.renderHead(response);
-
- response.render(CssHeaderItem.forReference(
- new CssResourceReference(RequestListPage.class, "request-list.css")));
- }
-
- public static PageParameters paramsOf(Depot depot, SearchOption searchOption, SortOption sortOption) {
- PageParameters params = paramsOf(depot);
- searchOption.fillPageParams(params);
- sortOption.fillPageParams(params);
- return params;
- }
-
- @Override
- protected void onSelect(AjaxRequestTarget target, Depot depot) {
- setResponsePage(RequestListPage.class, paramsOf(depot));
- }
-
-}
+package com.pmease.gitplex.web.page.depot.pullrequest.requestlist;
+
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.behavior.AttributeAppender;
+import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.DataTable;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.NavigationToolbar;
+import org.apache.wicket.extensions.markup.html.repeater.data.table.NoRecordsToolbar;
+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.link.AbstractLink;
+import org.apache.wicket.markup.html.link.BookmarkablePageLink;
+import org.apache.wicket.markup.html.link.Link;
+import org.apache.wicket.markup.html.navigation.paging.PagingNavigator;
+import org.apache.wicket.markup.html.panel.Fragment;
+import org.apache.wicket.markup.repeater.Item;
+import org.apache.wicket.markup.repeater.data.IDataProvider;
+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.pmease.commons.hibernate.dao.Dao;
+import com.pmease.commons.hibernate.dao.EntityCriteria;
+import com.pmease.commons.wicket.component.menu.MenuItem;
+import com.pmease.commons.wicket.component.menu.MenuLink;
+import com.pmease.commons.wicket.editable.BeanContext;
+import com.pmease.commons.wicket.editable.EditableUtils;
+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.manager.AccountManager;
+import com.pmease.gitplex.web.Constants;
+import com.pmease.gitplex.web.component.AccountLink;
+import com.pmease.gitplex.web.component.BranchLink;
+import com.pmease.gitplex.web.component.pullrequest.requeststatus.RequestStatusPanel;
+import com.pmease.gitplex.web.page.depot.DepotPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.PullRequestPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.newrequest.NewRequestPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestdetail.overview.RequestOverviewPage;
+import com.pmease.gitplex.web.page.depot.pullrequest.requestlist.SearchOption.Status;
+import com.pmease.gitplex.web.util.DateUtils;
+
+import de.agilecoders.wicket.core.markup.html.bootstrap.navigation.BootstrapPagingNavigator;
+
+@SuppressWarnings("serial")
+public class RequestListPage extends PullRequestPage {
+
+ private static final Map<SortOption, String> sortNames = new LinkedHashMap<>();
+
+ static {
+ sortNames.put(new SortOption("submitDate", false), "Newest");
+ sortNames.put(new SortOption("submitDate", true), "Oldest");
+ sortNames.put(new SortOption("lastEventDate", false), "Recently updated");
+ sortNames.put(new SortOption("lastEventDate", true), "Least recently updated");
+ }
+
+ private SearchOption searchOption;
+
+ private SortOption sortOption;
+
+ public RequestListPage(PageParameters params) {
+ super(params);
+
+ searchOption = new SearchOption(params);
+ sortOption = new SortOption(params);
+ }
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ add(new MenuLink("filters") {
+
+ @Override
+ protected List<MenuItem> getMenuItems() {
+ List<MenuItem> menuItems = new ArrayList<>();
+
+ Account currentUser = GitPlex.getInstance(AccountManager.class).getCurrent();
+ if (currentUser != null) {
+ final String userName = currentUser.getName();
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getIconClass() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Open requests assigned to me";
+ }
+
+ @Override
+ public AbstractLink newLink(String id) {
+ return new Link<Void>(id) {
+
+ @Override
+ public void onClick() {
+ searchOption = new SearchOption();
+ searchOption.setStatus(Status.OPEN);
+ searchOption.setAssigneeName(userName);
+
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ }
+
+ });
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getIconClass() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "Open requests submitted by me";
+ }
+
+ @Override
+ public AbstractLink newLink(String id) {
+ return new Link<Void>(id) {
+
+ @Override
+ public void onClick() {
+ searchOption = new SearchOption();
+ searchOption.setStatus(Status.OPEN);
+ searchOption.setSubmitterName(userName);
+
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ }
+
+ });
+ }
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getIconClass() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "All open requests";
+ }
+
+ @Override
+ public AbstractLink newLink(String id) {
+ return new Link<Void>(id) {
+
+ @Override
+ public void onClick() {
+ searchOption = new SearchOption();
+ searchOption.setStatus(Status.OPEN);
+
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ }
+
+ });
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getIconClass() {
+ return null;
+ }
+
+ @Override
+ public String getLabel() {
+ return "All closed requests";
+ }
+
+ @Override
+ public AbstractLink newLink(String id) {
+ return new Link<Void>(id) {
+
+ @Override
+ public void onClick() {
+ searchOption = new SearchOption();
+ searchOption.setStatus(Status.CLOSED);
+
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ }
+
+ });
+ return menuItems;
+ }
+
+ });
+
+ add(new MenuLink("sortBy") {
+
+ @Override
+ protected List<MenuItem> getMenuItems() {
+ List<MenuItem> menuItems = new ArrayList<>();
+
+ for (Map.Entry<SortOption, String> entry: sortNames.entrySet()) {
+ final SortOption sortOption = entry.getKey();
+ final String displayName = entry.getValue();
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getLabel() {
+ return displayName;
+ }
+
+ @Override
+ public String getIconClass() {
+ if (RequestListPage.this.sortOption.equals(sortOption))
+ return "fa fa-check";
+ else
+ return null;
+ }
+
+ @Override
+ public AbstractLink newLink(String id) {
+ return new Link<Void>(id) {
+
+ @Override
+ public void onClick() {
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ }
+
+ });
+ }
+
+ return menuItems;
+ }
+
+ });
+
+ add(new Link<Void>("newRequest") {
+
+ @Override
+ public void onClick() {
+ DepotPage page = (DepotPage) getPage();
+ setResponsePage(NewRequestPage.class, NewRequestPage.paramsOf(page.getDepot()));
+ }
+
+ });
+
+ Form<?> form = new Form<Void>("filterForm") {
+
+ @Override
+ protected void onSubmit() {
+ super.onSubmit();
+
+ setResponsePage(RequestListPage.class, paramsOf(getDepot(), searchOption, sortOption));
+ }
+
+ };
+ form.add(BeanContext.editBean("editor", searchOption));
+ add(form);
+
+ List<IColumn<PullRequest, Void>> columns = new ArrayList<>();
+ columns.add(new AbstractColumn<PullRequest, Void>(Model.of("Pull Request")) {
+
+ @Override
+ public void populateItem(Item<ICellPopulator<PullRequest>> cellItem,
+ String componentId, final IModel<PullRequest> rowModel) {
+ PullRequest request = rowModel.getObject();
+ Fragment fragment = new Fragment(componentId, "requestFrag", RequestListPage.this);
+ fragment.add(new Label("number", "#" + request.getNumber()));
+ fragment.add(new BookmarkablePageLink<Void>("title", RequestOverviewPage.class,
+ RequestOverviewPage.paramsOf(request)) {
+
+ @Override
+ public IModel<?> getBody() {
+ return Model.of(rowModel.getObject().getTitle());
+ }
+
+ });
+
+ fragment.add(new RequestStatusPanel("status", rowModel, false));
+ fragment.add(new AccountLink("submitter", rowModel.getObject().getSubmitter()));
+ fragment.add(new BranchLink("target", request.getTarget()));
+ fragment.add(new BranchLink("source", request.getSource()));
+ fragment.add(new Label("date", DateUtils.formatAge(request.getSubmitDate())));
+
+ WebMarkupContainer lastEventContainer = new WebMarkupContainer("lastEvent");
+ if (request.getLastEvent() != null) {
+ lastEventContainer.add(new AccountLink("user", request.getLastEvent().getUser())
+ .setVisible(request.getLastEvent().getUser()!=null));
+ String description = EditableUtils.getName(request.getLastEvent().getType());
+ lastEventContainer.add(new Label("description", description));
+ lastEventContainer.add(new Label("date", DateUtils.formatAge(request.getLastEvent().getDate())));
+ } else {
+ lastEventContainer.add(new AccountLink("user", (Account)null));
+ lastEventContainer.add(new Label("description"));
+ lastEventContainer.add(new Label("date"));
+ lastEventContainer.setVisible(false);
+ }
+ fragment.add(lastEventContainer);
+
+ cellItem.add(fragment);
+
+ Date lastActivityDate;
+ if (request.getLastEvent() != null)
+ lastActivityDate = request.getLastEvent().getDate();
+ else
+ lastActivityDate = request.getSubmitDate();
+ cellItem.add(AttributeAppender.append("class",
+ request.isVisitedAfter(lastActivityDate)?"request":"request new"));
+ }
+
+ });
+
+ IDataProvider<PullRequest> dataProvider = new IDataProvider<PullRequest>() {
+
+ @Override
+ public void detach() {
+ }
+
+ @Override
+ public Iterator<? extends PullRequest> iterator(long first, long count) {
+ DepotPage page = (DepotPage) getPage();
+
+ EntityCriteria<PullRequest> criteria = searchOption.getCriteria(page.getDepot());
+ criteria.addOrder(sortOption.getOrder());
+ return GitPlex.getInstance(Dao.class).findRange(criteria, (int)first, (int)count).iterator();
+ }
+
+ @Override
+ public long size() {
+ DepotPage page = (DepotPage) getPage();
+ return GitPlex.getInstance(Dao.class).count(searchOption.getCriteria(page.getDepot()));
+ }
+
+ @Override
+ public IModel<PullRequest> model(PullRequest object) {
+ final Long pullRequestId = object.getId();
+ return new LoadableDetachableModel<PullRequest>() {
+
+ @Override
+ protected PullRequest load() {
+ return GitPlex.getInstance(Dao.class).load(PullRequest.class, pullRequestId);
+ }
+
+ };
+ }
+
+ };
+ DataTable<PullRequest, Void> dataTable = new DataTable<>("requests", columns,
+ dataProvider, Constants.DEFAULT_PAGE_SIZE);
+ dataTable.addBottomToolbar(new NoRecordsToolbar(dataTable));
+ dataTable.addBottomToolbar(new NavigationToolbar(dataTable) {
+
+ @Override
+ protected PagingNavigator newPagingNavigator(String navigatorId, DataTable<?, ?> table) {
+ return new BootstrapPagingNavigator(navigatorId, dataTable);
+ }
+
+ });
+ add(dataTable);
+ }
+
+ @Override
+ public void renderHead(IHeaderResponse response) {
+ super.renderHead(response);
+
+ response.render(CssHeaderItem.forReference(
+ new CssResourceReference(RequestListPage.class, "request-list.css")));
+ }
+
+ public static PageParameters paramsOf(Depot depot, SearchOption searchOption, SortOption sortOption) {
+ PageParameters params = paramsOf(depot);
+ searchOption.fillPageParams(params);
+ sortOption.fillPageParams(params);
+ return params;
+ }
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Depot depot) {
+ setResponsePage(RequestListPage.class, paramsOf(depot));
+ }
+
+}
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.html
index 8b743f95dd..1f5a52d6d2 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.html
@@ -1,52 +1,52 @@
-<wicket:extend>
- <div id="main">
- <div wicket:id="mainHead" class="head clearfix">
- <div class="logo pull-left">
- <a wicket:id="home" title="Dashboard"><i class="fa fa-ext fa-gitplex-logo"></i></a>
- </div>
- <div wicket:id="context" class="context pull-left"></div>
- <div class="account pull-right">
- <wicket:enclosure child="login">
- <div class="logged-out">
- <a wicket:id="login">Log in</a>
- <span class="separator">|</span>
- <a wicket:id="register">Sign up</a>
- </div>
- </wicket:enclosure>
- <wicket:enclosure child="user">
- <div class="logged-in">
- <a wicket:id="notification" class="notifications" title="You've got tasks"><i class="fa fa-circle"></i></a>
- <a wicket:id="user" class="current"></a>
- <a wicket:id="userMenuTrigger" class="menu"><i class="fa fa-angle-down"></i></a>
- </div>
- </wicket:enclosure>
- </div>
- <div class="actions pull-right">
- <a wicket:id="createNewDropdown" title="Create new repository or organization"><i class="fa fa-plus"></i> <i class="fa fa-caret-down"></i></a>
- <a wicket:id="organizations" title="Joined organizations"><i class="fa fa-group"></i> <i class="fa fa-caret-down"></i></a>
- <a wicket:id="repositories" title="Accessible repositories"><i class="fa fa-ext fa-repo"></i> <i class="fa fa-caret-down"></i></a>
- <a wicket:id="administration" title="System administration"><i class="fa fa-gear"></i></a>
- </div>
- <div class="search pull-right">
- <input class="form-control input-sm" placeholder="Search..."></input>
- </div>
- </div>
- <div class="body">
- <wicket:child></wicket:child>
- </div>
- <div wicket:id="mainFoot" class="foot clearfix">
- <div class="pull-left">
- <a href="http://www.pmease.com">PMEase GitPlex</a>, 1.0.0, 2013-03-05, Commercial License for Site 'PMEase Inc.'
- </div>
- <div class="pull-right">
- <a href="http://www.pmease.com/support">Support</a> | <a href="http://track.pmease.com">Report Bug or Enhancement</a>
- </div>
- </div>
- </div>
- <wicket:fragment wicket:id="createNewFrag">
- <div class="create-new">
- <a wicket:id="createNewDepot">Create new repository</a>
- <a wicket:id="createNewOrganization">Create new organization</a>
- </div>
- </wicket:fragment>
+<wicket:extend>
+ <div id="main">
+ <div wicket:id="mainHead" class="head clearfix">
+ <div class="logo pull-left">
+ <a wicket:id="home" title="Dashboard"><i class="fa fa-ext fa-gitplex-logo"></i></a>
+ </div>
+ <div wicket:id="context" class="context pull-left"></div>
+ <div class="account pull-right">
+ <wicket:enclosure child="login">
+ <div class="logged-out">
+ <a wicket:id="login">Log in</a>
+ <span class="separator">|</span>
+ <a wicket:id="register">Sign up</a>
+ </div>
+ </wicket:enclosure>
+ <wicket:enclosure child="user">
+ <div class="logged-in">
+ <a wicket:id="notifications" class="notifications" title="You've got notifications"><i class="fa fa-circle"></i></a>
+ <a wicket:id="user" class="current"></a>
+ <a wicket:id="userMenuTrigger" class="menu"><i class="fa fa-angle-down"></i></a>
+ </div>
+ </wicket:enclosure>
+ </div>
+ <div class="actions pull-right">
+ <a wicket:id="createNewDropdown" title="Create new repository or organization"><i class="fa fa-plus"></i> <i class="fa fa-caret-down"></i></a>
+ <a wicket:id="organizations" title="Joined organizations"><i class="fa fa-group"></i> <i class="fa fa-caret-down"></i></a>
+ <a wicket:id="repositories" title="Accessible repositories"><i class="fa fa-ext fa-repo"></i> <i class="fa fa-caret-down"></i></a>
+ <a wicket:id="administration" title="System administration"><i class="fa fa-gear"></i></a>
+ </div>
+ <div class="search pull-right">
+ <input class="form-control input-sm" placeholder="Search..."></input>
+ </div>
+ </div>
+ <div class="body">
+ <wicket:child></wicket:child>
+ </div>
+ <div wicket:id="mainFoot" class="foot clearfix">
+ <div class="pull-left">
+ <a href="http://www.pmease.com">PMEase GitPlex</a>, 1.0.0, 2013-03-05, Commercial License for Site 'PMEase Inc.'
+ </div>
+ <div class="pull-right">
+ <a href="http://www.pmease.com/support">Support</a> | <a href="http://track.pmease.com">Report Bug or Enhancement</a>
+ </div>
+ </div>
+ </div>
+ <wicket:fragment wicket:id="createNewFrag">
+ <div class="create-new">
+ <a wicket:id="createNewDepot">Create new repository</a>
+ <a wicket:id="createNewOrganization">Create new organization</a>
+ </div>
+ </wicket:fragment>
</wicket:extend>
\ No newline at end of file
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.java
index bdef8ffa61..152ebc7d62 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/layout/LayoutPage.java
@@ -141,7 +141,7 @@ public abstract class LayoutPage extends BasePage {
head.add(new BookmarkablePageLink<Void>("register", RegisterPage.class).setVisible(!signedIn));
head.add(new BookmarkablePageLink<Void>("logout", LogoutPage.class).setVisible(signedIn));
if (user != null) {
- head.add(new BookmarkablePageLink<Void>("notification",
+ head.add(new BookmarkablePageLink<Void>("notifications",
NotificationListPage.class,
NotificationListPage.paramsOf(user)) {
@@ -153,7 +153,7 @@ public abstract class LayoutPage extends BasePage {
});
} else {
- head.add(new WebMarkupContainer("notification").setVisible(false));
+ head.add(new WebMarkupContainer("notifications").setVisible(false));
}
if (signedIn) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/security/ForgetPage.java b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/security/ForgetPage.java
index eb1c7cd350..7e6bc16d64 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/security/ForgetPage.java
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/security/ForgetPage.java
@@ -71,7 +71,7 @@ public class ForgetPage extends BasePage {
+ "-- Sent by GitPlex",
user.getDisplayName(), user.getName(), password);
- mailManager.sendMailNow(configManager.getMailSetting(), Arrays.asList(user),
+ mailManager.sendMail(configManager.getMailSetting(), Arrays.asList(user),
"Your GitPlex password has been reset", mailBody);
return new TestResult.Successful("Please check your email for the reset password.");
} catch (Exception e) {
diff --git a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
index 795b443f3a..3c1c86ca7a 100644
--- a/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
+++ b/gitplex.web/src/main/java/com/pmease/gitplex/web/page/test/TestPage.html
@@ -1,3 +1,6 @@
<wicket:extend>
- <a wicket:id="test">test</a>
+ <form wicket:id="form">
+ <input wicket:id="name"></input>
+ <input type="submit" wicket:id="submit" value="save"></input>
+ </form>
</wicket:extend>
\ No newline at end of file
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.java
index 61685ea2a9..e81d7a14d4 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,23 +1,31 @@
-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() {
- }
-
- });
- }
-
-}
+package com.pmease.gitplex.web.page.test;
+
+import org.apache.wicket.ajax.AjaxRequestTarget;
+import org.apache.wicket.ajax.markup.html.form.AjaxButton;
+import org.apache.wicket.markup.html.form.Form;
+import org.apache.wicket.markup.html.form.TextField;
+import org.apache.wicket.model.Model;
+
+import com.pmease.gitplex.web.page.base.BasePage;
+
+@SuppressWarnings("serial")
+public class TestPage extends BasePage {
+
+ @Override
+ protected void onInitialize() {
+ super.onInitialize();
+
+ Form<?> form = new Form<Void>("form");
+ form.add(new TextField<String>("name", Model.of("")));
+ form.add(new AjaxButton("submit") {
+
+ @Override
+ protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
+ super.onSubmit(target, form);
+ }
+
+ });
+ add(form);
+ }
+
+}