use of fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial in project muikku by otavanopisto.
the class WorkspaceBinaryMaterialServlet method process.
private void process(HttpServletRequest request, HttpServletResponse response, boolean serveContent) throws ServletException, IOException {
String workspaceUrl = request.getParameter("workspaceUrlName");
String materialPath = request.getParameter("workspaceMaterialUrlName");
WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityByUrlName(workspaceUrl);
if (workspaceEntity == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.findWorkspaceMaterialByWorkspaceEntityAndPath(workspaceEntity, materialPath);
if (workspaceMaterial == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Material material = workspaceMaterialController.getMaterialForWorkspaceMaterial(workspaceMaterial);
int materialSize = material instanceof BinaryMaterial ? ((BinaryMaterial) material).getContent().length : material instanceof HtmlMaterial ? ((HtmlMaterial) material).getHtml().length() : 0;
String eTag = DigestUtils.md5Hex(material.getTitle() + ':' + material.getId() + ':' + materialSize + ':' + material.getVersion());
response.setHeader("ETag", eTag);
String ifNoneMatch = request.getHeader("If-None-Match");
if (!StringUtils.equals(ifNoneMatch, eTag)) {
response.setStatus(HttpServletResponse.SC_OK);
if (material instanceof BinaryMaterial) {
BinaryMaterial binaryMaterial = (BinaryMaterial) material;
byte[] data = binaryMaterial.getContent();
// Byte range support
List<Range> ranges = new ArrayList<Range>();
String range = request.getHeader("Range");
if (range != null) {
if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
response.setHeader("Content-Range", "bytes */" + data.length);
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
for (String part : range.substring(6).split(",")) {
String startStr = StringUtils.substringBefore(part, "-");
String endStr = StringUtils.substringAfter(part, "-");
int start = NumberUtils.isDigits(startStr) ? NumberUtils.toInt(startStr) : -1;
int end = NumberUtils.isDigits(endStr) ? NumberUtils.toInt(endStr) : -1;
if (start == -1) {
start = data.length - end;
end = data.length - 1;
} else if (end == -1 || end > data.length - 1) {
end = data.length - 1;
}
if (start > end) {
response.setHeader("Content-Range", "bytes */" + data.length);
response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
return;
}
ranges.add(new Range(start, end, data.length));
}
}
response.setHeader("Accept-Ranges", "bytes");
response.setContentType(binaryMaterial.getContentType());
try {
if (ranges.isEmpty()) {
// Entire file
if (serveContent) {
response.setHeader("Content-Length", String.valueOf(data.length));
response.getOutputStream().write(data);
}
} else if (ranges.size() == 1) {
// Single byte range
Range r = ranges.get(0);
response.setHeader("Content-Range", String.format("bytes %d-%d/%d", r.start, r.end, r.total));
response.setHeader("Content-Length", String.valueOf(r.length));
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (serveContent) {
response.getOutputStream().write(data, r.start, r.length);
}
} else {
// Multiple byte ranges
response.setContentType("multipart/byteranges; boundary=MULTIPART_BYTERANGES");
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
if (serveContent) {
for (Range r : ranges) {
response.getOutputStream().println();
response.getOutputStream().println("--MULTIPART_BYTERANGES");
response.getOutputStream().println(String.format("Content-Type: %s", binaryMaterial.getContentType()));
response.getOutputStream().println(String.format("Content-Range: bytes %d-%d/%d", r.start, r.end, r.total));
response.getOutputStream().write(data, r.start, r.length);
}
response.getOutputStream().println();
response.getOutputStream().println("--MULTIPART_BYTERANGES--");
}
}
} finally {
response.getOutputStream().flush();
}
} else if (material instanceof HtmlMaterial) {
HtmlMaterial htmlMaterial = (HtmlMaterial) material;
byte[] data = htmlMaterial.getHtml().getBytes("UTF-8");
response.setContentLength(data.length);
response.setContentType("text/html; charset=UTF-8");
try {
response.getOutputStream().write(data);
} finally {
response.getOutputStream().flush();
}
}
} else {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
}
}
use of fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial in project muikku by otavanopisto.
the class TaskBase64Image method cleanElement.
@Override
protected void cleanElement(Element element) {
if ("img".equals(element.getTagName())) {
String src = element.getAttribute("src");
if (StringUtils.startsWith(src, "data:") && StringUtils.contains(src, ";base64,")) {
logger.info("Converting base64 image");
try {
String contentType = StringUtils.substringBetween(src, "data:", ";base64,");
byte[] data = Base64.decodeBase64(StringUtils.substringAfter(src, ";base64,"));
String prefix = null;
if (StringUtils.contains(contentType, "jpg") || StringUtils.contains(contentType, "jpeg")) {
prefix = "jpg";
} else if (StringUtils.contains(contentType, "gif")) {
prefix = "gif";
} else if (StringUtils.contains(contentType, "png")) {
prefix = "png";
} else {
logger.log(Level.WARNING, String.format("Image of content type %s prefixed as %s", contentType, prefix));
}
String name = prefix == null ? String.format("img%s", StringUtils.leftPad(++imageCounter + "", 3, '0')) : String.format("img%s.%s", StringUtils.leftPad(++imageCounter + "", 3, '0'), prefix);
String license = null;
BinaryMaterial material = binaryMaterialController.createBinaryMaterial(name, contentType, data, license);
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.createWorkspaceMaterial(getWorkspaceMaterial(), material);
String workspaceUrl = StringUtils.prependIfMissing(workspaceMaterialController.getCompletePath(workspaceMaterial), "/");
logger.info(String.format("Image converted to %s", workspaceUrl));
element.setAttribute("src", workspaceUrl);
markModified();
} catch (Exception e) {
logger.log(Level.SEVERE, String.format("Failed to fix image from %s", src), e);
}
}
}
}
use of fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial in project muikku by otavanopisto.
the class TaskM2Image method cleanElement.
@Override
protected void cleanElement(Element element) {
boolean needsModify = false;
if ("img".equals(element.getTagName())) {
String src = element.getAttribute("src");
if (StringUtils.startsWith(src, "https://muikku.otavanopisto.fi/fi")) {
needsModify = true;
} else if (StringUtils.startsWith(src, "http://muikku.otavanopisto.fi/fi")) {
needsModify = true;
} else if (StringUtils.startsWith(src, "muikku.otavanopisto.fi/fi")) {
src = "http://" + src;
needsModify = true;
}
if (needsModify) {
try {
logger.info(String.format("Fixing image from %s", src));
String m2Url = pluginSettingsController.getPluginSetting("deus-nex-machina", "m2.url");
String m2User = pluginSettingsController.getPluginSetting("deus-nex-machina", "m2.user");
String m2Pass = pluginSettingsController.getPluginSetting("deus-nex-machina", "m2.pass");
String m2Auth = pluginSettingsController.getPluginSetting("deus-nex-machina", "m2.auth");
String cookie = null;
URL authUrl = new URL(String.format("%s?u=%s&p=%s&c=%s", m2Url, m2User, m2Pass, m2Auth));
URLConnection authUrlConnection = authUrl.openConnection();
authUrlConnection.connect();
try {
String headerName = null;
for (int i = 1; (headerName = authUrlConnection.getHeaderFieldKey(i)) != null; i++) {
if (StringUtils.equals(headerName, "Set-Cookie")) {
if (StringUtils.contains(authUrlConnection.getHeaderField(i), "IxAuth")) {
cookie = authUrlConnection.getHeaderField(i);
break;
}
}
}
if (cookie != null) {
URL imgUrl = new URL(src);
URLConnection imgUrlConnection = imgUrl.openConnection();
imgUrlConnection.setRequestProperty("Cookie", cookie);
imgUrlConnection.connect();
String contentType = imgUrlConnection.getContentType();
if (StringUtils.startsWith(contentType, "image/")) {
String prefix = null;
if (StringUtils.contains(contentType, "jpg") || StringUtils.contains(contentType, "jpeg")) {
prefix = "jpg";
} else if (StringUtils.contains(contentType, "gif")) {
prefix = "gif";
} else if (StringUtils.contains(contentType, "png")) {
prefix = "png";
} else {
prefix = StringUtils.substringAfter(contentType, "image/");
logger.log(Level.WARNING, String.format("Image of content type %s prefixed as %s", contentType, prefix));
}
InputStream is = imgUrlConnection.getInputStream();
byte[] data = {};
try {
data = IOUtils.toByteArray(is);
} finally {
is.close();
}
String name = String.format("img%s.%s", StringUtils.leftPad(++imageCounter + "", 3, '0'), prefix);
String license = null;
BinaryMaterial material = binaryMaterialController.createBinaryMaterial(name, contentType, data, license);
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.createWorkspaceMaterial(getWorkspaceMaterial(), material);
String workspaceUrl = StringUtils.prependIfMissing(workspaceMaterialController.getCompletePath(workspaceMaterial), "/");
logger.info(String.format("Image converted to %s", workspaceUrl));
element.setAttribute("src", workspaceUrl);
markModified();
} else {
logger.log(Level.SEVERE, String.format("Skipping image due to questionable content type %s", contentType));
}
} else {
logger.log(Level.SEVERE, "Cookie get fail");
}
} finally {
URL logoutUrl = new URL(String.format("%s", m2Url));
URLConnection logoutUrlConnection = logoutUrl.openConnection();
logoutUrlConnection.connect();
}
} catch (Exception e) {
logger.log(Level.SEVERE, String.format("Failed to fix image from %s", src), e);
}
}
}
}
use of fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial in project muikku by otavanopisto.
the class WorkspaceMaterialUploadBackingBean method upload.
public String upload() {
ObjectMapper objectMapper = new ObjectMapper();
if (!sessionController.isLoggedIn()) {
return "/error/internal-error.jsf";
}
// Workspace
WorkspaceEntity workspaceEntity = workspaceController.findWorkspaceEntityById(workspaceEntityId);
if (workspaceEntity == null) {
return "/error/internal-error.jsf";
}
WorkspaceUserEntity workspaceUserEntity = workspaceUserEntityController.findWorkspaceUserEntityByWorkspaceAndUserIdentifier(workspaceEntity, sessionController.getLoggedUser());
if (workspaceUserEntity == null || workspaceUserEntity.getWorkspaceUserRole() == null || workspaceUserEntity.getWorkspaceUserRole().getArchetype() != WorkspaceRoleArchetype.TEACHER) {
return "/error/internal-error.jsf";
}
WorkspaceNode parent = null;
if (getFolderId() != null) {
WorkspaceFolder workspaceFolder = workspaceMaterialController.findWorkspaceFolderById(getFolderId());
if (workspaceFolder == null) {
return "/error/internal-error.jsf";
}
WorkspaceRootFolder workspaceRootFolder = workspaceMaterialController.findWorkspaceRootFolderByWorkspaceNode(workspaceFolder);
if (workspaceRootFolder == null) {
return "/error/internal-error.jsf";
}
if (!workspaceRootFolder.getWorkspaceEntityId().equals(workspaceEntityId)) {
return "/error/internal-error.jsf";
}
} else {
parent = workspaceMaterialController.findWorkspaceRootFolderByWorkspaceEntity(workspaceEntity);
}
try {
FileMeta[] fileMetas = objectMapper.readValue(getUploadMeta(), FileMeta[].class);
for (FileMeta fileMeta : fileMetas) {
String fileId = fileMeta.getId();
try {
String contentType = fileMeta.getContentType();
String fileName = fileMeta.getName();
byte[] fileData = TempFileUtils.getTempFileData(fileId);
String license = null;
BinaryMaterial binaryMaterial = binaryMaterialController.createBinaryMaterial(fileName, contentType, fileData, license);
workspaceMaterialController.createWorkspaceMaterial(parent, binaryMaterial);
} finally {
TempFileUtils.deleteTempFile(fileId);
}
}
} catch (IOException e) {
logger.log(Level.SEVERE, "File uploading filed", e);
return "/error/internal-error.jsf";
}
return null;
}
use of fi.otavanopisto.muikku.plugins.material.model.BinaryMaterial in project muikku by otavanopisto.
the class TaskMathMl method cleanElement.
@Override
protected void cleanElement(Element element) {
boolean needsModify = false;
if ("img".equals(element.getTagName()) && element.hasAttribute("ix_mathmldata")) {
String src = element.getAttribute("src");
if (StringUtils.startsWith(src, "/~Repository/ResourceAPI/RenderMathML")) {
src = "http://muikku.otavanopisto.fi" + src;
needsModify = true;
} else if (StringUtils.startsWith(src, "muikku.otavanopisto.fi/~Repository/ResourceAPI/RenderMathML")) {
src = "http://" + src;
needsModify = true;
} else if (StringUtils.startsWith(src, "http://muikku.otavanopisto.fi/~Repository/ResourceAPI/RenderMathML")) {
needsModify = true;
}
if (needsModify) {
try {
logger.info("Converting MathML from " + src);
URL url = new URL(src);
InputStream is = url.openStream();
byte[] data = {};
try {
data = IOUtils.toByteArray(is);
} finally {
is.close();
}
String name = "mathml" + StringUtils.leftPad(++imageCounter + "", 3, '0') + ".png";
String license = null;
BinaryMaterial material = binaryMaterialController.createBinaryMaterial(name, "image/png", data, license);
WorkspaceMaterial workspaceMaterial = workspaceMaterialController.createWorkspaceMaterial(getWorkspaceMaterial(), material);
String workspaceUrl = StringUtils.prependIfMissing(workspaceMaterialController.getCompletePath(workspaceMaterial), "/");
logger.info("MathML converted to " + workspaceUrl);
element.setAttribute("src", workspaceUrl);
element.removeAttribute("ix_mathml");
element.removeAttribute("ix_mathmldata");
markModified();
} catch (Exception e) {
logger.log(Level.SEVERE, "Failed to process MathML from URL " + src, e);
}
}
}
}
Aggregations