Search in sources :

Example 21 with NextProtException

use of org.nextprot.api.commons.exception.NextProtException in project nextprot-api by calipho-sib.

the class StatementTransformationUtil method computeTargetIsoformsForProteoformAnnotation.

public static TargetIsoformSet computeTargetIsoformsForProteoformAnnotation(Statement proteoformStatement, IsoformMappingService isoformMappingService, List<Statement> subjectsForThisProteoform, boolean isIsoSpecific, String isoSpecificAccession, List<String> isoformAccessions) {
    List<String> isoformsToBeConsidered = new ArrayList<>();
    if (isIsoSpecific) {
        isoformsToBeConsidered.add(isoSpecificAccession);
    } else {
        isoformsToBeConsidered.addAll(isoformAccessions);
    }
    Set<TargetIsoformStatementPosition> result = new TreeSet<>();
    for (String isoformAccession : isoformsToBeConsidered) {
        String name = null;
        boolean allOk = true;
        for (Statement s : subjectsForThisProteoform) {
            TargetIsoformSet targetIsoforms = TargetIsoformSet.deSerializeFromJsonString(s.getValue(StatementField.TARGET_ISOFORMS));
            List<TargetIsoformStatementPosition> targetIsoformsFiltered = targetIsoforms.stream().filter(ti -> ti.getIsoformAccession().equals(isoformAccession)).collect(Collectors.toList());
            if (targetIsoformsFiltered.isEmpty()) {
                LOGGER.debug("(skip) Could not map to isoform " + isoformAccession);
                allOk = false;
                break;
            } else if (targetIsoformsFiltered.size() > 1) {
                throw new NextProtException("Something got wrong. Found more than one target isoform for same accession" + isoformAccession);
            }
            TargetIsoformStatementPosition tisp = targetIsoformsFiltered.iterator().next();
            if (name == null) {
                name = tisp.getName();
            } else {
                name += (" + " + tisp.getName());
            }
        }
        if (name != null && allOk) {
            if (isIsoSpecific) {
                result.add(new TargetIsoformStatementPosition(isoformAccession, IsoTargetSpecificity.SPECIFIC.name(), name));
            } else {
                result.add(new TargetIsoformStatementPosition(isoformAccession, IsoTargetSpecificity.UNKNOWN.name(), name));
            }
        }
    }
    return new TargetIsoformSet(result);
}
Also used : NPreconditions(org.nextprot.api.commons.exception.NPreconditions) java.util(java.util) FeatureQueryResult(org.nextprot.api.isoform.mapper.domain.FeatureQueryResult) IsoTargetSpecificity(org.nextprot.commons.constants.IsoTargetSpecificity) org.nextprot.commons.statements(org.nextprot.commons.statements) NextProtException(org.nextprot.api.commons.exception.NextProtException) IsoformFeatureResult(org.nextprot.api.isoform.mapper.domain.impl.SingleFeatureQuerySuccessImpl.IsoformFeatureResult) IsoformMappingService(org.nextprot.api.isoform.mapper.service.IsoformMappingService) Collectors(java.util.stream.Collectors) FeatureQuerySuccess(org.nextprot.api.isoform.mapper.domain.FeatureQuerySuccess) SingleFeatureQuery(org.nextprot.api.isoform.mapper.domain.SingleFeatureQuery) Logger(org.apache.log4j.Logger) AnnotationType(org.nextprot.commons.statements.constants.AnnotationType) IsoformService(org.nextprot.api.core.service.IsoformService) FeatureQueryFailure(org.nextprot.api.isoform.mapper.domain.FeatureQueryFailure) Isoform(org.nextprot.api.core.domain.Isoform) NextProtException(org.nextprot.api.commons.exception.NextProtException)

Example 22 with NextProtException

use of org.nextprot.api.commons.exception.NextProtException in project nextprot-api by calipho-sib.

the class RdfHelpServiceImpl method getRdfTypeFullInfoList.

@Cacheable("rdfhelp")
@Override
public synchronized List<RdfTypeInfo> getRdfTypeFullInfoList() {
    long t0 = System.currentTimeMillis();
    Set<String> rdfTypesNames = getRdfTypesNames();
    List<Future<RdfTypeInfo>> rdfFutureTypes = new ArrayList<Future<RdfTypeInfo>>();
    List<RdfTypeInfo> rdfTypes = Collections.synchronizedList(new ArrayList<RdfTypeInfo>());
    ExecutorService executor = Executors.newFixedThreadPool(NUMBER_THREADS);
    for (String rdfTypeName : rdfTypesNames) {
        // LOGGER.info("step1 - found rdf:type name " + rdfTypeName);
        Future<RdfTypeInfo> futureRdfTypeInfo = executor.submit(new FillRdfTypeInfoTask(this, rdfTypeName));
        rdfFutureTypes.add(futureRdfTypeInfo);
    }
    executor.shutdown();
    try {
        executor.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        e.printStackTrace();
        throw new NextProtException(e.getLocalizedMessage());
    }
    for (Future<RdfTypeInfo> futureRdfTypeInfo : rdfFutureTypes) {
        try {
            rdfTypes.add(futureRdfTypeInfo.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    // now populate parent and parent triples of each type
    for (RdfTypeInfo rti : rdfTypes) {
        // LOGGER.info("step2 - updating rdf:type " + rti.getTypeName());
        for (RdfTypeInfo parent : rdfTypes) {
            List<TripleInfo> triples = parent.findTriplesWithObjectType(rti.getTypeName());
            if (triples.size() > 0) {
                // LOGGER.info("step3 - linking parent rdf:type " + parent.getTypeName()  + " to rdf:type " + rti.getTypeName() + " , triple size: " + triples.size());
                rti.addParent(parent.getTypeName());
                for (TripleInfo triple : triples) rti.addParentTriple(triple);
            }
        }
    }
    Map<String, RdfTypeInfo> fullMap = new HashMap<String, RdfTypeInfo>();
    for (RdfTypeInfo rti : rdfTypes) {
        fullMap.put(rti.getTypeName(), rti);
    }
    if (fullMap.containsKey(":Entry"))
        buildPathToOrigin(fullMap, fullMap.get(":Entry"), "?entry ", 0);
    long seconds = (System.currentTimeMillis() - t0) / 1000;
    String duration = String.format("%d:%02d:%02d", seconds / 3600, (seconds % 3600) / 60, (seconds % 60)) + " [H:MM:SS]";
    LOGGER.info("errors: " + errorCount);
    LOGGER.info("duration: " + duration);
    return rdfTypes;
}
Also used : HashMap(java.util.HashMap) RdfTypeInfo(org.nextprot.api.rdf.domain.RdfTypeInfo) ArrayList(java.util.ArrayList) TripleInfo(org.nextprot.api.rdf.domain.TripleInfo) NextProtException(org.nextprot.api.commons.exception.NextProtException) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) Cacheable(org.springframework.cache.annotation.Cacheable)

Example 23 with NextProtException

use of org.nextprot.api.commons.exception.NextProtException in project nextprot-api by calipho-sib.

the class SparqlServiceImpl method findEntries.

@Override
@Cacheable("sparql")
public List<String> findEntries(String sparql, String sparqlEndpointUrl, String sparqlTitle) {
    String query = SparqlUtils.buildQuery(prefix, sparql);
    List<String> results = new ArrayList<String>();
    QueryExecution qExec = null;
    try {
        qExec = QueryExecutionFactory.sparqlService(sparqlEndpointUrl, query);
    } catch (QueryParseException qe) {
        String msg = ExceptionUtils.fixLineNumberInErrorMessage(qe.getLocalizedMessage());
        throw new NextProtException("Malformed SPARQL: " + msg);
    }
    ResultSet rs = qExec.execSelect();
    /**
     * This give an empty graph....
     * Model m = rs.getResourceModel();
     * Graph g = m.getGraph();
     * System.err.println("The graph is" + g);
     */
    Var x = Var.alloc("entry");
    while (rs.hasNext()) {
        Binding b = rs.nextBinding();
        Node entryNode = b.get(x);
        if (entryNode == null) {
            qExec.close();
            throw new NextProtException("Bind your protein result to a variable called ?entry. Example: \"?entry :classifiedWith cv:KW-0813.\"");
        } else if (entryNode.toString().indexOf(ENTRY_SUFFIX_URI) == -1) {
            qExec.close();
            throw new NextProtException("Any entry found in the output, however was found: " + entryNode.toString());
        }
        String entry = entryNode.toString().replace(ENTRY_SUFFIX_URI, "").trim();
        results.add(entry);
    }
    qExec.close();
    return results;
}
Also used : Binding(com.hp.hpl.jena.sparql.engine.binding.Binding) NextProtException(org.nextprot.api.commons.exception.NextProtException) Var(com.hp.hpl.jena.sparql.core.Var) Node(com.hp.hpl.jena.graph.Node) ArrayList(java.util.ArrayList) ResultSet(com.hp.hpl.jena.query.ResultSet) QueryExecution(com.hp.hpl.jena.query.QueryExecution) QueryParseException(com.hp.hpl.jena.query.QueryParseException) Cacheable(org.springframework.cache.annotation.Cacheable)

Example 24 with NextProtException

use of org.nextprot.api.commons.exception.NextProtException in project nextprot-api by calipho-sib.

the class SparqlQueryRunnerController method runSparqlQueries.

private void runSparqlQueries(HttpServletResponse response, HttpServletRequest request, String tags, AccessMode accessMode) {
    String fileName = "run-sparql-queries.tsv";
    response.setContentType("text/tab-separated-values");
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    long t0 = System.currentTimeMillis();
    List<String> expectedTagList = Arrays.asList(tags.split(","));
    List<UserQuery> queryList = UserQueryUtils.filterByTagList(userQueryService.getNxqQueries(), expectedTagList);
    try {
        // write header
        PrintWriter w = response.getWriter();
        w.write("SPARQL end point" + TAB + sparqlEndpoint.getUrl() + CRLF);
        w.write("Access mode\t" + accessMode.toString() + CRLF);
        w.write("Running queries with tags\t" + tags + CRLF);
        w.write("Query count\t" + queryList.size() + CRLF);
        w.write("Starting at\t" + new Date() + CRLF);
        w.write(CRLF);
        w.write("Results" + CRLF);
        w.flush();
        for (String col : COLUMNS) w.write(col + TAB);
        w.write(CRLF);
        // write output of each query
        int errorCount = 0;
        int queryNum = 0;
        for (UserQuery q : queryList) {
            queryNum++;
            Map<String, String> result = getQueryResult(q, accessMode);
            if (result.get(COL_STATUS).equals("error"))
                errorCount++;
            for (String col : COLUMNS) w.write(result.get(col) + TAB);
            w.write(CRLF);
            w.flush();
            System.out.println(new Date() + " - query " + String.valueOf(queryNum) + "/" + String.valueOf(queryList.size()) + " - " + result.get(COL_ID) + " - " + result.get(COL_STATUS) + " - " + result.get(COL_ROWS));
        }
        long t = (System.currentTimeMillis() - t0) / 1000;
        w.write(CRLF);
        w.write("Total duration[s]" + TAB + String.valueOf(t) + CRLF);
        w.write("Total error(s)" + TAB + String.valueOf(errorCount) + CRLF);
        w.write("Status" + TAB + (errorCount == 0 ? "OK" : "ERROR(S)") + CRLF);
        w.write("Ending at\t" + new Date() + CRLF);
        w.write("End" + CRLF);
        w.flush();
    } catch (Exception e) {
        throw new NextProtException(e.getMessage(), e);
    }
}
Also used : NextProtException(org.nextprot.api.commons.exception.NextProtException) UserQuery(org.nextprot.api.user.domain.UserQuery) Date(java.util.Date) SparqlEndpoint(org.nextprot.api.rdf.service.SparqlEndpoint) SparqlProxyEndpoint(org.nextprot.api.rdf.service.SparqlProxyEndpoint) NextProtException(org.nextprot.api.commons.exception.NextProtException) PrintWriter(java.io.PrintWriter)

Example 25 with NextProtException

use of org.nextprot.api.commons.exception.NextProtException in project nextprot-api by calipho-sib.

the class UserProteinListUtils method parseAccessionNumbers.

/**
 * Extract set of accession numbers from uploaded file. Only nextprot or
 * uniprot accession numbers allowed.
 *
 * <p>
 * uniprot accession numbers should be converted in nextprot (prefixed with "NX_")
 * </p>
 *
 * @param file the uploaded file
 * @param ignoreEntryNotFoundException if true this method ignores EntryNotFoundException else throw it
 *
 * @return a set of accession numbers
 * @throws IOException
 *             input exception occurred
 */
public static Set<String> parseAccessionNumbers(MultipartFile file, Set<String> validAccessionNumbers, boolean ignoreEntryNotFoundException) throws NextProtException {
    NPreconditions.checkNotNull(file, "The uploaded file should not be null");
    InputStream inputStream;
    try {
        inputStream = file.getInputStream();
        if (file.getInputStream() != null)
            return parseAccessionNumbers(new InputStreamReader(inputStream), validAccessionNumbers, ignoreEntryNotFoundException);
    } catch (IOException e) {
        throw new NextProtException(e);
    }
    return new HashSet<>();
}
Also used : NextProtException(org.nextprot.api.commons.exception.NextProtException) HashSet(java.util.HashSet)

Aggregations

NextProtException (org.nextprot.api.commons.exception.NextProtException)68 IOException (java.io.IOException)30 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)9 ApiMethod (org.jsondoc.core.annotation.ApiMethod)8 OutputStream (java.io.OutputStream)7 NamedParameterJdbcTemplate (org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate)7 Cacheable (org.springframework.cache.annotation.Cacheable)6 Isoform (org.nextprot.api.core.domain.Isoform)5 SolrServerException (org.apache.solr.client.solrj.SolrServerException)4 Annotation (org.nextprot.api.core.domain.annotation.Annotation)4 NextprotMediaType (org.nextprot.api.core.service.export.format.NextprotMediaType)4 MapSqlParameterSource (org.springframework.jdbc.core.namedparam.MapSqlParameterSource)4 java.util (java.util)3 ArrayList (java.util.ArrayList)3 HashSet (java.util.HashSet)3 CvTerm (org.nextprot.api.core.domain.CvTerm)3 AnnotationVariant (org.nextprot.api.core.domain.annotation.AnnotationVariant)3 Query (org.nextprot.api.solr.Query)3 SearchResult (org.nextprot.api.solr.SearchResult)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2