This method is supposed to be used as exception mapper
from <code>WebApplicationException</code>, sent in REST response,
to <code>AuxiliaryStorageException</code>.

@param exception Exception to convert from.
179907
private void handleWebException(WebApplicationException  exception)  {

       Response response = exception.getResponse();
       if (response == null) {
           throw new AuxiliaryStorageException("Mapping exception error: response is null");
       }

       int responseStatus = response.getStatus();

       if (Status.BAD_REQUEST.getStatusCode() == responseStatus) {
           throw new IllegalParameterException("Bad request server error");
       } else if (Status.NOT_FOUND.getStatusCode() == responseStatus) {
           throw new ObjectNotFoundException("Object not found in auxiliary storage");
       } else if (Status.CONFLICT.getStatusCode() == responseStatus) {
           throw new ObjectAlreadyExistsException("Object already exists in auxiliary storage");
       } else if (Status.INTERNAL_SERVER_ERROR.getStatusCode() == responseStatus) {
           throw new AuxiliaryStorageException("Internal server error");
       } else {
           throw new AuxiliaryStorageException("Unknown server error");
       }
   }
898287
@Override
    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
        if (!notifiedOnFailure) {
            notifiedOnFailure = true;
            try {
                responseHandler.onFailure(new SdkClientException("Unable to execute HTTP request.", cause));
            } finally {
                ctx.channel().close();
            }
        }
    }
745662
@SuppressWarnings("ProhibitedExceptionDeclared")
    @PostConstruct
    public void init() throws Exception {
        final String configFileLocation = getConfigFileLocation();
        T fileConfig = getEmptyConfig();

        boolean fileExists = false;

        log.info("Using {} as config file location", configFileLocation);

        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFileLocation), "UTF-8"))) {
            fileConfig = mapper.readValue(reader, getConfigClass());

            if (fileConfig instanceof PasswordsConfig<?>) {
                fileConfig = ((PasswordsConfig<T>) fileConfig).withDecryptedPasswords(textEncryptor);
            }

            fileExists = true;
        } catch (final FileNotFoundException e) {
            log.warn("Config file not found, using empty configuration object");
        } catch (final IOException e) {
            log.error("Error reading config file at {}", configFileLocation);
            log.error("Recording stack trace", e);
            // throw this so we don't continue to start the webapp
            throw new IllegalStateException("Could not initialize configuration", e);
        }

        if (StringUtils.isNotBlank(defaultConfigFile)) {
            try (InputStream defaultConfigInputStream = getClass().getResourceAsStream(defaultConfigFile)) {
                if (defaultConfigInputStream != null) {
                    final T defaultConfig = mapper.readValue(defaultConfigInputStream, getConfigClass());

                    fileConfig = fileConfig.merge(defaultConfig);

                    if (!fileExists) {
                        fileConfig = generateDefaultLogin(fileConfig);

                        try {
                            writeOutConfigFile(fileConfig, configFileLocation);
                        } catch (final IOException e) {
                            throw new IllegalStateException("Could not initialize configuration", e);
                        }
                    }
                }
            } catch (final IOException e) {
                log.error("Error reading default config file", e);
                // throw this so we don't continue to start the webapp
                throw new IllegalStateException("Could not initialize configuration", e);
            }
        }

        try {
            fileConfig.basicValidate("Root");
        } catch (final ConfigException e) {
            log.error("Config validation failed in " + e);
            throw new IllegalStateException("Could not initialize configuration", e);
        }

        config.set(fileConfig);
        postInitialise(getConfig());
    }
705822
@Override
    public void handleExceptions(MessageEvent messageEvent, Exception exception) {

        if(exception instanceof InvalidMetadataException) {
            logger.error("Exception when deleting. The requested key does not exist in this partition",
                         exception);
            writeErrorResponse(messageEvent,
                               HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE,
                               "The requested key does not exist in this partition");
        } else if(exception instanceof PersistenceFailureException) {
            logger.error("Exception when deleting. Operation failed", exception);
            writeErrorResponse(messageEvent,
                               HttpResponseStatus.INTERNAL_SERVER_ERROR,
                               "Operation failed");
        } else if(exception instanceof UnsupportedOperationException) {
            logger.error("Exception when deleting. Operation not supported in read-only store ",
                         exception);
            writeErrorResponse(messageEvent,
                               HttpResponseStatus.METHOD_NOT_ALLOWED,
                               "Operation not supported in read-only store");
        } else if(exception instanceof StoreTimeoutException) {
            String errorDescription = "DELETE Request timed out: " + exception.getMessage();
            logger.error(errorDescription);
            writeErrorResponse(messageEvent, HttpResponseStatus.REQUEST_TIMEOUT, errorDescription);
        } else if(exception instanceof InsufficientOperationalNodesException) {
            String errorDescription = "DELETE Request failed: " + exception.getMessage();
            logger.error(errorDescription);
            writeErrorResponse(messageEvent,
                               HttpResponseStatus.INTERNAL_SERVER_ERROR,
                               errorDescription);
        } else {
            super.handleExceptions(messageEvent, exception);
        }
    }
1369284
@Override
  public void onException(Throwable failureCause) {
    Preconditions.checkNotNull(failureCause, "failureCause");
    Status status = Status.UNAVAILABLE.withCause(failureCause);
    startGoAway(0, ErrorCode.INTERNAL_ERROR, status);
  }
12121
public void execute() throws Exception {
        final var jsonFile = new File(buildDir, "classes/java/main/META-INF/spring-configuration-metadata.json");
        if (!jsonFile.exists()) {
            throw new RuntimeException("Could not locate file " + jsonFile.getCanonicalPath());
        }
        final var mapper = new ObjectMapper().findAndRegisterModules();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);

        final TypeReference<Map<String, Set<ConfigurationMetadataProperty>>> values = new TypeReference<>() {
        };
        final Map<String, Set> jsonMap = mapper.readValue(jsonFile, values);
        final Set<ConfigurationMetadataProperty> properties = jsonMap.get("properties");
        final Set<ConfigurationMetadataProperty> groups = jsonMap.get("groups");

        final Set<ConfigurationMetadataProperty> collectedProps = new HashSet<>();
        final Set<ConfigurationMetadataProperty> collectedGroups = new HashSet<>();

        properties.stream()
            .filter(p -> NESTED_TYPE_PATTERN.matcher(p.getType()).matches())
            .forEach(Unchecked.consumer(p -> {
                final var matcher = NESTED_TYPE_PATTERN.matcher(p.getType());
                final var indexBrackets = matcher.matches();
                final var typeName = matcher.group(1);
                final var typePath = ConfigurationMetadataClassSourceLocator.buildTypeSourcePath(this.sourcePath, typeName);

                final var parser = new ConfigurationMetadataUnitParser(this.sourcePath);
                parser.parseCompilationUnit(collectedProps, collectedGroups, p, typePath, typeName, indexBrackets);
            }));

        properties.addAll(collectedProps);
        groups.addAll(collectedGroups);

        final var hints = processHints(properties, groups);

        processNestedEnumProperties(properties, groups);

        jsonMap.put("properties", properties);
        jsonMap.put("groups", groups);
        jsonMap.put("hints", hints);

        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        final var pp = new MinimalPrettyPrinter();
        final var writer = mapper.writer(pp);
        writer.writeValue(jsonFile, jsonMap);
    }
1303070
@Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        final IoSessionInputStream in = (IoSessionInputStream) session
                .getAttribute(KEY_IN);

        IOException e = null;
        if (cause instanceof StreamIoException) {
            e = (IOException) cause.getCause();
        } else if (cause instanceof IOException) {
            e = (IOException) cause;
        }

        if (e != null && in != null) {
            in.throwException(e);
        } else {
            LOGGER.warn("Unexpected exception.", cause);
            session.close(true);
        }
    }
373927
public RuntimeException handleException(final Exception e) {
        log.error(e.getMessage(), e);
        if (e instanceof RuntimeException && EnvUtil.isPortableType(e.getClass()) ) {
            return (RuntimeException) e;
        }
        return new GenericPortableException( e.getMessage(), e );
    }
304327
private void handleRetryForStorageException(final StorageException exs) throws StorageException {
    retries++;
    if (retries > maxRetries) {
      throw new StorageException(
          exs.getCode(),
          "All "
              + maxRetries
              + " retries failed. Waited a total of "
              + totalWaitTime
              + " ms between attempts",
          exs);
    }
    sleepForAttempt(retries);
  }
645098
public static Exception getLowestException(final Exception exception, final String exceptionPrefix) {

		if (exception == null) {
			return null;
		}

		Throwable nestedException = (Throwable) exception;
		Exception lastLowException = null;
		while (nestedException != null) {
			if (nestedException.getClass().toString().startsWith("class " + exceptionPrefix)) {
				lastLowException = (Exception) nestedException;
			}

			nestedException = getInnerException(nestedException);
		}

		return lastLowException;
	}
803280
@Override
    public ApiResponse handleApplicationException(ApiFailureResource resource, RuntimeException cause) {
        final FaihyUnifiedFailureType failureType = FaihyUnifiedFailureType.BUSINESS_ERROR;
        final FaihyUnifiedFailureResult result = createFailureResult(failureType, resource, cause);
        return asJson(result).httpStatus(prepareBusinessFailureStatus());
    }
720345
@Override
    public void sendAppException(Throwable throwable) {
        checkState();
        SofaResponse response = new SofaResponse();
        response.setAppResponse(throwable);
        sendSofaResponse(response, null);
    }
627583
private EJBException mapException(EJSDeployedSupport s, Throwable ex) //117817.1
    {
        EJBException ejbex;
        String message = null;

        // If necessary, wrap root with WsEJBException.  This is done if
        // root is not an instance of Exception.
        Exception rootEx = ExceptionUtil.Exception(s.rootEx); // F71894.1

        // Now map Throwable to a EJBException to return.
        if (ex instanceof CSIException)
        {
            ejbex = mapCSIException(s, (CSIException) ex, rootEx);
        }
        else if (ex instanceof NoSuchObjectException)
        {
            ejbex = new NoSuchObjectLocalException(message, rootEx);
        }
        else if (ex instanceof EJBStoppedException) // d350987
        {
            ejbex = new NoSuchObjectLocalException(message, rootEx);
        }
        else if (ex instanceof HomeDisabledException) // d350987
        {
            ejbex = new NoSuchObjectLocalException(message, rootEx);
        }
        else if (ex instanceof TransactionRequiredException)
        {
            ejbex = new TransactionRequiredLocalException(message);
        }
        else if (ex instanceof TransactionRolledbackException)
        {
            ejbex = new TransactionRolledbackLocalException(message, rootEx);
        }
        else if (ex instanceof InvalidTransactionException)
        {
            ejbex = new InvalidTransactionLocalException(message, rootEx);
        }
        else if (ex instanceof AccessException)
        {
            ejbex = new AccessLocalException(message, rootEx);
        }
        //        else if (ex instanceof ActivityRequiredException)
//        {
//            ejbex = new ActivityRequiredLocalException(message, rootEx);
//        }
//        else if (ex instanceof InvalidActivityException) //126946.3
//        {
//            ejbex = new InvalidActivityLocalException(message, rootEx); //126946.3
//        }
//        else if (ex instanceof ActivityCompletedException)
//        {
//            ejbex = new ActivityCompletedLocalException(message, rootEx); //126946.3
//        }
        else if (ex instanceof EJBException)
        {
            // Even though this is already an EJBException we will nest it inside another EJBException that we create.
            // This is done to ensure that but the getCause() and getCausedByException() methods will work on it.   //253963
            ejbex = ExceptionUtil.EJBException(ex); //253963
        }
        else if (ex instanceof RemoteException)
        {
            // If the RemoteException is already wrapping an EJBException, then
            // use that exception, otherwise create a new EJBException with the root  //253963
            if (((RemoteException) ex).detail instanceof EJBException)
            {
                ejbex = ExceptionUtil.EJBException(ex); //253963
            }
            else
                ejbex = ExceptionUtil.EJBException(rootEx); //253963
        }
        else if (ex instanceof IllegalArgumentException) // d184523
        {
            ejbex = ExceptionUtil.EJBException(rootEx); //253963
        }
        else
        {
            ejbex = new UnknownLocalException(message, rootEx);
        }

        // EJBException doesn't normally set the cause on Throwable, so
        // let's do that to be nice :-)                                    d354591
        // Geronimo EJBException.getCause returns getCausedbyException, so
        // we do not expect this code to be used.                           F53643
        if (rootEx != null &&
            rootEx != ejbex &&
            ejbex.getCause() == null)
        {
            ejbex.initCause(rootEx);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "mapException returning: " + ejbex); // d402055
        }

        return ejbex;
    }
1187628
private void handleReopenForStorageException(final StorageException exs) throws StorageException {
    reopens++;
    if (reopens > maxReopens) {
      throw new StorageException(
          exs.getCode(),
          "All "
              + maxReopens
              + " reopens failed. Waited a total of "
              + totalWaitTime
              + " ms between attempts",
          exs);
    }
    sleepForAttempt(reopens);
  }
929404
public static boolean isRequestEntityTooLargeException(SdkBaseException exception) {
        return isAse(exception) && toAse(exception).getStatusCode() == HttpStatus.SC_REQUEST_TOO_LONG;
    }
60283
public static String convertExceptionToMessage(Throwable ex)
  {
    StringBuilder sb = new StringBuilder();
    if(ex != null)
    {
      sb.append("Exception type: ").append(ex.getClass().getName()).append("\n");
      sb.append("Message: ").append(ex.getLocalizedMessage()).append("\n");
      sb.append("Stacktrace: \n");
      StackTraceElement[] st = ex.getStackTrace();
      for (int i = 0; i < st.length; i++)
      {
        sb.append(st[i].toString());
        sb.append("\n");
      }
    }
    return sb.toString();
  }
1320086
static DatastoreException throwInvalidRequest(String massage, Object... params) {
    throw new DatastoreException(
        UNKNOWN_CODE, String.format(massage, params), "FAILED_PRECONDITION");
  }