Skip to content

The Unified and Autonomous Development Platform

Issues move/copy

Robin Shendc2c772a143c
diff --git a/server-core/src/main/java/io/onedev/server/attachment/AttachmentManager.java b/server-core/src/main/java/io/onedev/server/attachment/AttachmentManager.java
index b392a3056c..edc4b1f534 100644
--- a/server-core/src/main/java/io/onedev/server/attachment/AttachmentManager.java
+++ b/server-core/src/main/java/io/onedev/server/attachment/AttachmentManager.java
@@ -11,7 +11,10 @@ public interface AttachmentManager {
File getAttachmentGroupDirLocal(Long projectId, String attachmentGroup);
void moveAttachmentGroupTargetLocal(Long targetProjectId, Long sourceProjectId, String attachmentGroup);
-
+
+ void copyAttachmentGroupTargetLocal(Long targetProjectId, String targetAttachmentGroup,
+ Long sourceProjectId, String sourceAttachmentGroup);
+
String saveAttachment(Long projectId, String attachmentGroup, String suggestedAttachmentName,
InputStream attachmentStream);
diff --git a/server-core/src/main/java/io/onedev/server/attachment/DefaultAttachmentManager.java b/server-core/src/main/java/io/onedev/server/attachment/DefaultAttachmentManager.java
index 05caaf1fbd..ece5a771bf 100644
--- a/server-core/src/main/java/io/onedev/server/attachment/DefaultAttachmentManager.java
+++ b/server-core/src/main/java/io/onedev/server/attachment/DefaultAttachmentManager.java
@@ -128,28 +128,8 @@ public class DefaultAttachmentManager implements AttachmentManager, SchedulableT
}
} else {
FileUtils.createDir(targetGroupDir);
-
- Client client = ClientBuilder.newClient();
- try {
- String fromServerUrl = clusterManager.getServerUrl(sourceStorageServerUUID);
- WebTarget target = client.target(fromServerUrl).path("/~api/cluster/attachments")
- .queryParam("projectId", sourceProjectId)
- .queryParam("attachmentGroup", attachmentGroup);
- Invocation.Builder builder = target.request();
- builder.header(HttpHeaders.AUTHORIZATION,
- KubernetesHelper.BEARER + " " + clusterManager.getCredentialValue());
-
- try (Response response = builder.get()) {
- KubernetesHelper.checkStatus(response);
- try (InputStream is = response.readEntity(InputStream.class)) {
- FileUtils.untar(is, targetGroupDir, false);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
- } finally {
- client.close();
- }
+ downloadAttachments(targetGroupDir, sourceStorageServerUUID,
+ sourceProjectId, attachmentGroup);
projectManager.runOnProjectServer(sourceProjectId, new ClusterTask<Void>() {
@@ -167,6 +147,53 @@ public class DefaultAttachmentManager implements AttachmentManager, SchedulableT
}
}
+ public void copyAttachmentGroupTargetLocal(Long targetProjectId, String targetAttachmentGroup,
+ Long sourceProjectId, String sourceAttachmentGroup) {
+ File targetBaseDir = storageManager.getProjectAttachmentDir(targetProjectId);
+ File targetGroupDir = getPermanentAttachmentGroupDir(targetBaseDir, targetAttachmentGroup);
+
+ UUID sourceStorageServerUUID = projectManager.getStorageServerUUID(sourceProjectId, true);
+ if (sourceStorageServerUUID.equals(clusterManager.getLocalServerUUID())) {
+ File sourceBaseDir = storageManager.getProjectAttachmentDir(sourceProjectId);
+ File sourceGroupDir = getPermanentAttachmentGroupDir(sourceBaseDir, sourceAttachmentGroup);
+ FileUtils.createDir(targetGroupDir.getParentFile());
+ try {
+ FileUtils.copyDirectory(sourceGroupDir, targetGroupDir);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ FileUtils.createDir(targetGroupDir);
+ downloadAttachments(targetGroupDir, sourceStorageServerUUID,
+ sourceProjectId, sourceAttachmentGroup);
+ }
+ }
+
+ private void downloadAttachments(File targetDir, UUID sourceStorageServerUUID,
+ Long sourceProjectId, String sourceAttachmentGroup) {
+ Client client = ClientBuilder.newClient();
+ try {
+ String fromServerUrl = clusterManager.getServerUrl(sourceStorageServerUUID);
+ WebTarget target = client.target(fromServerUrl).path("/~api/cluster/attachments")
+ .queryParam("projectId", sourceProjectId)
+ .queryParam("attachmentGroup", sourceAttachmentGroup);
+ Invocation.Builder builder = target.request();
+ builder.header(HttpHeaders.AUTHORIZATION,
+ KubernetesHelper.BEARER + " " + clusterManager.getCredentialValue());
+
+ try (Response response = builder.get()) {
+ KubernetesHelper.checkStatus(response);
+ try (InputStream is = response.readEntity(InputStream.class)) {
+ FileUtils.untar(is, targetDir, false);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ } finally {
+ client.close();
+ }
+ }
+
private File getPermanentAttachmentGroupDir(File baseAttachmentDir, String attachmentGroup) {
String prefix = attachmentGroup.substring(0, 2);
return new File(baseAttachmentDir, PERMANENT + "/" + prefix + "/" + attachmentGroup);
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/IssueManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/IssueManager.java
index a5cc76f747..d0bc4bdf9e 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/IssueManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/IssueManager.java
@@ -67,7 +67,9 @@ public interface IssueManager extends EntityManager<Issue> {
@Override
void delete(Issue issue);
- void move(Project targetProject, Collection<Issue> issues);
+ void move(Collection<Issue> issues, Project targetProject);
+
+ void copy(Collection<Issue> issues, Project targetProject);
void delete(Collection<Issue> issues);
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
index 905184b0fa..6e76e99e72 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueManager.java
@@ -1,44 +1,8 @@
package io.onedev.server.entitymanager.impl;
-import java.io.ObjectStreamException;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
-import javax.annotation.Nullable;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.persistence.criteria.CriteriaBuilder;
-import javax.persistence.criteria.CriteriaQuery;
-import javax.persistence.criteria.Join;
-import javax.persistence.criteria.JoinType;
-import javax.persistence.criteria.Path;
-import javax.persistence.criteria.Predicate;
-import javax.persistence.criteria.Root;
-import javax.persistence.criteria.Subquery;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.wicket.util.lang.Objects;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.query.Query;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.unbescape.java.JavaEscape;
-
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.hazelcast.core.HazelcastInstance;
-
import edu.emory.mathcs.backport.java.util.Collections;
import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.ExplicitException;
@@ -46,18 +10,7 @@ import io.onedev.server.attachment.AttachmentManager;
import io.onedev.server.cluster.ClusterManager;
import io.onedev.server.cluster.ClusterRunnable;
import io.onedev.server.cluster.ClusterTask;
-import io.onedev.server.entitymanager.IssueAuthorizationManager;
-import io.onedev.server.entitymanager.IssueChangeManager;
-import io.onedev.server.entitymanager.IssueCommentManager;
-import io.onedev.server.entitymanager.IssueFieldManager;
-import io.onedev.server.entitymanager.IssueLinkManager;
-import io.onedev.server.entitymanager.IssueManager;
-import io.onedev.server.entitymanager.IssueQueryPersonalizationManager;
-import io.onedev.server.entitymanager.LinkSpecManager;
-import io.onedev.server.entitymanager.ProjectManager;
-import io.onedev.server.entitymanager.RoleManager;
-import io.onedev.server.entitymanager.SettingManager;
-import io.onedev.server.entitymanager.UserManager;
+import io.onedev.server.entitymanager.*;
import io.onedev.server.entityreference.EntityReferenceManager;
import io.onedev.server.entityreference.ReferenceMigrator;
import io.onedev.server.entityreference.ReferencedFromAware;
@@ -68,17 +21,8 @@ import io.onedev.server.event.project.issue.IssueChanged;
import io.onedev.server.event.project.issue.IssueEvent;
import io.onedev.server.event.project.issue.IssueOpened;
import io.onedev.server.event.system.SystemStarted;
-import io.onedev.server.model.Issue;
-import io.onedev.server.model.IssueAuthorization;
-import io.onedev.server.model.IssueChange;
-import io.onedev.server.model.IssueComment;
-import io.onedev.server.model.IssueField;
-import io.onedev.server.model.IssueQueryPersonalization;
-import io.onedev.server.model.IssueSchedule;
-import io.onedev.server.model.LinkSpec;
-import io.onedev.server.model.Milestone;
-import io.onedev.server.model.Project;
-import io.onedev.server.model.User;
+import io.onedev.server.migration.VersionedXmlDoc;
+import io.onedev.server.model.*;
import io.onedev.server.model.support.LastUpdate;
import io.onedev.server.model.support.administration.GlobalIssueSetting;
import io.onedev.server.model.support.inputspec.choiceinput.choiceprovider.SpecifiedChoices;
@@ -102,17 +46,35 @@ import io.onedev.server.search.entity.issue.IssueQueryParseOption;
import io.onedev.server.search.entity.issue.IssueQueryUpdater;
import io.onedev.server.security.SecurityUtils;
import io.onedev.server.security.permission.AccessProject;
-import io.onedev.server.util.MilestoneAndIssueState;
-import io.onedev.server.util.Pair;
-import io.onedev.server.util.ProjectIssueStats;
-import io.onedev.server.util.ProjectScope;
-import io.onedev.server.util.ProjectScopedNumber;
+import io.onedev.server.util.*;
import io.onedev.server.util.criteria.Criteria;
import io.onedev.server.util.validation.ProjectPathValidator;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldResolution;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldValue;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedFieldValuesResolution;
import io.onedev.server.web.component.issue.workflowreconcile.UndefinedStateResolution;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.tuple.ImmutableTriple;
+import org.apache.commons.lang3.tuple.Triple;
+import org.apache.wicket.util.lang.Objects;
+import org.hibernate.criterion.Order;
+import org.hibernate.criterion.Restrictions;
+import org.hibernate.query.Query;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.unbescape.java.JavaEscape;
+
+import javax.annotation.Nullable;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.persistence.criteria.Path;
+import javax.persistence.criteria.*;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
@Singleton
public class DefaultIssueManager extends BaseEntityManager<Issue> implements IssueManager, Serializable {
@@ -167,19 +129,22 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss
private final IssueChangeManager changeManager;
+ private final IssueScheduleManager scheduleManager;
+
private final SequenceGenerator numberGenerator;
private volatile Map<String, Long> issueIds;
@Inject
- public DefaultIssueManager(Dao dao, IssueFieldManager fieldManager,
- TransactionManager transactionManager, IssueQueryPersonalizationManager queryPersonalizationManager,
- SettingManager settingManager, ListenerRegistry listenerRegistry,
- ProjectManager projectManager, UserManager userManager, ClusterManager clusterManager,
- RoleManager roleManager, AttachmentManager attachmentStorageManager,
- IssueCommentManager commentManager, EntityReferenceManager entityReferenceManager,
- LinkSpecManager linkSpecManager, IssueLinkManager linkManager,
- IssueAuthorizationManager authorizationManager, IssueChangeManager changeManager) {
+ public DefaultIssueManager(Dao dao, IssueFieldManager fieldManager, TransactionManager transactionManager,
+ IssueQueryPersonalizationManager queryPersonalizationManager,
+ SettingManager settingManager, ListenerRegistry listenerRegistry,
+ ProjectManager projectManager, UserManager userManager, ClusterManager clusterManager,
+ RoleManager roleManager, AttachmentManager attachmentStorageManager,
+ IssueCommentManager commentManager, EntityReferenceManager entityReferenceManager,
+ LinkSpecManager linkSpecManager, IssueLinkManager linkManager,
+ IssueAuthorizationManager authorizationManager, IssueChangeManager changeManager,
+ IssueScheduleManager scheduleManager) {
super(dao);
this.fieldManager = fieldManager;
this.queryPersonalizationManager = queryPersonalizationManager;
@@ -197,6 +162,7 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss
this.authorizationManager = authorizationManager;
this.clusterManager = clusterManager;
this.changeManager = changeManager;
+ this.scheduleManager = scheduleManager;
numberGenerator = new SequenceGenerator(Issue.class, clusterManager, dao);
}
@@ -1023,23 +989,154 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss
@Transactional
@Override
- public void move(Project targetProject, Collection<Issue> issues) {
+ public void copy(Collection<Issue> issues, Project targetProject) {
+ List<Issue> sortedIssues = new ArrayList<>(issues);
+ Collections.sort(sortedIssues);
+ Map<Issue, Issue> cloneMapping = new HashMap<>();
+ Map<Long, Long> numberMapping = new HashMap<>();
+ List<Triple<Long, String, String>> attachmentGroupInfos = new ArrayList<>();
+
+ sortedIssues.forEach(issue -> {
+ Issue clonedIssue = VersionedXmlDoc.cloneBean(issue);
+ clonedIssue.setId(null);
+ clonedIssue.setUUID(UUID.randomUUID().toString());
+ clonedIssue.setProject(targetProject);
+ Project numberScope = targetProject.getForkRoot();
+ clonedIssue.setNumberScope(numberScope);
+ clonedIssue.setNumber(getNextNumber(numberScope));
+ cloneMapping.put(issue, clonedIssue);
+ numberMapping.put(issue.getNumber(), clonedIssue.getNumber());
+ attachmentGroupInfos.add(new ImmutableTriple<>(
+ issue.getAttachmentProject().getId(),
+ issue.getAttachmentGroup(),
+ clonedIssue.getAttachmentGroup()));
+ });
+
+ cloneMapping.forEach((key, value) -> {
+ var description = value.getDescription();
+ if (description != null) {
+ description = description.replace(
+ key.getAttachmentProject().getId() + "/attachments/" + key.getAttachmentGroup(),
+ value.getAttachmentProject().getId() + "/attachments/" + value.getAttachmentGroup());
+ description = new ReferenceMigrator(Issue.class, numberMapping)
+ .migratePrefixed(description, "#");
+ value.setDescription(description);
+ }
+ save(value);
+
+ for (IssueSchedule schedule: key.getSchedules()) {
+ if (schedule.getMilestone().getProject().isSelfOrAncestorOf(targetProject)) {
+ IssueSchedule clonedSchedule = VersionedXmlDoc.cloneBean(schedule);
+ clonedSchedule.setId(null);
+ clonedSchedule.setIssue(value);
+ dao.persist(clonedSchedule);
+ }
+ }
+
+ key.getComments().forEach(comment -> {
+ var clonedComment = VersionedXmlDoc.cloneBean(comment);
+ clonedComment.setId(null);
+ clonedComment.setIssue(value);
+ String content = clonedComment.getContent();
+ content = content.replace(
+ key.getAttachmentProject().getId() + "/attachments/" + key.getAttachmentGroup(),
+ value.getAttachmentProject().getId() + "/attachments/" + value.getAttachmentGroup());
+ content = new ReferenceMigrator(Issue.class, numberMapping)
+ .migratePrefixed(content, "#");
+ clonedComment.setContent(content);
+ dao.persist(clonedComment);
+ });
+
+ key.getChanges().forEach(change -> {
+ var clonedChange = VersionedXmlDoc.cloneBean(change);
+ clonedChange.setId(null);
+ clonedChange.setIssue(value);
+ dao.persist(clonedChange);
+ });
+
+ key.getFields().forEach(field -> {
+ var clonedField = VersionedXmlDoc.cloneBean(field);
+ clonedField.setId(null);
+ clonedField.setIssue(value);
+ dao.persist(clonedField);
+ });
+
+ });
+
+ var processedLinks = new HashSet<>();
+ cloneMapping.forEach((key, value) -> {
+ key.getSourceLinks().forEach(link -> {
+ if (processedLinks.add(link)) {
+ var clonedSource = cloneMapping.get(link.getSource());
+ if (clonedSource != null) {
+ var clonedLink = VersionedXmlDoc.cloneBean(link);
+ clonedLink.setId(null);
+ clonedLink.setSource(clonedSource);
+ clonedLink.setTarget(value);
+ dao.persist(clonedLink);
+ }
+ }
+ });
+ key.getTargetLinks().forEach(link -> {
+ if (processedLinks.add(link)) {
+ var clonedTarget = cloneMapping.get(link.getTarget());
+ if (clonedTarget != null) {
+ var clonedLink = VersionedXmlDoc.cloneBean(link);
+ clonedLink.setId(null);
+ clonedLink.setTarget(clonedTarget);
+ clonedLink.setSource(value);
+ dao.persist(clonedLink);
+ }
+ }
+ });
+ });
+
+ Long targetProjectId = targetProject.getId();
+ transactionManager.runAfterCommit(new ClusterRunnable() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public void run() {
+ projectManager.runOnProjectServer(targetProjectId, new ClusterTask<Void>() {
+
+ private static final long serialVersionUID = 1L;
+
+ @Override
+ public Void call() throws Exception {
+ for (var attachmentGroupInfo: attachmentGroupInfos) {
+ attachmentManager.copyAttachmentGroupTargetLocal(targetProjectId,
+ attachmentGroupInfo.getRight(), attachmentGroupInfo.getLeft(),
+ attachmentGroupInfo.getMiddle());
+ }
+ return null;
+ }
+
+ });
+ }
+
+ });
+ }
+
+ @Transactional
+ @Override
+ public void move(Collection<Issue> issues, Project targetProject) {
List<Pair<Long, String>> attachmentGroupInfos = new ArrayList<>();
Map<Long, Long> numberMapping = new HashMap<>();
- List<Issue> issueList = new ArrayList<>(issues);
- Collections.sort(issueList);
- for (Issue issue: issueList) {
+ List<Issue> sortedIssues = new ArrayList<>(issues);
+ Collections.sort(sortedIssues);
+ for (Issue issue: sortedIssues) {
attachmentGroupInfos.add(new Pair<>(issue.getAttachmentProject().getId(), issue.getAttachmentGroup()));
if (issue.getDescription() != null) {
issue.setDescription(issue.getDescription().replace(
- issue.getAttachmentProject().getId() + "/attachment/" + issue.getAttachmentGroup(),
- targetProject.getId() + "/attachment/" + issue.getAttachmentGroup()));
+ issue.getAttachmentProject().getId() + "/attachments/" + issue.getAttachmentGroup(),
+ targetProject.getId() + "/attachments/" + issue.getAttachmentGroup()));
}
for (IssueComment comment: issue.getComments()) {
comment.setContent(comment.getContent().replace(
- issue.getAttachmentProject().getId() + "/attachment/" + issue.getAttachmentGroup(),
- targetProject.getId() + "/attachment/" + issue.getAttachmentGroup()));
+ issue.getAttachmentProject().getId() + "/attachments/" + issue.getAttachmentGroup(),
+ targetProject.getId() + "/attachments/" + issue.getAttachmentGroup()));
}
Project oldProject = issue.getProject();
@@ -1066,7 +1163,7 @@ public class DefaultIssueManager extends BaseEntityManager<Issue> implements Iss
changeManager.save(change);
}
- for (Issue issue: issueList) {
+ for (Issue issue: sortedIssues) {
if (issue.getDescription() != null) {
issue.setDescription(new ReferenceMigrator(Issue.class, numberMapping)
.migratePrefixed(issue.getDescription(), "#"));
diff --git a/server-core/src/main/java/io/onedev/server/migration/VersionedXmlDoc.java b/server-core/src/main/java/io/onedev/server/migration/VersionedXmlDoc.java
index 464613845e..cf4e75b813 100644
--- a/server-core/src/main/java/io/onedev/server/migration/VersionedXmlDoc.java
+++ b/server-core/src/main/java/io/onedev/server/migration/VersionedXmlDoc.java
@@ -1,565 +1,569 @@
-package io.onedev.server.migration;
-
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.io.OutputStream;
-import java.io.StringReader;
-import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
-import java.nio.charset.StandardCharsets;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.annotation.Nullable;
-
-import org.apache.commons.lang3.ObjectUtils;
-import org.apache.commons.lang3.ObjectUtils.Null;
-import org.dom4j.Attribute;
-import org.dom4j.Branch;
-import org.dom4j.Comment;
-import org.dom4j.Document;
-import org.dom4j.DocumentHelper;
-import org.dom4j.DocumentType;
-import org.dom4j.Element;
-import org.dom4j.InvalidXPathException;
-import org.dom4j.Node;
-import org.dom4j.ProcessingInstruction;
-import org.dom4j.QName;
-import org.dom4j.Visitor;
-import org.dom4j.XPath;
-import org.dom4j.io.OutputFormat;
-import org.dom4j.io.SAXReader;
-import org.dom4j.io.XMLWriter;
-import org.hibernate.proxy.HibernateProxyHelper;
-import org.xml.sax.EntityResolver;
-
-import com.google.common.base.Preconditions;
-import com.thoughtworks.xstream.XStream;
-import com.thoughtworks.xstream.core.util.HierarchicalStreams;
-import com.thoughtworks.xstream.io.HierarchicalStreamReader;
-import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
-import com.thoughtworks.xstream.io.xml.Dom4JReader;
-import com.thoughtworks.xstream.io.xml.Dom4JWriter;
-import com.thoughtworks.xstream.mapper.CannotResolveClassException;
-
-import io.onedev.commons.loader.AppLoader;
-import io.onedev.commons.utils.ExceptionUtils;
-import io.onedev.commons.utils.FileUtils;
-import io.onedev.commons.utils.StringUtils;
-
-public final class VersionedXmlDoc implements Document, Externalizable {
-
- private static final long serialVersionUID = 1L;
-
- private static final Pattern SPECIAL_CHARACTERS = Pattern.compile("&#\\d+;");
-
- private transient String xml;
-
- private transient Document wrapped;
-
- public VersionedXmlDoc() {
- wrapped = DocumentHelper.createDocument();
- }
-
- public VersionedXmlDoc(Document wrapped) {
- this.wrapped = Preconditions.checkNotNull(wrapped);
- }
-
- public synchronized void setWrapped(Document wrapped) {
- this.wrapped = Preconditions.checkNotNull(wrapped);
- }
-
- public Document addComment(String comment) {
- return getWrapped().addComment(comment);
- }
-
- public Document addDocType(String name, String publicId, String systemId) {
- return getWrapped().addDocType(name, publicId, systemId);
- }
-
- public Document addProcessingInstruction(String target, String text) {
- return getWrapped().addProcessingInstruction(target, text);
- }
-
- public Document addProcessingInstruction(String target, Map<String, String> data) {
- return getWrapped().addProcessingInstruction(target, data);
- }
-
- public DocumentType getDocType() {
- return getWrapped().getDocType();
- }
-
- public EntityResolver getEntityResolver() {
- return getWrapped().getEntityResolver();
- }
-
- public Element getRootElement() {
- return getWrapped().getRootElement();
- }
-
- public String getXMLEncoding() {
- return getWrapped().getXMLEncoding();
- }
-
- public void setDocType(DocumentType docType) {
- getWrapped().setDocType(docType);
- }
-
- public void setEntityResolver(EntityResolver entityResolver) {
- getWrapped().setEntityResolver(entityResolver);
- }
-
- public void setRootElement(Element rootElement) {
- getWrapped().setRootElement(rootElement);
- }
-
- public void setXMLEncoding(String encoding) {
- getWrapped().setXMLEncoding(encoding);
- }
-
- public void add(Node node) {
- getWrapped().add(node);
- }
-
- public void add(Comment comment) {
- getWrapped().add(comment);
- }
-
- public void add(Element element) {
- getWrapped().add(element);
- }
-
- public void add(ProcessingInstruction pi) {
- getWrapped().add(pi);
- }
-
- public Element addElement(String name) {
- return getWrapped().addElement(name);
- }
-
- public Element addElement(QName qname) {
- return getWrapped().addElement(qname);
- }
-
- public Element addElement(String qualifiedName, String namespaceURI) {
- return getWrapped().addElement(qualifiedName, namespaceURI);
- }
-
- public void appendContent(Branch branch) {
- getWrapped().appendContent(branch);
- }
-
- public void clearContent() {
- getWrapped().clearContent();
- }
-
- public List<Node> content() {
- return getWrapped().content();
- }
-
- public Element elementByID(String elementID) {
- return getWrapped().elementByID(elementID);
- }
-
- public int indexOf(Node node) {
- return getWrapped().indexOf(node);
- }
-
- public Node node(int index) throws IndexOutOfBoundsException {
- return getWrapped().node(index);
- }
-
- public int nodeCount() {
- return getWrapped().nodeCount();
- }
-
- public Iterator<Node> nodeIterator() {
- return getWrapped().nodeIterator();
- }
-
- public void normalize() {
- getWrapped().normalize();
- }
-
- public ProcessingInstruction processingInstruction(String target) {
- return getWrapped().processingInstruction(target);
- }
-
- public List<ProcessingInstruction> processingInstructions() {
- return getWrapped().processingInstructions();
- }
-
- public List<ProcessingInstruction> processingInstructions(String target) {
- return getWrapped().processingInstructions(target);
- }
-
- public boolean remove(Node node) {
- return getWrapped().remove(node);
- }
-
- public boolean remove(Comment comment) {
- return getWrapped().remove(comment);
- }
-
- public boolean remove(Element element) {
- return getWrapped().remove(element);
- }
-
- public boolean remove(ProcessingInstruction pi) {
- return getWrapped().remove(pi);
- }
-
- public boolean removeProcessingInstruction(String target) {
- return getWrapped().removeProcessingInstruction(target);
- }
-
- public void setContent(List<Node> content) {
- getWrapped().setContent(content);
- }
-
- public void setProcessingInstructions(List<ProcessingInstruction> listOfPIs) {
- getWrapped().setProcessingInstructions(listOfPIs);
- }
-
- public void accept(Visitor visitor) {
- getWrapped().accept(visitor);
- }
-
- public String asXML() {
- return getWrapped().asXML();
- }
-
- public Node asXPathResult(Element parent) {
- return getWrapped().asXPathResult(parent);
- }
-
- public XPath createXPath(String xpathExpression)
- throws InvalidXPathException {
- return getWrapped().createXPath(xpathExpression);
- }
-
- public Node detach() {
- return getWrapped().detach();
- }
-
- public Document getDocument() {
- return getWrapped().getDocument();
- }
-
- public String getName() {
- return getWrapped().getName();
- }
-
- public short getNodeType() {
- return getWrapped().getNodeType();
- }
-
- public String getNodeTypeName() {
- return getWrapped().getNodeTypeName();
- }
-
- public Element getParent() {
- return getWrapped().getParent();
- }
-
- public String getPath() {
- return getWrapped().getPath();
- }
-
- public String getPath(Element context) {
- return getWrapped().getPath(context);
- }
-
- public String getStringValue() {
- return getWrapped().getStringValue();
- }
-
- public String getText() {
- return getWrapped().getText();
- }
-
- public String getUniquePath() {
- return getWrapped().getUniquePath();
- }
-
- public String getUniquePath(Element context) {
- return getWrapped().getUniquePath(context);
- }
-
- public boolean hasContent() {
- return getWrapped().hasContent();
- }
-
- public boolean isReadOnly() {
- return getWrapped().isReadOnly();
- }
-
- public boolean matches(String xpathExpression) {
- return getWrapped().matches(xpathExpression);
- }
-
- public Number numberValueOf(String xpathExpression) {
- return getWrapped().numberValueOf(xpathExpression);
- }
-
- public List<Node> selectNodes(String xpathExpression) {
- return getWrapped().selectNodes(xpathExpression);
- }
-
- public List<Node> selectNodes(String xpathExpression,
- String comparisonXPathExpression) {
- return getWrapped().selectNodes(xpathExpression, comparisonXPathExpression);
- }
-
- public List<Node> selectNodes(String xpathExpression,
- String comparisonXPathExpression, boolean removeDuplicates) {
- return getWrapped().selectNodes(xpathExpression, comparisonXPathExpression,
- removeDuplicates);
- }
-
- public Object selectObject(String xpathExpression) {
- return getWrapped().selectObject(xpathExpression);
- }
-
- public Node selectSingleNode(String xpathExpression) {
- return getWrapped().selectSingleNode(xpathExpression);
- }
-
- public void setDocument(Document document) {
- getWrapped().setDocument(document);
- }
-
- public void setName(String name) {
- getWrapped().setName(name);
- }
-
- public void setParent(Element parent) {
- getWrapped().setParent(parent);
- }
-
- public void setText(String text) {
- getWrapped().setText(text);
- }
-
- public boolean supportsParent() {
- return getWrapped().supportsParent();
- }
-
- public String valueOf(String xpathExpression) {
- return getWrapped().valueOf(xpathExpression);
- }
-
- public void write(Writer writer) throws IOException {
- getWrapped().write(writer);
- }
-
- @Override
- public Object clone() {
- return new VersionedXmlDoc((Document) getWrapped().clone());
- }
-
- public String toXML() {
- return toXML(true);
- }
-
- public String toXML(boolean pretty) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
- OutputFormat format = new OutputFormat();
- format.setEncoding(StandardCharsets.UTF_8.name());
- if (pretty) {
- format.setIndent(true);
- format.setIndentSize(4);
- format.setNewlines(true);
- } else {
- format.setIndent(false);
- format.setNewlines(false);
- }
- new XMLWriter(baos, format).write(getWrapped());
- return baos.toString(StandardCharsets.UTF_8.name());
- } catch (Exception e) {
- throw ExceptionUtils.unchecked(e);
- }
- }
-
- public void writeToFile(File file, boolean pretty) {
- try (OutputStream os = new FileOutputStream(file)){
- OutputFormat format = new OutputFormat();
- format.setIndent(pretty);
- format.setNewlines(pretty);
- format.setEncoding(StandardCharsets.UTF_8.name());
- XMLWriter writer = new XMLWriter(os, format);
- writer.write(this);
- } catch (Exception e) {
- throw ExceptionUtils.unchecked(e);
- }
- }
-
- public static VersionedXmlDoc fromXML(String xml) {
- try {
- // remove special characters
- Matcher matcher = SPECIAL_CHARACTERS.matcher(xml);
- StringBuffer buffer = new StringBuffer();
- while (matcher.find())
- matcher.appendReplacement(buffer, "");
- matcher.appendTail(buffer);
-
- return new VersionedXmlDoc(new SAXReader().read(new StringReader(buffer.toString())));
- } catch (Exception e) {
- throw ExceptionUtils.unchecked(e);
- }
- }
-
- public static VersionedXmlDoc fromFile(File file) {
- try {
- return fromXML(FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()));
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- public synchronized Document getWrapped() {
- if (wrapped == null) {
- wrapped = fromXML(Preconditions.checkNotNull(xml)).getWrapped();
- }
- return wrapped;
- }
-
- public static VersionedXmlDoc fromBean(@Nullable Object bean) {
- Document dom = DocumentHelper.createDocument();
- AppLoader.getInstance(XStream.class).marshal(bean, new Dom4JWriter(dom));
- VersionedXmlDoc versionedDom = new VersionedXmlDoc(dom);
- if (bean != null) {
- versionedDom.setVersion(MigrationHelper.getVersion(HibernateProxyHelper.getClassWithoutInitializingProxy(bean)));
- }
- return versionedDom;
- }
-
- /**
- * Convert this document to bean. Migration will performed if necessary.
- * During the migration, content of the document will also get updated
- * to reflect current migration result.
- * @return
- */
- public Object toBean() {
- return toBean(null);
- }
-
- /**
- * Convert this document to bean. Migration will be performed if necessary.
- * During the migration, content of the document will also get updated
- * to reflect current migration result.
- * @return
- */
- @SuppressWarnings("unchecked")
- public <T> T toBean(@Nullable Class<T> beanClass) {
- XStream xstream = AppLoader.getInstance(XStream.class);
- Dom4JReader domReader = new Dom4JReader(this);
- Class<?> origBeanClass;
- try {
- origBeanClass = HierarchicalStreams.readClassType(domReader, xstream.getMapper());
- } catch (CannotResolveClassException e) {
- if (beanClass == null)
- throw e;
- else
- origBeanClass = beanClass;
- }
-
- if (origBeanClass == null)
- return null;
- else if (origBeanClass == Null.class)
- return (T) ObjectUtils.NULL;
-
- if (beanClass == null)
- beanClass = (Class<T>) origBeanClass;
- else
- getRootElement().setName(xstream.getMapper().serializedClass(beanClass));
- if (getVersion() != null) {
- try {
- Object migrator = beanClass.getDeclaredConstructor().newInstance();
- if (MigrationHelper.migrate(getVersion(), migrator, this)) {
- setVersion(MigrationHelper.getVersion(migrator.getClass()));
- Object bean = xstream.unmarshal(domReader);
- return (T) bean;
- } else {
- return (T) xstream.unmarshal(domReader);
- }
- } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
- | InvocationTargetException | NoSuchMethodException | SecurityException e) {
- throw new RuntimeException(e);
- }
- } else {
- return (T) xstream.unmarshal(domReader);
- }
- }
-
- public String getVersion() {
- Preconditions.checkNotNull(getRootElement());
- return getRootElement().attributeValue("revision");
- }
-
- public void setVersion(String version) {
- Preconditions.checkNotNull(getRootElement());
- getRootElement().addAttribute("revision", version);
- }
-
- @Override
- public synchronized void writeExternal(ObjectOutput out) throws IOException {
- if (wrapped != null)
- out.writeObject(toXML(false));
- else
- out.writeObject(xml);
- }
-
- @Override
- public synchronized void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
- xml = Preconditions.checkNotNull((String) in.readObject());
- wrapped = null;
- }
-
- public void marshall(HierarchicalStreamWriter writer) {
- marshallElement(writer, getRootElement());
- }
-
- private void marshallElement(HierarchicalStreamWriter writer, Element element) {
- writer.startNode(element.getName());
- for (Attribute attribute: (List<Attribute>)element.attributes())
- writer.addAttribute(attribute.getName(), attribute.getValue());
- if (element.getText().trim().length() != 0)
- writer.setValue(element.getText().trim());
- for (Element child: (List<Element>)element.elements())
- marshallElement(writer, child);
- writer.endNode();
- }
-
- public static VersionedXmlDoc unmarshall(HierarchicalStreamReader reader) {
- VersionedXmlDoc dom = new VersionedXmlDoc();
- unmarshallElement(reader, dom);
- return dom;
- }
-
- private static void unmarshallElement(HierarchicalStreamReader reader, Branch branch) {
- Element element = branch.addElement(reader.getNodeName());
- for (int i=0; i<reader.getAttributeCount(); i++) {
- String attributeName = reader.getAttributeName(i);
- String attributeValue = reader.getAttribute(i);
- element.addAttribute(attributeName, attributeValue);
- }
- if (StringUtils.isNotBlank(reader.getValue()))
- element.setText(reader.getValue().trim());
- while (reader.hasMoreChildren()) {
- reader.moveDown();
- unmarshallElement(reader, element);
- reader.moveUp();
- }
- }
-
-}
+package io.onedev.server.migration;
+
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.OutputStream;
+import java.io.StringReader;
+import java.io.Writer;
+import java.lang.reflect.InvocationTargetException;
+import java.nio.charset.StandardCharsets;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.annotation.Nullable;
+
+import org.apache.commons.lang3.ObjectUtils;
+import org.apache.commons.lang3.ObjectUtils.Null;
+import org.dom4j.Attribute;
+import org.dom4j.Branch;
+import org.dom4j.Comment;
+import org.dom4j.Document;
+import org.dom4j.DocumentHelper;
+import org.dom4j.DocumentType;
+import org.dom4j.Element;
+import org.dom4j.InvalidXPathException;
+import org.dom4j.Node;
+import org.dom4j.ProcessingInstruction;
+import org.dom4j.QName;
+import org.dom4j.Visitor;
+import org.dom4j.XPath;
+import org.dom4j.io.OutputFormat;
+import org.dom4j.io.SAXReader;
+import org.dom4j.io.XMLWriter;
+import org.hibernate.proxy.HibernateProxyHelper;
+import org.xml.sax.EntityResolver;
+
+import com.google.common.base.Preconditions;
+import com.thoughtworks.xstream.XStream;
+import com.thoughtworks.xstream.core.util.HierarchicalStreams;
+import com.thoughtworks.xstream.io.HierarchicalStreamReader;
+import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
+import com.thoughtworks.xstream.io.xml.Dom4JReader;
+import com.thoughtworks.xstream.io.xml.Dom4JWriter;
+import com.thoughtworks.xstream.mapper.CannotResolveClassException;
+
+import io.onedev.commons.loader.AppLoader;
+import io.onedev.commons.utils.ExceptionUtils;
+import io.onedev.commons.utils.FileUtils;
+import io.onedev.commons.utils.StringUtils;
+
+public final class VersionedXmlDoc implements Document, Externalizable {
+
+ private static final long serialVersionUID = 1L;
+
+ private static final Pattern SPECIAL_CHARACTERS = Pattern.compile("&#\\d+;");
+
+ private transient String xml;
+
+ private transient Document wrapped;
+
+ public VersionedXmlDoc() {
+ wrapped = DocumentHelper.createDocument();
+ }
+
+ public VersionedXmlDoc(Document wrapped) {
+ this.wrapped = Preconditions.checkNotNull(wrapped);
+ }
+
+ public synchronized void setWrapped(Document wrapped) {
+ this.wrapped = Preconditions.checkNotNull(wrapped);
+ }
+
+ public Document addComment(String comment) {
+ return getWrapped().addComment(comment);
+ }
+
+ public Document addDocType(String name, String publicId, String systemId) {
+ return getWrapped().addDocType(name, publicId, systemId);
+ }
+
+ public Document addProcessingInstruction(String target, String text) {
+ return getWrapped().addProcessingInstruction(target, text);
+ }
+
+ public Document addProcessingInstruction(String target, Map<String, String> data) {
+ return getWrapped().addProcessingInstruction(target, data);
+ }
+
+ public DocumentType getDocType() {
+ return getWrapped().getDocType();
+ }
+
+ public EntityResolver getEntityResolver() {
+ return getWrapped().getEntityResolver();
+ }
+
+ public Element getRootElement() {
+ return getWrapped().getRootElement();
+ }
+
+ public String getXMLEncoding() {
+ return getWrapped().getXMLEncoding();
+ }
+
+ public void setDocType(DocumentType docType) {
+ getWrapped().setDocType(docType);
+ }
+
+ public void setEntityResolver(EntityResolver entityResolver) {
+ getWrapped().setEntityResolver(entityResolver);
+ }
+
+ public void setRootElement(Element rootElement) {
+ getWrapped().setRootElement(rootElement);
+ }
+
+ public void setXMLEncoding(String encoding) {
+ getWrapped().setXMLEncoding(encoding);
+ }
+
+ public void add(Node node) {
+ getWrapped().add(node);
+ }
+
+ public void add(Comment comment) {
+ getWrapped().add(comment);
+ }
+
+ public void add(Element element) {
+ getWrapped().add(element);
+ }
+
+ public void add(ProcessingInstruction pi) {
+ getWrapped().add(pi);
+ }
+
+ public Element addElement(String name) {
+ return getWrapped().addElement(name);
+ }
+
+ public Element addElement(QName qname) {
+ return getWrapped().addElement(qname);
+ }
+
+ public Element addElement(String qualifiedName, String namespaceURI) {
+ return getWrapped().addElement(qualifiedName, namespaceURI);
+ }
+
+ public void appendContent(Branch branch) {
+ getWrapped().appendContent(branch);
+ }
+
+ public void clearContent() {
+ getWrapped().clearContent();
+ }
+
+ public List<Node> content() {
+ return getWrapped().content();
+ }
+
+ public Element elementByID(String elementID) {
+ return getWrapped().elementByID(elementID);
+ }
+
+ public int indexOf(Node node) {
+ return getWrapped().indexOf(node);
+ }
+
+ public Node node(int index) throws IndexOutOfBoundsException {
+ return getWrapped().node(index);
+ }
+
+ public int nodeCount() {
+ return getWrapped().nodeCount();
+ }
+
+ public Iterator<Node> nodeIterator() {
+ return getWrapped().nodeIterator();
+ }
+
+ public void normalize() {
+ getWrapped().normalize();
+ }
+
+ public ProcessingInstruction processingInstruction(String target) {
+ return getWrapped().processingInstruction(target);
+ }
+
+ public List<ProcessingInstruction> processingInstructions() {
+ return getWrapped().processingInstructions();
+ }
+
+ public List<ProcessingInstruction> processingInstructions(String target) {
+ return getWrapped().processingInstructions(target);
+ }
+
+ public boolean remove(Node node) {
+ return getWrapped().remove(node);
+ }
+
+ public boolean remove(Comment comment) {
+ return getWrapped().remove(comment);
+ }
+
+ public boolean remove(Element element) {
+ return getWrapped().remove(element);
+ }
+
+ public boolean remove(ProcessingInstruction pi) {
+ return getWrapped().remove(pi);
+ }
+
+ public boolean removeProcessingInstruction(String target) {
+ return getWrapped().removeProcessingInstruction(target);
+ }
+
+ public void setContent(List<Node> content) {
+ getWrapped().setContent(content);
+ }
+
+ public void setProcessingInstructions(List<ProcessingInstruction> listOfPIs) {
+ getWrapped().setProcessingInstructions(listOfPIs);
+ }
+
+ public void accept(Visitor visitor) {
+ getWrapped().accept(visitor);
+ }
+
+ public String asXML() {
+ return getWrapped().asXML();
+ }
+
+ public Node asXPathResult(Element parent) {
+ return getWrapped().asXPathResult(parent);
+ }
+
+ public XPath createXPath(String xpathExpression)
+ throws InvalidXPathException {
+ return getWrapped().createXPath(xpathExpression);
+ }
+
+ public Node detach() {
+ return getWrapped().detach();
+ }
+
+ public Document getDocument() {
+ return getWrapped().getDocument();
+ }
+
+ public String getName() {
+ return getWrapped().getName();
+ }
+
+ public short getNodeType() {
+ return getWrapped().getNodeType();
+ }
+
+ public String getNodeTypeName() {
+ return getWrapped().getNodeTypeName();
+ }
+
+ public Element getParent() {
+ return getWrapped().getParent();
+ }
+
+ public String getPath() {
+ return getWrapped().getPath();
+ }
+
+ public String getPath(Element context) {
+ return getWrapped().getPath(context);
+ }
+
+ public String getStringValue() {
+ return getWrapped().getStringValue();
+ }
+
+ public String getText() {
+ return getWrapped().getText();
+ }
+
+ public String getUniquePath() {
+ return getWrapped().getUniquePath();
+ }
+
+ public String getUniquePath(Element context) {
+ return getWrapped().getUniquePath(context);
+ }
+
+ public boolean hasContent() {
+ return getWrapped().hasContent();
+ }
+
+ public boolean isReadOnly() {
+ return getWrapped().isReadOnly();
+ }
+
+ public boolean matches(String xpathExpression) {
+ return getWrapped().matches(xpathExpression);
+ }
+
+ public Number numberValueOf(String xpathExpression) {
+ return getWrapped().numberValueOf(xpathExpression);
+ }
+
+ public List<Node> selectNodes(String xpathExpression) {
+ return getWrapped().selectNodes(xpathExpression);
+ }
+
+ public List<Node> selectNodes(String xpathExpression,
+ String comparisonXPathExpression) {
+ return getWrapped().selectNodes(xpathExpression, comparisonXPathExpression);
+ }
+
+ public List<Node> selectNodes(String xpathExpression,
+ String comparisonXPathExpression, boolean removeDuplicates) {
+ return getWrapped().selectNodes(xpathExpression, comparisonXPathExpression,
+ removeDuplicates);
+ }
+
+ public Object selectObject(String xpathExpression) {
+ return getWrapped().selectObject(xpathExpression);
+ }
+
+ public Node selectSingleNode(String xpathExpression) {
+ return getWrapped().selectSingleNode(xpathExpression);
+ }
+
+ public void setDocument(Document document) {
+ getWrapped().setDocument(document);
+ }
+
+ public void setName(String name) {
+ getWrapped().setName(name);
+ }
+
+ public void setParent(Element parent) {
+ getWrapped().setParent(parent);
+ }
+
+ public void setText(String text) {
+ getWrapped().setText(text);
+ }
+
+ public boolean supportsParent() {
+ return getWrapped().supportsParent();
+ }
+
+ public String valueOf(String xpathExpression) {
+ return getWrapped().valueOf(xpathExpression);
+ }
+
+ public void write(Writer writer) throws IOException {
+ getWrapped().write(writer);
+ }
+
+ @Override
+ public Object clone() {
+ return new VersionedXmlDoc((Document) getWrapped().clone());
+ }
+
+ public String toXML() {
+ return toXML(true);
+ }
+
+ public String toXML(boolean pretty) {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try {
+ OutputFormat format = new OutputFormat();
+ format.setEncoding(StandardCharsets.UTF_8.name());
+ if (pretty) {
+ format.setIndent(true);
+ format.setIndentSize(4);
+ format.setNewlines(true);
+ } else {
+ format.setIndent(false);
+ format.setNewlines(false);
+ }
+ new XMLWriter(baos, format).write(getWrapped());
+ return baos.toString(StandardCharsets.UTF_8.name());
+ } catch (Exception e) {
+ throw ExceptionUtils.unchecked(e);
+ }
+ }
+
+ public void writeToFile(File file, boolean pretty) {
+ try (OutputStream os = new FileOutputStream(file)){
+ OutputFormat format = new OutputFormat();
+ format.setIndent(pretty);
+ format.setNewlines(pretty);
+ format.setEncoding(StandardCharsets.UTF_8.name());
+ XMLWriter writer = new XMLWriter(os, format);
+ writer.write(this);
+ } catch (Exception e) {
+ throw ExceptionUtils.unchecked(e);
+ }
+ }
+
+ public static VersionedXmlDoc fromXML(String xml) {
+ try {
+ // remove special characters
+ Matcher matcher = SPECIAL_CHARACTERS.matcher(xml);
+ StringBuffer buffer = new StringBuffer();
+ while (matcher.find())
+ matcher.appendReplacement(buffer, "");
+ matcher.appendTail(buffer);
+
+ return new VersionedXmlDoc(new SAXReader().read(new StringReader(buffer.toString())));
+ } catch (Exception e) {
+ throw ExceptionUtils.unchecked(e);
+ }
+ }
+
+ public static VersionedXmlDoc fromFile(File file) {
+ try {
+ return fromXML(FileUtils.readFileToString(file, StandardCharsets.UTF_8.name()));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public synchronized Document getWrapped() {
+ if (wrapped == null) {
+ wrapped = fromXML(Preconditions.checkNotNull(xml)).getWrapped();
+ }
+ return wrapped;
+ }
+
+ public static VersionedXmlDoc fromBean(@Nullable Object bean) {
+ Document dom = DocumentHelper.createDocument();
+ AppLoader.getInstance(XStream.class).marshal(bean, new Dom4JWriter(dom));
+ VersionedXmlDoc versionedDom = new VersionedXmlDoc(dom);
+ if (bean != null) {
+ versionedDom.setVersion(MigrationHelper.getVersion(HibernateProxyHelper.getClassWithoutInitializingProxy(bean)));
+ }
+ return versionedDom;
+ }
+
+ /**
+ * Convert this document to bean. Migration will performed if necessary.
+ * During the migration, content of the document will also get updated
+ * to reflect current migration result.
+ * @return
+ */
+ public Object toBean() {
+ return toBean(null);
+ }
+
+ /**
+ * Convert this document to bean. Migration will be performed if necessary.
+ * During the migration, content of the document will also get updated
+ * to reflect current migration result.
+ * @return
+ */
+ @SuppressWarnings("unchecked")
+ public <T> T toBean(@Nullable Class<T> beanClass) {
+ XStream xstream = AppLoader.getInstance(XStream.class);
+ Dom4JReader domReader = new Dom4JReader(this);
+ Class<?> origBeanClass;
+ try {
+ origBeanClass = HierarchicalStreams.readClassType(domReader, xstream.getMapper());
+ } catch (CannotResolveClassException e) {
+ if (beanClass == null)
+ throw e;
+ else
+ origBeanClass = beanClass;
+ }
+
+ if (origBeanClass == null)
+ return null;
+ else if (origBeanClass == Null.class)
+ return (T) ObjectUtils.NULL;
+
+ if (beanClass == null)
+ beanClass = (Class<T>) origBeanClass;
+ else
+ getRootElement().setName(xstream.getMapper().serializedClass(beanClass));
+ if (getVersion() != null) {
+ try {
+ Object migrator = beanClass.getDeclaredConstructor().newInstance();
+ if (MigrationHelper.migrate(getVersion(), migrator, this)) {
+ setVersion(MigrationHelper.getVersion(migrator.getClass()));
+ Object bean = xstream.unmarshal(domReader);
+ return (T) bean;
+ } else {
+ return (T) xstream.unmarshal(domReader);
+ }
+ } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
+ | InvocationTargetException | NoSuchMethodException | SecurityException e) {
+ throw new RuntimeException(e);
+ }
+ } else {
+ return (T) xstream.unmarshal(domReader);
+ }
+ }
+
+ public String getVersion() {
+ Preconditions.checkNotNull(getRootElement());
+ return getRootElement().attributeValue("revision");
+ }
+
+ public void setVersion(String version) {
+ Preconditions.checkNotNull(getRootElement());
+ getRootElement().addAttribute("revision", version);
+ }
+
+ @Override
+ public synchronized void writeExternal(ObjectOutput out) throws IOException {
+ if (wrapped != null)
+ out.writeObject(toXML(false));
+ else
+ out.writeObject(xml);
+ }
+
+ @Override
+ public synchronized void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ xml = Preconditions.checkNotNull((String) in.readObject());
+ wrapped = null;
+ }
+
+ public void marshall(HierarchicalStreamWriter writer) {
+ marshallElement(writer, getRootElement());
+ }
+
+ private void marshallElement(HierarchicalStreamWriter writer, Element element) {
+ writer.startNode(element.getName());
+ for (Attribute attribute: (List<Attribute>)element.attributes())
+ writer.addAttribute(attribute.getName(), attribute.getValue());
+ if (element.getText().trim().length() != 0)
+ writer.setValue(element.getText().trim());
+ for (Element child: (List<Element>)element.elements())
+ marshallElement(writer, child);
+ writer.endNode();
+ }
+
+ public static VersionedXmlDoc unmarshall(HierarchicalStreamReader reader) {
+ VersionedXmlDoc dom = new VersionedXmlDoc();
+ unmarshallElement(reader, dom);
+ return dom;
+ }
+
+ private static void unmarshallElement(HierarchicalStreamReader reader, Branch branch) {
+ Element element = branch.addElement(reader.getNodeName());
+ for (int i=0; i<reader.getAttributeCount(); i++) {
+ String attributeName = reader.getAttributeName(i);
+ String attributeValue = reader.getAttribute(i);
+ element.addAttribute(attributeName, attributeValue);
+ }
+ if (StringUtils.isNotBlank(reader.getValue()))
+ element.setText(reader.getValue().trim());
+ while (reader.hasMoreChildren()) {
+ reader.moveDown();
+ unmarshallElement(reader, element);
+ reader.moveUp();
+ }
+ }
+
+ public static <T> T cloneBean(T bean) {
+ return (T) VersionedXmlDoc.fromBean(bean).toBean();
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/model/AbstractEntity.java b/server-core/src/main/java/io/onedev/server/model/AbstractEntity.java
index 43ca3add5d..1913662bd1 100644
--- a/server-core/src/main/java/io/onedev/server/model/AbstractEntity.java
+++ b/server-core/src/main/java/io/onedev/server/model/AbstractEntity.java
@@ -1,24 +1,21 @@
package io.onedev.server.model;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-
-import javax.annotation.Nullable;
-import javax.persistence.GeneratedValue;
-import javax.persistence.Id;
-import javax.persistence.MappedSuperclass;
-
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import io.onedev.server.model.support.EntityWatch;
+import io.onedev.server.rest.annotation.Api;
+import io.onedev.server.util.facade.EntityFacade;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.proxy.HibernateProxy;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.onedev.server.model.support.EntityWatch;
-import io.onedev.server.rest.annotation.Api;
-import io.onedev.server.util.facade.EntityFacade;
+import javax.annotation.Nullable;
+import javax.persistence.GeneratedValue;
+import javax.persistence.Id;
+import javax.persistence.MappedSuperclass;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
@MappedSuperclass
@JsonIgnoreProperties("handler")
@@ -148,5 +145,5 @@ public abstract class AbstractEntity implements Serializable, Comparable<Abstrac
public EntityFacade getFacade() {
return null;
}
-
+
}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/persistence/dao/Dao.java b/server-core/src/main/java/io/onedev/server/persistence/dao/Dao.java
index a091e737e2..464841538e 100644
--- a/server-core/src/main/java/io/onedev/server/persistence/dao/Dao.java
+++ b/server-core/src/main/java/io/onedev/server/persistence/dao/Dao.java
@@ -88,8 +88,6 @@ public interface Dao {
/**
* This method expects to lookup a single entity with specified criteria
*
- * @param detachedCriteria
- * Hibernate {@link DetachedCriteria}
* @return
* the first matching entity, or null if not found
*/
@@ -106,4 +104,5 @@ public interface Dao {
SessionManager getSessionManager();
Session getSession();
+
}
diff --git a/server-core/src/main/java/io/onedev/server/persistence/dao/EntityManager.java b/server-core/src/main/java/io/onedev/server/persistence/dao/EntityManager.java
index 01042cc566..8340befb86 100644
--- a/server-core/src/main/java/io/onedev/server/persistence/dao/EntityManager.java
+++ b/server-core/src/main/java/io/onedev/server/persistence/dao/EntityManager.java
@@ -84,8 +84,7 @@ public interface EntityManager<T extends AbstractEntity> {
/**
* This method expects to lookup a single entity with specified criteria
*
- * @param detachedCriteria
- * Hibernate {@link DetachedCriteria}
+ * @param entityCriteria
* @return
* the first matching entity, or null if not found
*/
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
index f2a55f4501..48e6a74d24 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
@@ -13,6 +13,7 @@ import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.Component;
+import org.apache.wicket.Session;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
@@ -663,7 +664,7 @@ public abstract class IssueListPanel extends Panel {
@Override
protected List<Project> load() {
- return getTargetProjects();
+ return getTargetProjects(true);
}
}) {
@@ -685,9 +686,10 @@ public abstract class IssueListPanel extends Panel {
Collection<Issue> issues = new ArrayList<>();
for (IModel<Issue> each: selectionColumn.getSelections())
issues.add(each.getObject());
- OneDev.getInstance(IssueManager.class).move(getTargetProject(), issues);
- selectionColumn.getSelections().clear();
- target.add(body);
+ OneDev.getInstance(IssueManager.class).move(issues, getTargetProject());
+ setResponsePage(ProjectIssueListPage.class,
+ ProjectIssueListPage.paramsOf(getTargetProject(), null, 0));
+ Session.get().success("Issues moved");
}
@Override
@@ -726,6 +728,88 @@ public abstract class IssueListPanel extends Panel {
}
});
+
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getLabel() {
+ return "Copy Selected Issues To...";
+ }
+
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
+
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new ProjectSelector(id, new LoadableDetachableModel<List<Project>>() {
+
+ @Override
+ protected List<Project> load() {
+ return getTargetProjects(false);
+ }
+
+ }) {
+
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Project project) {
+ dropdown.close();
+ dropdown2.close();
+
+ Long projectId = project.getId();
+ new ConfirmModalPanel(target) {
+
+ private Project getTargetProject() {
+ return OneDev.getInstance(ProjectManager.class).load(projectId);
+ }
+
+ @Override
+ protected void onConfirm(AjaxRequestTarget target) {
+ Collection<Issue> issues = new ArrayList<>();
+ for (IModel<Issue> each: selectionColumn.getSelections())
+ issues.add(each.getObject());
+ OneDev.getInstance(IssueManager.class).copy(issues, getTargetProject());
+ setResponsePage(ProjectIssueListPage.class,
+ ProjectIssueListPage.paramsOf(getTargetProject(), null, 0));
+ Session.get().success("Issues copied");
+ }
+
+ @Override
+ protected String getConfirmMessage() {
+ return "Type <code>yes</code> below to copy selected issues to project '" + getTargetProject() + "'";
+ }
+
+ @Override
+ protected String getConfirmInput() {
+ return "yes";
+ }
+
+ };
+ }
+
+ }.add(AttributeAppender.append("class", "no-current"));
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(!selectionColumn.getSelections().isEmpty());
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "Please select issues to copy");
+ }
+ }
+
+ };
+ }
+
+ });
menuItems.add(new MenuItem() {
@@ -881,7 +965,7 @@ public abstract class IssueListPanel extends Panel {
@Override
protected List<Project> load() {
- return getTargetProjects();
+ return getTargetProjects(true);
}
}) {
@@ -905,10 +989,10 @@ public abstract class IssueListPanel extends Panel {
for (Iterator<Issue> it = (Iterator<Issue>) dataProvider.iterator(0, issuesTable.getItemCount()); it.hasNext();) {
issues.add(it.next());
}
- OneDev.getInstance(IssueManager.class).move(getTargetProject(), issues);
- dataProvider.detach();
- selectionColumn.getSelections().clear();
- target.add(body);
+ OneDev.getInstance(IssueManager.class).move(issues, getTargetProject());
+ setResponsePage(ProjectIssueListPage.class,
+ ProjectIssueListPage.paramsOf(getTargetProject(), null, 0));
+ Session.get().success("Issues moved");
}
@Override
@@ -947,7 +1031,91 @@ public abstract class IssueListPanel extends Panel {
}
});
-
+
+ menuItems.add(new MenuItem() {
+
+ @Override
+ public String getLabel() {
+ return "Copy All Queried Issues To...";
+ }
+
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
+
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new ProjectSelector(id, new LoadableDetachableModel<List<Project>>() {
+
+ @Override
+ protected List<Project> load() {
+ return getTargetProjects(false);
+ }
+
+ }) {
+
+ @SuppressWarnings("unchecked")
+ @Override
+ protected void onSelect(AjaxRequestTarget target, Project project) {
+ dropdown.close();
+ dropdown2.close();
+
+ Long projectId = project.getId();
+ new ConfirmModalPanel(target) {
+
+ private Project getTargetProject() {
+ return OneDev.getInstance(ProjectManager.class).load(projectId);
+ }
+
+ @Override
+ protected void onConfirm(AjaxRequestTarget target) {
+ Collection<Issue> issues = new ArrayList<>();
+ for (Iterator<Issue> it = (Iterator<Issue>) dataProvider.iterator(0, issuesTable.getItemCount()); it.hasNext();) {
+ issues.add(it.next());
+ }
+ OneDev.getInstance(IssueManager.class).copy(issues, getTargetProject());
+ setResponsePage(ProjectIssueListPage.class,
+ ProjectIssueListPage.paramsOf(getTargetProject(), null, 0));
+ Session.get().success("Issues copied");
+ }
+
+ @Override
+ protected String getConfirmMessage() {
+ return "Type <code>yes</code> below to copy all queried issues to project '" + getTargetProject() + "'";
+ }
+
+ @Override
+ protected String getConfirmInput() {
+ return "yes";
+ }
+
+ };
+ }
+
+ }.add(AttributeAppender.append("class", "no-current"));
+ }
+
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(issuesTable.getItemCount() != 0);
+ }
+
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "No issues to copy");
+ }
+ }
+
+ };
+ }
+
+ });
+
menuItems.add(new MenuItem() {
@Override
@@ -1014,7 +1182,7 @@ public abstract class IssueListPanel extends Panel {
return menuItems;
}
- private List<Project> getTargetProjects() {
+ private List<Project> getTargetProjects(boolean excludeCurrent) {
Collection<Project> collection = getProjectManger().getPermittedProjects(new AccessProject());
ProjectCache cache = getProjectManger().cloneCache();
@@ -1026,7 +1194,9 @@ public abstract class IssueListPanel extends Panel {
}
});
- collection.remove(getProject());
+
+ if (excludeCurrent)
+ collection.remove(getProject());
List<Project> list = new ArrayList<>(collection);
list.sort(cache.comparingPath());