Search in sources :

Example 11 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class BaseSearchResult method searchObjects.

/**
 * Search for keyword in the given scopes. Limit the search only to Objects.
 *
 * @param number number of results to be returned
 * @param start 0-based start offset
 * @param orderField the field to be used to order the results
 * @param order "asc" or "desc"
 * @return the results
 */
protected List<SearchResult> searchObjects(String keywords, String wikiName, String space, boolean hasProgrammingRights, int number, int start, String orderField, String order, Boolean withPrettyNames) throws QueryException, IllegalArgumentException, UriBuilderException, XWikiException {
    XWikiContext xwikiContext = Utils.getXWikiContext(componentManager);
    XWiki xwikiApi = Utils.getXWikiApi(componentManager);
    String database = Utils.getXWikiContext(componentManager).getWikiId();
    /* This try is just needed for executing the finally clause. */
    try {
        List<SearchResult> result = new ArrayList<SearchResult>();
        if (keywords == null) {
            return result;
        }
        Formatter f = new Formatter();
        /*
             * If the order field is already one of the field hard coded in the base query, then do not add it to the
             * select clause.
             */
        String addColumn = (orderField.equals("") || orderField.equals("fullName") || orderField.equals("name") || orderField.equals("space")) ? "" : ", doc." + orderField;
        if (space != null) {
            f.format("select distinct doc.fullName, doc.space, doc.name, obj.className, obj.number");
            f.format(addColumn);
            f.format(" from XWikiDocument as doc, BaseObject as obj, StringProperty as sp, LargeStringProperty as lsp where doc.space = :space and obj.name=doc.fullName and sp.id.id = obj.id and lsp.id.id = obj.id and (upper(sp.value) like :keywords or upper(lsp.value) like :keywords) ");
        } else {
            f.format("select distinct doc.fullName, doc.space, doc.name, obj.className, obj.number");
            f.format(addColumn);
            f.format(" from XWikiDocument as doc, BaseObject as obj, StringProperty as sp, LargeStringProperty as lsp where obj.name=doc.fullName and sp.id.id = obj.id and lsp.id.id = obj.id and (upper(sp.value) like :keywords or upper(lsp.value) like :keywords) ");
        }
        /* Build the order clause. */
        String orderClause = null;
        if (StringUtils.isBlank(orderField)) {
            orderClause = "doc.fullName asc";
        } else {
            /* Check if the order parameter is a valid "asc" or "desc" string, otherwise use "asc" */
            if ("asc".equals(order) || "desc".equals(order)) {
                orderClause = String.format("doc.%s %s", orderField, order);
            } else {
                orderClause = String.format("doc.%s asc", orderField);
            }
        }
        /* Add some filters if the user doesn't have programming rights. */
        if (hasProgrammingRights) {
            f.format(" order by %s", orderClause);
        } else {
            f.format(" and doc.space<>'XWiki' and doc.space<>'Admin' and doc.space<>'Panels' and doc.name<>'WebPreferences' order by %s", orderClause);
        }
        String query = f.toString();
        List<Object> queryResult = null;
        /* This is needed because if the :space placeholder is not in the query, setting it would cause an exception */
        if (space != null) {
            queryResult = queryManager.createQuery(query, Query.XWQL).bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())).bindValue("space", space).setLimit(number).execute();
        } else {
            queryResult = queryManager.createQuery(query, Query.XWQL).bindValue("keywords", String.format("%%%s%%", keywords.toUpperCase())).setLimit(number).execute();
        }
        /* Build the result. */
        for (Object object : queryResult) {
            Object[] fields = (Object[]) object;
            String spaceId = (String) fields[1];
            List<String> spaces = Utils.getSpacesFromSpaceId(spaceId);
            String pageName = (String) fields[2];
            String className = (String) fields[3];
            int objectNumber = (Integer) fields[4];
            String id = Utils.getObjectId(wikiName, spaces, pageName, className, objectNumber);
            String pageId = Utils.getPageId(wikiName, spaces, pageName);
            String pageFullName = Utils.getPageFullName(wikiName, spaces, pageName);
            /*
                 * Check if the user has the right to see the found document. We also prevent guest users to access
                 * object data in order to avoid leaking important information such as emails to crawlers.
                 */
            if (xwikiApi.hasAccessLevel("view", pageId) && xwikiContext.getUserReference() != null) {
                Document doc = xwikiApi.getDocument(pageFullName);
                String title = doc.getDisplayTitle();
                SearchResult searchResult = objectFactory.createSearchResult();
                searchResult.setType("object");
                searchResult.setId(id);
                searchResult.setPageFullName(pageFullName);
                searchResult.setTitle(title);
                searchResult.setWiki(wikiName);
                searchResult.setSpace(spaceId);
                searchResult.setPageName(pageName);
                searchResult.setVersion(doc.getVersion());
                searchResult.setClassName(className);
                searchResult.setObjectNumber(objectNumber);
                searchResult.setAuthor(doc.getAuthor());
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(doc.getDate());
                searchResult.setModified(calendar);
                if (withPrettyNames) {
                    searchResult.setAuthorName(Utils.getAuthorName(doc.getAuthorReference(), componentManager));
                }
                String pageUri = Utils.createURI(uriInfo.getBaseUri(), PageResource.class, wikiName, spaces, pageName).toString();
                Link pageLink = new Link();
                pageLink.setHref(pageUri);
                pageLink.setRel(Relations.PAGE);
                searchResult.getLinks().add(pageLink);
                String objectUri = Utils.createURI(uriInfo.getBaseUri(), ObjectResource.class, wikiName, spaces, pageName, className, objectNumber).toString();
                Link objectLink = new Link();
                objectLink.setHref(objectUri);
                objectLink.setRel(Relations.OBJECT);
                searchResult.getLinks().add(objectLink);
                result.add(searchResult);
            }
        }
        return result;
    } finally {
        Utils.getXWikiContext(componentManager).setWikiId(database);
    }
}
Also used : PageResource(org.xwiki.rest.resources.pages.PageResource) Formatter(java.util.Formatter) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) XWikiContext(com.xpn.xwiki.XWikiContext) XWiki(com.xpn.xwiki.api.XWiki) SearchResult(org.xwiki.rest.model.jaxb.SearchResult) Document(com.xpn.xwiki.api.Document) ObjectResource(org.xwiki.rest.resources.objects.ObjectResource) Link(org.xwiki.rest.model.jaxb.Link)

Example 12 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class AttachmentResourceImpl method getAttachment.

@Override
public Response getAttachment(String wikiName, String spaceName, String pageName, String attachmentName) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, null, true, false);
        Document doc = documentInfo.getDocument();
        final com.xpn.xwiki.api.Attachment xwikiAttachment = doc.getAttachment(attachmentName);
        if (xwikiAttachment == null) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
        return Response.ok().type(xwikiAttachment.getMimeType()).entity(xwikiAttachment.getContent()).build();
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiDocument(com.xpn.xwiki.doc.XWikiDocument) XWikiException(com.xpn.xwiki.XWikiException)

Example 13 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class AttachmentsAtPageVersionResourceImpl method getAttachmentsAtPageVersion.

@Override
public Attachments getAttachmentsAtPageVersion(String wikiName, String spaceName, String pageName, String version, Integer start, Integer number, Boolean withPrettyNames) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, version, true, false);
        Document doc = documentInfo.getDocument();
        return getAttachmentsForDocument(doc, start, number, withPrettyNames);
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException)

Example 14 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class AttachmentsResourceImpl method addAttachment.

@Override
public Response addAttachment(String wikiName, String spaceName, String pageName, Multipart multipart) throws XWikiRestException {
    try {
        List<String> spaces = parseSpaceSegments(spaceName);
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaces, pageName, null, null, true, true);
        Document doc = documentInfo.getDocument();
        if (!doc.hasAccessLevel("edit", Utils.getXWikiUser(componentManager))) {
            throw new WebApplicationException(Status.UNAUTHORIZED);
        }
        /* The name to be used */
        String attachmentName = null;
        /* The actual filename of the sent file */
        String actualFileName = null;
        /* The specified file name using a form field */
        String overriddenFileName = null;
        String contentType = null;
        InputStream inputStream = null;
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            /* Get the content disposition headers */
            Enumeration e = bodyPart.getMatchingHeaders(new String[] { "Content-disposition" });
            while (e.hasMoreElements()) {
                Header h = (Header) e.nextElement();
                /* Parse header data. Normally headers are in the form form-data; key="value"; ... */
                if (h.getValue().startsWith("form-data")) {
                    String[] fieldData = h.getValue().split(";");
                    for (String s : fieldData) {
                        String[] pair = s.split("=");
                        if (pair.length == 2) {
                            String key = pair[0].trim();
                            String value = pair[1].replace("\"", "").trim();
                            if ("name".equals(key)) {
                                if (FORM_FILENAME_FIELD.equals(value)) {
                                    overriddenFileName = bodyPart.getContent().toString();
                                }
                            } else if ("filename".equals(key)) {
                                actualFileName = value;
                                contentType = bodyPart.getContentType();
                                inputStream = bodyPart.getInputStream();
                            }
                        }
                    }
                }
            }
        }
        if (overriddenFileName != null) {
            attachmentName = overriddenFileName;
        } else {
            attachmentName = actualFileName;
        }
        if (attachmentName == null) {
            throw new WebApplicationException(Status.BAD_REQUEST);
        }
        byte[] buffer = new byte[4096];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while (true) {
            int read = inputStream.read(buffer);
            if (read != 4096) {
                if (read != -1) {
                    baos.write(buffer, 0, read);
                }
                break;
            } else {
                baos.write(buffer);
            }
        }
        baos.flush();
        /* Attach the file */
        AttachmentInfo attachmentInfo = storeAttachment(doc, attachmentName, baos.toByteArray());
        if (attachmentInfo.isAlreadyExisting()) {
            return Response.status(Status.ACCEPTED).entity(attachmentInfo.getAttachment()).build();
        } else {
            return Response.created(Utils.createURI(uriInfo.getBaseUri(), AttachmentResource.class, wikiName, spaces, pageName, attachmentName)).entity(attachmentInfo.getAttachment()).build();
        }
    } catch (Exception e) {
        throw new XWikiRestException(e);
    }
}
Also used : BodyPart(javax.mail.BodyPart) AttachmentResource(org.xwiki.rest.resources.attachments.AttachmentResource) Enumeration(java.util.Enumeration) WebApplicationException(javax.ws.rs.WebApplicationException) InputStream(java.io.InputStream) XWikiRestException(org.xwiki.rest.XWikiRestException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException) XWikiRestException(org.xwiki.rest.XWikiRestException) WebApplicationException(javax.ws.rs.WebApplicationException) Header(javax.mail.Header)

Example 15 with Document

use of com.xpn.xwiki.api.Document in project xwiki-platform by xwiki.

the class AttachmentsResourceImpl method getAttachments.

@Override
public Attachments getAttachments(String wikiName, String spaceName, String pageName, Integer start, Integer number, Boolean withPrettyNames) throws XWikiRestException {
    try {
        DocumentInfo documentInfo = getDocumentInfo(wikiName, spaceName, pageName, null, null, true, false);
        Document doc = documentInfo.getDocument();
        return getAttachmentsForDocument(doc, start, number, withPrettyNames);
    } catch (XWikiException e) {
        throw new XWikiRestException(e);
    }
}
Also used : XWikiRestException(org.xwiki.rest.XWikiRestException) Document(com.xpn.xwiki.api.Document) XWikiException(com.xpn.xwiki.XWikiException)

Aggregations

Document (com.xpn.xwiki.api.Document)97 XWikiDocument (com.xpn.xwiki.doc.XWikiDocument)60 XWikiException (com.xpn.xwiki.XWikiException)41 XWikiRestException (org.xwiki.rest.XWikiRestException)40 DocumentReference (org.xwiki.model.reference.DocumentReference)37 BaseObject (com.xpn.xwiki.objects.BaseObject)24 Test (org.junit.Test)23 WebApplicationException (javax.ws.rs.WebApplicationException)22 ArrayList (java.util.ArrayList)16 Attachment (com.xpn.xwiki.api.Attachment)14 XWikiAttachment (com.xpn.xwiki.doc.XWikiAttachment)14 Vector (java.util.Vector)12 Link (org.xwiki.rest.model.jaxb.Link)10 XWikiContext (com.xpn.xwiki.XWikiContext)9 AbstractComponentTest (com.celements.common.test.AbstractComponentTest)7 Date (java.util.Date)7 XWiki (com.xpn.xwiki.api.XWiki)6 RangeIterable (org.xwiki.rest.internal.RangeIterable)6 Object (org.xwiki.rest.model.jaxb.Object)6 XWiki (com.xpn.xwiki.XWiki)5