use of org.structr.common.SecurityContext in project structr by structr.
the class DOMElement method renderContent.
static void renderContent(final DOMElement thisElement, final RenderContext renderContext, final int depth) throws FrameworkException {
if (thisElement.isDeleted() || thisElement.isHidden() || !thisElement.displayForLocale(renderContext) || !thisElement.displayForConditions(renderContext)) {
return;
}
// final variables
final SecurityContext securityContext = renderContext.getSecurityContext();
final AsyncBuffer out = renderContext.getBuffer();
final EditMode editMode = renderContext.getEditMode(securityContext.getUser(false));
final boolean isVoid = thisElement.isVoidElement();
final String _tag = thisElement.getTag();
// non-final variables
Result localResult = renderContext.getResult();
boolean anyChildNodeCreatesNewLine = false;
thisElement.renderStructrAppLib(out, securityContext, renderContext, depth);
if (depth > 0 && !thisElement.avoidWhitespace()) {
out.append(DOMNode.indent(depth, renderContext));
}
if (StringUtils.isNotBlank(_tag)) {
if (EditMode.DEPLOYMENT.equals(editMode)) {
// comment accordingly.
if (DOMNode.renderDeploymentExportComments(thisElement, out, false)) {
// restore indentation
if (depth > 0 && !thisElement.avoidWhitespace()) {
out.append(DOMNode.indent(depth, renderContext));
}
}
}
thisElement.openingTag(out, _tag, editMode, renderContext, depth);
try {
// in body?
if (lowercaseBodyName.equals(thisElement.getTagName())) {
renderContext.setInBody(true);
}
// only render children if we are not in a shared component scenario and not in deployment mode
if (thisElement.getSharedComponent() == null || !EditMode.DEPLOYMENT.equals(editMode)) {
// fetch children
final List<RelationshipInterface> rels = thisElement.getChildRelationships();
if (rels.isEmpty()) {
// No child relationships, maybe this node is in sync with another node
final DOMElement _syncedNode = (DOMElement) thisElement.getSharedComponent();
if (_syncedNode != null) {
rels.addAll(_syncedNode.getChildRelationships());
}
}
// apply configuration for shared component if present
final String _sharedComponentConfiguration = thisElement.getProperty(StructrApp.key(DOMElement.class, "sharedComponentConfiguration"));
if (StringUtils.isNotBlank(_sharedComponentConfiguration)) {
Scripting.evaluate(renderContext, thisElement, "${" + _sharedComponentConfiguration + "}", "shared component configuration");
}
for (final RelationshipInterface rel : rels) {
final DOMNode subNode = (DOMNode) rel.getTargetNode();
if (subNode instanceof DOMElement) {
anyChildNodeCreatesNewLine = (anyChildNodeCreatesNewLine || !(subNode.avoidWhitespace()));
}
subNode.render(renderContext, depth + 1);
}
}
} catch (Throwable t) {
out.append("Error while rendering node ").append(thisElement.getUuid()).append(": ").append(t.getMessage());
logger.warn("", t);
}
// render end tag, if needed (= if not singleton tags)
if (StringUtils.isNotBlank(_tag) && (!isVoid)) {
// only insert a newline + indentation before the closing tag if any child-element used a newline
final DOMElement _syncedNode = (DOMElement) thisElement.getSharedComponent();
final boolean isTemplate = _syncedNode != null && EditMode.DEPLOYMENT.equals(editMode);
if (anyChildNodeCreatesNewLine || isTemplate) {
out.append(DOMNode.indent(depth, renderContext));
}
if (_syncedNode != null && EditMode.DEPLOYMENT.equals(editMode)) {
out.append("</structr:component>");
} else if (isTemplate) {
out.append("</structr:template>");
} else {
out.append("</").append(_tag).append(">");
}
}
}
// Set result for this level again, if there was any
if (localResult != null) {
renderContext.setResult(localResult);
}
}
use of org.structr.common.SecurityContext in project structr by structr.
the class File method getInputStream.
static InputStream getInputStream(final File thisFile) {
final java.io.File fileOnDisk = thisFile.getFileOnDisk();
try {
final FileInputStream fis = new FileInputStream(fileOnDisk);
final SecurityContext securityContext = thisFile.getSecurityContext();
if (thisFile.isTemplate()) {
boolean editModeActive = false;
if (securityContext.getRequest() != null) {
final String editParameter = securityContext.getRequest().getParameter("edit");
if (editParameter != null) {
editModeActive = !RenderContext.EditMode.NONE.equals(RenderContext.editMode(editParameter));
}
}
if (!editModeActive) {
final String content = IOUtils.toString(fis, "UTF-8");
// close input stream here
fis.close();
try {
final String result = Scripting.replaceVariables(new ActionContext(securityContext), thisFile, content);
String encoding = "UTF-8";
final String cType = getContentType();
if (cType != null) {
final String charset = StringUtils.substringAfterLast(cType, "charset=").trim().toUpperCase();
try {
if (!"".equals(charset) && Charset.isSupported(charset)) {
encoding = charset;
}
} catch (IllegalCharsetNameException ice) {
logger.warn("Charset is not supported '{}'. Using 'UTF-8'", charset);
}
}
return IOUtils.toInputStream(result, encoding);
} catch (Throwable t) {
logger.warn("Scripting error in {}:\n{}\n{}", thisFile.getUuid(), content, t.getMessage());
}
}
}
return fis;
} catch (IOException ex) {
logger.warn("Unable to open input stream for {}: {}", fileOnDisk.getPath(), ex.getMessage());
}
return null;
}
use of org.structr.common.SecurityContext in project structr by structr.
the class Folder method setHasParent.
static void setHasParent(final Folder thisFolder) throws FrameworkException {
synchronized (thisFolder) {
final SecurityContext ctx = thisFolder.getSecurityContext();
thisFolder.setSecurityContext(SecurityContext.getSuperUserInstance());
thisFolder.setProperty(StructrApp.key(AbstractFile.class, "hasParent"), thisFolder.getParent() != null);
thisFolder.setSecurityContext(ctx);
}
}
use of org.structr.common.SecurityContext in project structr by structr.
the class Image method getScaledImage.
/**
* Get (down-)scaled image of this image
*
* If no scaled image of the requested size exists or the image is newer than the scaled image, create a new one.
*
* Default behaviour is to make the scaled image complete fit inside a rectangle of maxWidth x maxHeight.
*
* @param maxWidth
* @param maxHeight
* @param cropToFit if true, scale down until the shorter edge fits inside the rectangle, and then crop
*
* @return scaled image
*/
public static Image getScaledImage(final Image thisImage, final int maxWidth, final int maxHeight, final boolean cropToFit) {
final Class<Relation> thumbnailRel = StructrApp.getConfiguration().getRelationshipEntityClass("ImageTHUMBNAILImage");
final Iterable<Relation> thumbnailRelationships = thisImage.getOutgoingRelationships(thumbnailRel);
final SecurityContext securityContext = thisImage.getSecurityContext();
final List<Image> oldThumbnails = new LinkedList<>();
Image thumbnail = null;
final Image originalImage = thisImage;
final Integer origWidth = originalImage.getWidth();
final Integer origHeight = originalImage.getHeight();
final Long currentChecksum = originalImage.getChecksum();
Long newChecksum = 0L;
if (currentChecksum == null || currentChecksum == 0) {
try {
newChecksum = FileHelper.getChecksum(originalImage.getFileOnDisk());
if (newChecksum == null || newChecksum == 0) {
logger.warn("Unable to calculate checksum of {}", originalImage.getName());
return null;
}
} catch (IOException ex) {
logger.warn("Unable to calculate checksum of {}: {}", originalImage.getName(), ex.getMessage());
}
} else {
newChecksum = currentChecksum;
}
// Read Exif and GPS data from image and update properties
ImageHelper.getExifData(originalImage);
// Return self if SVG image
final String _contentType = thisImage.getContentType();
if (_contentType != null && (_contentType.startsWith("image/svg") || (_contentType.startsWith("image/") && _contentType.endsWith("icon")))) {
return thisImage;
}
if (origWidth != null && origHeight != null && thumbnailRelationships != null) {
for (final Relation r : thumbnailRelationships) {
final Integer w = r.getProperty(StructrApp.key(Image.class, "width"));
final Integer h = r.getProperty(StructrApp.key(Image.class, "height"));
if (w != null && h != null) {
// orginal image is equal or smaller than requested size
if (((w == maxWidth) && (h <= maxHeight)) || ((w <= maxWidth) && (h == maxHeight)) || ((origWidth <= w) && (origHeight <= h))) {
thumbnail = (Image) r.getTargetNode();
// Use thumbnail only if checksum of original image matches with stored checksum
final Long storedChecksum = r.getProperty(StructrApp.key(Image.class, "checksum"));
if (storedChecksum != null && storedChecksum.equals(newChecksum)) {
return thumbnail;
} else {
oldThumbnails.add(thumbnail);
}
}
}
}
}
if (originalImage.getIsCreatingThumb()) {
logger.debug("Another thumbnail is being created - waiting....");
} else {
try {
// No thumbnail exists, or thumbnail was too old, so let's create a new one
logger.debug("Creating thumbnail for {} (w={} h={} crop={})", new Object[] { getName(), maxWidth, maxHeight, cropToFit });
originalImage.unlockSystemPropertiesOnce();
originalImage.setIsCreatingThumb(true);
final App app = StructrApp.getInstance();
originalImage.unlockSystemPropertiesOnce();
originalImage.setProperty(StructrApp.key(File.class, "checksum"), newChecksum);
final Thumbnail thumbnailData = ImageHelper.createThumbnail(originalImage, maxWidth, maxHeight, cropToFit);
if (thumbnailData != null) {
final Integer tnWidth = thumbnailData.getWidth();
final Integer tnHeight = thumbnailData.getHeight();
byte[] data = null;
try {
data = thumbnailData.getBytes();
final String thumbnailName = ImageHelper.getThumbnailName(originalImage.getName(), tnWidth, tnHeight);
// create thumbnail node
thumbnail = ImageHelper.createImageNode(securityContext, data, "image/" + Thumbnail.defaultFormat, Image.class, thumbnailName, true);
} catch (IOException ex) {
logger.warn("Could not create thumbnail image for " + getUuid(), ex);
}
if (thumbnail != null && data != null) {
// Create a thumbnail relationship
final PropertyMap relProperties = new PropertyMap();
relProperties.put(StructrApp.key(Image.class, "width"), tnWidth);
relProperties.put(StructrApp.key(Image.class, "height"), tnHeight);
relProperties.put(StructrApp.key(Image.class, "checksum"), newChecksum);
app.create(originalImage, thumbnail, thumbnailRel, relProperties);
final PropertyMap properties = new PropertyMap();
properties.put(StructrApp.key(Image.class, "width"), tnWidth);
properties.put(StructrApp.key(Image.class, "height"), tnHeight);
properties.put(StructrApp.key(AbstractNode.class, "hidden"), originalImage.getProperty(AbstractNode.hidden));
properties.put(StructrApp.key(AbstractNode.class, "visibleToAuthenticatedUsers"), originalImage.getProperty(AbstractNode.visibleToAuthenticatedUsers));
properties.put(StructrApp.key(AbstractNode.class, "visibleToPublicUsers"), originalImage.getProperty(AbstractNode.visibleToPublicUsers));
properties.put(StructrApp.key(File.class, "size"), Long.valueOf(data.length));
properties.put(StructrApp.key(AbstractNode.class, "owner"), originalImage.getProperty(AbstractNode.owner));
properties.put(StructrApp.key(File.class, "parent"), originalImage.getParent());
properties.put(StructrApp.key(File.class, "hasParent"), originalImage.getProperty(StructrApp.key(Image.class, "hasParent")));
thumbnail.unlockSystemPropertiesOnce();
thumbnail.setProperties(securityContext, properties);
// Delete outdated thumbnails
for (final Image tn : oldThumbnails) {
app.delete(tn);
}
}
} else {
logger.debug("Could not create thumbnail for image {} ({})", getName(), getUuid());
}
originalImage.unlockSystemPropertiesOnce();
originalImage.setIsCreatingThumb(false);
} catch (FrameworkException fex) {
logger.warn("Unable to create thumbnail for " + getUuid(), fex);
}
}
return thumbnail;
}
use of org.structr.common.SecurityContext in project structr by structr.
the class MinifiedJavaScriptFile method minify.
static void minify(final MinifiedJavaScriptFile thisFile) throws FrameworkException, IOException {
logger.info("Running minify: {}", thisFile.getUuid());
final com.google.javascript.jscomp.Compiler compiler = new com.google.javascript.jscomp.Compiler();
final SecurityContext securityContext = thisFile.getSecurityContext();
final CompilerOptions options = new CompilerOptions();
final CompilationLevel selectedLevel = CompilationLevel.valueOf(thisFile.getOptimizationLevel());
selectedLevel.setOptionsForCompilationLevel(options);
compiler.setErrorManager(new BasicErrorManager() {
@Override
public void println(final CheckLevel level, final JSError error) {
}
@Override
protected void printSummary() {
if (getTypedPercent() > 0) {
if (getErrorCount() + getWarningCount() == 0) {
logger.info(SimpleFormat.format("%d error(s), %d warning(s), %.1f%% typed", getErrorCount(), getWarningCount(), getTypedPercent()));
} else {
logger.warn(SimpleFormat.format("%d error(s), %d warning(s), %.1f%% typed", getErrorCount(), getWarningCount(), getTypedPercent()));
}
} else if (getErrorCount() + getWarningCount() > 0) {
logger.warn(SimpleFormat.format("%d error(s), %d warning(s)", getErrorCount(), getWarningCount()));
}
}
});
compiler.compile(CommandLineRunner.getBuiltinExterns(options.getEnvironment()), MinifiedJavaScriptFile.getSourceFileList(thisFile), options);
FileHelper.setFileData(thisFile, compiler.toSource().getBytes(), thisFile.getContentType());
final PropertyMap changedProperties = new PropertyMap();
changedProperties.put(StructrApp.key(MinifiedJavaScriptFile.class, "warnings"), StringUtils.join(compiler.getWarnings(), System.lineSeparator()));
changedProperties.put(StructrApp.key(MinifiedJavaScriptFile.class, "errors"), StringUtils.join(compiler.getErrors(), System.lineSeparator()));
thisFile.setProperties(securityContext, changedProperties);
}
Aggregations