List of usage examples for org.springframework.web.client ResourceAccessException ResourceAccessException
public ResourceAccessException(String msg)
From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java
/** * Pulls the next job off of the Service Queue. * /*from w ww . j a v a 2 s . c o m*/ * @param userName * The name of the user. Used for verification. * @param serviceId * The ID of the Service * @return The information for the next Job, if one is present. */ @RequestMapping(value = { "/service/{serviceId}/task" }, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PiazzaResponse> getNextServiceJobFromQueue( @RequestParam(value = "userName", required = true) String userName, @PathVariable(value = "serviceId") String serviceId) { try { // Log the Request piazzaLogger.log(String.format("User %s Requesting to perform Work on Next Job for %s Service Queue.", userName, serviceId), Severity.INFORMATIONAL); // Check for Access boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName); if (!canAccess) { throw new ResourceAccessException("Service does not allow this user to access."); } // Get the Job. This will mark the Job as being processed. ExecuteServiceJob serviceJob = serviceTaskManager.getNextJobFromQueue(serviceId); // Return if (serviceJob != null) { // Return Job Information return new ResponseEntity<>(new ServiceJobResponse(serviceJob, serviceJob.getJobId()), HttpStatus.OK); } else { // No Job Found. Return Null in the Response. return new ResponseEntity<>(new ServiceJobResponse(), HttpStatus.OK); } } catch (Exception exception) { String error = String.format("Error Getting next Service Job for Service %s by User %s: %s", serviceId, userName, exception.getMessage()); LOGGER.error(error, exception); piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "errorGettingServiceJob", serviceId)); HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; if (exception instanceof ResourceAccessException) { status = HttpStatus.UNAUTHORIZED; } else if (exception instanceof InvalidInputException) { status = HttpStatus.NOT_FOUND; } return new ResponseEntity<>(new ErrorResponse(error, "ServiceController"), status); } }
From source file:de.codecentric.boot.admin.registry.StatusUpdaterTest.java
@Test public void test_update_offline() { when(template.getForEntity("health", Map.class)).thenThrow(new ResourceAccessException("error")); updater.updateStatus(Application.create("foo").withId("id").withHealthUrl("health").build()); assertThat(store.find("id").getStatusInfo().getStatus(), is("OFFLINE")); }
From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java
/** * Updates the Status for a Piazza Job./* w ww .j a v a2 s.c om*/ * * @param userName * The name of the user. Used for verification. * @param serviceId * The ID of the Service containing the Job * @param jobId * The ID of the Job to update * @param statusUpdate * The update contents, including status, percentage, and possibly results. * @return Success or error. */ @RequestMapping(value = { "/service/{serviceId}/task/{jobId}" }, method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<PiazzaResponse> updateServiceJobStatus( @RequestParam(value = "userName", required = true) String userName, @PathVariable(value = "serviceId") String serviceId, @PathVariable(value = "jobId") String jobId, @RequestBody StatusUpdate statusUpdate) { try { // Log the Request piazzaLogger.log( String.format("User %s Requesting to Update Job Status for Job %s for Task-Managed Service.", userName, jobId), Severity.INFORMATIONAL); // Check for Access boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName); if (!canAccess) { throw new ResourceAccessException("Service does not allow this user to access."); } // Simple Validation if ((statusUpdate.getStatus() == null) || (statusUpdate.getStatus().isEmpty())) { throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "`status` property must be provided in Update payload."); } // Process the Update serviceTaskManager.processStatusUpdate(serviceId, jobId, statusUpdate); // Return Success return new ResponseEntity<>(new SuccessResponse("OK", "ServiceController"), HttpStatus.OK); } catch (Exception exception) { String error = String.format("Could not Update status for Job %s for Service %s : %s", jobId, serviceId, exception.getMessage()); LOGGER.error(error, exception); piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "failedToUpdateServiceJob", jobId)); HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; if (exception instanceof ResourceAccessException) { status = HttpStatus.UNAUTHORIZED; } else if (exception instanceof InvalidInputException) { status = HttpStatus.NOT_FOUND; } else if (exception instanceof HttpServerErrorException) { status = ((HttpServerErrorException) exception).getStatusCode(); } return new ResponseEntity<>(new ErrorResponse(error, "ServiceController"), status); } }
From source file:org.venice.piazza.servicecontroller.ServiceControllerTest.java
@Test /**/* w w w . j av a 2s .com*/ * Test get service info sending a null */ public void testGetServiceInfoWithNull() { Mockito.doThrow(new ResourceAccessException("Service not found.")).when(accessorMock).getServiceById(null); PiazzaResponse piazzaResponse = sc.getServiceInfo(null).getBody(); assertThat("ErrorResponse should be returned", piazzaResponse, instanceOf(ErrorResponse.class)); }
From source file:com.netflix.genie.web.services.impl.HttpFileTransferImplTest.java
/** * Make sure can't get a file if the output location is a directory. * * @throws GenieException On Error//from w w w . j a va 2s . c om * @throws IOException On Error */ @Test(expected = ResourceAccessException.class) public void cantGetWithDirectoryAsOutput() throws GenieException, IOException { this.server.expect(MockRestRequestMatchers.requestTo(TEST_URL)) .andExpect(MockRestRequestMatchers.method(HttpMethod.GET)) .andRespond(MockRestResponseCreators.withSuccess("junk".getBytes(Charset.forName("UTF-8")), MediaType.APPLICATION_OCTET_STREAM)); try { this.httpFileTransfer.getFile(TEST_URL, this.temporaryFolder.getRoot().getCanonicalPath()); } finally { Mockito.verify(this.downloadTimerId, Mockito.times(1)) .withTags(MetricsUtils.newFailureTagsMapForException(new ResourceAccessException("test"))); Mockito.verify(this.downloadTimer, Mockito.times(1)).record(Mockito.anyLong(), Mockito.eq(TimeUnit.NANOSECONDS)); } }
From source file:org.venice.piazza.servicecontroller.controller.TaskManagedController.java
/** * Gets metadata for a specific Task-Managed Service. * /* ww w .ja va 2 s . c om*/ * @param userName * The name of the user. Used for verification. * @param serviceId * The ID of the Service * @return Map containing information regarding the Task-Managed Service */ @RequestMapping(value = { "/service/{serviceId}/task/metadata" }, method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> getServiceQueueData(@RequestParam(value = "userName", required = true) String userName, @PathVariable(value = "serviceId") String serviceId) { try { // Log the Request piazzaLogger.log(String.format("User %s Requesting Task-Managed Service Information for Service %s", userName, serviceId), Severity.INFORMATIONAL); // Check for Access boolean canAccess = mongoAccessor.canUserAccessServiceQueue(serviceId, userName); if (!canAccess) { throw new ResourceAccessException("Service does not allow this user to access."); } // Ensure this Service exists and is Task-Managed Service service = mongoAccessor.getServiceById(serviceId); if ((service.getIsTaskManaged() == null) || (service.getIsTaskManaged() == false)) { throw new InvalidInputException("The specified Service is not a Task-Managed Service."); } // Fill Map with Metadata Map<String, Object> response = mongoAccessor.getServiceQueueCollectionMetadata(serviceId); // Respond return new ResponseEntity<Map<String, Object>>(response, HttpStatus.OK); } catch (Exception exception) { String error = String.format("Could not retrieve Service Queue data for %s : %s", serviceId, exception.getMessage()); LOGGER.error(error, exception); piazzaLogger.log(error, Severity.ERROR, new AuditElement(userName, "failedToRetrieveServiceQueueMetadata", serviceId)); HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR; if (exception instanceof ResourceAccessException) { status = HttpStatus.UNAUTHORIZED; } else if (exception instanceof InvalidInputException) { status = HttpStatus.NOT_FOUND; } return new ResponseEntity<String>(error, status); } }
From source file:org.venice.piazza.servicecontroller.taskmanaged.ServiceTaskManager.java
/** * Pulls the next waiting Job off of the Jobs queue and returns it. * //from w w w .j av a 2 s .c om * @param serviceId * The ID of the Service whose Queue to pull a Job from * @return The Job information */ public ExecuteServiceJob getNextJobFromQueue(String serviceId) throws ResourceAccessException, InterruptedException, InvalidInputException { // Pull the Job off of the queue. ServiceJob serviceJob = mongoAccessor.getNextJobInServiceQueue(serviceId); // If no Job exists in the Queue, then return null. No work needs to be done. if (serviceJob == null) { return null; } // Read the Jobs collection for the full Job Details String jobId = serviceJob.getJobId(); Job job = mongoAccessor.getJobById(jobId); // Ensure the Job exists. If it does not, then throw an error. if (job == null) { String error = String.format( "Error pulling Service Job off Job Queue for Service %s and Job Id %s. The Job was not found in the database.", serviceId, jobId); piazzaLogger.log(error, Severity.ERROR); throw new ResourceAccessException(error); } // Update the Job Status as Running to Kafka StatusUpdate statusUpdate = new StatusUpdate(); statusUpdate.setStatus(StatusUpdate.STATUS_RUNNING); ProducerRecord<String, String> statusUpdateRecord; try { statusUpdateRecord = new ProducerRecord<String, String>( String.format("%s-%s", JobMessageFactory.UPDATE_JOB_TOPIC_NAME, SPACE), jobId, objectMapper.writeValueAsString(statusUpdate)); producer.send(statusUpdateRecord); } catch (JsonProcessingException exception) { String error = "Error Sending Pending Job Status to Job Manager: "; LOGGER.error(error, exception); piazzaLogger.log(error, Severity.ERROR); } // Return the Job Execution Information, including payload and parameters. if (job.getJobType() instanceof ExecuteServiceJob) { // Ensure that the ServiceJob has the JobID populated ExecuteServiceJob executeServiceJob = (ExecuteServiceJob) job.getJobType(); if (executeServiceJob.getJobId() == null) { executeServiceJob.setJobId(jobId); } // Return return executeServiceJob; } else { // The Job must be an ExecuteServiceJob. If for some reason it is not, then throw an error. String error = String.format( "Error pulling Job %s off of the Jobs Queue for Service %s. The Job was not the proper ExecuteServiceJob type. This Job cannot be processed.", jobId, serviceId); piazzaLogger.log(error, Severity.ERROR); throw new InvalidInputException(error); } }
From source file:edu.zipcloud.cloudstreetmarket.core.services.CommunityServiceImpl.java
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userRepository.findOne(username); Authentication auth;// w ww. j a v a2 s . com if (user != null) { return user; } SecurityContext securityContext = SecurityContextHolder.getContext(); if (securityContext != null) { auth = securityContext.getAuthentication(); if (auth != null) { Object principal = auth.getPrincipal(); if (principal instanceof User) { return (User) principal; } } } //fallback throw new ResourceAccessException("No found user for username: " + username); }
From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java
/** * Returns a ResourceMetadata object that matches the specified Id. * /*from w ww .j av a2 s .c o m*/ * @param jobId * Job Id * @return The Job with the specified Id */ public Service getServiceById(String serviceId) throws ResourceAccessException { BasicDBObject query = new BasicDBObject("serviceId", serviceId); Service service; try { if ((service = getServiceCollection().findOne(query)) == null) { throw new ResourceAccessException(String.format("Service not found : %s", serviceId)); } } catch (MongoTimeoutException mte) { LOGGER.error("MongoDB instance not available", mte); throw new ResourceAccessException("MongoDB instance not available."); } return service; }
From source file:org.venice.piazza.servicecontroller.data.mongodb.accessors.MongoAccessor.java
/** * Returns a list of ResourceMetadata based on the criteria provided * /*from w w w . java 2 s. co m*/ * @return List of matching services that match the search criteria */ public List<Service> search(SearchCriteria criteria) { List<Service> results = new ArrayList<Service>(); if (criteria != null) { LOGGER.debug("Criteria field=" + criteria.getField()); LOGGER.debug("Criteria field=" + criteria.getPattern()); Pattern pattern = Pattern.compile(criteria.pattern); BasicDBObject query = new BasicDBObject(criteria.field, pattern); try { DBCursor<Service> cursor = getServiceCollection().find(query); while (cursor.hasNext()) { results.add(cursor.next()); } // Now try to look for the field in the resourceMetadata just to make sure query = new BasicDBObject("resourceMetadata." + criteria.field, pattern); cursor = getServiceCollection().find(query); while (cursor.hasNext()) { Service serviceItem = cursor.next(); if (!exists(results, serviceItem.getServiceId())) results.add(serviceItem); } } catch (MongoTimeoutException mte) { LOGGER.error("MongoDB instance not available", mte); throw new ResourceAccessException("MongoDB instance not available."); } } return results; }