Ejemplo n.º 1
0
 public void run() {
   DBUtils.whereWeAre();
   empresa = ServiceLocator2.getConfiguracion().getSucursal().getEmpresa();
   System.out.println(
       "Cancelando pendientes para sucursal: "
           + ServiceLocator2.getConfiguracion().getSucursalLocalId());
   try {
     client = new CfdiClient();
     String sql =
         "SELECT x.uuid FROM sx_cxc_cargos_cancelados c join sx_cfdi x on(x.origen_id=c.cargo_id) where  X.UUID is not null and x.cancelacion is null";
     // Object args[]=new Object[]{};
     List<String> rows =
         ServiceLocator2.getJdbcTemplate()
             .queryForList(
                 sql
                 // , args
                 ,
                 String.class);
     for (String uuid : rows) {
       // System.out.println("Cancelando uuid: "+uuid);
       try {
         cancelar(uuid);
       } catch (Exception e) {
         System.out.println(
             "Error cancelando: " + uuid + " Error: " + ExceptionUtils.getRootCause(e));
       }
     }
   } catch (CfdiException e) {
     e.printStackTrace();
     System.out.println("Error en EDICOM: " + ExceptionUtils.getRootCauseMessage(e));
   }
 }
Ejemplo n.º 2
0
  private boolean analyze(CAS aCas, List<LogMessage> aMessages, boolean aFatalChecks) {
    boolean ok = true;
    for (Class<? extends Check> checkClass : checkClasses) {
      try {
        Check check = checkClass.newInstance();
        ok &= check.check(aCas, aMessages);
      } catch (InstantiationException | IllegalAccessException e) {
        aMessages.add(
            new LogMessage(
                this,
                LogLevel.ERROR,
                "Cannot instantiate [%s]: %s",
                checkClass.getSimpleName(),
                ExceptionUtils.getRootCauseMessage(e)));
        log.error(e);
      }
    }

    if (!ok && aFatalChecks) {
      aMessages.forEach(s -> log.error(s));
      throw new IllegalStateException("CasDoctor has detected problems and checks are fatal.");
    }

    return ok;
  }
Ejemplo n.º 3
0
  private void update(AjaxRequestTarget target) {
    JCas jCas = null;
    try {
      CuratorUtil.updatePanel(
          target,
          automateView,
          curationContainer,
          mergeVisualizer,
          repository,
          annotationSelectionByUsernameAndAddress,
          curationSegment,
          annotationService,
          userRepository);

      jCas = repository.readCorrectionCas(bModel.getDocument());
    } catch (UIMAException e) {
      error(ExceptionUtils.getRootCauseMessage(e));
    } catch (ClassNotFoundException e) {
      error(e.getMessage());
    } catch (IOException e) {
      error(e.getMessage());
    } catch (BratAnnotationException e) {
      error(e.getMessage());
    }

    gotoPageTextField.setModelObject(getFirstSentenceNumber(jCas, bModel.getSentenceAddress()) + 1);
    gotoPageAddress = getSentenceAddress(jCas, gotoPageTextField.getModelObject());

    target.add(gotoPageTextField);
    target.add(automateView);
    target.add(numberOfPages);
  }
Ejemplo n.º 4
0
 /**
  * Replica los clientes faltantes de enviar a las sucursales
  *
  * <p>Util para tareas especiales
  */
 public void replicarFaltantes() {
   final JdbcTemplate template = Services.getInstance().getJdbcTemplate();
   String sql =
       "select distinct clave from sx_clientes_log where tx_replicado is null order by modificado desc";
   List<Map<String, Object>> rows = template.queryForList(sql);
   if (rows.size() > 0) {
     logger.info("Clientes pendiente de replicado: " + rows.size());
   }
   for (Map<String, Object> row : rows) {
     String clave = (String) row.get("CLAVE");
     Cliente c = Services.getInstance().getClientesManager().buscarPorClave(clave);
     if (c != null) {
       logger.info("Replicando :" + c.getClave());
       for (Long sucursalId : getSucursales()) {
         HibernateTemplate target = ReplicaServices.getInstance().getHibernateTemplate(sucursalId);
         try {
           target.replicate(c, ReplicationMode.OVERWRITE);
           logger.info("Cliente replicado: " + c.getClave());
         } catch (Exception e) {
           logger.error(
               "Error replicando cliente: "
                   + c.getClave()
                   + " A sucursal: "
                   + sucursalId
                   + "  "
                   + ExceptionUtils.getRootCauseMessage(e));
         }
       }
     }
   }
 }
Ejemplo n.º 5
0
  private List<Resultado> validarEstructura() {

    final List<Resultado> resultados = new ArrayList<Resultado>();

    if (docto == null) {
      try {
        docto = ComprobanteDocument.Factory.parse(xmlFile);
      } catch (Exception e) {
        throw new RuntimeException(
            "Error procesando el archivo XML " + ExceptionUtils.getRootCauseMessage(e), e);
      }
    }

    final XmlOptions options = new XmlOptions();
    final List<XmlValidationError> errors = new ArrayList<XmlValidationError>();
    options.setErrorListener(errors);
    boolean valid = docto.validate(options);

    if (valid) {
      Resultado res = new Resultado("Estructura");
      res.setDescripcion("Estructura del CFD segun la versión 2 del schema del SAT");
      res.setResultado("CORRECTO");
      resultados.add(res);
    } else {
      for (XmlValidationError e : errors) {
        // buff.append(e.getMessage()+"\n");
        Resultado res = new Resultado("Estructura");
        res.setDescripcion(e.getMessage());
        res.setResultado("ERROR");
        resultados.add(res);
      }
    }
    return resultados;
  }
Ejemplo n.º 6
0
  public void repair(CAS aCas, List<LogMessage> aMessages) {
    boolean exception = false;
    for (Class<? extends Repair> repairClass : repairClasses) {
      try {
        Repair repair = repairClass.newInstance();
        repair.repair(aCas, aMessages);
      } catch (Exception e) {
        aMessages.add(
            new LogMessage(
                this,
                LogLevel.ERROR,
                "Cannot perform repair [%s]: %s",
                repairClass.getSimpleName(),
                ExceptionUtils.getRootCauseMessage(e)));
        log.error(e);
        exception = true;
      }
    }

    if (!repairClasses.isEmpty() && (exception || !analyze(aCas, aMessages, false))) {
      aMessages.forEach(s -> log.error(s));
      throw new IllegalStateException(
          "Repair attempt failed - ask system administrator " + "for details.");
    }
  }
Ejemplo n.º 7
0
  public void replicarPendientes() {
    for (Long sucursalId : getSucursales()) {
      importarPendientes(sucursalId);
    }
    final JdbcTemplate template = Services.getInstance().getJdbcTemplate();
    String sql =
        "select * from sx_clientes_log where tx_replicado is null and date(modificado)>=? order by modificado desc";
    Object[] values = new Object[] {new SqlParameterValue(Types.DATE, new Date())};
    List<Map<String, Object>> rows = template.queryForList(sql, values);
    if (rows.size() > 0) {
      logger.info("Client es pendiente de replicado: " + rows.size());
    }
    for (Map<String, Object> row : rows) {
      String clave = (String) row.get("CLAVE");
      Number id = (Number) row.get("ID");
      Cliente c = Services.getInstance().getClientesManager().buscarPorClave(clave);
      boolean aplicado = true;
      if (c != null) {
        logger.info("Replicando :" + c.getClave() + " Log ID:" + id);
        for (Long sucursalId : getSucursales()) {

          HibernateTemplate target = ReplicaServices.getInstance().getHibernateTemplate(sucursalId);
          try {

            target.replicate(c, ReplicationMode.OVERWRITE);

          } catch (Exception e) {
            aplicado = false;
            logger.error(
                "Error replicando cliente: "
                    + c.getClave()
                    + " A sucursal: "
                    + sucursalId
                    + "  "
                    + ExceptionUtils.getRootCauseMessage(e));
          }
        }
        if (aplicado) {
          try {
            Object[] params = {
              new SqlParameterValue(Types.TIMESTAMP, new Date()),
              new SqlParameterValue(Types.NUMERIC, id.longValue())
            };
            template.update("update sx_clientes_log set tx_replicado=? where id=?", params);
            // logger.info("Log replicado: "+id+ "Cliente : "+c.getClave());
          } catch (Exception e) {
            logger.error(e);
          }
          logger.info(
              "Actualizacion de cliente exitosa Log ID: " + id + " Cliente(Clave):" + c.getClave());
        }
      }
    }
  }
 @Test
 public void testExtremeValues_emptyFeatureExtractorSet() throws Exception {
   try {
     new ExtremeConfigurationSettingsExperiment().runEmptyFeatureExtractorSet();
   } catch (ExecutionException e) {
     if (!ExceptionUtils.getRootCauseMessage(e)
         .contains("No feature extractors have been added to the experiment.")) {
       Assert.fail("Unexpected exception");
     }
   }
 }
Ejemplo n.º 9
0
  public void cancelar(String uuid) throws Exception {
    String[] uuidList = new String[] {uuid};
    System.out.println("Mandando canclera CFDIS: " + ArrayUtils.toString(uuidList));

    String dirPath = "Z:\\CFDI\\cancelaciones";
    File dir = new File(dirPath);
    Assert.isTrue(dir.exists(), "No existe el directorio para cancelaciones: " + dirPath);
    Assert.isTrue(
        dir.isDirectory(), "La ruta para las cancelaciones no es un directorio " + dirPath);

    CancelaResponse res =
        client.cancelCfdi(
            "PAP830101CR3",
            "yqjvqfofb",
            empresa.getRfc(),
            uuidList,
            empresa.getCertificadoDigitalPfx(),
            pfxPassword);
    String msg = res.getText();
    String aka = res.getAck();
    // String[] uuids=res.getUuids();
    CFDI cfdi = ServiceLocator2.getCFDIManager().buscarPorUUID(uuid);
    Assert.notNull(cfdi, "No eixste el CFDI con UUID:" + uuid);

    try {
      // byte[] d1=Base64.decode(msg.getBytes());
      String xmlFile = StringUtils.remove(cfdi.getXmlFilePath(), "xml");
      byte[] d1 = msg.getBytes();
      File msgFile = new File(dir, xmlFile + "_MSG.xml");
      FileOutputStream out1 = new FileOutputStream(msgFile);
      out1.write(d1);
      out1.close();

      // byte[] d2=Base64.decode(aka.getBytes());
      byte[] d2 = aka.getBytes();
      File akaFile = new File(dir, xmlFile + "_AKA.xml");
      FileOutputStream out2 = new FileOutputStream(akaFile);
      out2.write(d2);
      out2.close();

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(
          "Error salvando archivos de cancelacion: " + ExceptionUtils.getRootCauseMessage(e));
    }
    cfdi.setCancelacion(new Date());
    ServiceLocator2.getHibernateTemplate().merge(cfdi);
  }
Ejemplo n.º 10
0
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class, ExtractQueryParameters.class})
 public static Result getUsers() {
   if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method Start");
   Context ctx = Http.Context.current.get();
   QueryParams criteria = (QueryParams) ctx.args.get(IQueryParametersKeys.QUERY_PARAMETERS);
   List<ODocument> profiles = null;
   ;
   try {
     profiles = UserService.getUsers(criteria, true);
   } catch (SqlInjectionException e) {
     return badRequest(
         ExceptionUtils.getMessage(e) + " -- " + ExceptionUtils.getRootCauseMessage(e));
   }
   String result = prepareResponseToJson(profiles);
   if (BaasBoxLogger.isTraceEnabled()) BaasBoxLogger.trace("Method End");
   return ok(result);
 }
Ejemplo n.º 11
0
 protected JComponent getControl(String property, Format format) {
   JComponent c = components.get(property);
   if (c == null) {
     JLabel label = createLabel();
     try {
       ValueModel valueModel =
           ConverterFactory.createStringConverter(model.getModel(property), format);
       Bindings.bind(label, valueModel);
     } catch (Exception e) {
       String msg = ExceptionUtils.getRootCauseMessage(e);
       label.setToolTipText("Binding error Property: " + property + "  " + msg);
       System.out.println("Binding error Property: " + property + "  " + msg);
     }
     components.put(property, label);
     return label;
   } else return c;
 }
Ejemplo n.º 12
0
 private Resultado validarCertificado() {
   final Comprobante comprobante = docto.getComprobante();
   try {
     String msg =
         ValidarVigenciaDelCSD.validar(
             comprobante.getNoCertificado(),
             comprobante.getEmisor().getRfc(),
             comprobante.getFecha().getTime());
     Resultado res = new Resultado("SERIE_FOLIO");
     res.setDescripcion(msg);
     res.setResultado("CORRECTO");
     return res;
   } catch (Exception e) {
     Resultado res = new Resultado("SERIE_FOLIO");
     res.setDescripcion(ExceptionUtils.getRootCauseMessage(e));
     res.setResultado("ERROR");
     return res;
   }
 }
Ejemplo n.º 13
0
 private Resultado validarSerieFolio() {
   final Comprobante comprobante = docto.getComprobante();
   try {
     String msg2 =
         ValidadorDeFoliosSAT.validar(
             comprobante.getEmisor().getRfc(),
             comprobante.getNoAprobacion().toString(),
             Integer.valueOf(comprobante.getAnoAprobacion()),
             comprobante.getSerie(),
             comprobante.getFolio());
     Resultado res = new Resultado("SERIE_FOLIO");
     res.setDescripcion(msg2);
     res.setResultado("CORRECTO");
     return res;
   } catch (Exception e) {
     Resultado res = new Resultado("SERIE_FOLIO");
     res.setDescripcion(ExceptionUtils.getRootCauseMessage(e));
     res.setResultado("ERROR");
     return res;
   }
 }
Ejemplo n.º 14
0
 private boolean processFeatures(
     FeatureProcessor processor,
     final T job,
     final DatasetHandlers<PersistableFeature> datasetHandlers,
     final FeatureCollection fc,
     final JobLogger jobLogger,
     final LogStringBuilder<AbstractProcess.MessageKey> userLog) {
   boolean error = false;
   try {
     int num = processFeatures(processor, job, datasetHandlers, fc, jobLogger);
     job.setFeatureCount(num);
     if (num == 0) {
       String message = userLog.logEvent(job, AbstractProcess.MessageKey.NO_FEATURES, LOG_LEVEL);
       technicalLog.warn(message);
       job.setResult(message);
       error = true;
     }
   } catch (ValidationException e) {
     String message =
         userLog.logEvent(
             job, AbstractProcess.MessageKey.XML_BLOCKING_FEATURE_ERROR, LogLevel.ERROR);
     technicalLog.warn(message);
     job.setResult(message);
     job.setFeatureCount(0);
     error = true;
   } catch (Exception e) {
     String message =
         userLog.logEvent(
             job,
             AbstractProcess.MessageKey.XML_FEATURES_EXCEPTION,
             LOG_LEVEL,
             ExceptionUtils.getRootCauseMessage(e));
     job.setResult(message);
     job.setFeatureCount(0);
     error = true;
     technicalLog.error("Error while parsing/processing features", e);
   }
   technicalLog.debug("processing features finished");
   return error;
 }
Ejemplo n.º 15
0
  private void addJCas(List<JCas> jCases, User user, SourceDocument sourceDocument) {
    try {
      // Check if there is an annotation document entry in the database. If there is none,
      // create one.
      AnnotationDocument annotationDocument =
          repository.createOrGetAnnotationDocument(sourceDocument, user);

      // Read the CAS
      JCas jcas = repository.readAnnotationCas(annotationDocument);

      // Update the annotation document CAS
      repository.upgradeCas(jcas.getCas(), annotationDocument);

      // After creating an new CAS or upgrading the CAS, we need to save it
      repository.writeAnnotationCas(
          jcas.getCas().getJCas(), annotationDocument.getDocument(), user);

      jCases.add(jcas);
    } catch (UIMAException e) {
      error(e.getMessage() + " : " + ExceptionUtils.getRootCauseMessage(e));
    } catch (IOException e) {
      error(e.getMessage());
    }
  }
Ejemplo n.º 16
0
  public CellDataSet execute(String queryName, ICellSetFormatter formatter) {
    String runId = "runId:" + ID_GENERATOR.getAndIncrement();
    try {
      //			System.out.println("Execute: ID " + Thread.currentThread().getId() + " Name: " +
      // Thread.currentThread().getName());
      IQuery query = getIQuery(queryName);
      OlapConnection con =
          olapDiscoverService.getNativeConnection(query.getSaikuCube().getConnectionName());

      Long start = (new Date()).getTime();
      if (query.getScenario() != null) {
        log.info(
            runId
                + "\tQuery: "
                + query.getName()
                + " Setting scenario:"
                + query.getScenario().getId());
        con.setScenario(query.getScenario());
      }

      if (query.getTag() != null) {
        query = applyTag(query, con, query.getTag());
      }

      String mdx = query.getMdx();
      log.info(runId + "\tType:" + query.getType() + ":\n" + mdx);

      CellSet cellSet = query.execute();
      Long exec = (new Date()).getTime();

      if (query.getScenario() != null) {
        log.info("Query (" + queryName + ") removing scenario:" + query.getScenario().getId());
        con.setScenario(null);
      }

      CellDataSet result = OlapResultSetUtil.cellSet2Matrix(cellSet, formatter);
      Long format = (new Date()).getTime();
      log.info(
          runId
              + "\tSize: "
              + result.getWidth()
              + "/"
              + result.getHeight()
              + "\tExecute:\t"
              + (exec - start)
              + "ms\tFormat:\t"
              + (format - exec)
              + "ms\t Total: "
              + (format - start)
              + "ms");
      result.setRuntime(new Double(format - start).intValue());
      getIQuery(queryName).storeCellset(cellSet);
      return result;
    } catch (Exception e) {
      if (log.isInfoEnabled()) {
        String error = ExceptionUtils.getRootCauseMessage(e);
        log.info(runId + "\tException: " + error);
      }
      throw new SaikuServiceException(runId + "\tCan't execute query: " + queryName, e);
    } catch (Error e) {
      if (log.isInfoEnabled()) {
        String error = ExceptionUtils.getRootCauseMessage(e);
        log.info(runId + "\tError: " + error);
      }
      throw new SaikuServiceException(runId + "\tCan't execute query: " + queryName, e);
    }
  }
Ejemplo n.º 17
0
  /**
   * Retrieves from the specified storage pool the tasks that exist on it and adds them to the
   * manager.
   *
   * @param sp the storage pool to retrieve running tasks from
   */
  public void addStoragePoolExistingTasks(StoragePool sp) {
    List<AsyncTaskCreationInfo> currPoolTasks = null;
    try {
      currPoolTasks = coco.getAllTasksInfo(sp.getId());
    } catch (RuntimeException e) {
      log.error(
          "Getting existing tasks on Storage Pool '{}' failed: {}", sp.getName(), e.getMessage());
      log.debug("Exception", e);
    }

    if (currPoolTasks != null && currPoolTasks.size() > 0) {
      synchronized (this) {
        final List<SPMTask> newlyAddedTasks = new ArrayList<>();

        for (AsyncTaskCreationInfo creationInfo : currPoolTasks) {
          creationInfo.setStoragePoolID(sp.getId());
          if (!_tasks.containsKey(creationInfo.getVdsmTaskId())) {
            try {
              SPMTask task;
              if (partiallyCompletedCommandTasks.containsKey(creationInfo.getVdsmTaskId())) {
                AsyncTask asyncTaskInDb =
                    partiallyCompletedCommandTasks.get(creationInfo.getVdsmTaskId());
                task = coco.construct(creationInfo, asyncTaskInDb);
                if (task.getEntitiesMap() == null) {
                  task.setEntitiesMap(new HashMap<>());
                }
                partiallyCompletedCommandTasks.remove(task.getVdsmTaskId());
                // mark it as a task of a partially completed command
                // Will result in failure of the command
                task.setPartiallyCompletedCommandTask(true);
              } else {
                task = coco.construct(creationInfo);
              }
              addTaskToManager(task);
              newlyAddedTasks.add(task);
            } catch (Exception e) {
              log.error(
                  "Failed to load task of type '{}' with id '{}': {}.",
                  creationInfo.getTaskType(),
                  creationInfo.getVdsmTaskId(),
                  ExceptionUtils.getRootCauseMessage(e));
              log.debug("Exception", e);
            }
          }
        }

        TransactionSupport.executeInNewTransaction(
            () -> {
              for (SPMTask task : newlyAddedTasks) {
                AsyncTaskUtils.addOrUpdateTaskInDB(task);
              }
              return null;
            });

        for (SPMTask task : newlyAddedTasks) {
          startPollingTask(task.getVdsmTaskId());
        }

        log.info(
            "Discovered {} tasks on Storage Pool '{}', {} added to manager.",
            currPoolTasks.size(),
            sp.getName(),
            newlyAddedTasks.size());
      }
    } else {
      log.info("Discovered no tasks on Storage Pool '{}'", sp.getName());
    }

    List<AsyncTask> tasksInDForStoragePool = tasksInDbAfterRestart.get(sp.getId());
    if (tasksInDForStoragePool != null) {
      for (AsyncTask task : tasksInDForStoragePool) {
        if (!_tasks.containsKey(task.getVdsmTaskId())) {
          coco.removeByVdsmTaskId(task.getVdsmTaskId());
        }
      }
    }

    // Either the tasks were only in DB - so they were removed from db, or they are polled -
    // in any case no need to hold them in the map that represents the tasksInDbAfterRestart
    tasksInDbAfterRestart.remove(sp.getId());
  }
Ejemplo n.º 18
0
  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);
        }
      }
    }
  }
  @Override
  protected String getDocumentData() {
    if (!dirty) {
      return docData;
    }

    dirty = false;

    // Clear the rendered document
    docData = EMPTY_DOC;

    // Check if a document is set
    if (getModelObject() == null) {
      return docData;
    }

    // Get CAS from the repository
    JCas jCas = null;
    try {
      jCas = repository.readAnnotationCas(getModelObject());
    } catch (IOException | DataRetrievalFailureException e) {
      LOG.error("Unable to read annotation document", e);
      error("Unable to read annotation document: " + ExceptionUtils.getRootCauseMessage(e));
    }
    // Generate BRAT object model from CAS
    GetDocumentResponse response = new GetDocumentResponse();
    response.setText(jCas.getDocumentText());

    BratAnnotatorModel bratAnnotatorModel = new BratAnnotatorModel();
    SpanAdapter.renderTokenAndSentence(jCas, response, bratAnnotatorModel);

    Map<String[], Queue<String>> colorQueues = new HashMap<>();
    for (AnnotationLayer layer : bratAnnotatorModel.getAnnotationLayers()) {
      if (layer.getName().equals(Token.class.getName())) {
        continue;
      }
      List<AnnotationFeature> features = annotationService.listAnnotationFeature(layer);
      List<AnnotationFeature> invisibleFeatures = new ArrayList<AnnotationFeature>();
      for (AnnotationFeature feature : features) {
        if (!feature.isVisible()) {
          invisibleFeatures.add(feature);
        }
      }
      features.removeAll(invisibleFeatures);

      ColoringStrategy coloringStrategy =
          ColoringStrategy.getBestStrategy(
              annotationService, layer, bratAnnotatorModel.getPreferences(), colorQueues);

      getAdapter(annotationService, layer)
          .render(jCas, features, response, bratAnnotatorModel, coloringStrategy);
    }

    // Serialize BRAT object model to JSON
    try {
      StringWriter out = new StringWriter();
      JsonGenerator jsonGenerator =
          JSONUtil.getJsonConverter().getObjectMapper().getFactory().createGenerator(out);
      jsonGenerator.writeObject(response);
      docData = out.toString();
    } catch (IOException e) {
      error(ExceptionUtils.getRootCauseMessage(e));
    }

    return docData;
  }