Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SAK-50720 Lessons include archive XML in CC exports #13070

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public class CCConfig {
private Map<String, CCResourceItem> assignmentMap = new HashMap<>(); // Assignments
private Map<String, CCResourceItem> forumsMap = new HashMap<>(); // Forums
private Map<String, CCResourceItem> bltiMap = new HashMap<>(); // BLTI instances
private Map<String, CCResourceItem> archiveMap = new HashMap<>(); // Archive entries
private Map<String, CCResourceItem> attachMap = new HashMap<>(); // Arrachment entries
private Set<Long> pagesDone = new HashSet<>(); // to prevent pages from being output more than once
private Map<Long, String> embedMap = new HashMap<>(); // Embed codes with fixups done
private Set<CCResourceItem> linkSet = new HashSet<>(); // Links
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,30 @@
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Stack;
import java.util.Optional;
import java.util.zip.ZipEntry;

import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Element;
import org.w3c.dom.Document;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.entity.api.EntityProducer;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.lessonbuildertool.SimplePageItem;
Expand All @@ -48,9 +57,12 @@
import org.sakaiproject.lessonbuildertool.util.ResourceLoaderMessageSource;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.api.TimeService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.user.api.PreferencesService;
import org.sakaiproject.util.Xml;

import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -70,6 +82,9 @@ public class CCExport {
@Setter private SessionManager sessionManager;
@Setter private SimplePageToolDao simplePageToolDao;
@Setter private SiteService siteService;
@Setter private EntityManager entityManager;
@Setter private TimeService timeService;
@Setter private String storagePath;

private ResourceLoaderMessageSource messageSource;

Expand Down Expand Up @@ -133,6 +148,8 @@ public void doExport(HttpServletResponse response, String siteId, String version
setErrKey("simplepage.exportcc-fileerr", e.getMessage(), ccConfig.getLocale());
}

Time now = timeService.newTime();

try (ZipPrintStream out = new ZipPrintStream(response.getOutputStream())) {
out.setLevel(serverConfigurationService.getInt("zip.compression.level", 1));
response.setHeader("Content-disposition", "inline; filename=sakai-export.imscc");
Expand All @@ -144,6 +161,124 @@ public void doExport(HttpServletResponse response, String siteId, String version
outputAllForums(ccConfig, out);
outputAllBlti(ccConfig, out);
outputAllTexts(ccConfig, out);

// common/archive-impl/impl2/src/java/org/sakaiproject/archive/impl/SiteArchiver.java

// this is the folder we are writing files to
// String archiveStorage = storagePath + siteId + "-archive/";
String archiveStorage = serverConfigurationService.getSakaiHomePath() + "archive/" + siteId + "-archive/";

// create the directory for the archive
File dir = new File(archiveStorage);

// clear the directory (if site already archived) so resources are not duplicated
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
log.warn("Could not clear existing archive: {}: {}", dir, e.toString());
}

dir.mkdirs();

// collect all the attachments we need
List attachments = entityManager.newReferenceList();
List<String> exportedLabels = new ArrayList<String>(); // LTI registers two providers
Collection<EntityProducer> producers = entityManager.getEntityProducers();
for (EntityProducer producer : producers) {
if (producer == null) continue;

final String serviceName = producer.getClass().getCanonicalName();
final String serviceLabel = producer.getLabel();

if (!producer.willArchiveMerge()) continue;
if ( exportedLabels.contains(serviceLabel) ) continue;

Document doc = Xml.createDocument();
Stack stack = new Stack();
Element root = doc.createElement("archive");
doc.appendChild(root);
root.setAttribute("source", siteId);

stack.push(root);

try {
String archive = producer.archive(siteId, doc, stack, archiveStorage, attachments);
String xml = Xml.writeDocumentToString(doc);

String zipId = "archive-"+serviceLabel;
String zipName = "sakai_archive/"+serviceLabel+".xml";
ZipEntry archiveEntry = new ZipEntry(zipName);
out.putNextEntry(archiveEntry);
out.print(xml);

String resourceId = ccConfig.getResourceId();
CCResourceItem res = new CCResourceItem(zipId, resourceId, zipName, null, null, null);
ccConfig.getArchiveMap().put(zipId, res);

exportedLabels.add(serviceLabel);

} catch (java.lang.Throwable t) {
String archiveError = "Error archiving "+serviceLabel+" "+serviceName+" "+t.toString();
log.error(archiveError);
t.printStackTrace();
ccConfig.getResults().add(archiveError);
}

}

// TODO: Handle attachments...
System.out.println("attachments="+attachments);
Comment on lines +229 to +230
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove



// archive the collected attachments
if (attachments.size() > 0)
{
Document doc = Xml.createDocument();
Stack stack = new Stack();
Element root = doc.createElement("archive");
doc.appendChild(root);
root.setAttribute("source", siteId);
root.setAttribute("server", serverConfigurationService.getServerId());
root.setAttribute("date", now.toString());
// root.setAttribute("xmlns:sakai", ArchiveService.SAKAI_ARCHIVE_NS);
// root.setAttribute("xmlns:CHEF", ArchiveService.SAKAI_ARCHIVE_NS.concat("CHEF"));
// root.setAttribute("xmlns:DAV", ArchiveService.SAKAI_ARCHIVE_NS.concat("DAV"));

stack.push(root);

ccConfig.getResults().add("<===== Attachments =====>\n");
ccConfig.getResults().add(contentHostingService.archiveResources(attachments, doc, stack, archiveStorage));
ccConfig.getResults().add("<===== End =====>\n\n");

stack.pop();

String xml = Xml.writeDocumentToString(doc);

String zipName = "sakai_archive/attachments.xml";
String zipId = "archive-attachments";
ZipEntry archiveEntry = new ZipEntry(zipName);
out.putNextEntry(archiveEntry);
out.print(xml);

String resourceId = ccConfig.getResourceId();
CCResourceItem res = new CCResourceItem(zipId, resourceId, zipName, null, null, null);
ccConfig.getArchiveMap().put(zipId, res);

addAllAttachments(out, ccConfig, dir, "");


}

// clear the directory since we are done with it
/*
try {
FileUtils.deleteDirectory(dir);
} catch (IOException e) {
log.warn("Could not clear existing archive: {}: {}", dir, e.toString());
}
*/
System.out.println("======= Did not clear ====== "+dir);

outputManifest(ccConfig, out);

ZipEntry zipEntry = new ZipEntry("cc-objects/export-errors.txt");
Expand All @@ -153,6 +288,7 @@ public void doExport(HttpServletResponse response, String siteId, String version
log.error("Lessons export error streaming file, {}", ioe.toString());
setErrKey("simplepage.exportcc-fileerr", ioe.getMessage(), ccConfig.getLocale());
}

}

public boolean addAllFiles(CCConfig ccConfig) {
Expand Down Expand Up @@ -656,6 +792,13 @@ public void outputManifest(CCConfig ccConfig, ZipPrintStream out) {
out.println(" </resource>");
}

for (Map.Entry<String, CCResourceItem> entry : ccConfig.getArchiveMap().entrySet()) {
out.println(" <resource href=\"" + StringEscapeUtils.escapeXml11(entry.getValue().getLocation()) + "\" identifier=\"" + entry.getValue().getResourceId() + "\" type=\"associatedcontent/imscc_xmlv1p1/learning-application-resource\">");
out.println(" <file href=\"" + StringEscapeUtils.escapeXml11(entry.getValue().getLocation()) + "\"/>");
entry.getValue().getDependencies().forEach(d -> out.println(" <dependency identifierref=\"" + d + "\"/>"));
out.println(" </resource>");
}

// add error log at the very end
String errId = ccConfig.getResourceId();

Expand Down Expand Up @@ -717,5 +860,39 @@ public void outputManifest(CCConfig ccConfig, ZipPrintStream out) {
setErrKey("simplepage.exportcc-fileerr", e.getMessage(), ccConfig.getLocale());
}
}

/**
* Creates a zip entry for the path specified with a name built from the base passed in and the file/directory
* name. If the path is a directory, a recursive call is made such that the full directory is added to the zip.
*
* @param zOut The zip file's output stream
* @param path The filesystem path of the file/directory being added
* @param base The base prefix to for the name of the zip file entry
*
* @throws IOException If anything goes wrong
*/
private static void addAllAttachments(ZipPrintStream out, CCConfig ccConfig, File dir, String path) throws IOException {

File[] children = dir.listFiles();
if (children != null) {
for (File child : children) {
if (child.isFile()) {
ZipEntry attachmentEntry = new ZipEntry(path + child.getName());
out.putNextEntry(attachmentEntry);

FileInputStream fInputStream = null;
try {
fInputStream = new FileInputStream(child.getAbsolutePath());
IOUtils.copyLarge(fInputStream, out);
} finally {
IOUtils.closeQuietly(fInputStream);
}
} else {
String newPath = path + child.getName() + "/";
addAllAttachments(out, ccConfig, child, newPath);
}
}
}
}
}

3 changes: 3 additions & 0 deletions lessonbuilder/tool/src/webapp/WEB-INF/applicationContext.xml
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,9 @@ simplePageBean.addForumSummary,
<property name="sessionManager" ref="org.sakaiproject.tool.api.SessionManager"/>
<property name="simplePageToolDao" ref="org.sakaiproject.lessonbuildertool.model.SimplePageToolDao"/>
<property name="siteService" ref="org.sakaiproject.site.api.SiteService"/>
<property name="entityManager" ref="org.sakaiproject.entity.api.EntityManager"/>
<property name="timeService" ref="org.sakaiproject.time.api.TimeService"/>
<property name="storagePath"><value>${sakai.home}archive/</value></property>
</bean>

<bean id="org.sakaiproject.lessonbuildertool.ccexport.CCUtils"
Expand Down
Loading