@Override
 public Iterator<EntityReference> listData() {
   try {
     List<Object[]> data = this.docStore.search(DATA_REFERENCE_QUERY, 0, 0, this.context.get());
     return new ReferenceIterator(data);
   } catch (XWikiException ex) {
     this.logger.warn("Failed to list the database deleted attachments: {}", ex.getMessage());
     return Collections.emptyIterator();
   }
 }
 /**
  * Trigger a BaseObject job (execute it now).
  *
  * @param object the BaseObject Job to be triggered
  * @return true on success, false on failure.
  */
 public boolean triggerJob(BaseObject object) {
   try {
     getProtectedPlugin().triggerJob(object, this.context);
     LOGGER.debug("Trigger Job: [{}]", object.getStringValue("jobName"));
     return true;
   } catch (XWikiException e) {
     this.context.put("error", e.getMessage());
     return false;
   }
 }
 @Override
 public boolean hasData() {
   try {
     return !this.docStore.search(DATA_RETRIEVE_QUERY, 1, 0, this.context.get()).isEmpty();
   } catch (XWikiException ex) {
     this.logger.warn(
         "Failed to search for deleted attachments in the database trash: {}", ex.getMessage());
     return false;
   }
 }
 public void addWriter(String spaceName, String userName, boolean allowDowngrade) {
   if (hasProgrammingRights()) {
     try {
       getWorkspacesManager().addWriter(spaceName, userName, allowDowngrade, context);
     } catch (XWikiException e) {
       context.put("haserror", "1");
       context.put("lasterror", e.getMessage());
     }
   }
 }
 /** Remove a reader from a workspace, removing him as a member too */
 public void removeReader(String spaceName, String userName) {
   if (hasProgrammingRights()) {
     try {
       getWorkspacesManager().removeReader(spaceName, userName, context);
     } catch (XWikiException e) {
       context.put("haserror", "1");
       context.put("lasterror", e.getMessage());
     }
   }
 }
 @Override
 public Iterator<DeletedAttachment> getData() {
   try {
     List<Long> data = this.docStore.search(DATA_RETRIEVE_QUERY, 0, 0, this.context.get());
     this.logger.debug("Found [{}] deleted attachments in the database trash", data.size());
     return new DeletedAttachmentIterator(data);
   } catch (XWikiException ex) {
     this.logger.warn(
         "Failed to get the list of database deleted attachments: {}", ex.getMessage());
     return Collections.emptyIterator();
   }
 }
 /**
  * Loops over the {@code rightsCombinations} and attaches a new rights object for each combination
  * to the document.
  *
  * @param rightsCombinations the string array containing all the combinations for which there
  *     should be an object created
  * @param rightsObjects the map of existing rights objects
  * @param doc XWikiDocument
  * @param context XWikiContext
  */
 private void createRights(
     List<String> rightsCombinations,
     Map<String, BaseObject> rightsObjects,
     XWikiDocument doc,
     XWikiContext context) {
   for (String rights : rightsCombinations) {
     try {
       BaseObject newRightObject = doc.newXObject(RIGHTS_CLASS, context);
       newRightObject.setStringValue("levels", rights);
       newRightObject.setIntValue("allow", 1);
       rightsObjects.put(rights, newRightObject);
     } catch (XWikiException ex) {
       this.logger.error("Failed to create rights: {}", ex.getMessage(), ex);
     }
   }
 }
 @Override
 public boolean discardAllData() {
   boolean transaction = false;
   try {
     transaction = ((XWikiHibernateBaseStore) this.store).beginTransaction(this.context.get());
     Session session = ((XWikiHibernateBaseStore) this.store).getSession(this.context.get());
     session.createQuery("delete from DeletedAttachment").executeUpdate();
   } catch (XWikiException ex) {
     this.logger.warn(
         "Failed to cleanup all attachments from the database trash: {}", ex.getMessage());
     return false;
   } finally {
     if (transaction) {
       ((XWikiHibernateBaseStore) this.store).endTransaction(this.context.get(), transaction);
     }
   }
   return true;
 }
 @Override
 public boolean discardEntity(DeletedAttachment entity) {
   boolean transaction = false;
   try {
     transaction = ((XWikiHibernateBaseStore) this.store).beginTransaction(this.context.get());
     Session session = ((XWikiHibernateBaseStore) this.store).getSession(this.context.get());
     session.delete(entity);
     this.logger.debug(
         "Deleted deleted attachment [{}@{}#{}] from the database trash",
         entity.getDocName(),
         entity.getFilename(),
         entity.getId());
   } catch (XWikiException ex) {
     this.logger.warn("Failed to cleanup attachment from the database trash: {}", ex.getMessage());
     return false;
   } finally {
     if (transaction) {
       ((XWikiHibernateBaseStore) this.store).endTransaction(this.context.get(), transaction);
     }
   }
   return true;
 }
  @Override
  public Representation represent(Variant variant) throws ResourceException {
    setupXWiki();

    Request request = getRequest();
    String assetName = (String) request.getAttributes().get("assetName");
    String textId = (String) request.getAttributes().get("textId");
    // if (!textId.equals("0")) {
    //    throw error(Status.CLIENT_ERROR_NOT_FOUND, "An asset may only have one viditalk movie");
    // }

    TextAsset asset = null;
    try {
      asset = (TextAsset) plugin.fetchAssetAs(assetName, TextAsset.class);
    } catch (XWikiException e) {
      throw error(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage());
    }
    if (asset == null) {
      throw error(Status.CLIENT_ERROR_NOT_FOUND, "Asset " + assetName + " not found.");
    }

    String content = null;
    String syntax = null;
    try {
      content = asset.getText();
      syntax = asset.getTextSyntax();
    } catch (XWikiException e) {
      throw error(Status.CLIENT_ERROR_NOT_FOUND, "No texts found for " + assetName);
    }

    JSONObject json = new JSONObject();
    json.put("text", content);
    json.put("syntax", syntax);

    return formatJSON(json, variant);
  }
 public void update() {
   if (!stopUpdate) {
     if (updateInProgress == false) {
       updateInProgress = true;
       nbLoadedFeeds = 0;
       nbLoadedFeedsErrors = 0;
       exception = null;
       nbLoadedArticles = 0;
       endDate = null;
       startDate = new Date();
       XWikiContext context = getXWikiContext();
       try {
         // Make sure store sessions are cleaned up
         context.getWiki().getStore().cleanUp(context);
         // update the feeds
         nbLoadedArticles =
             feedPlugin.updateFeedsInSpace(space, fullContent, true, false, context);
       } catch (XWikiException e) {
         exception = e;
         e.printStackTrace();
       } finally {
         updateInProgress = false;
         endDate = new Date();
         context.getWiki().getStore().cleanUp(context);
       }
       // an update has been schedule..
       if ((forceUpdate == true) && (stopUpdate == false)) {
         forceUpdate = false;
         update();
       }
     } else {
       // let's schedule an update at the end of the current update
       forceUpdate = true;
     }
   }
 }
  public ActionForward execute(XWikiContext context) throws Exception {
    MonitorPlugin monitor = null;
    FileUploadPlugin fileupload = null;
    String docName = "";

    try {
      String action = context.getAction();

      // Initialize context.getWiki() with the main wiki
      XWiki xwiki;

      // Verify that the requested wiki exists
      try {
        xwiki = XWiki.getXWiki(this.waitForXWikiInitialization, context);

        // If XWiki is still initializing display initialization template
        if (xwiki == null) {
          // Display initialization template
          renderInit(context);

          // Initialization template has been displayed, stop here.
          return null;
        }
      } catch (XWikiException e) {
        // If the wiki asked by the user doesn't exist, then we first attempt to use any existing
        // global
        // redirects. If there are none, then we display the specific error template.
        if (e.getCode() == XWikiException.ERROR_XWIKI_DOES_NOT_EXIST) {
          xwiki = XWiki.getMainXWiki(context);

          // Initialize the url factory
          XWikiURLFactory urlf =
              xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
          context.setURLFactory(urlf);

          // Initialize the velocity context and its bindings so that it may be used in the velocity
          // templates
          // that we
          // are parsing below.
          VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
          VelocityContext vcontext = velocityManager.getVelocityContext();

          if (!sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
            // Starting XWiki 5.0M2, 'xwiki.virtual.redirect' was removed. Warn users still using
            // it.
            if (!StringUtils.isEmpty(context.getWiki().Param("xwiki.virtual.redirect"))) {
              LOGGER.warn(
                  String.format(
                      "%s %s",
                      "'xwiki.virtual.redirect' is no longer supported.",
                      "Please update your configuration and/or see XWIKI-8914 for more details."));
            }

            // Display the error template only for actions that are not ignored
            if (!ACTIONS_IGNORED_WHEN_WIKI_DOES_NOT_EXIST.contains(action)) {

              // Add localization resources to the context
              xwiki.prepareResources(context);

              // Set the main home page in the main space of the main wiki as the current requested
              // entity
              // since we cannot set the non existing one as it would generate errors obviously...
              EntityReferenceValueProvider valueProvider =
                  Utils.getComponent(EntityReferenceValueProvider.class);
              xwiki.setPhonyDocument(
                  new DocumentReference(
                      valueProvider.getDefaultValue(EntityType.WIKI),
                      valueProvider.getDefaultValue(EntityType.SPACE),
                      valueProvider.getDefaultValue(EntityType.DOCUMENT)),
                  context,
                  vcontext);

              // Parse the error template
              Utils.parseTemplate(
                  context.getWiki().Param("xwiki.wiki_exception", "wikidoesnotexist"), context);

              // Error template was displayed, stop here.
              return null;
            }

            // At this point, we allow regular execution of the ignored action because even if the
            // wiki
            // does not exist, we still need to allow UI resources to be retrieved (from the
            // filesystem
            // and the main wiki) or our error template will not be rendered properly.

            // Proceed with serving the main wiki

          } else {
            // Global redirect was executed, stop here.
            return null;
          }
        } else {
          LOGGER.error("Uncaught exception during XWiki initialisation:", e);
          throw e;
        }
      }

      // Send global redirection (if any)
      if (sendGlobalRedirect(context.getResponse(), context.getURL().toString(), context)) {
        return null;
      }

      XWikiURLFactory urlf =
          xwiki.getURLFactoryService().createURLFactory(context.getMode(), context);
      context.setURLFactory(urlf);

      String sajax = context.getRequest().get("ajax");
      boolean ajax = false;
      if (sajax != null && !sajax.trim().equals("") && !sajax.equals("0")) {
        ajax = true;
      }
      context.put("ajax", ajax);

      // Any error before this will be treated using a redirection to an error page

      if (monitor != null) {
        monitor.startTimer("request");
      }

      VelocityManager velocityManager = Utils.getComponent(VelocityManager.class);
      VelocityContext vcontext = velocityManager.getVelocityContext();

      boolean eventSent = false;
      try {
        // Prepare documents and put them in the context
        if (!xwiki.prepareDocuments(context.getRequest(), context, vcontext)) {
          return null;
        }

        // Start monitoring timer
        monitor = (MonitorPlugin) xwiki.getPlugin("monitor", context);
        if (monitor != null) {
          monitor.startRequest("", context.getAction(), context.getURL());
          monitor.startTimer("multipart");
        }

        // Parses multipart so that params in multipart are available for all actions
        fileupload = Utils.handleMultipart(context.getRequest().getHttpServletRequest(), context);
        if (monitor != null) {
          monitor.endTimer("multipart");
        }

        if (monitor != null) {
          monitor.setWikiPage(context.getDoc().getFullName());
        }

        // Let's handle the notification and make sure it never fails
        if (monitor != null) {
          monitor.startTimer("prenotify");
        }

        // For the moment we're sending the XWiki context as the data, but this will be
        // changed in the future, when the whole platform will be written using components
        // and there won't be a need for the context.
        try {
          ObservationManager om = Utils.getComponent(ObservationManager.class);
          ActionExecutingEvent event = new ActionExecutingEvent(context.getAction());
          om.notify(event, context.getDoc(), context);
          eventSent = true;
          if (event.isCanceled()) {
            // Action has been canceled
            // TODO: do something special ?
            return null;
          }
        } catch (Throwable ex) {
          LOGGER.error(
              "Cannot send action notifications for document ["
                  + context.getDoc()
                  + " using action ["
                  + context.getAction()
                  + "]",
              ex);
        }

        if (monitor != null) {
          monitor.endTimer("prenotify");
        }

        // Call the Actions

        // Call the new Entity Resource Reference Handler.
        ResourceReferenceHandler entityResourceReferenceHandler =
            Utils.getComponent(
                new DefaultParameterizedType(
                    null, ResourceReferenceHandler.class, ResourceType.class),
                "bin");
        ResourceReference resourceReference =
            Utils.getComponent(ResourceReferenceManager.class).getResourceReference();
        try {
          entityResourceReferenceHandler.handle(
              resourceReference,
              new DefaultResourceReferenceHandlerChain(
                  Collections.<ResourceReferenceHandler>emptyList()));
          // Don't let the old actions kick in!
          return null;
        } catch (NotFoundResourceHandlerException e) {
          // No Entity Resource Action has been found. Don't do anything and let it go through
          // so that the old Action system kicks in...
        } catch (Throwable e) {
          // Some real failure, log it since it's a problem but still allow the old Action system a
          // chance
          // to do something...
          LOGGER.error("Failed to handle Action for Resource [{}]", resourceReference, e);
        }

        // Then call the old Actions for backward compatibility (and because a lot of them have not
        // been
        // migrated to new Actions yet).
        String renderResult = null;
        XWikiDocument doc = context.getDoc();
        docName = doc.getFullName();
        if (action(context)) {
          renderResult = render(context);
        }

        if (renderResult != null) {
          if (doc.isNew()
              && "view".equals(context.getAction())
              && !"recyclebin".equals(context.getRequest().get("viewer"))) {
            String page = Utils.getPage(context.getRequest(), "docdoesnotexist");
            Utils.parseTemplate(page, context);
          } else {
            String page = Utils.getPage(context.getRequest(), renderResult);
            Utils.parseTemplate(page, !page.equals("direct"), context);
          }
        }
        return null;
      } catch (Throwable e) {
        if (e instanceof IOException) {
          e =
              new XWikiException(
                  XWikiException.MODULE_XWIKI_APP,
                  XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION,
                  "Exception while sending response",
                  e);
        }

        if (!(e instanceof XWikiException)) {
          e =
              new XWikiException(
                  XWikiException.MODULE_XWIKI_APP,
                  XWikiException.ERROR_XWIKI_UNKNOWN,
                  "Uncaught exception",
                  e);
        }

        try {
          XWikiException xex = (XWikiException) e;
          if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
            // Connection aborted from the client side, there's not much we can do on the server
            // side. We
            // simply ignore it.
            LOGGER.debug("Connection aborted", e);
            // We don't write any other message to the response, as the connection is broken,
            // anyway.
            return null;
          } else if (xex.getCode() == XWikiException.ERROR_XWIKI_ACCESS_DENIED) {
            Utils.parseTemplate(
                context.getWiki().Param("xwiki.access_exception", "accessdenied"), context);
            return null;
          } else if (xex.getCode() == XWikiException.ERROR_XWIKI_USER_INACTIVE) {
            Utils.parseTemplate(
                context.getWiki().Param("xwiki.user_exception", "userinactive"), context);
            return null;
          } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_ATTACHMENT_NOT_FOUND) {
            context.put("message", "attachmentdoesnotexist");
            Utils.parseTemplate(
                context.getWiki().Param("xwiki.attachment_exception", "attachmentdoesnotexist"),
                context);
            return null;
          } else if (xex.getCode() == XWikiException.ERROR_XWIKI_APP_URL_EXCEPTION) {
            vcontext.put("message", context.getMessageTool().get("platform.core.invalidUrl"));
            xwiki.setPhonyDocument(
                xwiki.getDefaultSpace(context) + "." + xwiki.getDefaultPage(context),
                context,
                vcontext);
            context.getResponse().setStatus(HttpServletResponse.SC_BAD_REQUEST);
            Utils.parseTemplate(
                context.getWiki().Param("xwiki.invalid_url_exception", "error"), context);
            return null;
          }
          vcontext.put("exp", e);
          if (LOGGER.isWarnEnabled()) {
            // Don't log "Broken Pipe" exceptions since they're not real errors and we don't want to
            // pollute
            // the logs with unnecessary stack traces. It just means the client side has cancelled
            // the
            // connection.
            if (ExceptionUtils.getRootCauseMessage(e).equals("IOException: Broken pipe")) {
              return null;
            }
            LOGGER.warn("Uncaught exception: " + e.getMessage(), e);
          }
          // If the request is an AJAX request, we don't return a whole HTML page, but just the
          // exception
          // inline.
          String exceptionTemplate = ajax ? "exceptioninline" : "exception";
          Utils.parseTemplate(Utils.getPage(context.getRequest(), exceptionTemplate), context);
          return null;
        } catch (XWikiException ex) {
          if (ex.getCode() == XWikiException.ERROR_XWIKI_APP_SEND_RESPONSE_EXCEPTION) {
            LOGGER.error("Connection aborted");
          }
        } catch (Exception e2) {
          // I hope this never happens
          LOGGER.error("Uncaught exceptions (inner): ", e);
          LOGGER.error("Uncaught exceptions (outer): ", e2);
        }
        return null;
      } finally {
        // Let's make sure we have flushed content and closed
        try {
          context.getResponse().getWriter().flush();
        } catch (Throwable e) {
          // This might happen if the connection was closed, for example.
          // If we can't flush, then there's nothing more we can send to the client.
        }

        if (monitor != null) {
          monitor.endTimer("request");
          monitor.startTimer("notify");
        }

        if (eventSent) {
          // For the moment we're sending the XWiki context as the data, but this will be
          // changed in the future, when the whole platform will be written using components
          // and there won't be a need for the context.
          try {
            ObservationManager om = Utils.getComponent(ObservationManager.class);
            om.notify(new ActionExecutedEvent(context.getAction()), context.getDoc(), context);
          } catch (Throwable ex) {
            LOGGER.error(
                "Cannot send action notifications for document ["
                    + docName
                    + " using action ["
                    + context.getAction()
                    + "]",
                ex);
          }
        }

        if (monitor != null) {
          monitor.endTimer("notify");
        }

        // Make sure we cleanup database connections
        // There could be cases where we have some
        if ((context != null) && (xwiki != null)) {
          xwiki.getStore().cleanUp(context);
        }
      }
    } finally {
      // End request
      if (monitor != null) {
        monitor.endRequest();
      }

      if (context != null) {

        if (fileupload != null) {
          fileupload.cleanFileList(context);
        }
      }
    }
  }