Example usage for java.util NoSuchElementException getMessage

List of usage examples for java.util NoSuchElementException getMessage

Introduction

In this page you can find the example usage for java.util NoSuchElementException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:uk.ac.ebi.arrayexpress.app.ApplicationPreferences.java

public Boolean getBoolean(String key) {
    Boolean value = null;/*  ww  w.j a v  a 2  s  .c  o  m*/
    try {
        value = prefs.getBoolean(key);
    } catch (NoSuchElementException x) {
        logger.error(x.getMessage());
    } catch (Exception x) {
        logger.error("Caught an exception:", x);
    }

    return value;
}

From source file:com.largecode.interview.rustem.controller.UsersController.java

@PreAuthorize("@userRightResolverServiceImpl.canAccessToUser(principal, #id)")
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT)/* www  . j  a va 2  s.c om*/
@ApiOperation(value = "Delete User by ID.", notes = "Returns NO_CONTENT if deletion was successful.")
@ApiResponses(value = { @ApiResponse(code = 401, message = "Only authenticated access allowed."),
        @ApiResponse(code = 403, message = "Only user of ADMIN role or User has authenticated with this Id can have access."),
        @ApiResponse(code = 404, message = "User with such Id not found."), })
public void deleteUser(@PathVariable Long id) {
    LOGGER.debug("Delete user by id={}", id);
    try {
        usersService.deleteUser(id);
    } catch (NoSuchElementException exception) {
        throw new ExceptionUserNotFound(exception.getMessage());
    }
}

From source file:com.hcb.uiautomator.server.SocketServer.java

/**
 * When {@link #handleClientData()} has valid data, this method delegates the
 * command.//ww w  .  j a va 2 s .  co m
 *
 * @param cmd
 *     AndroidCommand
 * @return Result
 */
private String runCommand(final PraseCommand cmd) {
    ActionResult res;
    try {
        res = executor.execute(cmd);
    } catch (final NoSuchElementException e) {
        res = new ActionResult(WDStatus.NO_SUCH_ELEMENT, e.getMessage());
    } catch (final Exception e) {
        Logger.debug("Command returned error:" + e);
        res = new ActionResult(WDStatus.UNKNOWN_ERROR, e.getMessage());
    }
    return res.toString();
}

From source file:com.largecode.interview.rustem.controller.UsersController.java

@PreAuthorize("@userRightResolverServiceImpl.canAccessToUser(principal, #id)")
@ApiOperation(value = "Update User.", notes = "Returns NO_CONTENT if update was successful. Regular user can not change his Role.")
@ApiResponses(value = { @ApiResponse(code = 401, message = "Only authenticated access allowed."),
        @ApiResponse(code = 403, message = "Only user of ADMIN role or User has authenticated with this Id can have access."),
        @ApiResponse(code = 404, message = "User with such Id not found."),
        @ApiResponse(code = 400, message = "Reasons:\n" + "1:Passwords not same or too short.\n"
                + "2:Other userDto.email already exists.\n" + "3:Bad role name.\n"
                + "3:value of ID different between Id in URL and userDto \n") })
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT)/*from  w  w w. ja  v a2  s . c  o m*/
public void updateUser(@ApiParam(value = "ID of User from DB", required = true) @PathVariable Long id,
        @ApiParam(value = "new properties for User by userDto", required = true) @Valid @RequestBody UserDto userDto,
        @ApiParam(value = "Authentication", hidden = true) Authentication authentication) {
    SpringUser springUser = (SpringUser) authentication.getPrincipal();
    LOGGER.debug("Update user {} by user '{}'", userDto, springUser.getUsername());
    checkUrlAndBodyForId(id, userDto);
    checkEmailNotExists(userDto, "update user");
    try {
        usersService.updateUser(id, userDto, springUser.getRole());
    } catch (NoSuchElementException exception) {
        throw new ExceptionUserNotFound(exception.getMessage());
    }
}

From source file:com.netflix.spinnaker.orca.pipelinetemplate.PipelineTemplateService.java

/**
 * If {@code executionId} is set, it will be retrieved. Otherwise, {@code pipelineConfigId} will be used to find the
 * newest pipeline execution for that configuration.
 * @param executionId An explicit pipeline execution id.
 * @param pipelineConfigId A pipeline configuration id. Ignored if {@code executionId} is set.
 * @return The pipeline//w w w .j  a v a 2s  .com
 * @throws IllegalArgumentException if neither executionId or pipelineConfigId are provided
 * @throws ExecutionNotFoundException if no execution could be found
 */
public Execution retrievePipelineOrNewestExecution(@Nullable String executionId,
        @Nullable String pipelineConfigId) throws ExecutionNotFoundException {
    if (executionId != null) {
        // Use an explicit execution
        return executionRepository.retrieve(PIPELINE, executionId);
    } else if (pipelineConfigId != null) {
        // No executionId set - use last execution
        ExecutionRepository.ExecutionCriteria criteria = new ExecutionRepository.ExecutionCriteria()
                .setLimit(1);
        try {
            return executionRepository.retrievePipelinesForPipelineConfigId(pipelineConfigId, criteria)
                    .toSingle().toBlocking().value();
        } catch (NoSuchElementException e) {
            throw new ExecutionNotFoundException("No pipeline execution could be found for config id "
                    + pipelineConfigId + ": " + e.getMessage());
        }
    } else {
        throw new IllegalArgumentException("Either executionId or pipelineConfigId have to be set.");
    }
}

From source file:org.jvoicexml.implementation.pool.KeyedResourcePool.java

/**
 * Type safe return of the object to borrow from the pool.
 * @param key the type of the object to borrow from the pool
 * @return borrowed object//from  www.ja  v  a  2s.  co m
 * @exception NoresourceError
 *            the object could not be borrowed
 */
@SuppressWarnings("unchecked")
public synchronized T borrowObject(final Object key) throws NoresourceError {
    final ObjectPool pool = pools.get(key);
    if (pool == null) {
        throw new NoresourceError("Pool of type '" + key + "' is unknown!");
    }
    T resource;
    try {
        resource = (T) pool.borrowObject();
    } catch (NoSuchElementException e) {
        throw new NoresourceError(e.getMessage(), e);
    } catch (IllegalStateException e) {
        throw new NoresourceError(e.getMessage(), e);
    } catch (Exception e) {
        throw new NoresourceError(e.getMessage(), e);
    }
    LOGGER.info("borrowed object of type '" + key + "' (" + resource.getClass().getCanonicalName() + ")");
    if (LOGGER.isDebugEnabled()) {
        final int active = pool.getNumActive();
        final int idle = pool.getNumIdle();
        LOGGER.debug("pool has now " + active + " active/" + idle + " idle for key '" + key + "' ("
                + resource.getClass().getCanonicalName() + ") after borrow");
    }

    return resource;
}

From source file:com.streamreduce.rest.resource.api.OAuthResource.java

/**
 * Returns all details for a given provider in auth.  Presently this includes only an authorizationUrl that
 * users should be redirected to on the provider website in order to start an Oauth handshake.
 *
 * @response.representation.200.doc OAuth provider details
 * @response.representation.201.mediaType application/json
 * @response.representation.400.doc If the provideId does not exist
 * @response.representation.400.mediaType text/plain
 * @response.representation.500.doc If a general exception occurs.
 * @response.representation.500.mediaType text/plain
 *
 * @param providerId - A valid provider id.
 * @return Json Payload with k/v pairs for each detail about an OAuth enabled provider.
 *///from   w  ww  .  java 2 s  .c  o m
@Path("providers/{providerId}")
@GET
public Response getOAuthDetailsForProvider(@PathParam("providerId") String providerId) {
    try {
        OAuthEnabledConnectionProvider connectionProvider = connectionProviderFactory
                .oauthEnabledConnectionProviderFromId(providerId);
        String authorizationUrl = connectionProvider.getAuthorizationUrl();
        JSONObject providerOAuthDetail = new JSONObjectBuilder().add("authorizationUrl", authorizationUrl)
                .build();
        return Response.ok(providerOAuthDetail).build();
    } catch (NoSuchElementException e) {
        return error(providerId + " is not a registered oauth provider in Nodeable",
                Response.status(Response.Status.BAD_REQUEST));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return error(Response.Status.INTERNAL_SERVER_ERROR);
    }
}

From source file:org.kurento.repository.RepositoryService.java

/**
 * Wrapper for {@link Repository#findRepositoryItemById(String)} that throws a checked exception
 * when the item is not found.//from w ww  .j av a  2s. c o m
 *
 * @param itemId
 *          the id of a repository item
 * @return the found object
 * @throws ItemNotFoundException
 *           when there's no instance with the provided id
 */
private RepositoryItem findRepositoryItemById(String itemId) throws ItemNotFoundException {
    try {
        return repository.findRepositoryItemById(itemId);
    } catch (NoSuchElementException e) {
        log.debug("Provided id is not valid", e);
        throw new ItemNotFoundException(e.getMessage());
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.visualization.personpubcount.PersonPublicationCountVisCodeGenerator.java

/**
 * This method is used to setup parameters for the sparkline value object. These parameters
 * will be used in the template to construct the actual html/javascript code.
 * @param visMode/*from   w  w w .  j a va2  s.  c  om*/
 * @param visContainer
 * @return 
 */
private SparklineData setupSparklineParameters(String visMode, String providedVisContainerID) {

    SparklineData sparklineData = new SparklineData();
    sparklineData.setYearToActivityCount(yearToPublicationCount);

    int numOfYearsToBeRendered = 0;

    /*
     * It was decided that to prevent downward curve that happens if there are no publications 
     * in the current year seems a bit harsh, so we consider only publications from the last 10
     * complete years. 
     * */
    int currentYear = Calendar.getInstance().get(Calendar.YEAR) - 1;
    int shortSparkMinYear = currentYear - VisConstants.MINIMUM_YEARS_CONSIDERED_FOR_SPARKLINE + 1;

    /*
     * This is required because when deciding the range of years over which the vis
     * was rendered we dont want to be influenced by the "DEFAULT_PUBLICATION_YEAR".
     * */
    Set<String> publishedYears = new HashSet<String>(yearToPublicationCount.keySet());
    publishedYears.remove(VOConstants.DEFAULT_PUBLICATION_YEAR);

    /*
     * We are setting the default value of minPublishedYear to be 10 years before 
     * the current year (which is suitably represented by the shortSparkMinYear),
     * this in case we run into invalid set of published years.
     * */
    int minPublishedYear = shortSparkMinYear;

    String visContainerID = null;

    if (yearToPublicationCount.size() > 0) {
        try {
            minPublishedYear = Integer.parseInt(Collections.min(publishedYears));
        } catch (NoSuchElementException e1) {
            log.debug("vis: " + e1.getMessage() + " error occurred for " + yearToPublicationCount.toString());
        } catch (NumberFormatException e2) {
            log.debug("vis: " + e2.getMessage() + " error occurred for " + yearToPublicationCount.toString());
        }
    }

    int minPubYearConsidered = 0;

    /*
     * There might be a case that the author has made his first publication within the 
     * last 10 years but we want to make sure that the sparkline is representative of 
     * at least the last 10 years, so we will set the minPubYearConsidered to 
     * "currentYear - 10" which is also given by "shortSparkMinYear".
     * */
    if (minPublishedYear > shortSparkMinYear) {
        minPubYearConsidered = shortSparkMinYear;
    } else {
        minPubYearConsidered = minPublishedYear;
    }

    numOfYearsToBeRendered = currentYear - minPubYearConsidered + 1;

    sparklineData.setNumOfYearsToBeRendered(numOfYearsToBeRendered);

    int publicationCounter = 0;

    /*
     * For the purpose of this visualization I have come up with a term "Sparks" which 
     * essentially means data points. 
     * Sparks that will be rendered in full mode will always be the one's which have any year
     * associated with it. Hence.
     * */
    int renderedFullSparks = 0;

    List<YearToEntityCountDataElement> yearToPublicationCountDataTable = new ArrayList<YearToEntityCountDataElement>();

    for (int publicationYear = minPubYearConsidered; publicationYear <= currentYear; publicationYear++) {

        String stringPublishedYear = String.valueOf(publicationYear);
        Integer currentPublications = yearToPublicationCount.get(stringPublishedYear);

        if (currentPublications == null) {
            currentPublications = 0;
        }

        yearToPublicationCountDataTable.add(
                new YearToEntityCountDataElement(publicationCounter, stringPublishedYear, currentPublications));

        /*
         * Sparks that will be rendered will always be the one's which has 
         * any year associated with it. Hence.
         * */
        renderedFullSparks += currentPublications;
        publicationCounter++;
    }

    sparklineData.setYearToEntityCountDataTable(yearToPublicationCountDataTable);
    sparklineData.setRenderedSparks(renderedFullSparks);

    /*
     * Total publications will also consider publications that have no year associated with
     * it. Hence.
     * */
    Integer unknownYearPublications = 0;
    if (yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR) != null) {
        unknownYearPublications = yearToPublicationCount.get(VOConstants.DEFAULT_PUBLICATION_YEAR);
    }

    sparklineData.setUnknownYearPublications(unknownYearPublications);

    if (providedVisContainerID != null) {
        visContainerID = providedVisContainerID;
    } else {
        visContainerID = DEFAULT_VIS_CONTAINER_DIV_ID;
    }

    sparklineData.setVisContainerDivID(visContainerID);

    /*
     * By default these represents the range of the rendered sparks. Only in case of
     * "short" sparkline mode we will set the Earliest RenderedPublication year to
     * "currentYear - 10". 
     * */
    sparklineData.setEarliestYearConsidered(minPubYearConsidered);
    sparklineData.setEarliestRenderedPublicationYear(minPublishedYear);
    sparklineData.setLatestRenderedPublicationYear(currentYear);

    if (yearToPublicationCount.size() > 0) {

        sparklineData.setFullTimelineNetworkLink(UtilityFunctions.getCollaboratorshipNetworkLink(individualURI,
                VisualizationFrameworkConstants.PERSON_LEVEL_VIS,
                VisualizationFrameworkConstants.COAUTHOR_VIS_MODE));

        sparklineData.setDownloadDataLink(UtilityFunctions.getCSVDownloadURL(individualURI,
                VisualizationFrameworkConstants.PERSON_PUBLICATION_COUNT_VIS, ""));
    }

    /*
     * The Full Sparkline will be rendered by default. Only if the url has specific mention of
     * SHORT_SPARKLINE_MODE_URL_HANDLE then we render the short sparkline and not otherwise.
     * */
    if (VisualizationFrameworkConstants.SHORT_SPARKLINE_VIS_MODE.equalsIgnoreCase(visMode)) {

        sparklineData.setEarliestRenderedPublicationYear(shortSparkMinYear);
        sparklineData.setShortVisMode(true);

    } else {
        sparklineData.setShortVisMode(false);
    }

    return sparklineData;
}

From source file:org.jgentleframework.services.objectpooling.context.PoolScope.java

/**
 * Obtain instance./*w ww .j  a v a  2  s . c  o  m*/
 * 
 * @param pool
 *            the pool
 * @param poolingConfig
 *            the pooling config
 * @param targetClass
 *            the target class
 * @return the object
 */
private Object obtainInstance(Pool pool, Pooling poolingConfig, Class<?> targetClass) {

    Object result = null;
    if (poolingConfig.enable() == true) {
        if (poolingConfig.JustInTime() == true) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(targetClass);
            enhancer.setUseFactory(false);
            enhancer.setUseCache(true);
            enhancer.setNamingPolicy(new JGentleNamingPolicy());
            Callback callback = new PoolInvocationMethodInterceptor(pool);
            enhancer.setCallback(callback);
            result = enhancer.create();
        } else {
            try {
                result = pool.obtainObject();
            } catch (NoSuchElementException e) {
                if (log.isErrorEnabled()) {
                    log.error(e.getMessage(), e);
                }
            } catch (Throwable e) {
                if (log.isErrorEnabled()) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }
    return result;
}