示例#1
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());
    }
  }
示例#2
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));
   }
 }
 @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");
   }
 }
  @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();
    }
  }
  /**
   * 运行时,添加JVM参数“-Dsun.net.http.retryPost=false”,可阻止自动重连。
   *
   * @see 'http://www.coderanch.com/t/490463/sockets/java/Timeout-retry-URLHTTPRequest'
   */
  @Test
  public void testConnectionResetByHttpURLConnection() throws IOException {
    testConnectionResetCount = 0;

    String resp = null;
    try {
      HttpURLConnection conn =
          (HttpURLConnection) new URL("http://localhost:65532/soso").openConnection();
      conn.setDoOutput(true);
      conn.setRequestMethod("POST");
      conn.getOutputStream().write("username".getBytes());
      resp = conn.getResponseCode() + "";
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(2, testConnectionResetCount);
  }
  @Test
  public void testConnectionResetByHttpClientUtils() throws IOException {
    testConnectionResetCount = 0;

    httpClientUtils = new HttpClientUtils();
    httpClientUtils.initHttpClient();
    Logger.info(this, "-------------- HttpClient initialized -------------");

    String resp = null;
    try {
      resp = httpClientUtils.get("http://localhost:65532/soso");
    } catch (IOException e) {
      Throwable ee = ExceptionUtils.getRootCause(e);
      if (ee == null) {
        ee = e;
      }
      Logger.error(this, "", ee);
      Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
      Assert.assertSame(SocketException.class, ee.getClass());
      Assert.assertTrue(
          "Connection reset".equals(ee.getMessage())
              || "Socket closed".equals(ee.getMessage())
              || "Unexpected end of file from server".equals(ee.getMessage()));
    } finally {
      Logger.info(
          this,
          "resp[HttpURLConnection]-["
              + testConnectionResetCount
              + "]=========["
              + resp
              + "]=========");
    }
    Assert.assertEquals(1, testConnectionResetCount);
  }
  @Override
  public void handle() throws FacesException {

    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();
    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      // get the exception from context
      Throwable t = context.getException();

      final FacesContext fc = FacesContext.getCurrentInstance();
      final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();
      final NavigationHandler nav = fc.getApplication().getNavigationHandler();

      // here you do what ever you want with exception
      try {

        if (ExceptionUtils.getRootCause(t) instanceof AccessDeniedException) {
          throw (AccessDeniedException) ExceptionUtils.getRootCause(t);
        }

        log.error("złapano wyjątek: nieprzechwycony przez controller");
        log.error(t.getMessage(), t);
        t.printStackTrace();

        // redirect error page
        requestMap.put("exceptionMessage", t.getMessage());
        nav.handleNavigation(fc, null, "/error");
        fc.renderResponse();

        // remove the comment below if you want to report the error in a jsf error message
        //                JsfUtil.addErrorMessage(t.getMessage());

      } finally {
        // remove it from queue
        i.remove();
      }
    }
    // parent hanle
    getWrapped().handle();
  }
  @Test
  public void propagate_converter_failure() throws Exception {
    Callable<Object> callable = mock(Callable.class);
    when(callable.call()).thenThrow(new IllegalStateException("Need to cry"));

    List<Callable<Object>> callables = Lists.newArrayList(callable);
    try {
      new ViolationConverters(new Settings()).doExecute(new FakeTimerTask(), callables);
      fail();
    } catch (Exception e) {
      assertThat(ExceptionUtils.getRootCause(e).getMessage()).isEqualTo("Need to cry");
    }
  }
  protected static String getVcenterAPIMessage(Throwable t) {
    String message = null;

    if (ExceptionUtils.getRootCause(t) instanceof InvalidLogin) {
      message = "Login failed";
    }

    if (message == null) {
      return "Failed to validate vCenter (Invalid host, port, username or password)";
    } else {
      return String.format("Failed to validate vCenter (%s)", message);
    }
  }
示例#10
0
 private void invalidate(OpenVPMSException exception) {
   if (validationErrors != null) {
     validationErrors.clear();
   } else {
     validationErrors = new ArrayList<ValidatorError>();
   }
   Throwable cause = ExceptionUtils.getRootCause(exception);
   if (cause == null) {
     cause = exception;
   }
   ValidatorError error = new ValidatorError(this, cause.getMessage());
   validationErrors.add(error);
   resetValid();
 }
  protected static Metadata extractMetadata(
      InputStream inputStream, Metadata metadata, Parser parser) throws IOException {

    if (metadata == null) {
      metadata = new Metadata();
    }

    ParseContext parserContext = new ParseContext();

    parserContext.set(Parser.class, parser);

    ContentHandler contentHandler = new WriteOutContentHandler(new DummyWriter());

    try {
      parser.parse(inputStream, contentHandler, metadata, parserContext);
    } catch (Exception e) {
      Throwable throwable = ExceptionUtils.getRootCause(e);

      if ((throwable instanceof CryptographyException)
          || (throwable instanceof EncryptedDocumentException)
          || (throwable instanceof UnsupportedZipFeatureException)) {

        if (_log.isWarnEnabled()) {
          _log.warn("Unable to extract metadata from an encrypted file");
        }
      } else if (e instanceof TikaException) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to extract metadata");
        }
      } else {
        _log.error(e, e);
      }

      throw new IOException(e);
    }

    // Remove potential security risks

    metadata.remove(XMPDM.ABS_PEAK_AUDIO_FILE_PATH.getName());
    metadata.remove(XMPDM.RELATIVE_PEAK_AUDIO_FILE_PATH.getName());

    return metadata;
  }
 @Test
 public void testPostCustomerBodyAndCharset() {
   httpClientUtils = new HttpClientUtils();
   httpClientUtils.initHttpClient();
   Logger.info(this, "-------------- HttpClient initialized -------------");
   // testPostCustomerBodyAndCharset
   String resp = "";
   try {
     resp =
         httpClientUtils.post(
             "http://localhost:65534/test/testPostCustomerBodyAndCharset",
             "<?xml version=\"1.0\" encoding=\"GBK\"?><AIPG><INFO>你好</INFO></AIPG>",
             "GBK");
   } catch (IOException e) {
     Throwable ee = ExceptionUtils.getRootCause(e);
     if (ee == null) {
       ee = e;
     }
     Logger.error(this, "", ee);
     Assert.assertTrue(false);
     //            Assert.assertNotSame(NoHttpResponseException.class, ee.getClass());
     //            Assert.assertSame(SocketException.class, ee.getClass());
     //            Assert.assertTrue("Connection reset".equals(ee.getMessage()) || "Socket
     // closed".equals(ee.getMessage()) || "Unexpected end of file from
     // server".equals(ee.getMessage()));
   } finally {
     Logger.info(
         this,
         "resp[HttpURLConnection]-["
             + testConnectionResetCount
             + "]=========["
             + resp
             + "]=========");
   }
   //        Assert.assertEquals(1, testConnectionResetCount);
   Assert.assertTrue(true);
 }
示例#13
0
文件: Rest.java 项目: tcanvn/SParCEL
  /**
   * *
   *
   * @param httpServletRequest
   * @param httpServletResponse
   * @throws ServletException
   * @throws java.io.IOException
   */
  private void handle(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
      throws ServletException, IOException {
    JSONObject result = new JSONObject();
    JSONObject learningResult = new JSONObject();
    try {
      String conf = null;
      int limit = 5;
      if (!isSet("conf", httpServletRequest)) {
        throw new IllegalArgumentException("Missing parameter: conf is required. ");
      } else {
        conf = httpServletRequest.getParameter("conf");
        if (isSet("limit", httpServletRequest)) {
          limit = Integer.parseInt(httpServletRequest.getParameter("limit"));
        }
      }

      if (isSet("debug", httpServletRequest)
          && httpServletRequest.getParameter("debug").equalsIgnoreCase("true")) {

        String manchester = "author some (Artist and Writer)";
        String sparql =
            "prefix dbo: <http://dbpedia.org/ontology/>\n"
                + "SELECT ?instances WHERE {\n"
                + "?instances dbo:author ?o . ?o a dbo:Artist . ?o a dbo:Writer .\n"
                + "} ";

        learningResult.put("success", "1");
        learningResult.put("manchester", manchester);
        learningResult.put("kbsyntax", "other syntax");
        learningResult.put("sparql", sparql);
        learningResult.put("accuracy", 1.0);
        learningResult.put("truePositives", "uri1, uri2");
        learningResult.put("truePositives", "uri1, uri2");
        learningResult.put("trueNegatives", "uri1, uri2");
        learningResult.put("falseNegatives", "uri1, uri2");
      } else {

        EvaluatedDescriptionPosNeg ed = learn(conf);

        SparqlQueryDescriptionConvertVisitor sqd = new SparqlQueryDescriptionConvertVisitor();
        sqd.setLimit(limit);

        learningResult.put("success", "1");
        learningResult.put("manchester", ed.getDescription().toManchesterSyntaxString(null, null));
        learningResult.put("kbsyntax", ed.getDescription().toKBSyntaxString());
        learningResult.put("sparql", sqd.getSparqlQuery(ed.getDescription()));
        learningResult.put("accuracy", ed.getAccuracy());
        learningResult.put(
            "truePositives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getCoveredPositives()));
        learningResult.put(
            "falsePositives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getNotCoveredPositives()));
        learningResult.put(
            "trueNegatives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getNotCoveredNegatives()));
        learningResult.put(
            "falseNegatives", EvaluatedDescriptionPosNeg.getJSONArray(ed.getCoveredNegatives()));
      }

    } catch (IllegalArgumentException e) {
      String msg = e.getMessage(); // + printParameterMap(httpServletRequest);
      log.error("", ExceptionUtils.getRootCause(e));
      learningResult.put("success", "0");
      learningResult.put("error", msg);
      learningResult.put("stacktrace", ExceptionUtils.getRootCause(e));

    } catch (Exception e) {
      String msg =
          "An error occured: " + e.getMessage(); // + printParameterMap(httpServletRequest);
      log.error("", ExceptionUtils.getRootCause(e));
      learningResult.put("success", "0");
      learningResult.put("error", msg);
      learningResult.put("stacktrace", ExceptionUtils.getRootCause(e));
    }

    result.put("learningresult", learningResult);
    httpServletResponse.setContentType("text/plain");
    PrintWriter out = httpServletResponse.getWriter();
    out.println(result.toJSONString());
    out.close();
  }
示例#14
0
 private String determineExceptionMessage(Throwable throwable) {
   return throwable.getCause() == null
       ? throwable.getMessage()
       : ExceptionUtils.getRootCause(throwable).getMessage();
 }
  @Transactional
  @Override
  public CommandProcessingResult update(final Long productId, final JsonCommand command) {

    try {
      this.context.authenticatedUser();
      final SavingsProduct product = this.savingProductRepository.findOne(productId);
      if (product == null) {
        throw new SavingsProductNotFoundException(productId);
      }

      this.fromApiJsonDataValidator.validateForUpdate(command.json(), product);

      final Map<String, Object> changes = product.update(command);

      if (changes.containsKey(chargesParamName)) {
        final Set<Charge> savingsProductCharges =
            this.savingsProductAssembler.assembleListOfSavingsProductCharges(
                command, product.currency().getCode());
        final boolean updated = product.update(savingsProductCharges);
        if (!updated) {
          changes.remove(chargesParamName);
        }
      }

      if (changes.containsKey(taxGroupIdParamName)) {
        final TaxGroup taxGroup = this.savingsProductAssembler.assembleTaxGroup(command);
        product.setTaxGroup(taxGroup);
        if (product.withHoldTax() && product.getTaxGroup() == null) {
          final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
          final DataValidatorBuilder baseDataValidator =
              new DataValidatorBuilder(dataValidationErrors)
                  .resource(SAVINGS_PRODUCT_RESOURCE_NAME);
          final Long taxGroupId = null;
          baseDataValidator.reset().parameter(taxGroupIdParamName).value(taxGroupId).notBlank();
          throw new PlatformApiDataValidationException(dataValidationErrors);
        }
      }

      // accounting related changes
      final boolean accountingTypeChanged = changes.containsKey(accountingRuleParamName);
      final Map<String, Object> accountingMappingChanges =
          this.accountMappingWritePlatformService.updateSavingsProductToGLAccountMapping(
              product.getId(),
              command,
              accountingTypeChanged,
              product.getAccountingType(),
              DepositAccountType.SAVINGS_DEPOSIT);
      changes.putAll(accountingMappingChanges);

      if (!changes.isEmpty()) {
        this.savingProductRepository.saveAndFlush(product);
      }

      return new CommandProcessingResultBuilder() //
          .withEntityId(product.getId()) //
          .with(changes)
          .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();
    }
  }
  /**
   * Evaluate a script and allow for the submission of both a transform {@link Function} and {@link
   * Consumer}. The {@link Function} will transform the result after script evaluates but before
   * transaction commit and before the returned {@link CompletableFuture} is completed. The {@link
   * Consumer} will take the result for additional processing after the script evaluates and after
   * the {@link CompletableFuture} is completed, but before the transaction is committed.
   *
   * @param script the script to evaluate
   * @param language the language to evaluate it in
   * @param boundVars the bindings to evaluate in the context of the script
   * @param transformResult a {@link Function} that transforms the result - can be {@code null}
   * @param withResult a {@link Consumer} that accepts the result - can be {@code null}
   */
  public CompletableFuture<Object> eval(
      final String script,
      final String language,
      final Bindings boundVars,
      final Function<Object, Object> transformResult,
      final Consumer<Object> withResult) {
    final String lang = Optional.ofNullable(language).orElse("gremlin-groovy");

    logger.debug(
        "Preparing to evaluate script - {} - in thread [{}]",
        script,
        Thread.currentThread().getName());

    final Bindings bindings = new SimpleBindings();
    bindings.putAll(this.globalBindings);
    bindings.putAll(boundVars);
    beforeEval.accept(bindings);

    final CompletableFuture<Object> evaluationFuture = new CompletableFuture<>();
    final FutureTask<Void> f =
        new FutureTask<>(
            () -> {
              try {
                logger.debug(
                    "Evaluating script - {} - in thread [{}]",
                    script,
                    Thread.currentThread().getName());

                final Object o = scriptEngines.eval(script, bindings, lang);

                // apply a transformation before sending back the result - useful when trying to
                // force serialization
                // in the same thread that the eval took place given ThreadLocal nature of graphs as
                // well as some
                // transactional constraints
                final Object result = null == transformResult ? o : transformResult.apply(o);
                evaluationFuture.complete(result);

                // a mechanism for taking the final result and doing something with it in the same
                // thread, but
                // AFTER the eval and transform are done and that future completed.  this provides a
                // final means
                // for working with the result in the same thread as it was eval'd
                if (withResult != null) withResult.accept(result);

                afterSuccess.accept(bindings);
              } catch (Exception ex) {
                final Throwable root = null == ex.getCause() ? ex : ExceptionUtils.getRootCause(ex);

                // thread interruptions will typically come as the result of a timeout, so in those
                // cases,
                // check for that situation and convert to TimeoutException
                if (root instanceof InterruptedException)
                  evaluationFuture.completeExceptionally(
                      new TimeoutException(
                          String.format(
                              "Script evaluation exceeded the configured threshold of %s ms for request [%s]: %s",
                              scriptEvaluationTimeout, script, root.getMessage())));
                else {
                  afterFailure.accept(bindings, root);
                  evaluationFuture.completeExceptionally(root);
                }
              }

              return null;
            });

    executorService.execute(f);

    if (scriptEvaluationTimeout > 0) {
      // Schedule a timeout in the thread pool for future execution
      final ScheduledFuture<?> sf =
          scheduledExecutorService.schedule(
              () -> {
                logger.info(
                    "Timing out script - {} - in thread [{}]",
                    script,
                    Thread.currentThread().getName());
                if (!f.isDone()) {
                  afterTimeout.accept(bindings);
                  f.cancel(true);
                }
              },
              scriptEvaluationTimeout,
              TimeUnit.MILLISECONDS);

      // Cancel the scheduled timeout if the eval future is complete or the script evaluation failed
      // with exception
      evaluationFuture.handleAsync(
          (v, t) -> {
            logger.debug(
                "Killing scheduled timeout on script evaluation as the eval completed (possibly with exception).");
            return sf.cancel(true);
          });
    }

    return evaluationFuture;
  }