org.apache.commons.lang3.exception.ExceptionUtils Java Examples

The following examples show how to use org.apache.commons.lang3.exception.ExceptionUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SimpleTomEEFormatterTest.java    From tomee with Apache License 2.0 7 votes vote down vote up
@Test
public void formatNotNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);

    try {
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.CONFIG;
        final String exceptionMessage = "An example exception";
        final Throwable thrown = new Exception(exceptionMessage);

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(thrown);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue + ExceptionUtils.getStackTrace(thrown);

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}
 
Example #2
Source File: DefaultDebuggerExecutionExceptionHandler.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleException(final JobServiceConfiguration jobServiceConfiguration, final JobInfo job, final Throwable exception) {
    if (HANDLER_TYPE_BREAK_POINT.equals(job.getJobHandlerType())) {
        LOGGER.debug("break point execution throws an exception which will be swallowed", exception);
        jobServiceConfiguration.getCommandExecutor().execute( 
                commandContext -> {
                    JobEntity jobEntity = jobServiceConfiguration.getJobService().findJobById(job.getId());
                    SuspendedJobEntity suspendedJobEntity = jobServiceConfiguration.getJobService().moveJobToSuspendedJob(jobEntity);
                    if (exception != null) {
                        LOGGER.info("Debugger exception ", exception);
                        suspendedJobEntity.setExceptionMessage(exception.getMessage());
                        suspendedJobEntity.setExceptionStacktrace(ExceptionUtils.getStackTrace(exception));
                    }
                    return null;
                }
        );
        return true;
    }
    return false;
}
 
Example #3
Source File: ExceptionReturner.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * Clean return of Exception in JSon format & log Exception.
    * 
    * @param request
    * @param response
    * @param out
    * @param exception
    */
   public static void logAndReturnException(HttpServletRequest request,
    HttpServletResponse response, PrintWriter out,
    Exception exception) {

try {
    JsonErrorReturn jsonErrorReturn = new JsonErrorReturn(response,
	    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
	    JsonErrorReturn.ERROR_ACEQL_ERROR, exception.getMessage(),
	    ExceptionUtils.getStackTrace(exception));

    out.println(jsonErrorReturn.build());
    LoggerUtil.log(request, exception);
} catch (Exception e) {
    // Should never happen
    e.printStackTrace();
}

   }
 
Example #4
Source File: WebDialogs.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void show() {
    if (throwable == null) {
        throw new IllegalStateException("throwable should not be null");
    }

    Throwable rootCause = ExceptionUtils.getRootCause(throwable);
    if (rootCause == null) {
        rootCause = throwable;
    }

    ExceptionDialog dialog = new ExceptionDialog(rootCause, caption, message);
    for (com.vaadin.ui.Window window : ui.getWindows()) {
        if (window.isModal()) {
            dialog.setModal(true);
            break;
        }
    }
    ui.addWindow(dialog);
    dialog.focus();
}
 
Example #5
Source File: ReviewRunner.java    From sputnik with Apache License 2.0 6 votes vote down vote up
public void review(@NotNull ReviewProcessor processor) {
    log.info("Review started for processor {}", processor.getName());
    long start = System.currentTimeMillis();
    ReviewResult reviewResult = null;

    try {
        reviewResult = processor.process(review);
    } catch (ReviewException e) {
        log.error("Processor {} error", processor.getName(), e);
        review.addProblem(processor.getName(), ExceptionUtils.getRootCauseMessage(e));

    }
    log.info("Review finished for processor {}. Took {} s", processor.getName(), (System.currentTimeMillis() - start) / THOUSAND);

    if (reviewResult == null) {
        log.warn("Review for processor {} returned empty review", processor.getName());
    } else {
        log.info("Review for processor {} returned {} violations", processor.getName(), reviewResult.getViolations().size());
        review.add(processor.getName(), reviewResult);
    }
}
 
Example #6
Source File: GremlinDriverIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReportErrorWhenRequestCantBeSerialized() throws Exception {
    final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V3D0).create();
    final Client client = cluster.connect().alias("g");

    try {
        final Map<String,Object> params = new HashMap<>();
        params.put("r", Color.RED);
        client.submit("r", params).all().get();
        fail("Should have thrown exception over bad serialization");
    } catch (Exception ex) {
        final Throwable inner = ExceptionUtils.getRootCause(ex);
        assertThat(inner, instanceOf(ResponseException.class));
        assertEquals(ResponseStatusCode.REQUEST_ERROR_SERIALIZATION, ((ResponseException) inner).getResponseStatusCode());
        assertTrue(ex.getMessage().contains("An error occurred during serialization of this request"));
    }

    // should not die completely just because we had a bad serialization error.  that kind of stuff happens
    // from time to time, especially in the console if you're just exploring.
    assertEquals(2, client.submit("1+1").all().get().get(0).getInt());

    cluster.close();
}
 
Example #7
Source File: InterpreterRestApi.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
/**
 * Add new repository.
 *
 * @param message Repository
 */
@POST
@Path("repository")
@ZeppelinApi
public Response addRepository(String message) {
  try {
    Repository request = Repository.fromJson(message);
    interpreterSettingManager.addRepository(request.getId(), request.getUrl(),
        request.isSnapshot(), request.getAuthentication(), request.getProxy());
    logger.info("New repository {} added", request.getId());
  } catch (Exception e) {
    logger.error("Exception in InterpreterRestApi while adding repository ", e);
    return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, e.getMessage(),
        ExceptionUtils.getStackTrace(e)).build();
  }
  return new JsonResponse(Status.OK).build();
}
 
Example #8
Source File: RpcSupportHandler.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
@Override
public void onComplete(ListenableFuture<Object> future) throws Exception {
    if (context.session.isClosed()) {
        return;
    }

    final RpcErrorCode errorCode;
    final Object body;
    if (future.isCompletedExceptionally()) {
        errorCode = RpcErrorCode.SERVER_EXCEPTION;
        // 不返回完整信息,意义不大
        body = ExceptionUtils.getRootCauseMessage(future.cause());
    } else {
        errorCode = RpcErrorCode.SUCCESS;
        body = future.getNow();
    }

    // 此时已经在网络线程,直接write,但还是需要流经整个管道
    final RpcResponseMessage responseMessage = new RpcResponseMessage(context.requestGuid, context.sync, errorCode, body);
    context.session.fireWrite(responseMessage);
}
 
Example #9
Source File: WxMaTemplateMsgSender.java    From WePush with MIT License 6 votes vote down vote up
@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();

    try {
        String openId = msgData[0];
        WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
        wxMaSubscribeMessage.setToUser(openId);
        wxMaSubscribeMessage.setTemplateId(msgData[1]);
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
        return sendResult;
    }

    sendResult.setSuccess(true);
    return sendResult;
}
 
Example #10
Source File: UniverseClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
public boolean closeSession(String paragraphId) throws UniverseException {
  try {
    if (tokens.containsKey(paragraphId)) {
      HttpPost httpPost = new HttpPost(String.format("%s%s", apiUrl, "/logoff"));
      setHeaders(httpPost, tokens.get(paragraphId));
      HttpResponse response = httpClient.execute(httpPost);
      if (response.getStatusLine().getStatusCode() == 200) {
        return true;
      }
    }

    return false;
  } catch (Exception e) {
    throw new UniverseException(String.format(errorMessageTemplate, "UniverseClient "
        + "(close session): Request failed", ExceptionUtils.getStackTrace(e)));
  } finally {
    tokens.remove(paragraphId);
  }
}
 
Example #11
Source File: AbstractUiExceptionHandler.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handle(Throwable exception, UiContext context) {
    List<Throwable> list = ExceptionUtils.getThrowableList(exception);
    for (Throwable throwable : list) {
        if (classNames.contains(throwable.getClass().getName())
                && canHandle(throwable.getClass().getName(), throwable.getMessage(), throwable)) {
            doHandle(throwable.getClass().getName(), throwable.getMessage(), throwable, context);
            return true;
        }
        if (throwable instanceof RemoteException) {
            RemoteException remoteException = (RemoteException) throwable;
            for (RemoteException.Cause cause : remoteException.getCauses()) {
                if (classNames.contains(cause.getClassName())
                        && canHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable())) {
                    doHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable(), context);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #12
Source File: DatastreamRestClient.java    From brooklin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * move partitions to the target host
 * @param datastreamName
 *    Name of the datastream to move.
 * @param partitions
 *    partitions that need to be moved, separate by comma, ex topicA-0,topicB-1
 * @param targetHost
 *    the target host the partition assignment
 * @throws RemoteInvocationException
 */
public void movePartitions(String datastreamName, String partitions, String targetHost) throws RemoteInvocationException {
  Instant startTime = Instant.now();
  PollUtils.poll(() -> {
    try {
      ActionRequest<Void> request = _builders.actionMovePartitions().id(datastreamName).
          partitionsParam(partitions).targetHostParam(targetHost).build();
      ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
      return datastreamResponseFuture.getResponse();
    } catch (RemoteInvocationException e) {
      if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
        LOG.warn("Timeout: movePartitions. May retry...", e);
        return null;
      }
      if (isNotFoundHttpStatus(e)) {
        LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
        throw new DatastreamNotFoundException(datastreamName, e);
      } else {
        String errorMessage = String.format("move partitions failed with error, Datastream {%s}.", datastreamName);
        ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
      }
      return null; // not reachable
    }
  }, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
  LOG.info("move partitions for datastream {} took {} ms", datastreamName, Duration.between(startTime, Instant.now()).toMillis());
}
 
Example #13
Source File: WxMpTemplateMsgSender.java    From WePush with MIT License 6 votes vote down vote up
@Override
public SendResult send(String[] msgData) {
    SendResult sendResult = new SendResult();

    try {
        String openId = msgData[0];
        WxMpTemplateMessage wxMessageTemplate = wxMpTemplateMsgMaker.makeMsg(msgData);
        wxMessageTemplate.setToUser(openId);
        if (PushControl.dryRun) {
            sendResult.setSuccess(true);
            return sendResult;
        } else {
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMessageTemplate);
        }
    } catch (Exception e) {
        sendResult.setSuccess(false);
        sendResult.setInfo(e.getMessage());
        log.error(ExceptionUtils.getStackTrace(e));
        return sendResult;
    }

    sendResult.setSuccess(true);
    return sendResult;
}
 
Example #14
Source File: MssqlDateOutOfRangeExceptionHandler.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handle(Throwable exception, WindowManager windowManager) {
    List<Throwable> list = ExceptionUtils.getThrowableList(exception);
    for (Throwable throwable : list) {
        if (className.contains(throwable.getClass().getName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
            doHandle(windowManager);
            return true;
        }
        if (throwable instanceof RemoteException) {
            RemoteException remoteException = (RemoteException) throwable;
            for (RemoteException.Cause cause : remoteException.getCauses()) {
                if (className.contains(cause.getClassName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
                    doHandle(windowManager);
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #15
Source File: PulsarMetadata.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> listSchemaNames(ConnectorSession session) {
    List<String> prestoSchemas = new LinkedList<>();
    try {
        List<String> tenants = pulsarAdmin.tenants().getTenants();
        for (String tenant : tenants) {
            prestoSchemas.addAll(pulsarAdmin.namespaces().getNamespaces(tenant).stream().map(namespace ->
                rewriteNamespaceDelimiterIfNeeded(namespace, pulsarConnectorConfig)).collect(Collectors.toList()));
        }
    } catch (PulsarAdminException e) {
        if (e.getStatusCode() == 401) {
            throw new PrestoException(QUERY_REJECTED, "Failed to get schemas from pulsar: Unauthorized");
        }
        throw new RuntimeException("Failed to get schemas from pulsar: "
                + ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
    }
    return prestoSchemas;
}
 
Example #16
Source File: StoregateExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
@Override
public BackgroundException map(final ApiException failure) {
    for(Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if(cause instanceof SocketException) {
            // Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
            return new DefaultSocketExceptionMappingService().map((SocketException) cause);
        }
        if(cause instanceof HttpResponseException) {
            return new DefaultHttpResponseExceptionMappingService().map((HttpResponseException) cause);
        }
        if(cause instanceof IOException) {
            return new DefaultIOExceptionMappingService().map((IOException) cause);
        }
        if(cause instanceof IllegalStateException) {
            // Caused by: ch.cyberduck.core.sds.io.swagger.client.ApiException: javax.ws.rs.ProcessingException: java.lang.IllegalStateException: Connection pool shut down
            return new ConnectionCanceledException(cause);
        }
    }
    return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getCode(), failure.getMessage()));
}
 
Example #17
Source File: GremlinServerSslIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnableSslAndFailIfCiphersDontMatch() {
    final Cluster cluster = TestClientFactory.build().enableSsl(true).keyStore(JKS_SERVER_KEY).keyStorePassword(KEY_PASS)
            .sslSkipCertValidation(true).sslCipherSuites(Arrays.asList("SSL_RSA_WITH_RC4_128_SHA")).create();
    final Client client = cluster.connect();

    try {
        client.submit("'test'").one();
        fail("Should throw exception because ssl client requires TLSv1.2 whereas server supports only TLSv1.1");
    } catch (Exception x) {
        final Throwable root = ExceptionUtils.getRootCause(x);
        assertThat(root, instanceOf(TimeoutException.class));
    } finally {
        cluster.close();
    }
}
 
Example #18
Source File: KafkaRecordToFeatureRowDoFn.java    From feast with Apache License 2.0 6 votes vote down vote up
@ProcessElement
public void processElement(ProcessContext context) {
  byte[] value = context.element().getKV().getValue();
  FeatureRow featureRow;

  try {
    featureRow = FeatureRow.parseFrom(value);
  } catch (InvalidProtocolBufferException e) {
    context.output(
        getFailureTag(),
        FailedElement.newBuilder()
            .setTransformName("KafkaRecordToFeatureRow")
            .setStackTrace(ExceptionUtils.getStackTrace(e))
            .setJobName(context.getPipelineOptions().getJobName())
            .setPayload(new String(Base64.getEncoder().encode(value)))
            .setErrorMessage(e.getMessage())
            .build());
    return;
  }
  context.output(featureRow);
}
 
Example #19
Source File: AbstractTransmission.java    From beihu-boot with Apache License 2.0 6 votes vote down vote up
@Override
public void acquire() {
    lock.lock();
    try {
        acquireCnt++;
        while (!acquirable()) {
            try {
                doWait();
            } catch (InterruptedException e) {
                ExceptionUtils.wrapAndThrow(e);
            }
        }
        onAcquired();
    } finally {
        acquireCnt--;
        lock.unlock();
    }
}
 
Example #20
Source File: ProjectDetailPanel.java    From webanno with Apache License 2.0 5 votes vote down vote up
private void actionSave(AjaxRequestTarget aTarget, Form<Project> aForm)
{
    aTarget.add(getPage());
    // aTarget.add(((ApplicationPageBase) getPage()).getPageContent());
    // aTarget.addChildren(getPage(), IFeedback.class);
    
    Project project = aForm.getModelObject();
    if (isNull(project.getId())) {
        try {
            String username = SecurityContextHolder.getContext().getAuthentication().getName();
            projectService.createProject(project);

            projectService.createProjectPermission(
                    new ProjectPermission(project, username, PermissionLevel.MANAGER));
            projectService.createProjectPermission(
                    new ProjectPermission(project, username, PermissionLevel.CURATOR));
            projectService.createProjectPermission(
                    new ProjectPermission(project, username, PermissionLevel.ANNOTATOR));

            projectService.initializeProject(project);
        }
        catch (IOException e) {
            error("Project repository path not found " + ":"
                    + ExceptionUtils.getRootCauseMessage(e));
            LOG.error("Project repository path not found " + ":"
                    + ExceptionUtils.getRootCauseMessage(e));
        }
    }
    else {
        projectService.updateProject(project);
    }

    Session.get().setMetaData(CURRENT_PROJECT, project);
}
 
Example #21
Source File: MyTownDatasource.java    From MyTown2 with The Unlicense 5 votes vote down vote up
protected boolean loadTowns() {
    try {
        PreparedStatement loadTownsStatement = prepare("SELECT * FROM " + prefix + "Towns", true);
        ResultSet rs = loadTownsStatement.executeQuery();

        while (rs.next()) {
            Town town;
            if (rs.getBoolean("isAdminTown")) {
                town = new AdminTown(rs.getString("name"));
            } else {
                town = new Town(rs.getString("name"));
            }
            town.setSpawn(new Teleport(rs.getInt("spawnDim"), rs.getFloat("spawnX"), rs.getFloat("spawnY"), rs.getFloat("spawnZ"), rs.getFloat("cameraYaw"), rs.getFloat("cameraPitch")));
            town.townBlocksContainer.setExtraBlocks(rs.getInt("extraBlocks"));
            town.townBlocksContainer.setExtraFarClaims(rs.getInt("extraFarClaims"));
            town.plotsContainer.setMaxPlots(rs.getInt("maxPlots"));

            for (ForgeChunkManager.Ticket ticket : MyTownLoadingCallback.tickets) {
                if (ticket.getModData().getString("townName").equals(town.getName())) {
                    town.ticketMap.put(ticket.world.provider.dimensionId, ticket);
                }
            }

            MyTownUniverse.instance.addTown(town);
        }
    } catch (SQLException e) {
        LOG.error("Failed to load Towns!");
        LOG.error(ExceptionUtils.getStackTrace(e));
        return false;
    }

    return true;
}
 
Example #22
Source File: MyTownDatasource.java    From MyTown2 with The Unlicense 5 votes vote down vote up
public boolean deleteSelectedTown(Resident res) {
    try {
        PreparedStatement statement = prepare("DELETE FROM " + prefix + "SelectedTown WHERE resident=?", true);
        statement.setString(1, res.getUUID().toString());
        statement.executeUpdate();
    } catch (Exception e) {
        LOG.error("Failed to delete a town selection!");
        LOG.error(ExceptionUtils.getStackTrace(e));
        return false;
    }
    res.townsContainer.isSelectedTownSaved = false;
    return true;
}
 
Example #23
Source File: AuthenticationEndpoint.java    From divide with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/recover/{token}")
@Produces(MediaType.APPLICATION_JSON)
public Response recoverFromOneTimeToken(@Context ContainerRequestContext context, @PathParam("token") String token) {
    try{
        Credentials user = authServerLogic.getUserFromRecoveryToken(token);
        context.setSecurityContext(new UserContext(context.getUriInfo(),user));
        return Response.ok(user).build();
    }catch (ServerDAO.DAOException e) {
        e.printStackTrace();
        logger.severe(ExceptionUtils.getStackTrace(e));
        return fromDAOExpection(e);
    }
}
 
Example #24
Source File: Sanitizer.java    From warnings-ng-plugin with MIT License 5 votes vote down vote up
/**
 * Renders the specified HTML code. Removes unsafe HTML constructs.
 *
 * @param html
 *         the HTML to render
 *
 * @return safe HTML
 */
public String render(final String html) {
    try {
        return formatter.translate(html);
    }
    catch (IOException e) {
        return ExceptionUtils.getRootCauseMessage(e);
    }
}
 
Example #25
Source File: Predicates.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a safe {@code Predicate},
 *
 * @param <T>                the type of the input to the predicate
 * @param throwablePredicate the predicate that may throw an exception
 * @return the predicate result or {@code null} if exception was thrown
 * @throws NullPointerException if {@code throwablePredicate} is null
 */
public static <T> Predicate<T> uncheck(
        ThrowablePredicate<? super T, Throwable> throwablePredicate) {
    Objects.requireNonNull(throwablePredicate);
    return value -> {
        try {
            return throwablePredicate.test(value);
        } catch (Throwable throwable) {
            ExceptionUtils.wrapAndThrow(throwable);
            //never
            return false;
        }
    };
}
 
Example #26
Source File: Runs.java    From beihu-boot with Apache License 2.0 5 votes vote down vote up
public static <T, E extends Throwable> T uncheckCall(ThrowaleCallable<T, E> callable) {
    try {
        return callable.call();
    } catch (Throwable e) {
        ExceptionUtils.wrapAndThrow(e);
        return null;//不会触发
    }
}
 
Example #27
Source File: DataAccessException.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    Throwable rootException = this.getCause() instanceof SQLException
            ? ((SQLException) this.getCause()).getNextException()
            : this.getRootCause();

    if (rootException == null) {
        return ExceptionUtils.getStackTrace(this.getCause());
    } else {
        return ExceptionUtils.getStackTrace(this.getCause())
                + "\nWith Root Cause: " + ExceptionUtils.getStackTrace(rootException);
    }
}
 
Example #28
Source File: JsonHelperJackson2.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
private static IllegalArgumentException handleException(Exception e, String extraMessage) {
    String message = ExceptionUtils.getMessage(e);
    if (StringUtils.isNotBlank(extraMessage)) {
        message += ". " + extraMessage;
    }
    return new IllegalArgumentException(message, e);
}
 
Example #29
Source File: StatsFlowRuleJsonCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public StatsFlowRule decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }
    try {
        String srcIpPrefix = json.get(SRC_IP_PREFIX).asText();
        String dstIpPrefix = json.get(DST_IP_PREFIX).asText();

        DefaultStatsFlowRule.Builder flowRuleBuilder;

        if (json.get(IP_PROTOCOL) == null) {
            log.info("ipProtocol: null");
            flowRuleBuilder = DefaultStatsFlowRule.builder()
                    .srcIpPrefix(IpPrefix.valueOf(srcIpPrefix))
                    .dstIpPrefix(IpPrefix.valueOf(dstIpPrefix));
        } else {
            byte ipProtocol = getProtocolTypeFromString(json.get(IP_PROTOCOL).asText());
            int srcTpPort = json.get(SRC_TP_PORT).asInt();
            int dstTpPort = json.get(DST_TP_PORT).asInt();

            flowRuleBuilder = DefaultStatsFlowRule.builder()
                                .srcIpPrefix(IpPrefix.valueOf(srcIpPrefix))
                                .dstIpPrefix(IpPrefix.valueOf(dstIpPrefix))
                                .ipProtocol(ipProtocol)
                                .srcTpPort(TpPort.tpPort(srcTpPort))
                                .dstTpPort(TpPort.tpPort(dstTpPort));
        }
        return flowRuleBuilder.build();
    } catch (Exception ex) {
        log.error("Exception Stack:\n{}", ExceptionUtils.getStackTrace(ex));
    }
    return null;
}
 
Example #30
Source File: Address.java    From symbol-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a plain address is valid returning the problem message if it's not valid.
 *
 * @param plainAddress the address to be checked.
 * @return the error message or emtpy if the address is valid.
 */
public static Optional<String> validatePlainAddress(String plainAddress) {
    try {
        if (plainAddress == null) {
            return Optional.of("Plain Address it nos provided");
        }
        if (plainAddress.length() != PLAIN_ADDRESS_SIZE) {
            return Optional.of("Plain address '" + plainAddress + "' size is " + plainAddress.length() + " when "
                + PLAIN_ADDRESS_SIZE + " is required");
        }

        if ("AIQY".indexOf(plainAddress.charAt(plainAddress.toUpperCase().length() - 1)) < 0) {
            return Optional.of("Plain address '" + plainAddress + "' doesn't end with A I, Q or Y");
        }

        byte[] decodedArray = Base32Encoder.getBytes(plainAddress);

        if (decodedArray.length != RAW_ADDRESS_SIZE) {
            return Optional
                .of("Plain address '" + plainAddress + "' decoded address size is " + decodedArray.length + " when "
                    + RAW_ADDRESS_SIZE + " is required");
        }

        int checksumBegin = RAW_ADDRESS_SIZE - CHECKSUM_SIZE;
        byte[] expectedChecksum = Arrays
            .copyOf(Hashes.sha3_256(Arrays.copyOf(decodedArray, checksumBegin)), CHECKSUM_SIZE);

        byte[] providedChecksum = Arrays.copyOfRange(decodedArray, checksumBegin, decodedArray.length);
        if (!Arrays.equals(expectedChecksum, providedChecksum)) {
            return Optional.of("Plain address '" + plainAddress + "' checksum is incorrect. Address checksum is '"
                + ConvertUtils.toHex(providedChecksum) + "' when '" + ConvertUtils.toHex(expectedChecksum)
                + "' is expected");
        }
        return Optional.empty();
    } catch (IllegalArgumentException e) {
        return Optional
            .of("Plain address '" + plainAddress + "' is invalid. Error: " + ExceptionUtils.getMessage(e));
    }
}