private void loadCalendarEvents(
     final Calendar calendar,
     final CalendarListEntry calendarEntry,
     final UpdateInfo updateInfo,
     final Long since)
     throws IOException {
   String pageToken = null;
   do {
     long then = System.currentTimeMillis();
     final Calendar.Events.List eventsApiCall = calendar.events().list(calendarEntry.getId());
     final String uriTemplate = eventsApiCall.getUriTemplate();
     try {
       eventsApiCall.setPageToken(pageToken);
       eventsApiCall.setShowHiddenInvitations(true);
       eventsApiCall.setSingleEvents(true);
       eventsApiCall.setTimeMax(new DateTime(System.currentTimeMillis()));
       if (since != null) eventsApiCall.setTimeMin(new DateTime(since));
       final Events events = eventsApiCall.execute();
       countSuccessfulApiCall(updateInfo.apiKey, updateInfo.objectTypes, then, uriTemplate);
       final List<Event> eventList = events.getItems();
       storeEvents(updateInfo, calendarEntry, eventList);
       pageToken = events.getNextPageToken();
     } catch (Throwable e) {
       countFailedApiCall(
           updateInfo.apiKey,
           updateInfo.objectTypes,
           then,
           uriTemplate,
           ExceptionUtils.getStackTrace(e),
           eventsApiCall.getLastStatusCode(),
           eventsApiCall.getLastStatusMessage());
       throw (new RuntimeException(e));
     }
   } while (pageToken != null);
 }
Ejemplo n.º 2
0
  @Test
  public void testException() throws Exception {
    try {
      ClassLookup.find().orThrow(new NullPointerException()).get();
      fail(NullPointerException.class.getSimpleName() + " expected");
    } catch (NullPointerException e) {
      // expected
    }

    try {
      ClassLookup.find().orThrow(new IOException()).get();
      fail(RuntimeException.class.getSimpleName() + " expected");
    } catch (RuntimeException e) {
      assertSame(IOException.class, e.getCause().getClass());
    }

    String msg = "I knew it!";
    try {
      ClassLookup.find().orThrow(msg).get();
      fail(RuntimeException.class.getSimpleName() + " expected");
    } catch (RuntimeException e) {
      assertEquals(true, e.toString().endsWith(ExceptionUtils.getMessage(e)));
    }

    try {
      ClassLookup.find().orThrow(msg).list();
      fail(RuntimeException.class.getSimpleName() + " expected");
    } catch (Exception e) {
      assertEquals(true, e.toString().endsWith(ExceptionUtils.getMessage(e)));
    }
  }
Ejemplo n.º 3
0
    public void run() {
      try {
        if (reconnect) {
          reconnect = false;
          mysqlConnection.reconnect();
        } else if (!mysqlConnection.isConnected()) {
          mysqlConnection.connect();
        }
        Long startTime = System.currentTimeMillis();

        // 可能心跳sql为select 1
        if (StringUtils.startsWithIgnoreCase(detectingSQL.trim(), "select")) {
          mysqlConnection.query(detectingSQL);
        } else {
          mysqlConnection.update(detectingSQL);
        }

        Long costTime = System.currentTimeMillis() - startTime;
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onSuccess(costTime);
        }
      } catch (SocketTimeoutException e) {
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onFailed(e);
        }
        reconnect = true;
        logger.warn("connect failed by " + ExceptionUtils.getStackTrace(e));
      } catch (IOException e) {
        if (haController != null && haController instanceof HeartBeatCallback) {
          ((HeartBeatCallback) haController).onFailed(e);
        }
        reconnect = true;
        logger.warn("connect failed by " + ExceptionUtils.getStackTrace(e));
      }
    }
Ejemplo n.º 4
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.º 5
0
  public void initCapability() {

    try {
      log.info("INFO: Before test, getting queue...");
      Assert.assertNotNull(queueManagerFactory);

      queueCapability = queueManagerFactory.create(mockResource);
      queueCapability.initialize();

      protocolManager.getProtocolSessionManagerWithContext(
          mockResource.getResourceId(), newSessionContextNetconf());

      // Test elements not null
      log.info("Checking chassis factory");
      Assert.assertNotNull(chassisFactory);
      log.info("Checking capability descriptor");
      Assert.assertNotNull(mockResource.getResourceDescriptor().getCapabilityDescriptor("chassis"));
      log.info("Creating chassis capability");
      chassisCapability = chassisFactory.create(mockResource);
      Assert.assertNotNull(chassisCapability);
      chassisCapability.initialize();

      mockResource.addCapability(chassisCapability);
      mockResource.addCapability(queueCapability);

    } catch (Exception e) {
      e.printStackTrace();
      log.error(e.getMessage());
      if (ExceptionUtils.getRootCause(e) != null)
        log.error(ExceptionUtils.getRootCause(e).getMessage());
      Assert.fail(e.getMessage());
    }
  }
Ejemplo n.º 6
0
 @With({UserCredentialWrapFilter.class, ConnectToDBFilter.class})
 public static Result disable() {
   try {
     UserService.disableCurrentUser();
   } catch (UserNotFoundException e) {
     return badRequest(ExceptionUtils.getMessage(e));
   } catch (OpenTransactionException e) {
     BaasBoxLogger.error(ExceptionUtils.getFullStackTrace(e));
     throw new RuntimeException(e);
   }
   return ok();
 }
  public String registerStudy(String studyOid, String hostName) {
    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl =
        CoreResources.getField("portalURL")
            + "/app/rest/oc/authorizations?studyoid="
            + studyOid
            + "&instanceurl="
            + ocUrl;
    Authorization authRequest = new Authorization();
    Study authStudy = new Study();
    authStudy.setStudyOid(studyOid);
    authStudy.setInstanceUrl(ocUrl);
    authStudy.setHost(hostName);
    authRequest.setStudy(authStudy);

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);

    try {
      Authorization response = rest.postForObject(pManageUrl, authRequest, Authorization.class);
      if (response != null && response.getAuthorizationStatus() != null)
        return response.getAuthorizationStatus().getStatus();
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
Ejemplo n.º 8
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        String jsons = IOUtils.toString(arg0.getRequestBody());

        JSONObject json = (JSONObject) JSONSerializer.toJSON(jsons);
        if (!json.containsKey("valid")) return;
        Email response = new SimpleEmail();
        response.setHostName(properties.getProperty("org.iplantc.tnrs.mail.host"));
        response.setSmtpPort(
            Integer.parseInt(properties.getProperty("org.iplantc.tnrs.mail.port")));
        response.setFrom("*****@*****.**");
        response.setSubject("TNRS support Ticket");
        response.setMsg(
            "TNRS support ticket from: "
                + json.getString("name")
                + " ("
                + json.getString("email")
                + "). "
                + "\n\n\n"
                + json.getString("contents"));
        response.addTo("*****@*****.**");
        response.send();
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
Ejemplo n.º 9
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.º 10
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.º 11
0
 public List<ClientListInfo> getClientsDataTable(
     int startRecord, int recordsToShow, String clientNameKey) {
   try {
     Session session = sessionFactory.getCurrentSession();
     CallableStatement cstmt =
         session.connection().prepareCall("{call ADMIN_CLIENT_MANAGEMENT(?,?,?)}");
     List<ClientListInfo> clientListInfo = new ArrayList<ClientListInfo>();
     cstmt.setInt(1, startRecord);
     cstmt.setInt(2, recordsToShow);
     cstmt.setString(3, clientNameKey.trim());
     ResultSet rs = cstmt.executeQuery();
     if (rs != null) {
       while (rs.next()) {
         ClientListInfo clientInfo = new ClientListInfo();
         clientInfo.setIndex(rs.getInt(1));
         clientInfo.setClientId(rs.getInt(2));
         clientInfo.setClientName(rs.getString(3));
         clientInfo.setBusinessType(rs.getString(4));
         clientInfo.setContactPerson(rs.getString(5));
         clientInfo.setWorkPhone(rs.getString(6));
         clientInfo.setMobileNumber(rs.getString(7));
         clientInfo.setIsActive(rs.getBoolean(9));
         clientInfo.setEdit(rs.getInt(2));
         clientInfo.setDelete(rs.getInt(2));
         clientInfo.setTotalRows(rs.getInt(10));
         clientListInfo.add(clientInfo);
       }
     }
     return clientListInfo;
   } catch (Exception e) {
     log.error("Exception in get Client Data Table : DAO :" + ExceptionUtils.getStackTrace(e));
   }
   return null;
 }
  @Test
  public void testCommandGetSingleDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            p.put("collection", TEST_COLLECTION);
            p.put("id", sGenIds.get(0));
            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "get");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);

            assertNotNull(node);
            assertTrue(node.isObject());
            assertNotNull(node.get("generated"));
            assertNotNull(node.get("id"));
            assertEquals(node.get("id").asText(), sGenIds.get(0));
            assertEquals(node.get("@class").asText(), TEST_COLLECTION);
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  @Test
  public void testCreateDocument() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode params = MAPPER.createObjectNode();
            ObjectNode doc = MAPPER.createObjectNode();
            doc.put("fresh", "fresh");
            params.put("collection", TEST_COLLECTION);
            params.put("data", doc);
            ObjectNode cmd = ScriptCommands.createCommand("documents", "post", params);

            JsonNode exec = CommandRegistry.execute(cmd, null);
            assertNotNull(exec);
            assertTrue(exec.isObject());
            assertNotNull(exec.get("id"));
            assertEquals(TEST_COLLECTION, exec.get("@class").asText());

          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
  /**
   * Calls the Callable and returns the value it returns. If an exception occurs, it is logged and a
   * new non-chained exception is thrown.
   *
   * @param <T> return type
   * @param callable code to call
   * @param message verbose description of operation
   * @return return value of Callable
   */
  private <T> T callLogThrow(final Callable<T> callable, final String message) {
    try {
      return callable.call();
    } catch (Exception e) {
      // generate reference #
      String refNum = UUID.randomUUID().toString();
      if (logger.isDebugEnabled()) {
        logger.debug(
            Messages.getInstance().getString("ExceptionLoggingDecorator.referenceNumber", refNum),
            e); //$NON-NLS-1$
      }

      // list all exceptions in stack
      @SuppressWarnings("unchecked")
      List<Throwable> throwablesInStack = ExceptionUtils.getThrowableList(e);
      // reverse them so most specific exception (root cause) comes first
      Collections.reverse(throwablesInStack);

      for (Throwable t : throwablesInStack) {
        String className = t.getClass().getName();
        if (exceptionConverterMap.containsKey(className)) {
          throw exceptionConverterMap
              .get(className)
              .convertException((Exception) t, message, refNum);
        }
      }

      // no converter; throw general exception
      throw new UnifiedRepositoryException(
          Messages.getInstance()
              .getString(
                  "ExceptionLoggingDecorator.generalException", message, refNum)); // $NON-NLS-1$
    }
  }
  public Map<String, List<RDFNode>> queryModel(
      String queryString, List<String> queryVariables, VirtDataset virtDataset) {
    Map<String, List<RDFNode>> solution = new HashMap<String, List<RDFNode>>();
    QueryExecution qexec = null;
    try {
      qexec = QueryExecutionFactory.create(queryString, virtDataset);
      // ResultSet rs = executeQuery(sb.toString(), virtDataset);
    } catch (com.hp.hpl.jena.query.QueryParseException e) {
      System.err.println(ExceptionUtils.getStackTrace(e) + "\n Will return an empty map...");
      return Collections.EMPTY_MAP;
    }

    ResultSet results = qexec.execSelect();
    while (results.hasNext()) {
      QuerySolution sol = results.next();
      for (String variable : queryVariables) {

        RDFNode nodeVar = sol.get(variable);
        if (nodeVar != null) {
          if (solution.get(variable) == null) {
            solution.put(variable, new ArrayList<RDFNode>());
          }
          solution.get(variable).add(nodeVar);
        }
      }
    }

    return solution;
  }
Ejemplo n.º 16
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.º 17
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;
  }
  @Transactional
  @Override
  public CommandProcessingResult create(final JsonCommand command) {

    try {
      this.fromApiJsonDataValidator.validateForCreate(command.json());

      final SavingsProduct product = this.savingsProductAssembler.assemble(command);

      this.savingProductRepository.save(product);

      // save accounting mappings
      this.accountMappingWritePlatformService.createSavingProductToGLAccountMapping(
          product.getId(), command, DepositAccountType.SAVINGS_DEPOSIT);

      // check if the office specific products are enabled. If yes, then
      // save this savings product against a specific office
      // i.e. this savings product is specific for this office.
      fineractEntityAccessUtil.checkConfigurationAndAddProductResrictionsForUserOffice(
          FineractEntityAccessType.OFFICE_ACCESS_TO_SAVINGS_PRODUCTS, product.getId());

      return new CommandProcessingResultBuilder() //
          .withEntityId(product.getId()) //
          .build();
    } catch (final DataAccessException e) {
      handleDataIntegrityIssues(command, e.getMostSpecificCause(), e);
      return CommandProcessingResult.empty();
    } catch (final PersistenceException dve) {
      Throwable throwable = ExceptionUtils.getRootCause(dve.getCause());
      handleDataIntegrityIssues(command, throwable, dve);
      return CommandProcessingResult.empty();
    }
  }
Ejemplo n.º 19
0
  /**
   * This method is to get the roleId and roleName.
   *
   * @param roleLevel
   * @param tenantId
   * @param subTenantId
   * @param response
   * @return
   */
  @RequestMapping(value = "/getRoleInfo", method = RequestMethod.GET)
  public @ResponseBody String getRoleInfo(
      int roleLevel, int tenantId, int subTenantId, HttpServletResponse response) {
    try {
      ArrayList arrayObj = new ArrayList();
      List<Roles> roleInfoList = userService.getRoleInfo();

      for (int i = 0; i < roleInfoList.size(); i++) {
        Roles roleInfo = roleInfoList.get(i);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("roleId", roleInfo.getRoleId());
        jsonObject.put("roleName", roleInfo.getRoleName());

        arrayObj.add(jsonObject);
      }

      JSONObject myObj = new JSONObject();
      myObj.put("total", roleInfoList.size());
      myObj.put("success", true);
      myObj.put("roleInfo", arrayObj);

      return myObj.toString();

    } catch (Exception e) {
      log.error("Exception in getRoleInfo::" + ExceptionUtils.getStackTrace(e));
    }

    return "";
  }
Ejemplo n.º 20
0
 public static void inlinePic(HttpServletResponse res, String path) {
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
   if (path != null) {
     if (path.toLowerCase().endsWith(".jpg") || path.toLowerCase().endsWith(".jpeg")) {
       res.setContentType("image/jpeg");
       res.setHeader("Content-disposition", "inline; filename=\"license.jpg\";");
     } else if (path.toLowerCase().endsWith(".gif")) {
       res.setContentType("image/gif");
       res.setHeader("Content-disposition", "inline; filename=\"license.gif\";");
     } else if (path.toLowerCase().endsWith(".png")) {
       res.setContentType("image/png");
       res.setHeader("Content-disposition", "inline; filename=\"license.png\";");
     }
     res.setHeader("Content-Length", String.valueOf(new File(path).length()));
     try {
       bis = new BufferedInputStream(new FileInputStream(path));
       bos = new BufferedOutputStream(res.getOutputStream());
       IOUtils.copy(bis, bos);
     } catch (IOException e) {
       logger.error(ExceptionUtils.getStackTrace(e));
       throw new RuntimeException(e);
     } finally {
       IOUtils.closeQuietly(bis);
       IOUtils.closeQuietly(bos);
     }
   }
 }
  public String getStudyHost(String studyOid) throws Exception {

    String ocUrl = CoreResources.getField("sysURL.base") + "rest2/openrosa/" + studyOid;
    String pManageUrl = CoreResources.getField("portalURL");
    String pManageUrlFull =
        pManageUrl + "/app/rest/oc/authorizations?studyoid=" + studyOid + "&instanceurl=" + ocUrl;

    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    requestFactory.setReadTimeout(PARTICIPATE_READ_TIMEOUT);
    RestTemplate rest = new RestTemplate(requestFactory);
    try {
      Authorization[] response = rest.getForObject(pManageUrlFull, Authorization[].class);
      if (response.length > 0
          && response[0].getStudy() != null
          && response[0].getStudy().getHost() != null
          && !response[0].getStudy().getHost().equals("")) {
        URL url = new URL(pManageUrl);
        String port = "";
        if (url.getPort() > 0) port = ":" + String.valueOf(url.getPort());
        return url.getProtocol()
            + "://"
            + response[0].getStudy().getHost()
            + "."
            + url.getHost()
            + port
            + "/#/login";
      }
    } catch (Exception e) {
      logger.error(e.getMessage());
      logger.error(ExceptionUtils.getStackTrace(e));
    }
    return "";
  }
  public void onFailure(ITestResult result) {
    if (getWebDriver() == null) {
      System.out.println(
          "Can't take a screenshot and save HTML, because there is no driver available.");
      return;
    }

    Throwable throwable = result.getThrowable();
    String stacktrace = null;

    if (throwable != null) {
      stacktrace = ExceptionUtils.getStackTrace(throwable);
    }

    String filenameIdentification = getFilenameIdentification(result);

    // TODO traffic can be captured using BrowserMob Proxy
    // String traffic;
    // try {
    // traffic = selenium.captureNetworkTraffic(NetworkTrafficType.PLAIN).getTraffic();
    // } catch (SeleniumException e) {
    // traffic = ExceptionUtils.getFullStackTrace(e);
    // }

    try {
      File screenshot = null;
      if (((GrapheneProxyInstance) getWebDriver()).unwrap() instanceof TakesScreenshot) {
        screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.FILE);
      }

      String htmlSource = getWebDriver().getPageSource();

      File stacktraceOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/stacktrace.txt");
      File imageOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/screenshot.png");
      // File trafficOutputFile = new File(failuresOutputDir, filenameIdentification +
      // "/network-traffic.txt");
      // File logOutputFile = new File(failuresOutputDir, filenameIdentification +
      // "/selenium-log.txt");
      File htmlSourceOutputFile =
          new File(failuresOutputDir, filenameIdentification + "/html-source.html");

      File directory = imageOutputFile.getParentFile();
      FileUtils.forceMkdir(directory);

      FileUtils.writeStringToFile(stacktraceOutputFile, stacktrace);
      if (!HtmlUnitDriver.class.isInstance(getWebDriver())) {
        FileUtils.copyFile(screenshot, imageOutputFile);
      }

      // FileUtils.writeStringToFile(trafficOutputFile, traffic);
      // FileUtils.writeLines(logOutputFile, methodLog);
      FileUtils.writeStringToFile(htmlSourceOutputFile, htmlSource);
    } catch (Exception e) {
      System.err.println("Can't take a screenshot/save HTML source: " + e.getMessage());
      e.printStackTrace(System.err);
      // LOGGER.log(Level.WARNING, "Can't take a screenshot/save HTML source.", e);
    }
  }
Ejemplo n.º 23
0
  public int updateUser(User user) throws RuntimeException {
    logger.info("--> cs.simple.console.service.impl.UserServiceImpl.updateUser");
    int affected = 0;
    try {
      List<Object> args = new ArrayList<Object>();

      String password = user.getPassword();
      StringBuffer b = new StringBuffer();
      b.append("update tb_user set viewname = ? ");
      args.add(user.getViewname());

      if (StringUtils.hasText(password)) {
        b.append(", password = ? ");
        args.add(password(user.getPassword()));
      }

      b.append("where user_id = ?");
      args.add(user.getUserId());

      affected = jdbcTemplate.update(b.toString(), args.toArray());
    } catch (Exception e) {
      logger.error(ExceptionUtils.getStackTrace(e));
      throw new RuntimeException(e);
    }
    logger.info("<-- cs.simple.console.service.impl.UserServiceImpl.updateUser");
    return affected;
  }
Ejemplo n.º 24
0
    @Override
    public void run() {
      try {
        StopWatch stp2 = new StopWatch();
        stp2.start();
        JSONObject json = new JSONObject();
        job.setStatus("running");
        if (job.progress() == 100.0) {

          finalizeJob(job);
          return;
        }
        Vector<String> ids = new Vector<String>();
        Vector<String> original_names = new Vector<String>();

        String data = job.getNextDataBatch();

        if (data == null || data.equals("")) return;

        String[] lines = data.split("\n");

        if (job.containsId()) {
          for (int i = 0; i < lines.length; i++) {
            if (lines[i].trim().equals("")) continue;
            ids.add(NameUtil.getNameId(lines[i]));
          }
        }

        for (int i = 0; i < lines.length; i++) {
          original_names.add(NameUtil.processName(lines[i], job.containsId()));
        }

        String names = NameUtil.CleanNames(lines, job);

        if (names.equals("")) return;

        if (job.getType() == TnrsJob.NAME_MATCH_JOB) {

          TaxamatchInterface taxa_match = new TaxamatchInterface(tnrsBaseUrl);
          String result = taxa_match.queryTaxamatch(names, job);
          json = (JSONObject) JSONSerializer.toJSON(result);

        } else if (job.getType() == TnrsJob.PARSING_JOB) {

          json = gni_interface.parseNames(names);
        }
        if (job.outstandingNames() == 0) {
          JobHelper.persistJobInfo(baseFolder, job);
        }
        saveResults(job, json, ids, original_names, "");

        job.setStatus("idle");
        stp2.stop();
        log.info("overall :" + stp2.toString());
      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        job.setStatus("failed");
        ex.printStackTrace();
      }
    }
  @Test
  public void testCommandGetFilteredCollection() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            ObjectNode cmd = MAPPER.createObjectNode();
            ObjectNode p = MAPPER.createObjectNode();
            ObjectNode q = MAPPER.createObjectNode();
            q.put("where", "idx < ?");
            ArrayNode params = MAPPER.createArrayNode();
            params.add("5");
            q.put("params", params);
            p.put("collection", TEST_COLLECTION);
            p.put("query", q);

            cmd.put(ScriptCommand.RESOURCE, "documents");
            cmd.put(ScriptCommand.NAME, "list");
            cmd.put(ScriptCommand.PARAMS, p);

            JsonNode node = CommandRegistry.execute(cmd, null);
            assertNotNull(node);
            assertTrue(node.isArray());
            assertEquals(5, node.size());
          } catch (Throwable t) {
            fail(ExceptionUtils.getFullStackTrace(t));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Ejemplo n.º 26
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {

      try {
        JSONObject request =
            (JSONObject) JSONSerializer.toJSON(IOUtils.toString(arg0.getRequestBody()));
        String email = request.getString("email");
        String key = request.getString("key");

        for (int i = 0; i < jobs.size(); i++) {
          TnrsJob job = jobs.get(i);
          if (job.getRequest().getId().equals(key) && job.getRequest().getEmail().equals(email)) {
            JSONObject json = (JSONObject) JSONSerializer.toJSON(job.toJsonString());
            json.put("status", "incomplete");
            json.put("progress", job.progress());

            HandlerHelper.writeResponseRequest(arg0, 200, json.toString(), "application/json");
            return;
          }
        }
        if (JobHelper.jobFileExists(baseFolder, email, key)) {
          TnrsJob job = JobHelper.readJobInfo(baseFolder, email, key);

          HandlerHelper.writeResponseRequest(arg0, 200, job.toJsonString(), "application/json");
        } else {
          HandlerHelper.writeResponseRequest(
              arg0, 500, "No such job exists o it might have expired", "text/plain");
        }

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
  @BeforeClass
  public static void initTestser() {
    running(
        fakeApplication(),
        () -> {
          try {
            DbHelper.open("1234567890", "admin", "admin");
            ODocument user =
                UserService.signUp(TEST_USER, TEST_USER, new Date(), null, null, null, null, false);
            assertNotNull(user);
            ODocument alt =
                UserService.signUp(
                    TEST_ALT_USER, TEST_ALT_USER, new Date(), null, null, null, null, false);
            assertNotNull(alt);

            CollectionService.create(TEST_COLLECTION);
            DbHelper.close(DbHelper.getConnection());
            DbHelper.open("1234567890", TEST_USER, TEST_USER);
            sGenIds = createRandomDocuments(10);
            DbHelper.close(DbHelper.getConnection());
          } catch (Throwable e) {
            fail(ExceptionUtils.getFullStackTrace(e));
          } finally {
            DbHelper.close(DbHelper.getConnection());
          }
        });
  }
Ejemplo n.º 28
0
    @Override
    public void handle(HttpExchange arg0) throws IOException {
      try {
        String message =
            "<html><body><table border=\"1\"><tr><th>Email</th><th>Submitted at:</th><th>Progress:</th><th>Status:</th><th>Job id</th></tr>";
        for (int i = 0; i < jobs.size(); i++) {
          TnrsJob job = jobs.get(i);

          message +=
              "<tr> <td> "
                  + job.getRequest().getEmail()
                  + "</td><td>"
                  + job.getSubmissionDate()
                  + " </td><td> "
                  + job.progress()
                  + "% </td><td>  "
                  + job.status()
                  + "</td><td>"
                  + job.getRequest().getId()
                  + "</td></tr>\n";
        }
        message += "</table>";
        HandlerHelper.writeResponseRequest(arg0, 200, message, "text/html");

      } catch (Exception ex) {
        log.error(ExceptionUtils.getFullStackTrace(ex));
        throw new IOException(ex);
      }
    }
Ejemplo n.º 29
0
 @Override
 public <T extends ModelEntity> void refresh(T entity) throws PersistenceException {
   int numRetries = numberOfRefreshRetries;
   boolean notSuccessful = false;
   do {
     try {
       if (entity != null) {
         this._refresh(entity);
       }
     } catch (Exception e) {
       Throwable t = ExceptionUtils.getRootCause(e);
       if (!(t instanceof SQLException)) {
         throw new PersistenceException(e);
       }
       logger.warn("Unable to refresh model entity, " + numRetries + " left.  " + t.getMessage());
       numRetries--;
       notSuccessful = true;
       try {
         Thread.sleep(refreshRetryInterval);
       } catch (InterruptedException e1) {
         throw new PersistenceException(
             "Thread sleep interrupted during the refresh retry interval: " + e1.getMessage(), e1);
       }
     }
   } while (notSuccessful && numRetries != 0);
   if (numRetries == 0) {
     throw new PersistenceException(
         "Unable to refresh model entity.  " + numberOfRefreshRetries + " retries failed");
   }
 }
Ejemplo n.º 30
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));
         }
       }
     }
   }
 }