public AbstractAjaxResponder(HttpServlet servlet, VitroRequest vreq, HttpServletResponse resp) {
   this.servlet = servlet;
   this.vreq = vreq;
   this.resp = resp;
   this.indDao = vreq.getWebappDaoFactory().getIndividualDao();
   this.uaDao = vreq.getWebappDaoFactory().getUserAccountsDao();
 }
Beispiel #2
0
  @Override
  protected void doRequest(VitroRequest vreq, HttpServletResponse response) {

    String errorMsg = null;
    String rankPredicate = vreq.getParameter(RANK_PREDICATE_PARAMETER_NAME);
    if (rankPredicate == null) {
      errorMsg = "No rank parameter specified";
      log.error(errorMsg);
      doError(response, errorMsg, HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    String[] individualUris = vreq.getParameterValues(INDIVIDUAL_PREDICATE_PARAMETER_NAME);
    if (individualUris == null || individualUris.length == 0) {
      errorMsg = "No individuals specified";
      log.error(errorMsg);
      doError(response, errorMsg, HttpServletResponse.SC_BAD_REQUEST);
      return;
    }

    WebappDaoFactory wadf = vreq.getWebappDaoFactory();
    if (vreq.getWebappDaoFactory() == null) {
      errorMsg = "No WebappDaoFactory available";
      log.error(errorMsg);
      doError(response, errorMsg, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }

    DataPropertyStatementDao dpsDao = wadf.getDataPropertyStatementDao();
    if (dpsDao == null) {
      errorMsg = "No DataPropertyStatementDao available";
      log.error(errorMsg);
      doError(response, errorMsg, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return;
    }

    // check permissions
    // TODO: (bdc34)This is not yet implemented, must check the IDs against the policies for
    // permissons before doing an edit!
    // rjy7 This should be inherited from the superclass
    boolean hasPermission = true;
    if (!hasPermission) {
      // if not okay, send error message
      doError(response, "Insufficent permissions", HttpStatus.SC_UNAUTHORIZED);
      return;
    }

    // This may not be the most efficient way. Should we instead build up a Model of retractions and
    // additions, so
    // we only hit the database once?
    reorderIndividuals(individualUris, vreq, rankPredicate);

    response.setStatus(HttpServletResponse.SC_OK);
  }
  // Prepare for update or non-update
  // Originally included in edit request dispatch controller but moved here due to
  // exceptions such as default add missing individual form
  void prepare(VitroRequest vreq, EditConfigurationVTwo editConfig) {
    // setup the model selectors for query, write and display models on editConfig
    setupModelSelectorsFromVitroRequest(vreq, editConfig);

    OntModel queryModel = vreq.getJenaOntModel(); // (OntModel)vreq.getAttribute("jenaOntModel");

    if (editConfig.getSubjectUri() == null)
      editConfig.setSubjectUri(EditConfigurationUtils.getSubjectUri(vreq));
    if (editConfig.getPredicateUri() == null)
      editConfig.setPredicateUri(EditConfigurationUtils.getPredicateUri(vreq));

    String objectUri = EditConfigurationUtils.getObjectUri(vreq);
    Integer dataKey = EditConfigurationUtils.getDataHash(vreq);
    if (objectUri != null && !objectUri.trim().isEmpty()) {
      // editing existing object
      if (editConfig.getObject() == null)
        editConfig.setObject(EditConfigurationUtils.getObjectUri(vreq));
      editConfig.prepareForObjPropUpdate(queryModel);
    } else if (dataKey != null) { // edit of a data prop statement
      // do nothing since the data prop form generator must take care of it
      editConfig.prepareForDataPropUpdate(
          queryModel, vreq.getWebappDaoFactory().getDataPropertyDao());
    } else {
      // this might be a create new or a form
      editConfig.prepareForNonUpdate(queryModel);
    }
  }
 private void processOutputModelRequest(VitroRequest vreq, HttpServletResponse response) {
   String modelNameStr = vreq.getParameter("modelName");
   Model model = getModel(modelNameStr, vreq);
   JenaOutputUtils.setNameSpacePrefixes(model, vreq.getWebappDaoFactory());
   model.enterCriticalSection(Lock.READ);
   try {
     OutputStream out = response.getOutputStream();
     response.setContentType("application/x-turtle");
     // out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n".getBytes());
     model.write(out, "TTL");
     out.flush();
     out.close();
   } catch (com.hp.hpl.jena.shared.CannotEncodeCharacterException cece) {
     // there's got to be a better way to do this
     byte[] badCharBytes = String.valueOf(cece.getBadChar()).getBytes();
     String errorMsg = "Cannot encode character with byte values: (decimal) ";
     for (int i = 0; i < badCharBytes.length; i++) {
       errorMsg += badCharBytes[i];
     }
     throw new RuntimeException(errorMsg, cece);
   } catch (Exception e) {
     log.error(e, e);
   } finally {
     model.leaveCriticalSection();
   }
 }
  @Override
  protected ResponseValues processRequest(VitroRequest vreq) {
    // get the EditConfiguration
    EditConfigurationVTwo configuration = EditConfigurationUtils.getEditConfiguration(vreq);
    if (configuration == null) throw new Error("No edit configuration found.");

    // get the EditSubmission
    MultiValueEditSubmission submission =
        new MultiValueEditSubmission(vreq.getParameterMap(), configuration);
    EditSubmissionUtils.putEditSubmissionInSession(vreq.getSession(), submission);

    // if errors, return error response
    ResponseValues errorResponse = doValidationErrors(vreq, configuration, submission);
    if (errorResponse != null) return errorResponse;

    // get the models to work with in case the write model and query model are not the defaults
    OntModel queryModel = configuration.getQueryModelSelector().getModel(vreq, getServletContext());
    OntModel writeModel = configuration.getWriteModelSelector().getModel(vreq, getServletContext());

    // If data property check for back button confusion
    boolean isBackButton = checkForBackButtonConfusion(configuration, vreq, queryModel);
    if (isBackButton) {
      // Process back button issues and do a return here
      return doProcessBackButton(configuration, submission, vreq);
    }

    // Otherwise, process as usual

    AdditionsAndRetractions changes;
    try {

      ProcessRdfForm prf =
          new ProcessRdfForm(configuration, new NewURIMakerVitro(vreq.getWebappDaoFactory()));
      changes = prf.process(configuration, submission);

    } catch (Exception e) {
      throw new Error(e);
    }

    if (configuration.isUseDependentResourceDelete())
      changes = ProcessRdfForm.addDependentDeletes(changes, queryModel);

    N3EditUtils.preprocessModels(changes, configuration, vreq);

    ProcessRdfForm.applyChangesToWriteModel(
        changes, queryModel, writeModel, EditN3Utils.getEditorUri(vreq));

    // Here we are trying to get the entity to return to URL,
    // More involved processing for data property apparently
    String entityToReturnTo = N3EditUtils.processEntityToReturnTo(configuration, submission, vreq);

    // For data property processing, need to update edit configuration for back button
    N3EditUtils.updateEditConfigurationForBackButton(configuration, submission, vreq, writeModel);
    PostEditCleanupController.doPostEditCleanup(vreq);
    return PostEditCleanupController.doPostEditRedirect(vreq, entityToReturnTo);
  }
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    super.doGet(req, resp);
    resp.setContentType("application/json");
    VitroRequest vreq = new VitroRequest(req);

    try {
      if (vreq.getParameter("query") != null || vreq.getParameter("queries") != null) {
        JSONObject qJson = getResult(vreq, req, resp);
        log.debug("result: " + qJson.toString());
        String responseStr =
            (vreq.getParameter("callback") == null)
                ? qJson.toString()
                : vreq.getParameter("callback") + "(" + qJson.toString() + ")";
        // System.out.println("JSONReconcileServlet result: " + responseStr);
        ServletOutputStream out = resp.getOutputStream();
        out.print(responseStr);
      } else { // metadata
        String defaultNamespace = null;
        String defaultTypeList = null;
        String serverName = null;
        int serverPort = req.getServerPort();

        if (vreq.getWebappDaoFactory() != null) {
          defaultNamespace = vreq.getWebappDaoFactory().getDefaultNamespace();
        }
        defaultTypeList =
            ConfigurationProperties.getBean(req).getProperty("Vitro.reconcile.defaultTypeList");
        serverName = req.getServerName();
        JSONObject metaJson =
            getMetadata(req, resp, defaultNamespace, defaultTypeList, serverName, serverPort);
        String callbackStr =
            (vreq.getParameter("callback") == null) ? "" : vreq.getParameter("callback");
        ServletOutputStream out = resp.getOutputStream();
        out.print(callbackStr + "(" + metaJson.toString() + ")");
      }
    } catch (Exception ex) {
      log.warn(ex, ex);
    }
  }
  // Check for "back button" confusion specifically for data property editing although need to check
  // if this applies to object property editing?
  // TODO: Check if only applicable to data property editing
  private boolean checkForBackButtonConfusion(
      EditConfigurationVTwo editConfig, VitroRequest vreq, Model model) {
    // back button confusion limited to data property
    if (EditConfigurationUtils.isObjectProperty(editConfig.getPredicateUri(), vreq)) {
      return false;
    }

    WebappDaoFactory wdf = vreq.getWebappDaoFactory();
    if (!editConfig.isDataPropertyUpdate()) return false;

    Integer dpropHash = editConfig.getDatapropKey();
    DataPropertyStatement dps =
        RdfLiteralHash.getPropertyStmtByHash(
            editConfig.getSubjectUri(), editConfig.getPredicateUri(), dpropHash, model);
    if (dps != null) return false;

    DataProperty dp = wdf.getDataPropertyDao().getDataPropertyByURI(editConfig.getPredicateUri());
    if (dp != null) {
      if (dp.getDisplayLimit() == 1 /* || dp.isFunctional() */) return false;
      else return true;
    }
    return false;
  }
  @Override
  protected ResponseValues processRequest(VitroRequest vreq) {
    // There may be other non-html formats in the future
    Format format = getFormat(vreq);
    boolean wasXmlRequested = Format.XML == format;
    log.debug("xml was the requested format");
    boolean wasHtmlRequested = !wasXmlRequested;

    try {
      Portal portal = vreq.getPortal();
      PortalFlag portalFlag = vreq.getPortalFlag();

      // make sure an IndividualDao is available
      if (vreq.getWebappDaoFactory() == null
          || vreq.getWebappDaoFactory().getIndividualDao() == null) {
        log.error("Could not get webappDaoFactory or IndividualDao");
        throw new Exception("Could not access model.");
      }
      IndividualDao iDao = vreq.getWebappDaoFactory().getIndividualDao();
      VClassGroupDao grpDao = vreq.getWebappDaoFactory().getVClassGroupDao();
      VClassDao vclassDao = vreq.getWebappDaoFactory().getVClassDao();
      String alphaFilter = vreq.getParameter("alpha");

      int startIndex = 0;
      try {
        startIndex = Integer.parseInt(vreq.getParameter("startIndex"));
      } catch (Throwable e) {
        startIndex = 0;
      }
      log.debug("startIndex is " + startIndex);

      int hitsPerPage = defaultHitsPerPage;
      try {
        hitsPerPage = Integer.parseInt(vreq.getParameter("hitsPerPage"));
      } catch (Throwable e) {
        hitsPerPage = defaultHitsPerPage;
      }
      log.debug("hitsPerPage is " + hitsPerPage);

      int maxHitSize = defaultMaxSearchSize;
      if (startIndex >= defaultMaxSearchSize - hitsPerPage)
        maxHitSize = startIndex + defaultMaxSearchSize;
      if (alphaFilter != null) {
        maxHitSize = maxHitSize * 2;
        hitsPerPage = maxHitSize;
      }
      log.debug("maxHitSize is " + maxHitSize);

      String qtxt = vreq.getParameter(VitroQuery.QUERY_PARAMETER_NAME);
      Analyzer analyzer = getAnalyzer(getServletContext());

      Query query = null;
      try {
        query = getQuery(vreq, portalFlag, analyzer, qtxt);
        log.debug("query for '" + qtxt + "' is " + query.toString());
      } catch (ParseException e) {
        return doBadQuery(portal, qtxt, format);
      }

      IndexSearcher searcherForRequest = LuceneIndexFactory.getIndexSearcher(getServletContext());

      TopDocs topDocs = null;
      try {
        topDocs = searcherForRequest.search(query, null, maxHitSize);
      } catch (Throwable t) {
        log.error("in first pass at search: " + t);
        // this is a hack to deal with odd cases where search and index threads interact
        try {
          wait(150);
          topDocs = searcherForRequest.search(query, null, maxHitSize);
        } catch (Exception ex) {
          log.error(ex);
          String msg = makeBadSearchMessage(qtxt, ex.getMessage());
          if (msg == null) {
            msg = "The search request contained errors.";
          }
          return doFailedSearch(msg, qtxt, format);
        }
      }

      if (topDocs == null || topDocs.scoreDocs == null) {
        log.error("topDocs for a search was null");
        String msg = "The search request contained errors.";
        return doFailedSearch(msg, qtxt, format);
      }

      int hitsLength = topDocs.scoreDocs.length;
      if (hitsLength < 1) {
        return doNoHits(qtxt, format);
      }
      log.debug("found " + hitsLength + " hits");

      int lastHitToShow = 0;
      if ((startIndex + hitsPerPage) > hitsLength) {
        lastHitToShow = hitsLength;
      } else {
        lastHitToShow = startIndex + hitsPerPage - 1;
      }

      List<Individual> beans = new LinkedList<Individual>();
      for (int i = startIndex; i < topDocs.scoreDocs.length; i++) {
        try {
          if ((i >= startIndex) && (i <= lastHitToShow)) {
            Document doc = searcherForRequest.doc(topDocs.scoreDocs[i].doc);
            String uri = doc.get(Entity2LuceneDoc.term.URI);
            Individual ent = new IndividualImpl();
            ent.setURI(uri);
            ent = iDao.getIndividualByURI(uri);
            if (ent != null) beans.add(ent);
          }
        } catch (Exception e) {
          log.error("problem getting usable Individuals from search " + "hits" + e.getMessage());
        }
      }

      ParamMap pagingLinkParams = new ParamMap();
      pagingLinkParams.put("querytext", qtxt);
      pagingLinkParams.put("hitsPerPage", String.valueOf(hitsPerPage));

      if (wasXmlRequested) {
        pagingLinkParams.put(XML_REQUEST_PARAM, "1");
      }

      /* Start putting together the data for the templates */

      Map<String, Object> body = new HashMap<String, Object>();

      String classGroupParam = vreq.getParameter("classgroup");
      boolean classGroupFilterRequested = false;
      if (!StringUtils.isEmpty(classGroupParam)) {
        VClassGroup grp = grpDao.getGroupByURI(classGroupParam);
        classGroupFilterRequested = true;
        if (grp != null && grp.getPublicName() != null)
          body.put("classGroupName", grp.getPublicName());
      }

      String typeParam = vreq.getParameter("type");
      boolean typeFiltereRequested = false;
      if (!StringUtils.isEmpty(typeParam)) {
        VClass type = vclassDao.getVClassByURI(typeParam);
        typeFiltereRequested = true;
        if (type != null && type.getName() != null) body.put("typeName", type.getName());
      }

      /* Add classgroup and type refinement links to body */
      if (wasHtmlRequested) {
        // Search request includes no classgroup and no type, so add classgroup search refinement
        // links.
        if (!classGroupFilterRequested && !typeFiltereRequested) {
          List<VClassGroup> classgroups = getClassGroups(grpDao, topDocs, searcherForRequest);
          List<VClassGroupSearchLink> classGroupLinks =
              new ArrayList<VClassGroupSearchLink>(classgroups.size());
          for (VClassGroup vcg : classgroups) {
            if (vcg.getPublicName() != null) {
              classGroupLinks.add(new VClassGroupSearchLink(qtxt, vcg));
            }
          }
          body.put("classGroupLinks", classGroupLinks);

          // Search request is for a classgroup, so add rdf:type search refinement links
          // but try to filter out classes that are subclasses
        } else if (classGroupFilterRequested && !typeFiltereRequested) {
          List<VClass> vClasses = getVClasses(vclassDao, topDocs, searcherForRequest);
          List<VClassSearchLink> vClassLinks = new ArrayList<VClassSearchLink>(vClasses.size());
          for (VClass vc : vClasses) {
            vClassLinks.add(new VClassSearchLink(qtxt, vc));
          }
          body.put("classLinks", vClassLinks);
          pagingLinkParams.put("classgroup", classGroupParam);

          // This case is never displayed
        } else if (!StringUtils.isEmpty(alphaFilter)) {
          body.put("alphas", getAlphas(topDocs, searcherForRequest));
          alphaSortIndividuals(beans);
        } else {
          pagingLinkParams.put("type", typeParam);
        }
      }

      // Convert search result individuals to template model objects
      body.put(
          "individuals", ListedIndividualTemplateModel.getIndividualTemplateModelList(beans, vreq));

      body.put("querytext", qtxt);
      body.put("title", qtxt + " - " + portal.getAppName() + " Search Results");

      body.put("hitsLength", hitsLength);
      body.put("startIndex", startIndex);

      body.put(
          "pagingLinks",
          getPagingLinks(
              startIndex,
              hitsPerPage,
              hitsLength,
              maxHitSize,
              vreq.getServletPath(),
              pagingLinkParams));

      if (startIndex != 0) {
        body.put(
            "prevPage",
            getPreviousPageLink(startIndex, hitsPerPage, vreq.getServletPath(), pagingLinkParams));
      }
      if (startIndex < (hitsLength - hitsPerPage)) {
        body.put(
            "nextPage",
            getNextPageLink(startIndex, hitsPerPage, vreq.getServletPath(), pagingLinkParams));
      }

      String template = templateTable.get(format).get(Result.PAGED);

      return new TemplateResponseValues(template, body);
    } catch (Throwable e) {
      return doSearchError(e, format);
    }
  }
 /** may be null */
 private Object getName(EditConfigurationVTwo config, VitroRequest vreq) {
   Individual ind =
       vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(config.getSubjectUri());
   if (ind == null) return null;
   else return ind.getName();
 }
Beispiel #10
0
  private void reorderIndividuals(
      String[] individualUris, VitroRequest vreq, String rankPredicate) {
    // Testing new mechanism
    OntModel writeModel = vreq.getOntModelSelector().getABoxModel();
    Model additions = ModelFactory.createDefaultModel();
    Model retractions = ModelFactory.createDefaultModel();
    Property rankPredicateProperty = ResourceFactory.createProperty(rankPredicate);
    DataProperty dp =
        vreq.getWebappDaoFactory().getDataPropertyDao().getDataPropertyByURI(rankPredicate);
    String datapropURI = dp.getRangeDatatypeURI();
    int counter = 1;
    for (String individualUri : individualUris) {
      Resource individualResource = ResourceFactory.createResource(individualUri);
      // Deletions are all old statements with rank predicate
      retractions.add(
          writeModel.listStatements(individualResource, rankPredicateProperty, (RDFNode) null));
      log.debug("retractions = " + retractions);
      // New statement is new literal with the data property from
      Literal dataLiteral = null;
      if (datapropURI != null && datapropURI.length() > 0) {
        dataLiteral =
            ResourceFactory.createTypedLiteral(
                String.valueOf(counter), TypeMapper.getInstance().getSafeTypeByName(datapropURI));
      } else {
        dataLiteral = ResourceFactory.createPlainLiteral(String.valueOf(counter));
      }
      additions.add(individualResource, rankPredicateProperty, dataLiteral);
      log.debug("additions = " + additions);
      counter++;
    }

    Lock lock = null;
    try {
      lock = writeModel.getLock();
      lock.enterCriticalSection(Lock.WRITE);
      writeModel.getBaseModel().notifyEvent(new EditEvent(null, true));
      writeModel.remove(retractions);
      writeModel.add(additions);
    } catch (Throwable t) {
      log.error("error adding edit change n3required model to in memory model \n" + t.getMessage());
    } finally {
      writeModel.getBaseModel().notifyEvent(new EditEvent(null, false));
      lock.leaveCriticalSection();
    }

    // old code that for some reason doesn't seem to actually commit the changes
    /*
    * int counter = 1;
      for (String individualUri : individualUris) {
          // Retract all existing rank statements for this individual
          dpsDao.deleteDataPropertyStatementsForIndividualByDataProperty(individualUri, rankPredicate);

          // Then add the new rank statement for this individual
          // insertNewDataPropertyStatement will insert the rangeDatatype of the property, so we don't need to set that here.
          dpsDao.insertNewDataPropertyStatement(new DataPropertyStatementImpl(individualUri, rankPredicate, String.valueOf(counter)));

          counter++;
      }

    */

  }
Beispiel #11
0
  public PropertyListConfig(
      ObjectPropertyTemplateModel optm,
      TemplateLoader templateLoader,
      VitroRequest vreq,
      ObjectProperty op,
      boolean editing)
      throws InvalidConfigurationException {

    this.optm = optm;
    this.vreq = vreq;
    WebappDaoFactory wadf = vreq.getWebappDaoFactory();
    this.templateLoader = templateLoader;

    // Get the custom config filename
    String configFileName = wadf.getObjectPropertyDao().getCustomListViewConfigFileName(op);
    if (configFileName == null) { // no custom config; use default config
      configFileName = DEFAULT_CONFIG_FILE_NAME;
    }
    log.debug(
        "Using list view config file " + configFileName + " for object property " + op.getURI());

    String configFilePath = getConfigFilePath(configFileName);

    try {
      File config = new File(configFilePath);
      if (!isDefaultConfig(configFileName) && !config.exists()) {
        log.warn(
            "Can't find config file "
                + configFilePath
                + " for object property "
                + op.getURI()
                + "\n"
                + ". Using default config file instead.");
        configFilePath = getConfigFilePath(DEFAULT_CONFIG_FILE_NAME);
        // Should we test for the existence of the default, and throw an error if it doesn't exist?
      }
      setValuesFromConfigFile(configFilePath, wadf, editing);

    } catch (Exception e) {
      log.error(
          "Error processing config file " + configFilePath + " for object property " + op.getURI(),
          e);
      // What should we do here?
    }

    if (!isDefaultConfig(configFileName)) {
      ConfigError configError = checkConfiguration();
      if (configError != null) { // the configuration contains an error
        // If this is a collated property, throw an error: this results in creating an
        // UncollatedPropertyTemplateModel instead.
        if (optm instanceof CollatedObjectPropertyTemplateModel) {
          throw new InvalidConfigurationException(configError.getMessage());
        }
        // Otherwise, switch to the default config
        log.warn(
            "Invalid list view config for object property "
                + op.getURI()
                + " in "
                + configFilePath
                + ":\n"
                + configError
                + " Using default config instead.");
        configFilePath = getConfigFilePath(DEFAULT_CONFIG_FILE_NAME);
        setValuesFromConfigFile(configFilePath, wadf, editing);
      }
    }

    isDefaultConfig = isDefaultConfig(configFileName);
  }