Java 类javax.ws.rs.ProcessingException 实例源码

项目:beadledom    文件:ApacheHttpClient4Dot3Engine.java   
protected void loadHttpMethod(final ClientInvocation request, HttpRequestBase httpMethod)
    throws Exception {
  if (request.getEntity() != null) {
    if (httpMethod instanceof HttpGet) {
      throw new ProcessingException("A GET request cannot have a body.");
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    request.getDelegatingOutputStream().setDelegate(baos);
    try {
      HttpEntity entity = buildEntity(request);
      HttpPost post = (HttpPost) httpMethod;
      commitHeaders(request, httpMethod);
      post.setEntity(entity);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  } else // no body
  {
    commitHeaders(request, httpMethod);
  }
}
项目:verify-hub    文件:SoapRequestClientTest.java   
@Test
public void makePost_checkProcessingExceptionIsThrown() throws IOException, SAXException,
        ParserConfigurationException, URISyntaxException, SOAPRequestError {
    ProcessingException exception = mock(ProcessingException.class);
    when(webResourceBuilder.post(any(Entity.class))).thenThrow(exception);
    Element matchingServiceRequest = XmlUtils.convertToElement("<someElement/>");
    URI matchingServiceUri = new URI("http://heyyeyaaeyaaaeyaeyaa.com/abc1");

    try {
        soapRequestClient.makeSoapRequest(matchingServiceRequest, matchingServiceUri);
        fail("Exception should have been thrown");
    }
    catch(ProcessingException e) {
        assertThat(e).isEqualTo(exception);
    }
}
项目:Pet-Supply-Store    文件:NonBalancedCRUDOperations.java   
/**
 * Returns the entity with the specified id. Returns null if it does not exist.
 * @param id Id of the entity to find.
 * @param client The REST client to use.
 * @param <T> Type of entity to handle.
 * @throws NotFoundException If 404 was returned.
 * @throws TimeoutException If 408 was returned.
 * @return The entity; null if it does not exist.
 */
public static <T> T getEntity(RESTClient<T> client, long id) throws NotFoundException, TimeoutException {
    Response response = client.getService().path(client.getApplicationURI()).path(client.getEndpointURI()).
            path(String.valueOf(id)).request(MediaType.APPLICATION_JSON).get();
    if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        throw new NotFoundException();
    } else if (response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
        throw new TimeoutException();
    }
    T entity = null;
    try {
        entity = response.readEntity(client.getEntityClass());
    } catch (NullPointerException | ProcessingException e) {
        LOG.warn("Response did not conform to expected entity type.");
    }
    if (response != null) {
        response.close();
    }
    return entity;
}
项目:Pet-Supply-Store    文件:NonBalancedCRUDOperations.java   
/**
 * Returns an Entity of the relevant type by using a unique non-primary-key property.
 * Example: Get user with user name.
 * Note that the AbstractCRUDEndpoint does not offer this feature by default.
 * @param client The REST client to use.
 * @param propertyURI Name of the property. E.g., "name".
 * @param propertyValue Value of the property, e.g., "user1".
 * @param <T> Type of entity to handle.
 * @throws NotFoundException If 404 was returned.
 * @throws TimeoutException If 408 was returned.
 * @return The entity; null if it does not exist.
 */
public static <T> T getEntityWithProperty(RESTClient<T> client, String propertyURI,
        String propertyValue) throws NotFoundException, TimeoutException {
    WebTarget target = client.getService().path(client.getApplicationURI())
            .path(client.getEndpointURI()).path(propertyURI).path(propertyValue);
    Response response = target.request(MediaType.APPLICATION_JSON).get();
    if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
        throw new NotFoundException();
    } else if (response.getStatus() == Status.REQUEST_TIMEOUT.getStatusCode()) {
        throw new TimeoutException();
    }
    T entity = null;
    try {
        entity = response.readEntity(client.getEntityClass());
    } catch (NullPointerException | ProcessingException e) {
        //This happens if no entity was found
    }
    if (response != null) {
        response.close();
    }
    return entity;
}
项目:Pet-Supply-Store    文件:RegistryClient.java   
/**
 * Get all servers for a service in the {@link Service} enum from the registry.
 * @param targetService The service for which to get the servers.
 * @return List of servers.
 */
public List<Server> getServersForService(Service targetService) {
    List<String> list = null;
    List<Server> serverList = new ArrayList<Server>();
    try {
        Response response = getRESTClient(5000).target(registryRESTURL)
                .path("/" + targetService.getServiceName() + "/")
                .request(MediaType.APPLICATION_JSON).get();
        list = response.readEntity(new GenericType<List<String>>() { }); 
    } catch (ProcessingException e) {
        return null;
    }

    if (list != null) {
        for (String string: list) {
            serverList.add(new Server(string));
        }
    }

    return serverList;
}
项目:osc-core    文件:ServerControl.java   
private static boolean isRunningServer() {
    try {
        log.info("Check if server is running ...");
        VmidcServerRestClient restClient = new VmidcServerRestClient("localhost", apiPort, VMIDC_DEFAULT_LOGIN, VMIDC_DEFAULT_PASS, true);

        ServerStatusResponse res = getServerStatusResponse(restClient);

        String oldPid = res.getPid();

        log.warn("Current pid:" + ServerUtil.getCurrentPid() + ". Running server (pid:" + oldPid + ") version: "
                + res.getVersion() + " with db version: " + res.getDbVersion());

        return true;
    } catch (ProcessingException | ConnectException e1) {
        log.warn("Fail to connect to running server: "+ e1.getMessage());
    } catch (Exception ex) {
        log.warn("Fail to connect to running server. Assuming not running: " + ex);
    }

    return false;
}
项目:comms-router    文件:ApplicationContext.java   
private void handleAssignment(TaskAssignmentDto taskAssignment)
    throws CallbackException {

  try {
    String callbackUrl = taskAssignment.getTask().getCallbackUrl();

    Response response = client.target(callbackUrl)
        .property(ClientProperties.FOLLOW_REDIRECTS, configuration.getClientFollowRedirects())
        .request(MediaType.WILDCARD_TYPE)
        .post(Entity.entity(taskAssignment, MediaType.APPLICATION_JSON_TYPE));

    if (response.getStatus() == Status.SERVICE_UNAVAILABLE.getStatusCode()) {
      // On 503 response we will try again
      // TODO Retry-After header?!
      throw new CallbackException();
    }

  } catch (ProcessingException e) {
    throw new CallbackException();
  }
}
项目:CharmMylynConnector    文件:CharmAttachmentMessageBodyReader.java   
@Override
public CharmAttachmentMeta readFrom(Class<CharmAttachmentMeta> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmAttachmentMeta.class);
        Unmarshaller attachmentUnmarshaller = context.createUnmarshaller();
        return (CharmAttachmentMeta) attachmentUnmarshaller.unmarshal(entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error deserializing Attachment");
    }

}
项目:CharmMylynConnector    文件:CharmTaskMessageBodyWriter.java   
@Override
public void writeTo(CharmTask charmTask, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmTask.class);
        Marshaller taskMarshaller = context.createMarshaller();
        taskMarshaller.marshal(charmTask, entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error serializing Charm Task to output stream");
    }

}
项目:CharmMylynConnector    文件:CharmAttachmentPostWriter.java   
@Override
public void writeTo(CharmAttachmentPost attachment, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmAttachmentPost.class);
        Marshaller taskMarshaller = context.createMarshaller();
        taskMarshaller.marshal(attachment, entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error serializing Attachment to output stream");
    }

}
项目:CharmMylynConnector    文件:CharmTaskMessageBodyReader.java   
@Override
public CharmTask readFrom(Class<CharmTask> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    try {


        JAXBContext context = JAXBContext.newInstance(CharmTask.class);
        Unmarshaller taskUnmarshaller = context.createUnmarshaller();
        return (CharmTask) taskUnmarshaller.unmarshal(entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error deserializing Task");
    }

}
项目:CharmMylynConnector    文件:CharmErrorMessageBodyReader.java   
@Override
public CharmErrorMessage readFrom(Class<CharmErrorMessage> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    try {

        JAXBContext context = JAXBContext.newInstance(CharmErrorMessage.class);
        Unmarshaller errorUnmarshaller = context.createUnmarshaller();
        return (CharmErrorMessage) errorUnmarshaller.unmarshal(entityStream);

    } catch (JAXBException e) {
        throw new ProcessingException("Error deserializing Error Message");
    }

}
项目:biblebot    文件:RocketChatService.java   
public boolean waitAndLoginToApi() {
    LOGGER.info("wait 300 sec for REST API " + webTarget.getUri().toString() + " to come up");
    for (int i = 0; i < 300; i++) {
        try {
            loginResponse = login(apiUser, apiPassword);
            LOGGER.info("logged in.");
            return true;
        } catch (ProcessingException e) {
            // ok, try another time
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }
    LOGGER.error("couldn't connect to api.");
    return false;
}
项目:service-tools    文件:RestClient.java   
private <R> R request(String path, Function<Builder, Response> method,
        Class<R> responseType, int status) throws ServiceException {
    Builder builder = target.path(path) //
            .request() //
            .accept(mediaType);

    Response response = null;
    try {
        response = method.apply(builder);

        if (response.getStatus() != status) {
            throw new ConnectionException(Messages.ERROR_BAD_RESPONSE,
                    response.readEntity(String.class));
        }

        return response.readEntity(responseType);
    } catch (ProcessingException e) {
        throw new ConnectionException(Messages.ERROR_CONNECTION_FAILURE, e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
}
项目:snoopee    文件:SnoopEEServiceClient.java   
private SnoopEEConfig getConfigFromSnoopEE() throws SnoopEEServiceUnavailableException {

        try {
            Response response = ClientBuilder.newClient()
                    .target(serviceUrl)
                    .path("api")
                    .path("services")
                    .path(applicationName)
                    .request(APPLICATION_JSON)
                    .get();

            if (response.getStatus() == 200) {
                return response.readEntity(SnoopEEConfig.class);
            } else {
                throw new SnoopEEServiceUnavailableException("Response from \"" + serviceUrl + "\"=" + response.getStatus());
            }

        } catch (ProcessingException e) {
            throw new SnoopEEServiceUnavailableException(e);
        }
    }
项目:mycore    文件:MCRJerseyTest.java   
@Override
public void start() {
    System.out.println("Starting GrizzlyTestContainer...");
    try {
        this.server = GrizzlyHttpServerFactory.createHttpServer(uri, rc);

        // Initialize and register Jersey Servlet
        WebappContext context = new WebappContext("WebappContext", "");
        ServletRegistration registration = context.addServlet("ServletContainer", ServletContainer.class);
        registration.setInitParameter("javax.ws.rs.Application", rc.getClass().getName());
        // Add an init parameter - this could be loaded from a parameter in the constructor
        registration.setInitParameter("myparam", "myvalue");

        registration.addMapping("/*");
        context.deploy(server);
    } catch (ProcessingException e) {
        throw new TestContainerException(e);
    }
}
项目:pokebattler-fight    文件:ProtobufJsonProvider.java   
@Override
public Message readFrom(Class<Message> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {
    try (InputStreamReader reader = new InputStreamReader(entityStream)){
        final Method m = type.getMethod("newBuilder");
        final Message.Builder builder = (Message.Builder) m.invoke(null);
        parser.merge(reader, builder);

        return builder.build();
    } catch (final Exception e) {
        log.error("Could not read?", e);
        // TODO Auto-generated catch block
        throw new ProcessingException("Error deserializing proto");
    }

}
项目:bootique-jersey-client    文件:InstrumentedClientIT.java   
@Test
public void testTimer_ConnectionError() {

    Client client = app.getInstance(HttpClientFactory.class).newClient();

    MetricRegistry metrics = app.getInstance(MetricRegistry.class);

    Collection<Timer> timers = metrics.getTimers().values();
    assertEquals(1, timers.size());
    Timer timer = timers.iterator().next();
    assertEquals(0, timer.getCount());

    // bad request: assuming nothing listens on port=8081
    try {
        client.target("http://127.0.0.1:8081/get").request().get().close();
        fail("Exception expected");
    } catch (ProcessingException e) {
        // ignore...
    }

    assertEquals(0, timer.getCount());

    // successful request
    client.target("http://127.0.0.1:8080/get").request().get().close();
    assertEquals(1, timer.getCount());
}
项目:sigma-events    文件:APIGatewayServiceRegistry.java   
public void register(APIGatewayServiceInfo serviceInfo)
    throws APIGatewayServiceRegistrationFailure {

  boolean registrationComplete = false;
  while (!registrationComplete) {
    try {
      registerUpstreamURL(serviceInfo);
      if (!serviceRegistered(serviceInfo)) {
        createServiceRegistry(serviceInfo);
      }
      registrationComplete = true;
    } catch (ProcessingException | ConnectException e) {
      if (e instanceof ProcessingException && !(e.getCause() instanceof ConnectException)) {
        throw (ProcessingException) e;
      }
      System.out.println(
          "failed to connect to api-gateway, retry after " + REGISTRATION_RETRY_SEC + " sec ...");
      try {
        Thread.sleep(TimeUnit.SECONDS.toMillis(REGISTRATION_RETRY_SEC));
      } catch (InterruptedException e1) {
        throw new APIGatewayServiceRegistrationFailure(e);
      }
    }
  }
  System.out.println("service " + serviceInfo.getServiceId() + " registration with api-gateway successful !!");
}
项目:rest-hateoas-client    文件:ResponseBuilder.java   
public <S> Optional<ListResponse<S>> buildListResponse(@NonNull String responseString,
        @NonNull Class<S> responseClass, @NonNull URI uri) {
    JsonNode rawValue = getRawValue(responseString);
    ClientHyperSchema jsonHyperSchema = buildSchema(rawValue);
    JsonNode membersNode = rawValue.get("members");
    if (membersNode != null) {
        List<Response<S>> list = new LinkedList<>();
        for (Iterator<JsonNode> iterator = membersNode.elements(); iterator.hasNext();) {
            JsonNode jsonNode = iterator.next();
            list.add(buildSingleResponse(jsonNode, responseClass, uri).get());
        }
        return Optional.of(new ListResponseImpl<>(this, jsonHyperSchema, list, uri));
    } else {
        throw new ProcessingException("There is no members field in the response");
    }
}
项目:vespa    文件:NoRetryJaxRsStrategyTest.java   
@Test
public void testNoRetryAfterFailure() throws Exception {
    // Make the first call fail.
    when(mockApi.doSomething())
            .thenThrow(new ProcessingException("Fake timeout induced by test"))
            .thenReturn("a response");

    try {
        jaxRsStrategy.apply(TestJaxRsApi::doSomething);
        fail("The above statement should throw");
    } catch (IOException e) {
        // As expected.
    }

    // Check that there was no second attempt.
    verify(mockApi, times(1)).doSomething();
}
项目:vespa    文件:RetryingJaxRsStrategyTest.java   
@Test
public void testRetryGivesUpAfterTwoLoopsOverAvailableServers() throws Exception {
    when(mockApi.doSomething())
            .thenThrow(new ProcessingException("Fake timeout 1 induced by test"))
            .thenThrow(new ProcessingException("Fake timeout 2 induced by test"))
            .thenThrow(new ProcessingException("Fake timeout 3 induced by test"))
            .thenThrow(new ProcessingException("Fake timeout 4 induced by test"))
            .thenThrow(new ProcessingException("Fake timeout 5 induced by test"))
            .thenThrow(new ProcessingException("Fake timeout 6 induced by test"));

    try {
        jaxRsStrategy.apply(TestJaxRsApi::doSomething);
        fail("Exception should be thrown from above statement");
    } catch (IOException e) {
        // As expected.
    }

    verify(mockApi, times(6)).doSomething();
    verifyAllServersContacted(jaxRsClientFactory);
}
项目:fili    文件:RequestHandlerUtils.java   
/**
 * Builds error response from exception.
 *
 * @param status  the response status
 * @param druidQuery  failed Druid Query if available or null
 * @param cause  exception
 * @param writer  The Writer to use for writing errors
 *
 * @return Response
 */
public static Response makeErrorResponse(
        StatusType status,
        DruidQuery<?> druidQuery,
        Throwable cause,
        ObjectWriter writer
) {
    String reason = null;
    String description = null;

    // do not return JAX-RS processing exception, only the cause
    if (cause instanceof ProcessingException && cause.getCause() != null) {
        cause = cause.getCause();
    }

    if (cause != null) {
        reason = cause.getClass().getName();
        description = String.valueOf(cause.getMessage());
    }

    return makeErrorResponse(status.getStatusCode(), reason, description, druidQuery, writer);
}
项目:r360-java    文件:TimeRequest.java   
/**
 * Execute request
 * @return Time response
 * @throws Route360ClientException In case of error other than Gateway Timeout
 */
public TimeResponse get() throws Route360ClientException, ProcessingException {

    long requestStart = System.currentTimeMillis();

    WebTarget target = client.target(travelOptions.getServiceUrl()).path("v1/time")
            .queryParam("cb", CALLBACK)
            .queryParam("key", travelOptions.getServiceKey());

    Response response;
    String config = RequestConfigurator.getConfig(travelOptions);
    // Execute POST request
    response = target.request().post(Entity.entity(config, MediaType.APPLICATION_JSON_TYPE));

    long roundTripTime = System.currentTimeMillis() - requestStart;

    return validateResponse(response, requestStart, roundTripTime);
}
项目:robots    文件:HttpStatusHandlerTest.java   
@Test
public void test() {
    try {
        final Response response = target()
                .queryParam(STATUS_PARAM, statusCode)
                .request()
                .get();
        assertThat(response.getStatus(), equalTo(statusCode));
    } catch (ProcessingException e) {
        final Throwable cause = e.getCause();
        if (cause == null) {
            throw e;
        } else if (cause instanceof TemporaryAllow) {
            assertThat(expectedAction, equalTo(Action.TEMPORARY_ALLOW));
        } else if (cause instanceof TemporaryDisallow) {
            assertThat(expectedAction, equalTo(Action.TEMPORARY_DISALLOW));
        } else {
            throw e;
        }
    }
}
项目:providence    文件:ProvidenceMessageBodyWriter.java   
@Override
@SuppressWarnings("unchecked")
public void writeTo(PMessage entity,
                    Class<?> type,
                    Type genericType,
                    Annotation[] annotations,
                    MediaType mediaType,
                    MultivaluedMap<String, Object> httpHeaders,
                    OutputStream entityStream) throws IOException, WebApplicationException {
    try {
        provider.getSerializer(mediaType.toString())
                .serialize(entityStream, entity);
    } catch (NotSupportedException e) {
        throw new ProcessingException("Unknown media type: " + mediaType, e);
    } catch (SerializerException se) {
        throw new ProcessingException("Unable to serialize entity", se);
    }
}
项目:hawkular-client-java    文件:MetricTest.java   
@Test(dependsOnMethods = "findMetrics")
public void findMetricsAfterOtherClientCreated() throws URISyntaxException {
    // Make sure there's no breaking static config
    HawkularClient otherClient = HawkularClient.builder("other tenant")
            .uri("http://localhost:8080/fake")
            .build();

    ClientResponse<List<Metric<?>>> response = client()
            .metrics()
            .metric()
            .findMetrics(MetricType.AVAILABILITY, tags, metricName);

    Assert.assertTrue(response.isSuccess());

    ClientResponse<List<Metric<?>>> otherClientReponse = new DefaultClientResponse<>();
    try {
        otherClientReponse = otherClient
            .metrics()
            .metric()
            .findMetrics(MetricType.AVAILABILITY, tags, metricName);
    } catch (ProcessingException ex) {
        //If nothing is listening, you get a RESTEasy error
    }

    Assert.assertFalse(otherClientReponse.isSuccess());
}
项目:snoop    文件:SnoopServiceClient.java   
private SnoopConfig getConfigFromSnoop() throws SnoopServiceUnavailableException {

        try {
            Response response = ClientBuilder.newClient()
                    .target(serviceUrl)
                    .path("api")
                    .path("services")
                    .path(applicationName)
                    .request(APPLICATION_JSON)
                    .get();

            if (response.getStatus() == 200) {
                return response.readEntity(SnoopConfig.class);
            } else {
                throw new SnoopServiceUnavailableException("Response from \"" + serviceUrl + "\"=" + response.getStatus());
            }

        } catch (ProcessingException e) {
            throw new SnoopServiceUnavailableException(e);
        }
    }
项目:soabase    文件:JerseyRetryConnector.java   
@Override
public ClientResponse apply(ClientRequest request)
{
    RequestRunner<ClientRequest> requestRunner = new RequestRunner<>(retryComponents, headerSetter, request.getUri(), request.getMethod());
    while ( requestRunner.shouldContinue() )
    {
        URI uri = requestRunner.prepareRequest(request);
        request.setUri(uri);
        try
        {
            ClientResponse response = connector.apply(request);
            if ( requestRunner.isSuccessResponse(response.getStatus()) )
            {
                return response;
            }
        }
        catch ( Exception e )
        {
            if ( !requestRunner.shouldBeRetried(e) )
            {
                throw new ProcessingException(e);
            }
        }
    }
    throw new ProcessingException("Retries expired: " + requestRunner.getOriginalUri());
}
项目:hopsworks    文件:ClientWrapper.java   
private T getResponse(Response response) {
  Family statusFamily = response.getStatusInfo().getFamily();
  if (response.getMediaType().getSubtype().equals(MediaType.APPLICATION_JSON_TYPE.getSubtype())) {
    try {
      if (statusFamily == Family.INFORMATIONAL || statusFamily == Family.SUCCESSFUL) {
        T content = response.readEntity(respContentClass);
        return content;
      } else {
        JsonResponse jsonRes = response.readEntity(JsonResponse.class);
        throw new IllegalStateException(jsonRes.getErrorMsg());
      }
    } catch (ProcessingException e) {
      throw new IllegalStateException(e.getMessage());
    }
  } else {
    throw new IllegalStateException("Cannot Connect To Server.");
  }

}
项目:dropwizard-auth-example    文件:TLSClientAuthenticationIT.java   
@Test
public void thirdPartyHttpsClientIsRefused() throws Exception {
    Client client = getNewSecureClient("tls/third-party-service-keystore.jks");

    try {
        client.target(String.format("https://localhost:%d/users", 8443))
                .request()
                .header("Authorization", "Bearer " + adminJWT)
                .get(new GenericType<List<UserInfo>>() {
                });
        failBecauseExceptionWasNotThrown(ProcessingException.class);
    } catch (ProcessingException e) {
        // cause here can vary from SocketException to SSLHandshakeException
        Throwable cause = e.getCause();
        if (cause instanceof SocketException){
            assertThat(e).hasCauseExactlyInstanceOf(SocketException.class);
            assertThat(e).hasMessageEndingWith("Connection reset");
        } else if (cause instanceof SSLHandshakeException) {
            assertThat(e).hasCauseExactlyInstanceOf(SSLHandshakeException.class);
            assertThat(e).hasMessageEndingWith("Remote host closed connection during handshake");
        } else {
            failBecauseExceptionWasNotThrown(SocketException.class);
        }
    }
}
项目:streamline    文件:NamespaceCatalogResource.java   
@Timed
@POST
@Path("/namespaces")
public Response addNamespace(Namespace namespace, @Context SecurityContext securityContext) {
  SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_ENVIRONMENT_ADMIN);
  try {
    String namespaceName = namespace.getName();
    Namespace result = environmentService.getNamespaceByName(namespaceName);
    if (result != null) {
      throw new AlreadyExistsException("Namespace entity already exists with name " + namespaceName);
    }
    Namespace created = environmentService.addNamespace(namespace);
    SecurityUtil.addAcl(authorizer, securityContext, Namespace.NAMESPACE, created.getId(), EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(created, CREATED);
  } catch (ProcessingException ex) {
    throw BadRequestException.of();
  }
}
项目:streamline    文件:ServiceBundleResource.java   
/**
 * Add a new service bundle.
 */
@POST
@Path("/servicebundles")
@Timed
public Response addServiceBundle(ServiceBundle serviceBundle) throws IOException, ComponentConfigException {
    try {
        String serviceName = serviceBundle.getName();
        ServiceBundle result = environmentService.getServiceBundleByName(serviceName);
        if (result != null) {
            throw new AlreadyExistsException("Service bundle for " + serviceName + " is already registered.");
        }

        ServiceBundle created = environmentService.addServiceBundle(serviceBundle);
        return WSUtils.respondEntity(created, CREATED);
    } catch (ProcessingException ex) {
        throw BadRequestException.of();
    }
}
项目:el-bombillo    文件:RegistryService.java   
/**
 * Registers a service by it's specified information within {@code this} service registry.
 * <p />
 * The specified http client will be used to call the service registry.
 * <p />
 * Exceptions will be logged and won't be exposed by this method.
 *
 * @param serviceInformation the information of the service to register
 * @param client the http client
 */
public boolean register(final ServiceInformation serviceInformation, final Client client) {
    try {
        final HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic(credentials.getUsername(), credentials.getPassword());
        final Response response = client.register(authenticationFeature).target(baseUrl).path("/services").request()
                .buildPost(Entity.json(serviceInformation)).invoke();
        if (!response.getStatusInfo().getFamily().equals(Response.Status.Family.SUCCESSFUL)) {
            log.warn("failed to register service with response: {} (code: {})", response, response.getStatus());
            throw new ProcessingException("invalid registry response code: " + response.getStatus());
        }
        log.info("successfully registered service \"{}\"", serviceInformation.getName());
        return true;
    } catch (final ProcessingException e) {
        log.warn("failed to register service \"" + serviceInformation.getName() + "\"");
        return false;
    }
}
项目:qds-sdk-java    文件:RetryConnector.java   
private boolean tryRetry(ClientRequest request, int tryCount, ClientResponse clientResponse, ProcessingException e)
{
    if (retry.getRetryPolicy().shouldBeRetried(request.getUri(), tryCount, clientResponse, e, getRetryMode(request)))
    {
        try
        {
            retry.getRetrySleeper().sleep(tryCount);
        }
        catch (InterruptedException e1)
        {
            Thread.currentThread().interrupt();
            throw new ProcessingException(e1);
        }

        return true;
    }
    return false;
}
项目:pp-db-collector-template    文件:CollectorApplicationFactory.java   
private WebTarget createAndTestRestWebTarget(Client restClient) {
    String url = configuration.getProperty("performance.platform.url");
    WebTarget target = restClient.target(url).register(new AddBearerTokenRequestFilter(configuration.getProperty("performance.platform.auth.token")));

    //test the rest server at the other end with a test request
    Entity<JsonArray> json = Entity.json(Json.createArrayBuilder().build());
    try {
        Response result = target.request().post(json);
        if (result.getStatus() != 200) {
            logger.log(CollectorLogMessage.PerformancePlatformTestQueryFailed, url, result.getStatus());
            throw new ApplicationException();
        }
    } catch (ProcessingException e) {
        logger.log(CollectorLogMessage.CouldNotConnectToPerformancePlatform, url);
        throw new ApplicationException();
    }

    return target;
}
项目:NetLicensingClient-java    文件:RestProviderJersey.java   
/**
 * Reads entity of given type from response. Returns null when the response has a zero-length content.
 *
 * @param response
 *            service response
 * @param responseType
 *            expected response type
 * @return the response entity
 * @throws RestException
 */
private <RES> RES readEntity(final Response response, final Class<RES> responseType) throws RestException {
    boolean buffered = false;
    try {
        buffered = response.bufferEntity();
        return response.readEntity(responseType);
    } catch (final ProcessingException ex) {
        if (response.getStatus() == Response.Status.NO_CONTENT.getStatusCode() || ex.getCause() instanceof NoContentException) {
            return null;
        } else {
            if ((response.getStatusInfo().getFamily() == Response.Status.Family.CLIENT_ERROR)
                    || (response.getStatusInfo().getFamily() == Response.Status.Family.SERVER_ERROR)) {
                return null; // Ignore content interpretation errors if status is an error already
            }
            final String body = buffered ? " '" + response.readEntity(String.class) + "' of type '"
                    + response.getMediaType() + "'" : "";
            throw new RestException("Could not interpret the response body" + body, ex);
        }
    }
}
项目:addon-administration    文件:ExtensionsService.java   
private String requestExtensionTypes() {
    StatusType status;
    String content;
    try {
        Response response = target.path("/osiam/extension-definition")
                .request(MediaType.APPLICATION_JSON)
                .header("Authorization", BEARER + sessionData.getAccessToken().getToken())
                .get();

        status = response.getStatusInfo();
        content = response.readEntity(String.class);
    } catch (ProcessingException e) {
        throw new NullPointerException();
    }

    checkAndHandleResponse(content, status);
    return content;
}
项目:gitlab-plugin    文件:AddGitLabMergeRequestCommentStep.java   
@Override
protected Void run() throws Exception {
    GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class);
    if (cause != null) {
        MergeRequest mergeRequest = cause.getData().getMergeRequest();
        if (mergeRequest != null) {
            GitLabClient client = getClient(run);
            if (client == null) {
                println("No GitLab connection configured");
            } else {
                try {
                    client.createMergeRequestNote(mergeRequest, step.getComment());
                } catch (WebApplicationException | ProcessingException e) {
                    printf("Failed to add comment on Merge Request for project '%s': %s%n", mergeRequest.getProjectId(), e.getMessage());
                    LOGGER.log(Level.SEVERE, String.format("Failed to add comment on Merge Request for project '%s'", mergeRequest.getProjectId()), e);
                }
            }
        }
    }
    return null;
}
项目:gitlab-plugin    文件:AcceptGitLabMergeRequestStep.java   
@Override
protected Void run() throws Exception {
    GitLabWebHookCause cause = run.getCause(GitLabWebHookCause.class);
    if (cause != null) {
        MergeRequest mergeRequest = cause.getData().getMergeRequest();
        if (mergeRequest != null) {
            GitLabClient client = getClient(run);
            if (client == null) {
                println("No GitLab connection configured");
            } else {
                try {
                    client.acceptMergeRequest(mergeRequest, step.mergeCommitMessage, false);
                } catch (WebApplicationException | ProcessingException e) {
                    printf("Failed to accept merge request for project '%s': %s%n", mergeRequest.getProjectId(), e.getMessage());
                    LOGGER.log(Level.SEVERE, String.format("Failed to accept merge request for project '%s'", mergeRequest.getProjectId()), e);
                }
            }
        }
    }
    return null;
}