Search in sources :

Example 16 with Publication

use of cz.metacentrum.perun.cabinet.model.Publication in project perun by CESNET.

the class OBD30Strategy method parseResponse.

/**
	 * Parse String response as XML document and retrieve Publications from it.
	 * @param xml XML response from OBD 3.0
	 * @return List of Publications
	 * @throws CabinetException If anything fails
	 */
protected List<Publication> parseResponse(String xml) throws CabinetException {
    assert xml != null;
    List<Publication> result = new ArrayList<Publication>();
    //hook for titles with &
    xml = xml.replace("&", "&amp;");
    //log.debug("RESPONSE: "+xml);
    //Create new document factory builder
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException ex) {
        throw new CabinetException("Error when creating newDocumentBuilder.", ex);
    }
    Document doc;
    try {
        doc = builder.parse(new InputSource(new StringReader(xml)));
    } catch (SAXParseException ex) {
        throw new CabinetException("Error when parsing uri by document builder.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    } catch (SAXException ex) {
        throw new CabinetException("Problem with parsing is more complex, not only invalid characters.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    } catch (IOException ex) {
        throw new CabinetException("Error when parsing uri by document builder. Problem with input or output.", ErrorCodes.MALFORMED_HTTP_RESPONSE, ex);
    }
    //Prepare xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression publicationsQuery;
    try {
        publicationsQuery = xpath.compile("/zaznamy/zaznam");
    } catch (XPathExpressionException ex) {
        throw new CabinetException("Error when compiling xpath query.", ex);
    }
    NodeList nodeList;
    try {
        nodeList = (NodeList) publicationsQuery.evaluate(doc, XPathConstants.NODESET);
    } catch (XPathExpressionException ex) {
        throw new CabinetException("Error when evaluate xpath query on document.", ex);
    }
    //Test if there is any nodeset in result
    if (nodeList.getLength() == 0) {
        //There is no results, return empty subjects
        return result;
    }
    //Iterate through nodes and convert them to Map<String,String>
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node singleNode = nodeList.item(i);
        // remove node from original structure in order to keep access time constant (otherwise is exp.)
        singleNode.getParentNode().removeChild(singleNode);
        try {
            Publication publication = convertNodeToPublication(singleNode);
            result.add(publication);
        } catch (InternalErrorException ex) {
            log.error("Unable to parse Publication:", ex);
        }
    }
    return result;
}
Also used : XPath(javax.xml.xpath.XPath) XPathExpression(javax.xml.xpath.XPathExpression) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) XPathExpressionException(javax.xml.xpath.XPathExpressionException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Publication(cz.metacentrum.perun.cabinet.model.Publication) IOException(java.io.IOException) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 17 with Publication

use of cz.metacentrum.perun.cabinet.model.Publication in project perun by CESNET.

the class CabinetManagerBlImpl method findExternalPublicationsOfUser.

public List<Publication> findExternalPublicationsOfUser(PerunSession sess, int userId, int yearSince, int yearTill, String pubSysNamespace) throws CabinetException, InternalErrorException {
    // get PubSys
    PublicationSystem ps = getPublicationSystemManagerBl().getPublicationSystemByNamespace(pubSysNamespace);
    // get user
    User user;
    try {
        user = perun.getUsersManagerBl().getUserById(sess, userId);
    } catch (UserNotExistsException ex) {
        throw new CabinetException("User with ID: " + userId + " doesn't exists.", ErrorCodes.PERUN_EXCEPTION, ex);
    }
    // result list
    List<Publication> result = new ArrayList<Publication>();
    // PROCESS MU PUB SYS
    if (ps.getLoginNamespace().equalsIgnoreCase("mu")) {
        // get UCO
        List<UserExtSource> ues = perun.getUsersManagerBl().getUserExtSources(sess, user);
        String authorId = "";
        for (UserExtSource es : ues) {
            // get login from LDAP
            if (es.getExtSource().getName().equalsIgnoreCase("LDAPMU")) {
                // get only UCO
                authorId = es.getLogin();
                break;
            // get login from IDP
            } else if (es.getExtSource().getName().equalsIgnoreCase("https://idp2.ics.muni.cz/idp/shibboleth")) {
                // get only UCO from UCO@mail.muni.cz
                authorId = es.getLogin().substring(0, es.getLogin().indexOf("@"));
                break;
            }
        }
        // check
        if (authorId.isEmpty()) {
            throw new CabinetException("You don't have assigned identity in Perun for MU (LDAPMU / Shibboleth IDP).", ErrorCodes.NO_IDENTITY_FOR_PUBLICATION_SYSTEM);
        }
        // get publications
        result.addAll(findPublicationsInPubSys(authorId, yearSince, yearTill, ps));
        return result;
    // PROCESS ZCU 3.0 PUB SYS
    } else if (ps.getLoginNamespace().equalsIgnoreCase("zcu")) {
        // search is based on "lastName,firstName"
        String authorId = user.getLastName() + "," + user.getFirstName();
        result.addAll(findPublicationsInPubSys(authorId, yearSince, yearTill, ps));
        return result;
    } else {
        log.error("Publication System with namespace: [{}] found but not supported for import.", pubSysNamespace);
        throw new CabinetException("PubSys namespace found but not supported for import.");
    }
}
Also used : UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) ArrayList(java.util.ArrayList) Publication(cz.metacentrum.perun.cabinet.model.Publication) PublicationSystem(cz.metacentrum.perun.cabinet.model.PublicationSystem) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException)

Example 18 with Publication

use of cz.metacentrum.perun.cabinet.model.Publication in project perun by CESNET.

the class CabinetManagerBlImpl method findPublicationsInPubSys.

// methods --------------------------------------
public List<Publication> findPublicationsInPubSys(String authorId, int yearSince, int yearTill, PublicationSystem ps) throws CabinetException {
    if (StringUtils.isBlank(authorId))
        throw new CabinetException("AuthorId cannot be empty while searching for publications");
    if (ps == null)
        throw new CabinetException("Publication system cannot be null while searching for publications");
    // authorId must be an publication system internal id i.e. UCO! not memberId, userId etc.
    PublicationSystemStrategy prezentator = null;
    try {
        log.debug("Attempting to instantiate class [{}]...", ps.getType());
        prezentator = (PublicationSystemStrategy) Class.forName(ps.getType()).newInstance();
        log.debug("Class [{}] successfully created.", ps.getType());
    } catch (Exception e) {
        throw new CabinetException(e);
    }
    HttpUriRequest request = prezentator.getHttpRequest(authorId, yearSince, yearTill, ps);
    HttpResponse response = prezentator.execute(request);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new CabinetException("Can't contact publication system. HTTP error code: " + response.getStatusLine().getStatusCode(), ErrorCodes.HTTP_IO_EXCEPTION);
    }
    List<Publication> publications = prezentator.parseHttpResponse(response);
    for (Publication p : publications) {
        // set pub system for founded publications
        p.setPublicationSystemId(ps.getId());
    }
    return publications;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpResponse(org.apache.http.HttpResponse) Publication(cz.metacentrum.perun.cabinet.model.Publication) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) PublicationSystemStrategy(cz.metacentrum.perun.cabinet.strategy.PublicationSystemStrategy) InternalErrorException(cz.metacentrum.perun.core.api.exceptions.InternalErrorException) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) AttributeNotExistsException(cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException) UserNotExistsException(cz.metacentrum.perun.core.api.exceptions.UserNotExistsException) PerunException(cz.metacentrum.perun.core.api.exceptions.PerunException)

Example 19 with Publication

use of cz.metacentrum.perun.cabinet.model.Publication in project perun by CESNET.

the class PublicationManagerBlImpl method updatePublication.

@Override
public Publication updatePublication(PerunSession sess, Publication publication) throws CabinetException, InternalErrorException {
    if (publication.getId() == 0 || publication.getExternalId() == 0 || publication.getPublicationSystemId() == 0) {
        // such publication can't exists
        throw new CabinetException("Publication doesn't exists: " + publication, ErrorCodes.PUBLICATION_NOT_EXISTS);
    }
    // strip long params in new publication
    stripLongParams(publication);
    //don't create already existing publication (same id or externalId&&pubSysId)
    Publication dbPublication = getPublicationByExternalId(publication.getExternalId(), publication.getPublicationSystemId());
    if (publication.getId() != (dbPublication.getId())) {
        throw new CabinetException("Cannot update to duplicate publication: " + publication, ErrorCodes.PUBLICATION_ALREADY_EXISTS);
    }
    // save old pub
    Publication oldPub = getPublicationById(publication.getId());
    // update publication in DB
    getPublicationManagerDao().updatePublication(sess, publication);
    log.debug("{} updated.", publication);
    // if updated and rank or category was changed
    if ((oldPub.getRank() != publication.getRank()) || (oldPub.getCategoryId() != publication.getCategoryId())) {
        synchronized (CabinetManagerBlImpl.class) {
            // update coefficient for all it's authors
            List<Author> authors = getAuthorshipManagerBl().getAuthorsByPublicationId(oldPub.getId());
            for (Author a : authors) {
                getCabinetManagerBl().updatePriorityCoefficient(sess, a.getId(), getAuthorshipManagerBl().calculateNewRank(a.getAuthorships()));
            }
        }
    }
    return publication;
}
Also used : Publication(cz.metacentrum.perun.cabinet.model.Publication) Author(cz.metacentrum.perun.cabinet.model.Author) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException)

Example 20 with Publication

use of cz.metacentrum.perun.cabinet.model.Publication in project perun by CESNET.

the class CabinetBaseIntegrationTest method beforeClass.

// test -------------------------------
@Before
public void beforeClass() throws Exception {
    //do only once for all tests
    if (init)
        return;
    // principal
    PerunPrincipal pp = new PerunPrincipal("perunTests", ExtSourcesManager.EXTSOURCE_NAME_INTERNAL, ExtSourcesManager.EXTSOURCE_INTERNAL);
    sess = perun.getPerunSession(pp, new PerunClient());
    // setup world
    User user = new User();
    user.setLastName("cabinetTestUser");
    user.setServiceUser(false);
    user = perun.getUsersManagerBl().createUser(sess, user);
    USER_ID = user.getId();
    User user2 = new User();
    user2.setLastName("cabinetTestUser2");
    user2.setServiceUser(false);
    user2 = perun.getUsersManagerBl().createUser(sess, user2);
    USER_ID_2 = user2.getId();
    // owner
    Owner owner = new Owner();
    owner.setName("PubOwner");
    owner.setContact("Call me");
    owner.setType(OwnerType.administrative);
    this.owner = perun.getOwnersManagerBl().createOwner(sess, owner);
    // category
    c1 = new Category(0, "patent", 3.9);
    c1 = getCabinetManager().createCategory(sess, c1);
    // publication systems
    PublicationSystem ps = new PublicationSystem();
    ps.setFriendlyName("OBD");
    ps.setLoginNamespace("zcu");
    ps.setUrl("http://obd.zcu.cz:6443/fcgi/verso.fpl?");
    ps.setType("cz.metacentrum.perun.cabinet.strategy.impl.OBD30Strategy");
    pubSysZcu = getCabinetManager().createPublicationSystem(sess, ps);
    assertTrue(pubSysZcu.getId() > 0);
    PublicationSystem ps2 = new PublicationSystem();
    ps2.setFriendlyName("Masarykova Univerzita - Prezentátor");
    ps2.setLoginNamespace("mu");
    ps2.setUrl("https://is.muni.cz/auth/prezentator/index.pl");
    ps2.setUsername(cabinetProperties.getProperty("perun.cabinet.mu.login"));
    ps2.setPassword(cabinetProperties.getProperty("perun.cabinet.mu.password"));
    ps2.setType("cz.metacentrum.perun.cabinet.strategy.impl.MUStrategy");
    pubSysMu = getCabinetManager().createPublicationSystem(sess, ps2);
    assertTrue(pubSysMu.getId() > 0);
    // create publication
    Publication p1 = new Publication();
    p1.setCategoryId(c1.getId());
    p1.setExternalId(666);
    p1.setPublicationSystemId(ps.getId());
    p1.setCreatedBy(sess.getPerunPrincipal().getActor());
    p1.setCreatedDate(new Date());
    p1.setTitle("Some title");
    p1.setIsbn("ISBN");
    p1.setMain("MAIN");
    p1.setYear(2020);
    p1.setRank(0.0);
    p1.setLocked(false);
    p1.setDoi("DOI1");
    Publication p2 = new Publication();
    p2.setCategoryId(c1.getId());
    p2.setExternalId(333);
    p2.setPublicationSystemId(ps.getId());
    p2.setCreatedBy(sess.getPerunPrincipal().getActor());
    p2.setCreatedDate(new Date());
    p2.setTitle("Some title vol. 2");
    p2.setIsbn("ISBN2");
    p2.setMain("MAIN2");
    p2.setYear(2025);
    p2.setRank(0.0);
    p2.setLocked(false);
    p2.setDoi("DOI2");
    publicationOne = getCabinetManager().createPublication(sess, p1);
    publicationTwo = getCabinetManager().createPublication(sess, p2);
    Authorship a1 = new Authorship();
    a1.setCreatedBy(sess.getPerunPrincipal().getActor());
    a1.setCreatedDate(new Date());
    // for PUB 1
    a1.setPublicationId(p1.getId());
    a1.setUserId(USER_ID);
    Authorship a2 = new Authorship();
    a2.setCreatedBy(sess.getPerunPrincipal().getActor());
    a2.setCreatedDate(new Date());
    // for PUB 1
    a2.setPublicationId(p1.getId());
    a2.setUserId(USER_ID_2);
    a1 = getCabinetManager().createAuthorship(sess, a1);
    a2 = getCabinetManager().createAuthorship(sess, a2);
    authorshipOne = a1;
    authorshipTwo = a2;
    init = true;
}
Also used : Category(cz.metacentrum.perun.cabinet.model.Category) Authorship(cz.metacentrum.perun.cabinet.model.Authorship) Publication(cz.metacentrum.perun.cabinet.model.Publication) PublicationSystem(cz.metacentrum.perun.cabinet.model.PublicationSystem) Date(java.util.Date) Before(org.junit.Before)

Aggregations

Publication (cz.metacentrum.perun.cabinet.model.Publication)20 CabinetException (cz.metacentrum.perun.cabinet.bl.CabinetException)9 Test (org.junit.Test)8 ArrayList (java.util.ArrayList)6 Author (cz.metacentrum.perun.cabinet.model.Author)5 InternalErrorException (cz.metacentrum.perun.core.api.exceptions.InternalErrorException)5 Date (java.util.Date)5 Category (cz.metacentrum.perun.cabinet.model.Category)3 PublicationSystem (cz.metacentrum.perun.cabinet.model.PublicationSystem)3 IOException (java.io.IOException)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3 XPathExpressionException (javax.xml.xpath.XPathExpressionException)3 Node (org.w3c.dom.Node)3 NodeList (org.w3c.dom.NodeList)3 SAXException (org.xml.sax.SAXException)3 SAXParseException (org.xml.sax.SAXParseException)3 Authorship (cz.metacentrum.perun.cabinet.model.Authorship)2 UserNotExistsException (cz.metacentrum.perun.core.api.exceptions.UserNotExistsException)2 StringReader (java.io.StringReader)2 HashSet (java.util.HashSet)2