Search in sources :

Example 1 with IRISyntaxException

use of org.apache.abdera.i18n.iri.IRISyntaxException in project dataverse by IQSS.

the class StatementManagerImpl method getStatement.

@Override
public Statement getStatement(String editUri, Map<String, String> map, AuthCredentials authCredentials, SwordConfiguration swordConfiguration) throws SwordServerException, SwordError, SwordAuthException {
    AuthenticatedUser user = swordAuth.auth(authCredentials);
    DataverseRequest dvReq = new DataverseRequest(user, httpRequest);
    urlManager.processUrl(editUri);
    String globalId = urlManager.getTargetIdentifier();
    if (urlManager.getTargetType().equals("study") && globalId != null) {
        logger.fine("request for sword statement by user " + user.getDisplayInfo().getTitle());
        Dataset dataset = datasetService.findByGlobalId(globalId);
        if (dataset == null) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "couldn't find dataset with global ID of " + globalId);
        }
        Dataverse dvThatOwnsDataset = dataset.getOwner();
        if (!permissionService.isUserAllowedOn(user, new GetDraftDatasetVersionCommand(dvReq, dataset), dataset)) {
            throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + user.getDisplayInfo().getTitle() + " is not authorized to view dataset with global ID " + globalId);
        }
        String feedUri = urlManager.getHostnamePlusBaseUrlPath(editUri) + "/edit/study/" + dataset.getGlobalId();
        String author = dataset.getLatestVersion().getAuthorsStr();
        String title = dataset.getLatestVersion().getTitle();
        // in the statement, the element is called "updated"
        Date lastUpdatedFinal = new Date();
        Date lastUpdateTime = dataset.getLatestVersion().getLastUpdateTime();
        if (lastUpdateTime != null) {
            lastUpdatedFinal = lastUpdateTime;
        } else {
            logger.info("lastUpdateTime was null, trying createtime");
            Date createtime = dataset.getLatestVersion().getCreateTime();
            if (createtime != null) {
                lastUpdatedFinal = createtime;
            } else {
                logger.info("creatime was null, using \"now\"");
                lastUpdatedFinal = new Date();
            }
        }
        AtomDate atomDate = new AtomDate(lastUpdatedFinal);
        String datedUpdated = atomDate.toString();
        Statement statement = new AtomStatement(feedUri, author, title, datedUpdated);
        Map<String, String> states = new HashMap<>();
        states.put("latestVersionState", dataset.getLatestVersion().getVersionState().toString());
        Boolean isMinorUpdate = dataset.getLatestVersion().isMinorUpdate();
        states.put("isMinorUpdate", isMinorUpdate.toString());
        if (dataset.isLocked()) {
            states.put("locked", "true");
            states.put("lockedDetail", dataset.getLocks().stream().map(l -> l.getInfo()).collect(joining(",")));
            Optional<DatasetLock> earliestLock = dataset.getLocks().stream().min((l1, l2) -> (int) Math.signum(l1.getStartTime().getTime() - l2.getStartTime().getTime()));
            states.put("lockedStartTime", earliestLock.get().getStartTime().toString());
        } else {
            states.put("locked", "false");
        }
        statement.setStates(states);
        List<FileMetadata> fileMetadatas = dataset.getLatestVersion().getFileMetadatas();
        for (FileMetadata fileMetadata : fileMetadatas) {
            DataFile dataFile = fileMetadata.getDataFile();
            // We are exposing the filename for informational purposes. The file id is what you
            // actually operate on to delete a file, etc.
            // 
            // Replace spaces to avoid IRISyntaxException
            String fileNameFinal = fileMetadata.getLabel().replace(' ', '_');
            String fileUrlString = urlManager.getHostnamePlusBaseUrlPath(editUri) + "/edit-media/file/" + dataFile.getId() + "/" + fileNameFinal;
            IRI fileUrl;
            try {
                fileUrl = new IRI(fileUrlString);
            } catch (IRISyntaxException ex) {
                throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Invalid URL for file ( " + fileUrlString + " ) resulted in " + ex.getMessage());
            }
            ResourcePart resourcePart = new ResourcePart(fileUrl.toString());
            // default to something that doesn't throw a org.apache.abdera.util.MimeTypeParseException
            String finalFileFormat = "application/octet-stream";
            String contentType = dataFile.getContentType();
            if (contentType != null) {
                finalFileFormat = contentType;
            }
            resourcePart.setMediaType(finalFileFormat);
            /**
             * @todo: Why are properties set on a ResourcePart not exposed
             * when you GET a Statement? Asked about this at
             * http://www.mail-archive.com/sword-app-tech@lists.sourceforge.net/msg00394.html
             */
            // Map<String, String> properties = new HashMap<String, String>();
            // properties.put("filename", studyFile.getFileName());
            // properties.put("category", studyFile.getLatestCategory());
            // properties.put("originalFileType", studyFile.getOriginalFileType());
            // properties.put("id", studyFile.getId().toString());
            // properties.put("UNF", studyFile.getUnf());
            // resourcePart.setProperties(properties);
            statement.addResource(resourcePart);
        /**
         * @todo it's been noted at
         * https://github.com/IQSS/dataverse/issues/892#issuecomment-54159284
         * that at the file level the "updated" date is always "now",
         * which seems to be set here:
         * https://github.com/swordapp/JavaServer2.0/blob/sword2-server-1.0/src/main/java/org/swordapp/server/AtomStatement.java#L70
         */
        }
        return statement;
    } else {
        throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine target type or identifier from URL: " + editUri);
    }
}
Also used : IRI(org.apache.abdera.i18n.iri.IRI) ResourcePart(org.swordapp.server.ResourcePart) SwordError(org.swordapp.server.SwordError) AtomStatement(org.swordapp.server.AtomStatement) HashMap(java.util.HashMap) Dataset(edu.harvard.iq.dataverse.Dataset) AtomStatement(org.swordapp.server.AtomStatement) Statement(org.swordapp.server.Statement) FileMetadata(edu.harvard.iq.dataverse.FileMetadata) AuthenticatedUser(edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser) Dataverse(edu.harvard.iq.dataverse.Dataverse) Date(java.util.Date) AtomDate(org.apache.abdera.model.AtomDate) DataverseRequest(edu.harvard.iq.dataverse.engine.command.DataverseRequest) DataFile(edu.harvard.iq.dataverse.DataFile) AtomDate(org.apache.abdera.model.AtomDate) GetDraftDatasetVersionCommand(edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand) DatasetLock(edu.harvard.iq.dataverse.DatasetLock) IRISyntaxException(org.apache.abdera.i18n.iri.IRISyntaxException)

Example 2 with IRISyntaxException

use of org.apache.abdera.i18n.iri.IRISyntaxException in project jaggery by wso2.

the class FeedHostObject method addEntry.

public void addEntry(Object entryObject) throws ScriptException {
    abdera = new Abdera();
    Factory factory = abdera.getFactory();
    entry = factory.newEntry();
    if (entryObject instanceof EntryHostObject) {
        EntryHostObject entryHostObject = (EntryHostObject) entryObject;
        entry = entryHostObject.getEntry();
        feed.addEntry(entry);
    } else if (entryObject instanceof NativeObject) {
        try {
            NativeObject nativeObject = (NativeObject) entryObject;
            ScriptableObject scriptableObject = (ScriptableObject) nativeObject;
            // author and authors processing
            Object authorProperty = ScriptableObject.getProperty(nativeObject, "author");
            if (authorProperty instanceof String) {
                entry.addAuthor((String) (authorProperty));
            }
            Object authorsProperty = ScriptableObject.getProperty(nativeObject, "authors");
            if (authorsProperty instanceof NativeArray) {
                NativeArray authorsPropertyArray = (NativeArray) authorsProperty;
                for (Object o1 : authorsPropertyArray.getIds()) {
                    int indexx = (Integer) o1;
                    String name = authorsPropertyArray.get(indexx, null).toString();
                    entry.addAuthor(name);
                }
            }
            // processing category
            Object categoryProperty = ScriptableObject.getProperty(nativeObject, "category");
            if (categoryProperty instanceof String) {
                entry.addCategory((String) (categoryProperty));
            }
            Object categoriesProperty = ScriptableObject.getProperty(nativeObject, "categories");
            if (categoriesProperty instanceof NativeArray) {
                NativeArray categoriesPropertyArray = (NativeArray) categoriesProperty;
                for (Object o1 : categoriesPropertyArray.getIds()) {
                    int indexC = (Integer) o1;
                    String name = categoriesPropertyArray.get(indexC, null).toString();
                    entry.addCategory(name);
                }
            }
            // process content
            Object content = ScriptableObject.getProperty(nativeObject, "content");
            if (content instanceof XMLObject) {
                entry.setContentAsXhtml(content.toString());
            } else if (content instanceof String) {
                entry.setContent(content.toString());
            } else {
                throw new ScriptException("Unsupported Content");
            }
            // process contributor
            Object contributorProperty = ScriptableObject.getProperty(nativeObject, "contributor");
            if (contributorProperty instanceof String) {
                entry.addContributor(contributorProperty.toString());
            }
            Object contributorsProperty = ScriptableObject.getProperty(nativeObject, "contributors");
            if (contributorsProperty instanceof NativeArray) {
                NativeArray contributorsPropertyArray = (NativeArray) contributorsProperty;
                for (Object o1 : contributorsPropertyArray.getIds()) {
                    int index = (Integer) o1;
                    String name = contributorsPropertyArray.get(index, null).toString();
                    entry.addContributor(name);
                }
            }
            // process id
            Object idProperty = ScriptableObject.getProperty(nativeObject, "id");
            if (idProperty instanceof String) {
                entry.setId((String) (idProperty));
            } else {
                entry.setId(FOMHelper.generateUuid());
            }
            // process link
            // TODO link object
            Object linkProperty = ScriptableObject.getProperty(nativeObject, "link");
            if (linkProperty instanceof String) {
                entry.addLink((String) (linkProperty));
            }
            Object linksProperty = ScriptableObject.getProperty(nativeObject, "links");
            if (linksProperty instanceof NativeArray) {
                NativeArray linksPropertyArray = (NativeArray) contributorsProperty;
                for (Object o1 : linksPropertyArray.getIds()) {
                    int index = (Integer) o1;
                    String name = linksPropertyArray.get(index, null).toString();
                    entry.addLink(name);
                }
            }
            // process published
            // TODO handle javascript date
            Object publishedProperty = ScriptableObject.getProperty(nativeObject, "published");
            if (publishedProperty instanceof String) {
                if (publishedProperty.equals("now")) {
                    entry.setPublished(new Date(System.currentTimeMillis()));
                } else {
                    entry.setPublished(publishedProperty.toString());
                }
            }
            // process rights
            Object rights = ScriptableObject.getProperty(nativeObject, "rights");
            if (rights instanceof XMLObject) {
                entry.setRightsAsXhtml(rights.toString());
            } else if (rights instanceof String) {
                entry.setRights(rights.toString());
            }
            // process summary
            Object summary = ScriptableObject.getProperty(nativeObject, "summary");
            if (summary instanceof XMLObject) {
                entry.setSummaryAsXhtml(summary.toString());
            } else if (summary instanceof String) {
                entry.setSummary(summary.toString());
            }
            // process title
            Object title = ScriptableObject.getProperty(nativeObject, "title");
            if (title instanceof XMLObject) {
                entry.setTitleAsXhtml(title.toString());
            } else if (title instanceof String) {
                entry.setTitle(title.toString());
            } else {
                throw new ScriptException("An Entry MUST have a title.");
            }
            // process updated
            Object updated = ScriptableObject.getProperty(nativeObject, "updated");
            if (updated instanceof String) {
                if (updated.equals("now")) {
                    entry.setUpdated(new Date(System.currentTimeMillis()));
                } else {
                    entry.setUpdated((String) updated);
                }
            }
        } catch (IRISyntaxException e) {
            throw new ScriptException(e);
        }
    } else if (!(entryObject instanceof EntryHostObject)) {
        throw new ScriptException("Invalid parameter");
    }
// log.info("New Added Entry" + entry);
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) Factory(org.apache.abdera.factory.Factory) LogFactory(org.apache.commons.logging.LogFactory) XMLObject(org.mozilla.javascript.xml.XMLObject) IRISyntaxException(org.apache.abdera.i18n.iri.IRISyntaxException) XMLObject(org.mozilla.javascript.xml.XMLObject) FileHostObject(org.jaggeryjs.hostobjects.file.FileHostObject) Date(java.util.Date) Abdera(org.apache.abdera.Abdera)

Example 3 with IRISyntaxException

use of org.apache.abdera.i18n.iri.IRISyntaxException in project jaggery by wso2.

the class FeedHostObject method jsFunction_getFeed.

public static synchronized void jsFunction_getFeed(Context cx, Scriptable thisObj, Object[] arguments, Function funObj) throws ScriptException {
    if (arguments.length != 1) {
        throw new ScriptException("Invalid parameter");
    }
    if (arguments[0] instanceof String) {
        feed = null;
        URL url = null;
        try {
            url = new URL((String) arguments[0]);
            feed = (Feed) Abdera.getNewParser().parse(url.openStream()).getRoot();
            isRssFeed = false;
        } catch (ClassCastException e) {
            XmlReader reader = null;
            try {
                reader = new XmlReader(url);
                rssFeed = new SyndFeedInput().build(reader);
                isRssFeed = true;
                for (Iterator i = rssFeed.getEntries().iterator(); i.hasNext(); ) {
                    SyndEntry entry = (SyndEntry) i.next();
                }
            } catch (IOException e1) {
                throw new ScriptException(e1);
            } catch (Exception e1) {
                throw new ScriptException(e1);
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException e1) {
                        throw new ScriptException(e1);
                    }
            }
        } catch (IRISyntaxException e) {
            throw new ScriptException(e);
        } catch (MalformedURLException e) {
            throw new ScriptException(e);
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        throw new ScriptException("Invalid parameter, It is must to be a String");
    }
}
Also used : ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) MalformedURLException(java.net.MalformedURLException) SyndFeedInput(com.sun.syndication.io.SyndFeedInput) SyndEntry(com.sun.syndication.feed.synd.SyndEntry) Iterator(java.util.Iterator) IRISyntaxException(org.apache.abdera.i18n.iri.IRISyntaxException) XmlReader(com.sun.syndication.io.XmlReader) IOException(java.io.IOException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) IRISyntaxException(org.apache.abdera.i18n.iri.IRISyntaxException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Aggregations

IRISyntaxException (org.apache.abdera.i18n.iri.IRISyntaxException)3 Date (java.util.Date)2 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)2 SyndEntry (com.sun.syndication.feed.synd.SyndEntry)1 SyndFeedInput (com.sun.syndication.io.SyndFeedInput)1 XmlReader (com.sun.syndication.io.XmlReader)1 DataFile (edu.harvard.iq.dataverse.DataFile)1 Dataset (edu.harvard.iq.dataverse.Dataset)1 DatasetLock (edu.harvard.iq.dataverse.DatasetLock)1 Dataverse (edu.harvard.iq.dataverse.Dataverse)1 FileMetadata (edu.harvard.iq.dataverse.FileMetadata)1 AuthenticatedUser (edu.harvard.iq.dataverse.authorization.users.AuthenticatedUser)1 DataverseRequest (edu.harvard.iq.dataverse.engine.command.DataverseRequest)1 GetDraftDatasetVersionCommand (edu.harvard.iq.dataverse.engine.command.impl.GetDraftDatasetVersionCommand)1 IOException (java.io.IOException)1 MalformedURLException (java.net.MalformedURLException)1 URISyntaxException (java.net.URISyntaxException)1 URL (java.net.URL)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1