Example usage for java.lang IllegalStateException getMessage

List of usage examples for java.lang IllegalStateException getMessage

Introduction

In this page you can find the example usage for java.lang IllegalStateException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.grails.orm.hibernate4.support.HibernatePersistenceContextInterceptor.java

public void reconnect() {
    if (getSessionFactory() == null)
        return;//from   ww w .j a  v  a 2  s .c om
    Session session = getSession();
    if (!session.isConnected() && !disconnected.isEmpty()) {
        try {
            Connection connection = disconnected.peekLast();
            getSession().reconnect(connection);
        } catch (IllegalStateException e) {
            // cannot reconnect on different exception. ignore
            LOG.debug(e.getMessage(), e);
        }
    }
}

From source file:hello.jaxrs.GreetingsResource.java

@POST
public Response addGreeting(@FormParam("greeting") final String greeting) {
    if (StringUtils.isBlank(greeting)) {
        return Response
                .seeOther(getUriInfo().getRequestUriBuilder().replaceQuery("errorMissingParameter").build())
                .build();//from   w  ww  .j av a  2 s  . c o m
    }

    // post to service
    try {
        getGreetingService().sayHello(greeting);
    } catch (final IllegalStateException e) {
        // no service is available; lets report that properly
        return Response.status(Status.SERVICE_UNAVAILABLE).entity(e.getMessage()).build();
    } catch (final Exception e) {
        // this looks like an issue deeper in some underlying code; we should log this properly
        return Response.serverError().entity(ExceptionUtils.getRootCauseMessage(e)).build();
    }

    // redirect and show success message
    return Response.seeOther(getUriInfo().getRequestUriBuilder().replaceQuery("added").build()).build();
}

From source file:de.siegmar.securetransfer.controller.SendController.java

private List<SecretFile> handleStream(final HttpServletRequest req, final KeyIv encryptionKey,
        final DataBinder binder) throws FileUploadException, IOException {

    final BindingResult errors = binder.getBindingResult();

    final MutablePropertyValues propertyValues = new MutablePropertyValues();
    final List<SecretFile> tmpFiles = new ArrayList<>();

    @SuppressWarnings("checkstyle:anoninnerlength")
    final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() {

        private OptionalInt expiration = OptionalInt.empty();

        @Override/* w  ww .ja  v a2  s.  c  om*/
        void emitField(final String name, final String value) {
            propertyValues.addPropertyValue(name, value);

            if ("expirationDays".equals(name)) {
                expiration = OptionalInt.of(Integer.parseInt(value));
            }
        }

        @Override
        void emitFile(final String fileName, final InputStream inStream) {
            final Integer expirationDays = expiration
                    .orElseThrow(() -> new IllegalStateException("No expirationDays configured"));

            tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey,
                    Instant.now().plus(expirationDays, ChronoUnit.DAYS)));
        }

    };

    try {
        visitor.processRequest(req);
        binder.bind(propertyValues);
        binder.validate();
    } catch (final IllegalStateException ise) {
        errors.reject(null, ise.getMessage());
    }

    return tmpFiles;
}

From source file:org.opcfoundation.ua.transport.https.HttpsServerPendingRequest.java

@Override
public void run() {
    // This code is ran in a worker thread.
    workerThread = Thread.currentThread();

    // 0. Check content Length from the header      
    Header header = httpRequest.getFirstHeader("Content-Length");
    if (header != null) {
        String len = header.getValue().trim();
        if (!len.isEmpty()) {
            try {
                long contentLength = Long.valueOf(len);
                long maxMessageSize = endpoint.endpointConfiguration.getMaxMessageSize();

                // 1. Reject content
                if (maxMessageSize != 0 && contentLength > maxMessageSize) {
                    sendError(500, StatusCodes.Bad_RequestTooLarge, "No request message");
                    return;
                }//from  w w  w . j a v  a  2s.  c  o m
            } catch (NumberFormatException nfe) {
            }
        }
    }

    // 1. Decode message
    try {
        byte[] data;
        if (httpRequest instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingRequest = (HttpEntityEnclosingRequest) httpRequest;
            requestEntity = entityEnclosingRequest.getEntity();

            // Check content length from the entity ( chucked case )
            long contentLength = requestEntity.getContentLength();
            long maxMessageSize = endpoint.endpointConfiguration.getMaxMessageSize();

            // 1. Reject content
            if (maxMessageSize != 0 && contentLength > maxMessageSize) {
                sendError(500, StatusCodes.Bad_RequestTooLarge, "No request message");
                return;
            }

            data = EntityUtils.toByteArray(requestEntity);
        } else {
            sendError(500, StatusCodes.Bad_RequestTypeInvalid, "No request message");
            return;
        }

        BinaryDecoder dec = new BinaryDecoder(data);
        dec.setEncoderContext(endpoint.getEncoderContext());

        super.request = dec.getMessage();
        logger.trace("request={}", super.request);
        logger.debug("request={}", super.request.getClass().getSimpleName());
    } catch (IllegalStateException e) {
        sendError(500, StatusCodes.Bad_UnexpectedError, e.getMessage());
        return;
    } catch (IOException e) {
        sendError(400, StatusCodes.Bad_UnexpectedError, e.getMessage());
        return;
    } catch (DecodingException e) {
        sendError(400, StatusCodes.Bad_RequestTypeInvalid, e.getMessage());
        return;
    }

    // Handle request
    endpoint.handleMessage(this);
}

From source file:jenkins.plugins.ec2slave.EC2ImageLaunchWrapper.java

@Override
public void launch(SlaveComputer computer, TaskListener listener) throws IOException, InterruptedException {
    try {// ww w .ja v a 2s  .c  om
        if (curInstanceId != null && getInstanceState(curInstanceId) == Pending) {
            throw new IllegalStateException("EC2 Instance " + curInstanceId
                    + " is in Pending state.  Not sure what to do here, try again?");
        }

        if (curInstanceId == null || getInstanceState(curInstanceId) == Terminated
                || getInstanceState(curInstanceId) == ShuttingDown) {
            //only create a new EC2 instance if we haven't tried before or the instance was terminated externally
            preLaunch(listener.getLogger());
            preLaunchOk = true;
        } else {
            LOGGER.info("Skipping EC2 part of launch, since the instance is already running");
        }
    } catch (IllegalStateException ise) {
        listener.error(ise.getMessage());
        return;
    } catch (AmazonServiceException ase) {
        listener.error(ase.getMessage());
        return;
    } catch (AmazonClientException ace) {
        listener.error(ace.getMessage());
        return;
    }

    LOGGER.info("EC2 instance " + curInstanceId
            + " has been created to serve as a Jenkins slave.  Passing control to computer launcher.");
    computerLauncher = computerConnector.launch(getInstancePublicHostName(), listener);
    computerLauncher.launch(computer, listener);
}

From source file:org.apache.metron.stellar.dsl.functions.resolver.ClasspathFunctionResolver.java

@Override
public void initialize(Context context) {
    super.initialize(context);
    if (context != null) {

        Optional<Object> optional = context.getCapability(STELLAR_CONFIG, false);
        if (optional.isPresent()) {
            Map<String, Object> stellarConfig = (Map<String, Object>) optional.get();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting up classloader using the following config: {}", stellarConfig);
            }//from   w  w w  .  j  a v  a 2  s .  c  o  m

            include(STELLAR_SEARCH_INCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            exclude(STELLAR_SEARCH_EXCLUDES_KEY.get(stellarConfig, String.class).split(STELLAR_SEARCH_DELIMS));
            Optional<ClassLoader> vfsLoader = Optional.empty();
            try {
                vfsLoader = VFSClassloaderUtil
                        .configureClassloader(STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                if (vfsLoader.isPresent()) {
                    LOG.debug("CLASSLOADER LOADED WITH: {}",
                            STELLAR_VFS_PATHS.get(stellarConfig, String.class));
                    if (LOG.isDebugEnabled()) {
                        for (FileObject fo : ((VFSClassLoader) vfsLoader.get()).getFileObjects()) {
                            LOG.error("{} - {}", fo.getURL(), fo.exists());
                        }
                    }
                    classLoaders(vfsLoader.get());
                }
            } catch (FileSystemException e) {
                LOG.error("Unable to process filesystem: {}", e.getMessage(), e);
            }
        } else {
            LOG.info("No stellar config set; I'm reverting to the context classpath with no restrictions.");
            if (LOG.isDebugEnabled()) {
                try {
                    throw new IllegalStateException("No config set, stacktrace follows.");
                } catch (IllegalStateException ise) {
                    LOG.error(ise.getMessage(), ise);
                }
            }
        }
    } else {
        throw new IllegalStateException("CONTEXT IS NULL!");
    }
}

From source file:com.cedarsoftware.ncube.NCubeManager.java

public static boolean renameCube(Connection connection, String oldName, String newName, String app,
        String version) {/*from  w  ww  .j a  va  2s.c  o m*/
    validate(connection, app, version);
    validateCubeName(oldName);
    validateCubeName(newName);

    if (oldName.equalsIgnoreCase(newName)) {
        throw new IllegalArgumentException("Old name cannot be the same as the new name, name: " + oldName);
    }

    synchronized (cubeList) {
        PreparedStatement stmt1 = null;

        try {
            stmt1 = connection.prepareStatement(
                    "UPDATE n_cube SET n_cube_nm = ? WHERE app_cd = ? AND version_no_cd = ? AND n_cube_nm = ? AND status_cd = '"
                            + ReleaseStatus.SNAPSHOT + "'");
            stmt1.setString(1, newName);
            stmt1.setString(2, app);
            stmt1.setString(3, version);
            stmt1.setString(4, oldName);
            int count = stmt1.executeUpdate();
            if (count < 1) {
                throw new IllegalArgumentException("No n-cube found to rename, for app:" + app + ", version: "
                        + version + ", original name: " + oldName);
            }

            cubeList.remove(makeCacheKey(oldName, version));
            return true;
        } catch (IllegalStateException e) {
            throw e;
        } catch (Exception e) {
            String s = "Unable to rename n-cube due to an error: " + e.getMessage();
            LOG.error(s, e);
            throw new RuntimeException(s, e);
        } finally {
            jdbcCleanup(stmt1);
        }
    }
}

From source file:com.thoughtworks.go.plugin.infra.monitor.DefaultPluginJarLocationMonitorTest.java

@Test
void shouldNotAllowMonitorToBeStartedMultipleTimes() throws Exception {
    try {//  w  w w .j a v a2 s  .  c om
        monitor.start();
        monitor.start();
        fail("Expected an IllegalStateException.");
    } catch (IllegalStateException e) {
        assertThat(e.getMessage()).isEqualTo("Cannot start the monitor multiple times.");
    }
}

From source file:org.openregistry.core.web.resources.SystemOfRecordPeopleResource.java

@PUT
@Path("{sorPersonId}")
@Consumes(MediaType.APPLICATION_XML)/*from ww w  .j a v  a  2  s .c  o m*/
public Response updateIncomingPerson(@PathParam("sorSourceId") final String sorSourceId,
        @PathParam("sorPersonId") final String sorPersonId, final PersonRequestRepresentation request) {
    final SorPerson sorPerson = findPersonOrThrowNotFoundException(sorSourceId, sorPersonId);
    PeopleResourceUtils.buildModifiedSorPerson(request, sorPerson, this.referenceRepository);

    try {
        ServiceExecutionResult<SorPerson> result = this.personService.updateSorPerson(sorPerson);

        if (!result.getValidationErrors().isEmpty()) {
            //HTTP 400
            logger.info("The incoming person payload did not pass validation. Validation errors: "
                    + result.getValidationErrors());
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity(new ErrorsResponseRepresentation(
                            ValidationUtils.buildValidationErrorsResponseAsList(result.getValidationErrors())))
                    .type(MediaType.APPLICATION_XML).build();
        }
    } catch (IllegalStateException e) {
        return Response.status(409).entity(new ErrorsResponseRepresentation(Arrays.asList(e.getMessage())))
                .type(MediaType.APPLICATION_XML).build();
    }

    //HTTP 204
    return null;
}

From source file:com.celamanzi.liferay.portlets.rails286.Rails286PortletFilter.java

private void filterRails(PortletRequest request, PortletResponse response) throws MalformedURLException {
    PortletSession session = request.getPortletSession(true);
    String session_id = request.getRequestedSessionId();
    log.debug("Render Filter activated for session " + session_id);

    if (log.isDebugEnabled()) {
        debugRequest(request);//from  ww w  . jav  a 2  s . com
    }

    URL railsBaseUrl = getRailsBaseURL(request);

    String railsRoute = null;
    String requestMethod = "get";
    URL httpReferer = null;

    if ((request.getParameter("railsRoute") == null) && (request.getAttribute("railsRoute") == null)) {
        /*
         * If the request does not define the route, it is reset to default.
         */
        log.debug("Unset request parameter \"railsRoute\" - reset portlet");
        railsRoute = route;
    } else {
        /** Request method. If POST via actionURL, this is set. */
        if (request.getAttribute("requestMethod") != null) {
            railsRoute = (String) request.getAttribute("railsRoute");
            requestMethod = (String) request.getAttribute("requestMethod");
        } else {
            /** Set the route from request parameter "railsRoute".
             */
            railsRoute = request.getParameter("railsRoute");
        }

        /** Set the HTTP Referer from session */
        if (session.getAttribute("railsRoute") != null) {
            String oldRoute = (String) session.getAttribute("railsRoute");
            if (oldRoute != null) {
                httpReferer = Rails286PortletFunctions.getRequestURL(railsBaseUrl, servlet, oldRoute);
                log.debug("Set HTTP referer: " + httpReferer.toString());
            }
        }
    }

    // railsRoute may contain variables to be replaced at runtime
    railsRoute = Rails286PortletFunctions.decipherPath(railsRoute, request);

    // For the cookies, get the UID from request 
    String uid = request.getRemoteUser();

    /** update the PortletSession */
    try {
        log.debug("Updating session id " + session_id);

        session.setAttribute("railsBaseUrl", railsBaseUrl, PortletSession.PORTLET_SCOPE);

        session.setAttribute("servlet", servlet, PortletSession.PORTLET_SCOPE);

        session.setAttribute("railsRoute", railsRoute, PortletSession.PORTLET_SCOPE);

        session.setAttribute("requestMethod", requestMethod, PortletSession.PORTLET_SCOPE);

        session.setAttribute("httpReferer", httpReferer, PortletSession.PORTLET_SCOPE);

        session.setAttribute("uid", uid, PortletSession.PORTLET_SCOPE);

        // Adding the resource url generated by liferay to achieve the serveResource method
        session.setAttribute("resourceURL", getResourceUrlValue(response), PortletSession.PORTLET_SCOPE);

        session.setAttribute(PreferencesAttributes.PREFERENCES_ROUTE, preferencesRoute,
                PortletSession.PORTLET_SCOPE);

    } catch (IllegalStateException e) {
        log.error(e.getMessage());
        throw e;

    } catch (IllegalArgumentException e) {
        log.error(e.getMessage());
        throw e;
    }

    if (log.isDebugEnabled()) {
        debugSession(session);
    }
}