Search in sources :

Example 96 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class PDFURIResolver method resolve.

@Override
public Source resolve(String href, String base) throws TransformerException {
    if (this.attachmentMap != null) {
        // implemented for TemporaryResource...
        if (href.contains(TEX_ACTION)) {
            // Note: See the comments in FormulaMacro to understand why we do a replace...
            AttachmentReference reference = this.attachmentMap.get(href.replace(TEX_ACTION, "/download/"));
            if (reference != null) {
                // Get the generated image's input stream
                ImageStorage storage = Utils.getComponent(ImageStorage.class);
                ImageData image = storage.get(reference.getName());
                return new StreamSource(new ByteArrayInputStream(image.getData()));
            }
        }
        // TODO: end HACK
        AttachmentReference reference = this.attachmentMap.get(href);
        if (reference != null) {
            try {
                XWikiDocument xdoc = this.context.getWiki().getDocument(reference.extractReference(EntityType.DOCUMENT), this.context);
                // TODO: handle revisions
                XWikiAttachment attachment = xdoc.getAttachment(reference.extractReference(EntityType.ATTACHMENT).getName());
                return new StreamSource(attachment.getContentInputStream(this.context));
            } catch (Exception e) {
                throw new TransformerException(String.format("Failed to resolve export URI [%s]", href), e);
            }
        }
    }
    // Defaults to the default URI Resolver in FO
    return null;
}
Also used : AttachmentReference(org.xwiki.model.reference.AttachmentReference) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) ImageStorage(org.xwiki.formula.ImageStorage) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageData(org.xwiki.formula.ImageData) StreamSource(javax.xml.transform.stream.StreamSource) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) TransformerException(javax.xml.transform.TransformerException) TransformerException(javax.xml.transform.TransformerException)

Example 97 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class RepositoryManager method getDownloadReference.

/**
 * @since 9.5RC1
 */
public ResourceReference getDownloadReference(XWikiDocument document, String extensionVersion) throws ResolveException {
    String downloadURL = null;
    // this
    BaseObject extensionVersionObject = getExtensionVersionObject(document, extensionVersion, false);
    // important
    if (extensionVersionObject != null) {
        downloadURL = getValue(extensionVersionObject, XWikiRepositoryModel.PROP_VERSION_DOWNLOAD);
    } else if (isVersionProxyingEnabled(document)) {
        downloadURL = resolveExtensionDownloadURL(document, extensionVersion);
    }
    ResourceReference resourceReference = null;
    if (StringUtils.isNotEmpty(downloadURL)) {
        resourceReference = this.resourceReferenceParser.parse(downloadURL);
    } else {
        BaseObject extensionObject = document.getXObject(XWikiRepositoryModel.EXTENSION_CLASSREFERENCE);
        String extensionId = getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_ID);
        String fileName = extensionId + '-' + extensionVersion + '.' + getValue(extensionObject, XWikiRepositoryModel.PROP_EXTENSION_TYPE);
        XWikiAttachment attachment = document.getAttachment(fileName);
        if (attachment == null) {
            // Try without the prefix
            int index = fileName.indexOf(':');
            if (index != -1 && index < extensionId.length()) {
                fileName = fileName.substring(index + 1);
                attachment = document.getAttachment(fileName);
            }
        }
        if (attachment != null) {
            resourceReference = new AttachmentResourceReference(this.entityReferenceSerializer.serialize(attachment.getReference()));
        }
    }
    return resourceReference;
}
Also used : AttachmentResourceReference(org.xwiki.rendering.listener.reference.AttachmentResourceReference) AttachmentResourceReference(org.xwiki.rendering.listener.reference.AttachmentResourceReference) ResourceReference(org.xwiki.rendering.listener.reference.ResourceReference) ExtensionResourceReference(org.xwiki.repository.internal.reference.ExtensionResourceReference) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) DefaultVersionConstraint(org.xwiki.extension.version.internal.DefaultVersionConstraint) BaseObject(com.xpn.xwiki.objects.BaseObject)

Example 98 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class VfsResourceReferenceHandlerTest method setUp.

private void setUp(String scheme, String wikiName, String spaceName, String pageName, String attachmentName, List<String> path) throws Exception {
    Provider<ComponentManager> componentManagerProvider = this.mocker.registerMockComponent(new DefaultParameterizedType(null, Provider.class, ComponentManager.class), "context");
    when(componentManagerProvider.get()).thenReturn(this.mocker);
    String attachmentReferenceAsString = String.format("%s:%s:%s.%s@%s", scheme, wikiName, spaceName, pageName, attachmentName);
    this.reference = new VfsResourceReference(URI.create(attachmentReferenceAsString), path);
    ResourceReferenceSerializer<VfsResourceReference, URI> trueVfsResourceReferenceSerializer = this.mocker.getInstance(new DefaultParameterizedType(null, ResourceReferenceSerializer.class, VfsResourceReference.class, URI.class), "truevfs");
    String truevfsURIFragment = String.format("%s://%s:%s.%s/%s/%s", scheme, wikiName, spaceName, pageName, attachmentName, StringUtils.join(path, '/'));
    when(trueVfsResourceReferenceSerializer.serialize(this.reference)).thenReturn(URI.create(truevfsURIFragment));
    Provider<XWikiContext> xwikiContextProvider = mocker.registerMockComponent(XWikiContext.TYPE_PROVIDER);
    XWikiContext xcontext = mock(XWikiContext.class);
    when(xwikiContextProvider.get()).thenReturn(xcontext);
    XWiki xwiki = mock(XWiki.class);
    when(xcontext.getWiki()).thenReturn(xwiki);
    DocumentReferenceResolver<String> documentReferenceResolver = mocker.registerMockComponent(DocumentReferenceResolver.TYPE_STRING);
    this.documentReference = new DocumentReference(wikiName, Arrays.asList(spaceName), pageName);
    String documentReferenceAsString = String.format("%s:%s.%s", wikiName, spaceName, pageName);
    when(documentReferenceResolver.resolve(documentReferenceAsString)).thenReturn(this.documentReference);
    XWikiDocument document = mock(XWikiDocument.class);
    when(xwiki.getDocument(this.documentReference, xcontext)).thenReturn(document);
    XWikiAttachment attachment = mock(XWikiAttachment.class);
    when(document.getAttachment(attachmentName)).thenReturn(attachment);
    when(attachment.getDate()).thenReturn(new Date());
    when(attachment.getContentSize(xcontext)).thenReturn(1000);
    when(attachment.getContentInputStream(xcontext)).thenReturn(createZipInputStream(StringUtils.join(path, '/'), "success!"));
    Container container = this.mocker.getInstance(Container.class);
    Response response = mock(Response.class);
    when(container.getResponse()).thenReturn(response);
    this.baos = new ByteArrayOutputStream();
    when(response.getOutputStream()).thenReturn(this.baos);
    // Register our custom Attach Driver in TrueVFS
    TConfig config = TConfig.current();
    // Note: Make sure we add our own Archive Detector to the existing Detector so that all archive formats
    // supported by TrueVFS are handled properly.
    config.setArchiveDetector(new TArchiveDetector(config.getArchiveDetector(), "attach", new AttachDriver(this.mocker)));
}
Also used : AttachDriver(org.xwiki.vfs.internal.attach.AttachDriver) ResourceReferenceSerializer(org.xwiki.resource.ResourceReferenceSerializer) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.XWiki) VfsResourceReference(org.xwiki.vfs.VfsResourceReference) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) ByteArrayOutputStream(java.io.ByteArrayOutputStream) URI(java.net.URI) Date(java.util.Date) Provider(javax.inject.Provider) Response(org.xwiki.container.Response) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) Container(org.xwiki.container.Container) ComponentManager(org.xwiki.component.manager.ComponentManager) TConfig(net.java.truevfs.access.TConfig) DefaultParameterizedType(org.xwiki.component.util.DefaultParameterizedType) TArchiveDetector(net.java.truevfs.access.TArchiveDetector) DocumentReference(org.xwiki.model.reference.DocumentReference)

Example 99 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class ImagePlugin method shrinkImage.

/**
 * Reduces the size (i.e. the number of bytes) of an image by scaling its width and height and by reducing its
 * compression quality. This helps decreasing the time needed to download the image attachment.
 *
 * @param attachment the image to be shrunk
 * @param requestedWidth the desired image width; this value is taken into account only if it is greater than zero
 *            and less than the current image width
 * @param requestedHeight the desired image height; this value is taken into account only if it is greater than zero
 *            and less than the current image height
 * @param keepAspectRatio {@code true} to preserve the image aspect ratio even when both requested dimensions are
 *            properly specified (in this case the image will be resized to best fit the rectangle with the
 *            requested width and height), {@code false} otherwise
 * @param requestedQuality the desired compression quality
 * @param context the XWiki context
 * @return the modified image attachment
 * @throws Exception if shrinking the image fails
 */
private XWikiAttachment shrinkImage(XWikiAttachment attachment, int requestedWidth, int requestedHeight, boolean keepAspectRatio, float requestedQuality, XWikiContext context) throws Exception {
    Image image = this.imageProcessor.readImage(attachment.getContentInputStream(context));
    // Compute the new image dimension.
    int currentWidth = image.getWidth(null);
    int currentHeight = image.getHeight(null);
    int[] dimensions = reduceImageDimensions(currentWidth, currentHeight, requestedWidth, requestedHeight, keepAspectRatio);
    float quality = requestedQuality;
    if (quality < 0) {
        // If no scaling is needed and the quality parameter is not specified, return the original image.
        if (dimensions[0] == currentWidth && dimensions[1] == currentHeight) {
            return attachment;
        }
        quality = this.defaultQuality;
    }
    // Scale the image to the new dimensions.
    RenderedImage shrunkImage = this.imageProcessor.scaleImage(image, dimensions[0], dimensions[1]);
    // Create an image attachment for the shrunk image.
    XWikiAttachment thumbnail = (XWikiAttachment) attachment.clone();
    thumbnail.loadAttachmentContent(context);
    OutputStream acos = thumbnail.getAttachment_content().getContentOutputStream();
    this.imageProcessor.writeImage(shrunkImage, attachment.getMimeType(context), quality, acos);
    IOUtils.closeQuietly(acos);
    return thumbnail;
}
Also used : OutputStream(java.io.OutputStream) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) Image(java.awt.Image) RenderedImage(java.awt.image.RenderedImage) RenderedImage(java.awt.image.RenderedImage)

Example 100 with XWikiAttachment

use of com.xpn.xwiki.doc.XWikiAttachment in project xwiki-platform by xwiki.

the class XWikiDocumentLocaleEventGenerator method writeRevision.

private void writeRevision(XWikiDocument document, Object filter, XWikiDocumentFilter documentFilter, DocumentInstanceInputProperties properties) throws FilterException {
    // > WikiDocumentRevision
    FilterEventParameters revisionParameters = new FilterEventParameters();
    if (document.getRelativeParentReference() != null) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_PARENT, document.getRelativeParentReference());
    }
    revisionParameters.put(WikiDocumentFilter.PARAMETER_TITLE, document.getTitle());
    if (!document.getCustomClass().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_CUSTOMCLASS, document.getCustomClass());
    }
    if (!document.getDefaultTemplate().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_DEFAULTTEMPLATE, document.getDefaultTemplate());
    }
    if (!document.getValidationScript().isEmpty()) {
        revisionParameters.put(WikiDocumentFilter.PARAMETER_VALIDATIONSCRIPT, document.getValidationScript());
    }
    revisionParameters.put(WikiDocumentFilter.PARAMETER_SYNTAX, document.getSyntax());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_HIDDEN, document.isHidden());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_AUTHOR, document.getAuthor());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_COMMENT, document.getComment());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_DATE, document.getDate());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_REVISION_MINOR, document.isMinorEdit());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_AUTHOR, document.getContentAuthor());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_DATE, document.getContentUpdateDate());
    revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT, document.getContent());
    if (properties.isWithWikiDocumentContentHTML()) {
        try {
            XWikiContext xcontext = this.xcontextProvider.get();
            revisionParameters.put(WikiDocumentFilter.PARAMETER_CONTENT_HTML, document.getRenderedContent(xcontext));
        } catch (XWikiException e) {
            this.logger.error("Failed to render content of document [{}] as HTML", document.getDocumentReference(), e);
        }
    }
    documentFilter.beginWikiDocumentRevision(document.getVersion(), revisionParameters);
    if (properties.isWithWikiAttachments()) {
        List<XWikiAttachment> sortedAttachments = new ArrayList<XWikiAttachment>(document.getAttachmentList());
        Collections.sort(sortedAttachments, new Comparator<XWikiAttachment>() {

            @Override
            public int compare(XWikiAttachment attachement1, XWikiAttachment attachement2) {
                if (attachement1 == null || attachement2 == null) {
                    int result = 0;
                    if (attachement1 != null) {
                        result = -1;
                    } else if (attachement2 != null) {
                        result = 1;
                    }
                    return result;
                }
                return attachement1.getFilename().compareTo(attachement2.getFilename());
            }
        });
        for (XWikiAttachment attachment : sortedAttachments) {
            ((XWikiAttachmentEventGenerator) this.attachmentEventGenerator).write(attachment, filter, documentFilter, properties);
        }
    }
    // Document Class
    if (properties.isWithWikiClass()) {
        BaseClass xclass = document.getXClass();
        if (!xclass.getFieldList().isEmpty()) {
            ((BaseClassEventGenerator) this.classEventGenerator).write(xclass, filter, documentFilter, properties);
        }
    }
    // Objects (THEIR ORDER IS MOLDED IN STONE!)
    if (properties.isWithWikiObjects()) {
        for (List<BaseObject> xobjects : document.getXObjects().values()) {
            for (BaseObject xobject : xobjects) {
                if (xobject != null) {
                    ((BaseObjectEventGenerator) this.objectEventGenerator).write(xobject, filter, documentFilter, properties);
                }
            }
        }
    }
    // < WikiDocumentRevision
    documentFilter.endWikiDocumentRevision(document.getVersion(), revisionParameters);
}
Also used : ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) XWikiAttachment(com.xpn.xwiki.doc.XWikiAttachment) BaseObject(com.xpn.xwiki.objects.BaseObject) FilterEventParameters(org.xwiki.filter.FilterEventParameters) BaseClass(com.xpn.xwiki.objects.classes.BaseClass) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)133 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)71 DocumentReference (org.xwiki.model.reference.DocumentReference)51 Test (org.junit.Test)40 XWikiContext (com.xpn.xwiki.XWikiContext)35 XWikiException (com.xpn.xwiki.XWikiException)25 ByteArrayInputStream (java.io.ByteArrayInputStream)20 Attachment (com.xpn.xwiki.api.Attachment)18 Date (java.util.Date)17 IOException (java.io.IOException)15 ArrayList (java.util.ArrayList)15 Document (com.xpn.xwiki.api.Document)14 XWiki (com.xpn.xwiki.XWiki)13 BaseObject (com.xpn.xwiki.objects.BaseObject)13 AttachmentReference (org.xwiki.model.reference.AttachmentReference)13 InputStream (java.io.InputStream)11 BaseClass (com.xpn.xwiki.objects.classes.BaseClass)10 File (java.io.File)10 URL (java.net.URL)7 List (java.util.List)7