/** * {@inheritDoc} */ @Override public String sign(final JwtClaims claims) { try { final RsaJsonWebKey aSigningKey = cachedDataProvider.getASigningKey(); final JsonWebSignature jws = new JsonWebSignature(); jws.setPayload(claims.toJson()); jws.setKeyIdHeaderValue(aSigningKey.getKeyId()); jws.setKey(aSigningKey.getPrivateKey()); jws.setAlgorithmHeaderValue(aSigningKey.getAlgorithm()); jws.sign(); return jws.getCompactSerialization(); } catch (final JoseException e) { throw new InternalServerErrorException(e); } }
/** * {@inheritDoc} */ @Override public JwtClaims toClaimsSet(final String jwt, final String audience, final HttpsJwks httpsJwks) { final JwtConsumerBuilder builder = new JwtConsumerBuilder() .setVerificationKeyResolver(new HttpsJwksVerificationKeyResolver(httpsJwks)); if (audience == null) { builder.setSkipDefaultAudienceValidation(); } else { builder.setExpectedAudience(audience); } final JwtConsumer jwtConsumer = builder .build(); try { return jwtConsumer.processToClaims(jwt); } catch (final InvalidJwtException e) { throw new InternalServerErrorException(e); } }
@GET @Path("/issue") @Produces(MediaType.TEXT_PLAIN) public Response issue(@Context SecurityContext securityContext) { // get Authentication Authentication authc = (Authentication) securityContext.getUserPrincipal(); // configuration JwtConfiguration configuration = ResourceUtils.lookupResource(getClass(), JwtConfiguration.class, providers) .orElseThrow(() -> new InternalServerErrorException("JWT configuration not available")); // build JWT String jwt = JwtTokenBuilder.buildJwtToken(configuration, authc, UUID.randomUUID().toString()); // ok return Response.ok(jwt, MediaType.TEXT_PLAIN).build(); }
/** Returns all lectures, in proper order, that given {@link Unit} is part of.*/ public List<Lecture> list(Unit unit){ List<Lecture> lectures = new ArrayList<Lecture>(); String query = "SELECT * FROM lectures JOIN lecture_units ON (lectures.lecture_id = lecture_units.lecture_id) WHERE lecture_units.unit_id = ? ORDER BY lecture_units.unit_ordinal ASC"; try (PreparedStatement statement = connProvider.get().prepareStatement(query)){ statement.setObject(1, unit.getId()); try(ResultSet resultSet = statement.executeQuery()){ while(resultSet.next()) lectures.add(lectureFromResultSet(resultSet)); } } catch(SQLException e){ throw new InternalServerErrorException("Unable to list lectures for unit " + unit.toString(), e); } Log.debug("User {} listed lectures that unit {} is part of", userProvider.get().me(), unit.toString()); return lectures; }
/** * Updates existing <code>Course</code> in database. Returns <code>Course</code> * if successful. */ public Course update(Course newValues) { if (newValues.getTitle() == null || newValues.getDescription() == null || newValues.getAuthor() == null) { throw new BadRequestException("Missing Parameter(s) on updating course by user " + userProvider.get().me()); } if(findById(newValues.getId()) == null) { throw new NotFoundException("Course " + newValues.toString() + " not found while updating by user " + userProvider.get().me()); } String query = "UPDATE courses SET course_title=?, course_description=?, author_id=?, course_keywords=? WHERE course_id=?"; try (PreparedStatement statement = connProvider.get().prepareStatement(query)) { int index = 0; statement.setString(++index, newValues.getTitle()); statement.setString(++index, newValues.getDescription()); statement.setObject(++index, newValues.getAuthor().getId()); statement.setArray(++index, connProvider.get().createArrayOf("text", newValues.getKeywords().toArray())); statement.setObject(++index, newValues.getId()); if(statement.executeUpdate() == 1) { Log.info("User {} updated course {}", userProvider.get().me(), newValues.toString()); } } catch (SQLException e) { throw new InternalServerErrorException("Unable to update course by user " + userProvider.get().me(), e); } return newValues; }
/** * Deletes a <code>Course</code> from database. */ public Course delete(Course course) { if(findById(course.getId()) == null) { throw new NotFoundException("Course " + course.toString() + " not found while deleting by user " + userProvider.get().me()); } String query = "BEGIN; DELETE FROM course_lectures WHERE course_id=?; DELETE FROM courses WHERE course_id=?; COMMIT;"; try (PreparedStatement statement = connProvider.get().prepareStatement(query)) { int index = 0; statement.setObject(++index, course.getId()); statement.setObject(++index, course.getId()); statement.executeUpdate(); Log.info("User: {} Deleted Course: {}", userProvider.get().me(), course.toString()); return course; } catch (SQLException e) { throw new InternalServerErrorException("Unable To Delete Course " + course.toString() + " By User " + userProvider.get().me(), e); } }
/** * Parses given ResultSet and extract {@link Course} from it. If ResultSet * had <code>NULL</code> in <code>course_id</code> column, <code>null</code> * is returned. */ public Course fromResultSet(ResultSet resultSet) { Course course = new Course(); try { course.setId(UUID.class.cast(resultSet.getObject("course_id"))); if (resultSet.wasNull()) return null; course.setTitle(resultSet.getString("course_title")); course.setDescription(resultSet.getString("course_description")); course.setAuthor(userProvider.get().findById(UUID.class.cast(resultSet.getObject("author_id")))); course.setKeywords(JdbcUtils.array2List(resultSet.getArray("course_keywords"), String[].class)); } catch (SQLException e) { throw new InternalServerErrorException("Unable to resolve course from result set", e); } return course; }
/** Returns head {@link Unit} for given {@link Course}.*/ public Unit getHeadUnit(Course course) { Unit headUnit = null; String query = "SELECT * FROM units JOIN courses ON (unit_id=course_head_unit_id) AND course_id=?"; try(PreparedStatement statement = connProvider.get().prepareStatement(query)){ statement.setObject(1, course.getId()); try(ResultSet resultSet = statement.executeQuery()){ if(resultSet.next()) headUnit = unitProvider.get().fromResultSet(resultSet); } } catch(SQLException e){ throw new InternalServerErrorException("Unable to resolve head unit in course " + course.toString() + " for user " + userProvider.get().me(), e); } Log.debug("Returned head unit in course {} for user {}", course.toString(), userProvider.get().me()); return headUnit; }
/** * Verifies: on 500 server error, broker invalidates session and client receives 500 correctly. * * @throws Exception */ @Test public void testAuthenticationFilterNegative() throws Exception { log.info("-- Starting {} test --", methodName); Map<String, String> authParams = new HashMap<>(); authParams.put("tlsCertFile", TLS_CLIENT_CERT_FILE_PATH); authParams.put("tlsKeyFile", TLS_CLIENT_KEY_FILE_PATH); Authentication authTls = new AuthenticationTls(); authTls.configure(authParams); internalSetup(authTls); final String cluster = "use"; final ClusterData clusterData = new ClusterData(brokerUrl.toString(), brokerUrlTls.toString(), "pulsar://localhost:" + BROKER_PORT, "pulsar+ssl://localhost:" + BROKER_PORT_TLS); // this will cause NPE and it should throw 500 doReturn(null).when(pulsar).getGlobalZkCache(); try { admin.clusters().createCluster(cluster, clusterData); } catch (PulsarAdminException e) { Assert.assertTrue(e.getCause() instanceof InternalServerErrorException); } log.info("-- Exiting {} test --", methodName); }
@Override public Response endActiveConversations(List<ConversationStatus> conversationStatuses) { try { for (ConversationStatus conversationStatus : conversationStatuses) { String conversationId = conversationStatus.getConversationId(); conversationMemoryStore.setConversationState( conversationId, ConversationState.ENDED); ConversationDescriptor conversationDescriptor = conversationDescriptorStore. readDescriptor(conversationId, 0); conversationDescriptor.setConversationState(ConversationState.ENDED); conversationDescriptorStore.setDescriptor(conversationId, 0, conversationDescriptor); log.info(String.format("conversation (%s) has been set to ENDED", conversationId)); } return Response.ok().build(); } catch (IResourceStore.ResourceStoreException | IResourceStore.ResourceNotFoundException e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(); } }
@Override public Response webHook(final String botId, final String callbackPayload, final String sha1PayloadSignature) { SystemRuntime.getRuntime().submitCallable((Callable<Void>) () -> { try { log.info("webhook called"); getMessageClient(botId).getReceiveClient(). processCallbackPayload(callbackPayload, sha1PayloadSignature); } catch (MessengerVerificationException e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException("Error when processing callback payload"); } return null; }, null); return Response.ok().build(); }
@Override public Response deployBot(final Deployment.Environment environment, final String botId, final Integer version, final Boolean autoDeploy) { RuntimeUtilities.checkNotNull(environment, "environment"); RuntimeUtilities.checkNotNull(botId, "botId"); RuntimeUtilities.checkNotNull(version, "version"); RuntimeUtilities.checkNotNull(autoDeploy, "autoDeploy"); try { deploy(environment, botId, version, autoDeploy); return Response.accepted().build(); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(e.getLocalizedMessage(), e); } }
@Override public Response undeployBot(Deployment.Environment environment, String botId, Integer version) { RuntimeUtilities.checkNotNull(environment, "environment"); RuntimeUtilities.checkNotNull(botId, "botId"); RuntimeUtilities.checkNotNull(version, "version"); try { Long activeConversationCount = conversationMemoryStore.getActiveConversationCount(botId, version); if (activeConversationCount > 0) { String message = "%s active (thus not ENDED) conversation(s) going on with this bot!"; message = String.format(message, activeConversationCount); return Response.status(Response.Status.CONFLICT).entity(message).type(MediaType.TEXT_PLAIN).build(); } undeploy(environment, botId, version); return Response.accepted().build(); } catch (Exception e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(e.getLocalizedMessage(), e); } }
@Override public Response startConversation(Deployment.Environment environment, String botId) { RuntimeUtilities.checkNotNull(environment, "environment"); RuntimeUtilities.checkNotNull(botId, "botId"); try { IBot latestBot = botFactory.getLatestBot(environment, botId); if (latestBot == null) { String message = "No instance of bot (botId=%s) deployed in environment (environment=%s)!"; message = String.format(message, botId, environment); return Response.status(Response.Status.NOT_FOUND).type(MediaType.TEXT_PLAIN).entity(message).build(); } IConversation conversation = latestBot.startConversation(null); String conversationId = storeConversationMemory(conversation.getConversationMemory(), environment); URI createdUri = RestUtilities.createURI(resourceURI, conversationId); return Response.created(createdUri).build(); } catch (ServiceException | IResourceStore.ResourceStoreException | InstantiationException | LifecycleException | IllegalAccessException e) { log.error(e.getLocalizedMessage(), e); throw new InternalServerErrorException(e.getLocalizedMessage(), e); } }
@Test public void testCreateException() { assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class); assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class); assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class); assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class); assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class); assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class); assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class); assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class); assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class); assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class); assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class); assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class); assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class); }
/** * Create an {@link InternalServerErrorException} instance to indicate * that an Authlete API call failed. */ private InternalServerErrorException apiFailure(String path, AuthleteApiException e) { // Error message. String message = String.format("Authlete %s API failed: %s", path, e.getMessage()); // Response body in the response from the Authlete server. if (e.getResponseBody() != null) { // Append the content of the response body to the error message. message = new StringBuilder(message) .append(": ").append(e.getResponseBody()).toString(); } // 500 Internal Server Error return internalServerError(message, e); }
public Object put(String path, InputStream fileInputStream, Long contentLenght) { try { ByteArrayOutputStream buffer = bufferInputStream(fileInputStream); // TODO make it parallel uploadThumbnail(path, buffer, 480, 360); // TODO make it parallel return super.put(path, new ByteArrayInputStream(buffer.toByteArray()), Long.valueOf(buffer.size())); } catch (IOException e) { // TODO handle and log e.printStackTrace(); throw new InternalServerErrorException("Error uploading image"); } }
protected FindContentLengthResult findContentLength(InputStream fileInputStream) { try { ByteArrayOutputStream buffer = bufferInputStream(fileInputStream); FindContentLengthResult result = new FindContentLengthResult(); result.setContentLength(Long.valueOf(buffer.size())); result.setFileInputStream(new ByteArrayInputStream(buffer.toByteArray())); return result; } catch (IOException e) { // TODO handle and log e.printStackTrace(); throw new InternalServerErrorException("Error uploading image"); } }
@PostConstruct protected void postConstruct() { DescribeDomainsRequest describeDomainsRequest = new DescribeDomainsRequest().withDomainNames(getDomainName()); List<DomainStatus> list = amazonCloudSearch.describeDomains(describeDomainsRequest).getDomainStatusList(); if (list.isEmpty()) { throw new InternalServerErrorException("Could not find CloudSearch domain: " + getDomainName()); } ServiceEndpoint searchService = list.get(0).getSearchService(); if (searchService == null || searchService.getEndpoint() == null) { throw new InternalServerErrorException("Could not find SearchService for: " + getDomainName()); } domain = createDomain(); domain.setEndpoint(searchService.getEndpoint()); }
protected IndexArtifact addArtifactToStorage(JavaIndexKey key, StorageRequest sr) { // Artifacts are uploaded, but for them to become live they need // metadata uploaded. // All this does is save it successfully. try { // Create the entry for the index that contains current information // about the artifact. IndexArtifact ia = getStorage().getIndexArtifact(key, getPath()); // Upload the file we need. getStorage().uploadSnapshotArtifactStream(ia, sr); return ia; } catch (IndexException | StorageException se) { throw new InternalServerErrorException(); } }
/** * This version is different as we need to re-write the filename with the * timestamp for the latest version. * * @param key * IndexKey to find the Artifact in the Index * @param filename * Filename from the request * @return StreamingOutput from the Storage Layer */ protected StreamingOutput getSnapshotArtifact(JavaIndexKey key, String filename) { logger.info("[Downloading Snapshot] " + key); try { if (getIndex().isArtifact(key)) { JavaIndexArtifact ia = (JavaIndexArtifact) getIndex().getArtifact(key); String snapshotFilename = filename.replace(key.getVersion(), ia.getSnapshotVersion()); return getStorage().getArtifactStream(ia, snapshotFilename); } else { throw new NotFoundException(); } } catch (IndexException ie) { throw new InternalServerErrorException(); } }
public StreamingOutput getProxiedArtifact(String[] proxies, String path, String artifact) { StorageRequest sr = super.requestProxiedArtifact(proxies, path + artifact, artifact); // Artifact needs to be the "package" name, not the filename. IndexKey pk; try { pk = getStorage().getStorageTranslator(getPath()).generateIndexKey(artifact, sr.getFilename()); } catch (IndexException e) { throw new InternalServerErrorException(); } addArtifactToStorage(pk, sr); return sr.getStreamingOutput(); }
protected IndexArtifact addArtifactToStorage(IndexKey key, StorageRequest sr) { // Artifacts are uploaded, but for them to become live they need // metadata uploaded. // All this does is save it successfully. try { // Create the entry for the index that contains current information // about the artifact. IndexArtifact ia = getStorage().getIndexArtifact(key, getPath()); // Upload the file we need. getStorage().uploadSnapshotArtifactStream(ia, sr); return ia; } catch (StorageException | IndexException se) { throw new InternalServerErrorException(); } }
/** * Test of deleteTask method, of class TaskService. * Delete with exception to check the correct close of the entity manager */ @Test public final void testDeleteTaskException() { Task t = TestData.createTask(TestData.TASKTYPE.SSH); Mockito.when(this.em.find( ArgumentMatchers.eq(Task.class), ArgumentMatchers.anyString())). thenReturn(t); Mockito.doThrow(new RuntimeException()).when(em).remove( ArgumentMatchers.eq(t)); final TaskService ts = this.getTaskService(); try { ts.deleteTask(t.getApplicationId()); } catch (InternalServerErrorException isee) { Mockito.verify(this.em).close(); Mockito.verify(this.em).remove(t); } }
@Test public void client_handles_jetty_errors_500() throws Exception { try { SchedulerRMProxyFactory schedulerFactory = mock(SchedulerRMProxyFactory.class); when(schedulerFactory.connectToScheduler(Matchers.<CredData> any())).thenThrow(new LoginException()); SharedSessionStore.getInstance().setSchedulerRMProxyFactory(schedulerFactory); SchedulerRestClient client = new SchedulerRestClient("http://localhost:" + port + "/"); client.getScheduler().login("demo", "demo"); fail("Should have throw an exception"); } catch (WebApplicationException e) { assertTrue(e instanceof InternalServerErrorException); assertEquals(500, e.getResponse().getStatus()); } }
@Test public void getLogFileFailsAfter10Attempts() throws Exception { QueueDispatcher dispatcher = new QueueDispatcher(); dispatcher.setFailFast(new MockResponse().setResponseCode(500)); mockWebServer.setDispatcher(dispatcher); try { client.getLogFile(Id.of("17"), RestLogFileHandle.builder() .agentId("test-agent") .fileName("test-task-1.log") .fileSize(4711) .fileTime(Instant.now().truncatedTo(SECONDS)) .taskName("test-task-1") .build()); fail(); } catch (InternalServerErrorException ignore) { } assertThat(mockWebServer.getRequestCount(), is(10)); }
@Override public T provide() { if (_request != null) { final String header = _request.getHeader(HttpHeaders.AUTHORIZATION); try { if (header != null) { final TokenCredentials credentials = new TokenCredentials(header); final Optional<T> result = authenticator().authenticate(credentials); if (result.isPresent()) { return result.get(); } } } catch (AuthenticationException e) { LOGGER.warn("Error authenticating credentials", e); throw new InternalServerErrorException(); } } throw new WebApplicationException(_unauthorizedHandler.buildResponse("", _realm)); }
/** * Processes the OCSP request and catches any exceptions that occur to attempt to * return an INTERNAL_ERROR response. If it still can't do that, 500s. * * @param ocspReq The OCSP request * @return The OCSP response if possible * @throws InternalServerErrorException if returning a proper OCSP response is not possible */ private OCSPResp processOCSPRequest(OCSPReq ocspReq) { try { return doProcessOCSPRequest(ocspReq); } catch (OCSPException e) { try { // Try making an internal error response as a last ditch attempt. LOG.error("Error processing OCSP Request!", e); throw new InternalServerErrorException("Error processing OCSP Request", Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity( new OCSPRespBuilder().build(OCSPRespBuilder.INTERNAL_ERROR, null) ).build(), e); } catch (OCSPException e1) { LOG.error("Could not return a response!", e1); throw new InternalServerErrorException("Could not build proper response", e1); } } }
@GET @Path("{reminderid}/image") @Produces("image/jpeg") public InputStream getImage(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId) throws IOException { Reminder reminder = em.find(Reminder.class, reminderId); if (reminder == null || reminder.getList().getId() != listId || reminder.getImage() == null) { throw new NotFoundException(); } java.nio.file.Path path = IMAGES_BASE_DIR.resolve(reminder.getImage()); if (!Files.exists(path)) { throw new InternalServerErrorException("Could not load image " + reminder.getImage()); } return Files.newInputStream(path); }
@GET @Path("{username}/picture") @Produces("image/png") public InputStream getProfilePicture(@PathParam("username") String username) throws IOException { User user = em.find(User.class, username); if (user == null) { throw new NotFoundException(); } java.nio.file.Path path = IMAGES_BASE_DIR.resolve(user.getProfilePicture()); if (!Files.exists(path)) { throw new InternalServerErrorException("Could not load profile picture " + user.getProfilePicture()); } return Files.newInputStream(path); }
@Test public void testLogsForRequestID() throws Exception { exception.expect(InternalServerErrorException.class); try{ createRequest((ResteasyClient client) -> { return client .target(getDataUrl()) .path("/find/fake") .queryParam("Q", "_id:abc") .register(new BasicAuthentication("fakeuser", "secret")); }).get(String.class); } catch(Exception e) { assertFalse(logAppender.getEvents().isEmpty()); boolean atLeastOne = false; for (LoggingEvent le : logAppender.getEvents()) { if (le.getRenderedMessage().contains("log for testing")) { assertNotNull(le.getRenderedMessage(), le.getMDC(LoggingFilter.HEADER_REQUEST_ID)); atLeastOne = true; } } assertTrue(atLeastOne); throw e; } }
@Test public void testLogsForPrincipal() throws Exception { exception.expect(InternalServerErrorException.class); try{ createRequest((ResteasyClient client) -> { return client .target(getDataUrl()) .path("/find/fake") .queryParam("Q", "_id:abc") .register(new BasicAuthentication("fakeuser", "secret")); }).get(String.class); } catch(Exception e) { assertFalse(logAppender.getEvents().isEmpty()); boolean atLeastOne = false; for (LoggingEvent le : logAppender.getEvents()) { if (le.getRenderedMessage().contains("log for testing")) { assertEquals(le.getRenderedMessage(), "fakeuser", le.getMDC(LoggingFilter.HEADER_REQUEST_PRINCIPAL)); atLeastOne = true; } } assertTrue(atLeastOne); throw e; } }
/** * <p>parseHttpStatus.</p> * * @param exception a {@link java.lang.Throwable} object. * @return a int. */ public static int parseHttpStatus(Throwable exception) { int status = 500; Exception ex = Requests.getProperty(DefaultExceptionMapper.BEFORE_EXCEPTION_KEY); if (ex != null) { exception = ex; } if (exception instanceof InternalServerErrorException) { if (exception.getCause() instanceof MessageBodyProviderNotFoundException) { MessageBodyProviderNotFoundException e = (MessageBodyProviderNotFoundException) exception.getCause(); if (e.getMessage().startsWith("MessageBodyReader")) { status = 415; } else if (e.getMessage().startsWith("MessageBodyWriter")) { status = 406; } } } else if (exception instanceof WebApplicationException) { status = ((WebApplicationException) exception).getResponse().getStatus(); } else if (exception instanceof FileNotFoundException) { status = 404; } return status; }
@Override public String getMimeType(String uri) throws RepositoryException { RepositoryConnection conn = null; try { conn = sesameService.getConnection(); if(ldpService.exists(conn, uri)) { return ldpService.getMimeType(conn, uri); } throw new NotFoundException("mimetype for resource not found"); } catch (RepositoryException e) { e.printStackTrace(); throw new InternalServerErrorException("repository exception"); } finally { conn.close(); } }
/** * {@inheritDoc} */ @Override public Response toResponse(final InternalServerErrorException exception) { if (L.isDebugEnabled()) { L.debug(R.getString("D-REST-JERSEY-MAPPER#0004")); } ErrorMessage error = ErrorMessages.create(exception) .id() .code(ErrorCode.INTERNAL_SERVER_ERROR.code()) .resolve() .get(); L.error(error.log(), exception); return Response.status(exception.getResponse().getStatusInfo()) .entity(error) .type(MediaType.APPLICATION_JSON) .build(); }
/** * Test handleGetRequest when an RestconfException is thrown. */ @Test public void testHandleGetRequestRestconfException() { expect(restconfService .runGetOperationOnDataResource(URI.create(getBaseUri() + DATA_IETF_SYSTEM_SYSTEM))) .andThrow(new RestconfException("Suitable error message", RestconfError.ErrorTag.OPERATION_FAILED, INTERNAL_SERVER_ERROR, Optional.of("/" + DATA_IETF_SYSTEM_SYSTEM), Optional.of("More info about the error"))) .anyTimes(); replay(restconfService); WebTarget wt = target(); try { String response = wt.path("/" + DATA_IETF_SYSTEM_SYSTEM).request().get(String.class); fail("Expecting fail as response is RestconfException"); } catch (InternalServerErrorException e) { assertNotNull(e.getResponse()); assertRestconfErrorJson(e.getResponse()); } }
/** * Test handleGetRequest when an Exception is thrown. */ @Test public void testHandleGetRequestIoException() { expect(restconfService .runGetOperationOnDataResource(URI.create(getBaseUri() + DATA_IETF_SYSTEM_SYSTEM))) .andThrow(new IllegalArgumentException("A test exception")) .anyTimes(); replay(restconfService); WebTarget wt = target(); try { String response = wt.path("/" + DATA_IETF_SYSTEM_SYSTEM).request().get(String.class); fail("Expecting fail as response is IllegalArgumentException"); } catch (InternalServerErrorException e) { assertNotNull(e.getResponse()); assertRestconfErrorJson(e.getResponse()); } }
@Test public void testGetMepNotFound() throws CfmConfigException, IOException { expect(mepService.getMep(MDNAME1, MANAME1, MepId.valueOf((short) 2))) .andReturn(null).anyTimes(); replay(mepService); final WebTarget wt = target(); try { final String response = wt.path("md/" + MDNAME1.mdName() + "/ma/" + MANAME1.maName() + "/mep/" + 2).request().get(String.class); fail("Expected exception to be thrown"); } catch (InternalServerErrorException e) { ByteArrayInputStream is = (ByteArrayInputStream) e.getResponse().getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } assertEquals("{ \"failure\":\"MEP md-1/ma-1-1/2 not found\" }", sb.toString()); } }
@Test public void testGetMdEmpty() throws IOException { final MdId mdName3 = MdIdCharStr.asMdId("md-3"); expect(mdService.getMaintenanceDomain(mdName3)) .andReturn(Optional.empty()).anyTimes(); replay(mdService); final WebTarget wt = target(); try { final String response = wt.path("md/" + mdName3).request().get(String.class); fail("Expected InternalServerErrorException, as MD is unknown"); } catch (InternalServerErrorException e) { ByteArrayInputStream is = (ByteArrayInputStream) e.getResponse().getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } assertThat(sb.toString(), is("{ \"failure\":" + "\"java.lang.IllegalArgumentException: MD md-3 not Found\" }")); } }
@Test public void testGetMaEmpty() throws IOException { MaIdShort maId2 = MaIdCharStr.asMaId("ma-2"); expect(mdService .getMaintenanceAssociation(MDNAME1, maId2)) .andReturn(Optional.empty()).anyTimes(); replay(mdService); final WebTarget wt = target(); try { final String response = wt.path("md/" + MDNAME1.mdName() + "/ma/" + maId2.maName()).request().get(String.class); fail("Expected InternalServerErrorException, as MA is unknown"); } catch (InternalServerErrorException e) { ByteArrayInputStream is = (ByteArrayInputStream) e.getResponse().getEntity(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { sb.append(line); } assertThat(sb.toString(), is("{ \"failure\":" + "\"java.lang.IllegalArgumentException: MA ma-2 not Found\" }")); } }