Java 类javax.ws.rs.client.Invocation.Builder 实例源码

项目:syndesis    文件:ConnectionActionHandlerTest.java   
@Test
public void shouldProvideActionDefinition() {
    @SuppressWarnings({"unchecked", "rawtypes"})
    final Class<Entity<Map<String, Object>>> entityType = (Class) Entity.class;
    final ArgumentCaptor<Entity<Map<String, Object>>> entity = ArgumentCaptor.forClass(entityType);

    final DynamicActionMetadata suggestions = new DynamicActionMetadata.Builder().putProperty("sObjectName",
        Arrays.asList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Account", "Account"),
            DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Contact", "Contact")))
        .build();
    when(invocationBuilder.post(entity.capture(), eq(DynamicActionMetadata.class))).thenReturn(suggestions);

    final ConnectorDescriptor definition = handler.enrichWithMetadata(SALESFORCE_CREATE_OR_UPDATE,
        Collections.emptyMap());

    final ConnectorDescriptor enrichedDefinitioin = new ConnectorDescriptor.Builder()
        .createFrom(createOrUpdateSalesforceObjectDescriptor)
        .replaceConfigurationProperty("sObjectName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Account", "Account"),
                ConfigurationProperty.PropertyValue.Builder.of("Contact", "Contact")))
        .build();

    assertThat(definition).isEqualTo(enrichedDefinitioin);
}
项目:Java-APIs    文件:OEClientReadOnly.java   
/**
 * Return the concept with the supplied URI with pref label, uri and type fields populated
 * @param conceptUri - the concept to be returned
 * @return - the requested concept 
 * @throws OEClientException - an error has occurred contacting the server
 */
public Concept getConcept(String conceptUri) throws OEClientException {
    logger.info("getConcept entry: {}", conceptUri);

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", basicProperties);
    queryParameters.put("path", getPathParameter(conceptUri));
    Invocation.Builder invocationBuilder = getInvocationBuilder(getApiURL(), queryParameters);

    Date startDate = new Date();
    logger.info("getConcept making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("getConcept call complete: {}", startDate.getTime());

    logger.info("getConceptDetails - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isDebugEnabled()) logger.debug("getConceptDetails: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        return new Concept(this, jsonResponse.get("@graph").getAsArray().get(0).getAsObject());
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:Java-APIs    文件:OEClientReadOnly.java   
/**
 * Return the concept with the supplied identifier
 * @param identifier - the unique identifier for the concept (not the URI)
 * @return - the requested concept
 * @throws OEClientException - an error has occurred contacting the server
 */
public Concept getConceptByIdentifier(Identifier identifier) throws OEClientException {
    logger.info("getConceptByIdentifier entry: {}", identifier);

    String url = getModelURL() + "/skos:Concept/meta:transitiveInstance";

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", basicProperties);
    queryParameters.put("filters", String.format("subject(exists %s \"%s\")", getWrappedUri(identifier.getUri()), identifier.getValue()));
    Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters);

    Date startDate = new Date();
    logger.info("getConceptByIdentifier making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("getConceptByIdentifier call complete: {}", startDate.getTime());

    logger.info("getConceptByIdentifier - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isDebugEnabled()) logger.debug("getConceptByIdentifier: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        return new Concept(this, jsonResponse.get("@graph").getAsArray().get(0).getAsObject());
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:Java-APIs    文件:OEClientReadOnly.java   
public void populateRelatedConceptUris(String relationshipUri, Concept concept) throws OEClientException {
    logger.info("populateNarrowerConceptURIs entry: {}", concept.getUri());

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", getWrappedUri(relationshipUri));
    Invocation.Builder invocationBuilder = getInvocationBuilder(getResourceURL(concept.getUri()), queryParameters);

    Date startDate = new Date();
    logger.info("populateNarrowerConceptURIs making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("populateNarrowerConceptURIs call complete: {}", startDate.getTime());

    logger.info("populateNarrowerConceptURIs - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isDebugEnabled()) logger.debug("populateNarrowerConceptURIs: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        concept.populateRelatedConceptUris(relationshipUri, jsonResponse.get("@graph").getAsArray().get(0).getAsObject());
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:Java-APIs    文件:OEClientReadOnly.java   
public void populateMetadata(String metadataUri, Concept concept) throws OEClientException {
    logger.info("populateMetadata entry: {}", concept.getUri());

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", getWrappedUri(metadataUri));
    Invocation.Builder invocationBuilder = getInvocationBuilder(getResourceURL(concept.getUri()), queryParameters);

    Date startDate = new Date();
    logger.info("populateMetadata making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("populateMetadata call complete: {}", startDate.getTime());

    logger.info("populateMetadata - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isDebugEnabled()) logger.debug("populateNarrowerConceptURIs: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        concept.populateMetadata(metadataUri, jsonResponse.get("@graph").getAsArray().get(0).getAsObject());
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:sample-acmegifts    文件:LoginResourceTest.java   
public static Response processRequest(
    String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目: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();
        }
    }
}
项目:mycore    文件:MCRWorksPublisher.java   
/** Publishes the object (its MODS) as a new "work" in the ORCID profile */
MCRWork createWorkFrom(MCRObjectID objectID)
    throws IOException, JDOMException, SAXException {
    WebTarget target = orcid.getWebTarget().path("work");
    Builder builder = buildInvocation(target);

    Document workXML = buildWorkXMLFrom(objectID);
    Entity<InputStream> input = buildRequestEntity(workXML);

    LOGGER.info("post (create){} at {}", objectID, target.getUri());
    Response response = builder.post(input);
    expect(response, Response.Status.CREATED);

    String putCode = getPutCode(response);
    MCRWork work = new MCRWork(orcid, putCode);
    work.fetchDetails();
    return work;
}
项目:syndesis-rest    文件:ConnectionActionHandlerTest.java   
@Test
public void shouldProvideActionDefinition() {
    @SuppressWarnings({"unchecked", "rawtypes"})
    final Class<Entity<Map<String, Object>>> entityType = (Class) Entity.class;
    final ArgumentCaptor<Entity<Map<String, Object>>> entity = ArgumentCaptor.forClass(entityType);

    final DynamicActionMetadata suggestions = new DynamicActionMetadata.Builder().putProperty("sObjectName",
        Arrays.asList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Account", "Account"),
            DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Contact", "Contact")))
        .build();
    when(invocationBuilder.post(entity.capture(), eq(DynamicActionMetadata.class))).thenReturn(suggestions);

    final ActionDefinition definition = handler.enrichWithMetadata(SALESFORCE_CREATE_OR_UPDATE,
        Collections.emptyMap());

    final ActionDefinition enrichedDefinitioin = new ActionDefinition.Builder()
        .createFrom(createOrUpdateSalesforceObjectDefinition)
        .replaceConfigurationProperty("sObjectName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Account", "Account"),
                ConfigurationProperty.PropertyValue.Builder.of("Contact", "Contact")))
        .build();

    assertThat(definition).isEqualTo(enrichedDefinitioin);
}
项目:rest-hateoas-client    文件:OngoingResponseImpl.java   
private String getResponse(String rel) {
    CallContext callContext = resolve(rel);
    if (callContext == null) {
        return null;
    }

    Builder b = callContext.target.request(callContext.getMediaType());
    javax.ws.rs.core.Response response;
    if (requestObject != null && bodyIsAllowed(callContext.method)) {
        response = b.method(callContext.method, Entity.entity(requestObject, callContext.getMediaType()));
    } else {
        response = b.method(callContext.method);
    }
    if (response.getStatus() >= 300) {
        throw new WebApplicationException(response);
    }
    String responseString = response.readEntity(String.class);
    return responseString;
}
项目:t-factory-server    文件:AgentRestClient.java   
/**
 * This method makes a GET request to the Agente Rest API. Obtain and
 * AgentDto.java object. If the call is successfully the object status is
 * OK, otherwise it will contain the HTTP error code obtained.
 * 
 * @param pTarget
 *            Targe URL.
 *            (http://xxx.xxx.xxx.xxx:xxxx/t-factory-agent/api)
 * @return AgentDto object.
 */
public AgentDto obtainAgenteSrv(String pTarget){

    AgentDto objAgentDto; 

    try {
        WebTarget myTarget = client.target(pTarget+"/agent/");
        Invocation.Builder invocationBuilder = myTarget.request(MediaType.APPLICATION_JSON); 
        Response response = invocationBuilder.get();

        if( response.getStatus() == 200){
            objAgentDto = response.readEntity(AgentDto.class);
        }else{
            objAgentDto = new AgentDto();
            objAgentDto.setStatus( String.valueOf( response.getStatus()));
        }
    } catch (Exception e) {
        System.out.println("Error trying consume the service: "+pTarget);
        //e.printStackTrace();
        objAgentDto = new AgentDto();
        objAgentDto.setStatus("Invalid URL.");
    }


    return objAgentDto;
}
项目:appverse-server    文件:RestPersistenceService.java   
@Override
public StatusResult updateStatusReturn(WebTarget webClient, final T object,
        final String idName, final Long id,
        final Map<String, Object> pathParams, final Map<String, Object> queryParams, final Map<String, Object> builderProperties)
        throws Exception {

    if (queryParams != null)
        webClient = applyQuery(webClient, queryParams);

    if (id != null && idName != null)
        webClient = webClient.resolveTemplate(idName, id);

    if (pathParams != null)
        webClient = webClient.resolveTemplates(pathParams);

    Builder builder = acceptMediaType(webClient.request());
       if (builderProperties != null){
           addBuilderProperties(builder, builderProperties);
       }
    Response resp = builder.put(Entity.entity(object, acceptMediaType()));
    return getStatusResult(resp);

}
项目:pulsar-reporting-api    文件:DruidRestDBConnector.java   
@SuppressWarnings("unchecked")
private Set<String> getDruidTables(WebTarget webTarget) {
    WebTarget dataSourceRs = webTarget.path(DATASOURCE);
    Builder builder = dataSourceRs.request(MediaType.APPLICATION_JSON_TYPE);
    builder.accept(MediaType.APPLICATION_JSON);
    Response response = builder.get();

    int statusCode = response.getStatus();
    Set<String> result = null;
    if (statusCode == Status.OK.getStatusCode()) {
        result = response.readEntity(Set.class);
    } else {
        String errorMsg = "Druid HTTP Status Code - " + statusCode + "; Response - " + response.readEntity(String.class) + "; GET - " + webTarget.getUri();
        logger.warn (errorMsg);
        throw new DataSourceException(errorMsg);
    }
    return result;
}
项目:im-java-api    文件:ImClient.java   
/**
 * Generic POST call.
 */
public <T> T post(final String path, final String bodyContent,
    final String contentType, final Class<T> type,
    final RestParameter... parameters) throws ImClientException {
  try {
    // Avoid sending null as body content
    String normalizedBodyContent = normalizeBodyContent(bodyContent);

    logCallInfo(HttpMethods.POST, path);
    logCallContent(HttpMethods.POST, normalizedBodyContent);

    Entity<String> content =
        Entity.entity(normalizedBodyContent, contentType);
    Builder clientConfigured = configureClient(path, parameters);
    return clientConfigured.post(content, type);
  } catch (WebApplicationException exception) {
    throw new ImClientErrorException(createReponseError(exception));
  }
}
项目:im-java-api    文件:ImClient.java   
/**
 * Returns a Rest client configured with the specified properties.
 * 
 * @param path
 *          : path where the client is going to connect (e.g.
 *          /infrastructures/asdalk-asd34/vms)
 * @param parameters
 *          : extra parameters for the call (if needed)
 * @return : REST client
 */
public Builder configureClient(final String path,
    final RestParameter... parameters) throws ImClientException {
  try {
    WebTarget webtarget = getClient()
        .target(UriBuilder.fromUri(getTargetUrl()).build()).path(path);

    if (parameters != null && parameters.length > 0
        && parameters[0] != null) {
      for (RestParameter parameter : parameters) {
        webtarget.queryParam(parameter.getName(), parameter.getValues());
      }
    }

    return webtarget.request(MediaType.APPLICATION_JSON)
        .header(AUTH_HEADER_TAG, getParsedAuthFile());
  } catch (IllegalArgumentException | UriBuilderException exception) {
    ImJavaApiLogger.severe(this.getClass(), exception);
    throw exception;
  }
}
项目:appverse-server    文件:RestPersistenceService.java   
@Override
public Response update(WebTarget webClient, final InputStream object, final String idName,
        final Long id,
        final Map<String, Object> pathParams, final Map<String, Object> queryParams, final Map<String, Object> builderProperties)
        throws Exception {
    if (queryParams != null)
        webClient = applyQuery(webClient, queryParams);

    if (id != null && idName != null)
        webClient = webClient.resolveTemplate(idName, id);

    if (pathParams != null)
        webClient = webClient.resolveTemplates(pathParams);

    Builder builder = acceptMediaType(webClient.request());
       if (builderProperties != null){
           addBuilderProperties(builder, builderProperties);
       }
    return builder.put(Entity.entity(object, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
项目:che_orion_api    文件:FileService.java   
@PUT
@Path(FILEPATH_PFX)
public Response updateFileContents(@PathParam(FILEPATH_PARAM) String filePathStr,
        @QueryParam(ProtocolConstants.PARM_SOURCE) String source,
        @HeaderParam(HttpHeaders.CONTENT_TYPE) String contentType, InputStream contents) throws IOException,
        URISyntaxException {
    PathInfo filePath = splitWorkspacePath(filePathStr);
    Builder cheReqBuilder = getFileTarget(filePath.workspaceId, filePath.path).request();
    // Pick the content stream
    InputStream contentStream;
    String effContentType;
    if (source != null) {
        URLConnection urlConn = new URL(source).openConnection();
        effContentType = urlConn.getContentType();
        contentStream = urlConn.getInputStream();
    } else {
        effContentType = contentType;
        contentStream = contents;
    }
    Response cheResp = cheReqBuilder.put(Entity.entity(contentStream, effContentType));
    assertValidResponse(cheResp);
    return Response.ok().build();
}
项目:MoodCat.me-Core    文件:EndToEndTest.java   
protected <T> T performRequestWithQueryParams(final Class<T> clazz,
        final String endPoint, final Function<Builder, T> callFunction,
        final Map<String, Object> queryParameters) {
    return this.performRequest(
            endPoint,
            callFunction,
            (target) -> {
                WebTarget targetWithParams = target;

                for (Entry<String, Object> entry : queryParameters.entrySet()) {
                    targetWithParams = targetWithParams.queryParam(entry.getKey(),
                            entry.getValue());
                }

                return targetWithParams;
            });
}
项目:t-factory-server    文件:AgentRestClient.java   
/**
 * Makes a HTTP PUT method for update the port number of a server.xml file inside a Tomcat instance on a remote slave server.
 * @param pServerUrl Remote server where the agent is hosted.
 * @param pUbicacionInstancia Path of tomcat instance inside the remote server.
 * @param pServerXml Object ServerXml.class containing the new port configuration.
 * @return True if success, otherwise false.
 */
public boolean actualizaArchivoServerXmlRemoto(String pServerUrl, String pStandarInstancePath, String pInstanceName, ServerXml pServerXml){
    System.out.println(" Startup Service: "+pServerUrl+"/instance/update/serverxml");

    WebTarget myTarget = client.target(pServerUrl+"/instance/update/serverxml");
    Builder invocationBuilder = myTarget.request().header("instancePath", pStandarInstancePath+"/"+pInstanceName); 
    Response response = invocationBuilder.put(Entity.entity(pServerXml, MediaType.APPLICATION_JSON_TYPE));

    if( response.getStatus() == 200){
        System.out.println("Update succed.");
          String responseMessageFromServer = response.getStatusInfo().getReasonPhrase();
          System.out.println("ResponseMessageFromServer: " + responseMessageFromServer);
          return(true);
    }else{
        System.out.println("ERROR, HTTP code <" + response.getStatus() + "> message:"+response.readEntity(String.class));
        return(false);
    }

}
项目:pulsar-reporting-api    文件:DruidRestDBConnector.java   
private DruidRestTableMeta getDruidTableMeta(String tableName, WebTarget webTarget) {
    WebTarget tableResource = webTarget.path(DATASOURCE).path(tableName);
    Builder builder = tableResource.request(MediaType.APPLICATION_JSON_TYPE);
    builder.accept(MediaType.APPLICATION_JSON);
    Response response = builder.get();

    int statusCode = response.getStatus();
    DruidRestTableMeta result = null;
    if (statusCode == Status.OK.getStatusCode()) {
        result = response.readEntity(DruidRestTableMeta.class);
    } else {
        String errorMsg = "Druid HTTP Status Code - " + statusCode + "; Response - " + response.readEntity(String.class) + "; GET - " + webTarget.getUri();
        logger.warn (errorMsg);
        throw new DataSourceException(errorMsg);
    }
    return result;
}
项目:t-factory-server    文件:AgentRestClient.java   
/**
 * Makes a Get request to obtain 5 available ports on a remote server.
 * @param pServerUrl Remote server Url where the Agente is hosted.
 * @param pInitilaRange Initial (inclusive) range of ports to be searched at the remote server.
 * @param pFinalRange Final (inclusive) range of ports to be searched at the remote server.
 * @param pExcludedList Port list to be excluded from the search.
 * @return List containing the 5 available ports.
 */
@SuppressWarnings("unchecked")
public List<Integer> obtain5AvailablePorts(String pServerUrl, int pInitilaRange, int pFinalRange, List<Integer> pExcludedList){
    System.out.println("Start invocation of service: "+pServerUrl+"/agent/obtain5AvailablePorts");

    try {
        WebTarget myTarget = client.target(pServerUrl+"/agent/obtain5AvailablePorts");
        WebTarget myTargetConParamas = myTarget.queryParam("initialRange", pInitilaRange).queryParam("finalRange", pFinalRange).queryParam("excluded", pExcludedList.toArray());
        Invocation.Builder invocationBuilder = myTargetConParamas.request(MediaType.APPLICATION_JSON);
        Response response = invocationBuilder.get();

        if( response.getStatus() == 200){
            return response.readEntity(List.class);
        }else{
            System.out.println(" ERROR, HTTP response code: "+response.getStatus());
            return null;
        }
    } catch (Exception e) {
        System.out.println("Error invoking service: "+pServerUrl);
        System.out.println(e);
        return null;
    }
}
项目:appverse-server    文件:RestPersistenceService.java   
@Override
public StatusResult insertStatusReturn(WebTarget webClient, final T object,
        final Map<String, Object> pathParams,
        final Map<String, Object> queryParams, final Map<String, Object> builderProperties) throws Exception {

    if (queryParams != null)
        webClient = applyQuery(webClient, queryParams);

    if (pathParams != null)
        webClient = webClient.resolveTemplates(pathParams);

    Builder builder = acceptMediaType(webClient.request());
       if (builderProperties != null){
           addBuilderProperties(builder, builderProperties);
       }
    Response resp = builder.post(Entity.entity(object, acceptMediaType()));
    return getStatusResult(resp);
}
项目:appverse-server    文件:RestPersistenceService.java   
@Override
public Response insert(WebTarget webClient, final InputStream object,
        final Map<String, Object> pathParams,
        final Map<String, Object> queryParams, final Map<String, Object> builderProperties) throws Exception {
    if (queryParams != null)
        webClient = applyQuery(webClient, queryParams);

    if (pathParams != null)
        webClient = webClient.resolveTemplates(pathParams);

    Builder builder = acceptMediaType(webClient.request());
       if (builderProperties != null){
           addBuilderProperties(builder, builderProperties);
       }
    return builder.post(Entity.entity(object, MediaType.APPLICATION_OCTET_STREAM_TYPE));
}
项目:appverse-server    文件:RestPersistenceService.java   
@Override
public StatusResult deleteStatusReturn(WebTarget webClient, final String idName, final Long id,
        final Map<String, Object> pathParams,
        final Map<String, Object> queryParams, final Map<String, Object> builderProperties) throws Exception
{
    if (queryParams != null)
        webClient = applyQuery(webClient, queryParams);

    if (id != null && idName != null)
        webClient = webClient.resolveTemplate(idName, id);

    if (pathParams != null)
        webClient = webClient.resolveTemplates(pathParams);

       Builder builder = acceptMediaType(webClient.request());
       if (builderProperties != null){
           addBuilderProperties(builder, builderProperties);
       }
    Response resp = builder.delete();
    return getStatusResult(resp);

}
项目:im-java-api    文件:ImClient.java   
/**
 * Generic PUT call.
 */
public <T> T put(final String path, final String bodyContent,
    final String contentType, final Class<T> type,
    final RestParameter... parameters) throws ImClientException {
  try {
    // Avoid sending null as body content
    String normalizedBodyContent = normalizeBodyContent(bodyContent);

    logCallInfo(HttpMethods.PUT, path);
    logCallContent(HttpMethods.PUT, normalizedBodyContent);

    Entity<String> content =
        Entity.entity(normalizedBodyContent, contentType);
    Builder clientConfigured = configureClient(path, parameters);
    return clientConfigured.put(content, type);
  } catch (WebApplicationException exception) {
    throw new ImClientErrorException(createReponseError(exception));
  }
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:OtherTestCase.java   
@Test
@RunAsClient
public void testJaxRSOptionsDeleteTypes() throws Exception {
    logger.info("start JaxRS options delete test");
    Client client = newClient();
    WebTarget target = client.target(url + "services/receiver/options");
    Response response = target.request().options();
    String calledMethod = response.getHeaderString("calledMethod");
    double value = response.readEntity(Double.class);
    assertEquals("options implemented: ", 88.99, value, 0.0);
    client.close();
    assertEquals("The filter registerCall is called only for @Logged services", OPTIONS, calledMethod);
    client = newClient();
    target = client.target(url + "services/receiver/delete");
    response = target.request().delete();
    calledMethod = response.getHeaderString("calledMethod");
    value = response.readEntity(Double.class);
    assertEquals("delete implemented: ", 99.66, value, 0.0);
    client.close();
    assertEquals("The filter registerCall is called only for @Logged services", DELETE, calledMethod);
    client = newClient();
    target = client.target(url + "services/receiver/header");
    Builder builder = target.request().header("my_new_header", "Hi all");
    response = builder.get();
    calledMethod = response.getHeaderString("calledMethod");
    String valueStr = response.readEntity(String.class);
    assertEquals("head implemented: ", "Hi all", valueStr);
    client.close();
    assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod);
    client = newClient();
    target = client.target(url + "services/receiver/headerWithContext");
    builder = target.request(TEXT_PLAIN).header("my_new_header", "Hi allll");
    response = builder.get();
    calledMethod = response.getHeaderString("calledMethod");
    valueStr = response.readEntity(String.class);
    assertEquals("head implemented: ", "Hi allll", valueStr);
    client.close();
    assertNotEquals("The filter registerCall is called only for @Logged services", HEAD, calledMethod);
}
项目:syndesis    文件:ConnectionActionHandlerTest.java   
@Before
public void setupMocks() {
    final WebTarget target = mock(WebTarget.class);
    when(client.target(anyString())).thenReturn(target);

    invocationBuilder = mock(Builder.class);
    when(target.request(MediaType.APPLICATION_JSON)).thenReturn(invocationBuilder);
}
项目:syndesis    文件:ConnectionActionHandlerTest.java   
@Test
public void shouldElicitActionPropertySuggestions() {
    @SuppressWarnings({"unchecked", "rawtypes"})
    final Class<Entity<Map<String, Object>>> entityType = (Class) Entity.class;
    final ArgumentCaptor<Entity<Map<String, Object>>> entity = ArgumentCaptor.forClass(entityType);

    final DynamicActionMetadata suggestions = new DynamicActionMetadata.Builder()
        .putProperty("sObjectName",
            Collections
                .singletonList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Contact", "Contact")))
        .putProperty("sObjectIdName",
            Arrays.asList(DynamicActionMetadata.ActionPropertySuggestion.Builder.of("ID", "Contact ID"),
                DynamicActionMetadata.ActionPropertySuggestion.Builder.of("Email", "Email"),
                DynamicActionMetadata.ActionPropertySuggestion.Builder.of("TwitterScreenName__c",
                    "Twitter Screen Name")))
        .build();
    when(invocationBuilder.post(entity.capture(), eq(DynamicActionMetadata.class))).thenReturn(suggestions);

    final ConnectorDescriptor enrichedDefinitioin = new ConnectorDescriptor.Builder()
        .createFrom(createOrUpdateSalesforceObjectDescriptor)
        .replaceConfigurationProperty("sObjectName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Contact", "Contact")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("ID", "Contact ID")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(ConfigurationProperty.PropertyValue.Builder.of("Email", "Email")))
        .replaceConfigurationProperty("sObjectIdName",
            c -> c.addEnum(
                ConfigurationProperty.PropertyValue.Builder.of("TwitterScreenName__c", "Twitter Screen Name")))
        .build();

    final Map<String, String> parameters = new HashMap<>();
    parameters.put("sObjectName", "Contact");

    assertThat(handler.enrichWithMetadata(SALESFORCE_CREATE_OR_UPDATE, parameters)).isEqualTo(enrichedDefinitioin);

    assertThat(entity.getValue().getEntity()).contains(entry("clientId", "some-clientId"),
        entry("sObjectIdName", null), entry("sObjectName", "Contact"));
}
项目:Java-APIs    文件:OEClientReadOnly.java   
protected Builder getInvocationBuilder(String url, Map<String, String> queryParameters) {
        ClientConfig clientConfig = new ClientConfig();
        if (getProxyAddress() != null) {
            clientConfig.connectorProvider(new ApacheConnectorProvider());
            clientConfig.property(ClientProperties.PROXY_URI, getProxyAddress());
        }
        Client client = ClientBuilder.newClient(clientConfig);
        client.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true);
        WebTarget webTarget = client.target(url);

        if (queryParameters != null) {
            for (Map.Entry<String, String> queryParameter: queryParameters.entrySet())
//              webTarget = webTarget.queryParam(queryParameter.getKey(), queryParameter.getValue().replace("_", "_1").replace("%",  "_0"));
                webTarget = webTarget.queryParam(queryParameter.getKey(), queryParameter.getValue());
        }


        return webTarget.request(MediaType.APPLICATION_JSON).accept("application/ld+json").header("Authorization", getCloudTokenValue());
    }
项目:Java-APIs    文件:OEClientReadOnly.java   
public Collection<Model> getAllModels() throws OEClientException {
    logger.info("getAllModels entry");

    String url = getApiURL() + "/sys/sys:Model/rdf:instance";
    logger.info("getAllModels URL: {}", url);
    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", "meta:displayName,meta:graphUri");

    Invocation.Builder invocationBuilder = getInvocationBuilder(url, queryParameters);

    Date startDate = new Date();
    logger.info("getAllModels making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("getAllModels call complete: {}", startDate.getTime());

    logger.info("getAllModels - status: {}", response.getStatus());

    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isInfoEnabled()) logger.info("getAllModels: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        JsonArray jsonArray = jsonResponse.get("@graph").getAsArray();
        Collection<Model> models = new ArrayList<Model>();
        Iterator<JsonValue> jsonValueIterator = jsonArray.iterator();
        while (jsonValueIterator.hasNext()) {
            JsonObject modelObject = jsonValueIterator.next().getAsObject();
            models.add(new Model(modelObject));
        }
        return models;
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:Java-APIs    文件:OEClientReadOnly.java   
private Collection<RelationshipType> getRelationshipTypes(String parentType) throws OEClientException {
    logger.info("getRelationshipTypes entry: {}", parentType);

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", "rdfs:label,owl:inverseOf,rdfs:subPropertyOf,owl:inverseOf/rdfs:label,owl:inverseOf/rdfs:subPropertyOf");
    Invocation.Builder invocationBuilder = getInvocationBuilder(getModelURL() + "/" + parentType +"/meta:transitiveSubProperty", queryParameters);

    Date startDate = new Date();
    logger.info("getRelationshipTypes making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("getRelationshipTypes call complete: {}", startDate.getTime());

    logger.info("getRelationshipTypes - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isInfoEnabled()) logger.info("getConceptClasses: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        JsonArray jsonArray = jsonResponse.get("@graph").getAsArray();
        Collection<RelationshipType> relationshipTypes = new HashSet<RelationshipType>();
        Iterator<JsonValue> jsonValueIterator = jsonArray.iterator();
        while (jsonValueIterator.hasNext()) {
            relationshipTypes.add(new RelationshipType(this, jsonValueIterator.next().getAsObject()));
        }
        return relationshipTypes;
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:Java-APIs    文件:OEClientReadOnly.java   
/**
 * Return all concept classes
 * @return - a collection containing all concept classes
 * @throws OEClientException - an error has occurred contacting the server
 */
public Collection<ConceptClass> getConceptClasses(int limit) throws OEClientException {
    logger.info("getConceptClasses entry");

    Map<String, String> queryParameters = new HashMap<String, String>();
    queryParameters.put("properties", "rdfs:label,rdfs:subClassOf");
    queryParameters.put("limit", Integer.toString(limit));
    Invocation.Builder invocationBuilder = getInvocationBuilder(getModelURL() + "/skos:Concept/meta:transitiveSubClass", queryParameters);

    Date startDate = new Date();
    logger.info("getConceptClasses making call  : {}", startDate.getTime());
    Response response = invocationBuilder.get();
    logger.info("getConceptClasses call complete: {}", startDate.getTime());

    logger.info("getConceptClasses - status: {}", response.getStatus());
    if (response.getStatus() == 200) {
        String stringResponse = response.readEntity(String.class);
        if (logger.isInfoEnabled()) logger.info("getConceptClasses: jsonResponse {}", stringResponse);
        JsonObject jsonResponse = JSON.parse(stringResponse);
        JsonArray jsonArray = jsonResponse.get("@graph").getAsArray();
        Collection<ConceptClass> conceptClasses = new HashSet<ConceptClass>();
        Iterator<JsonValue> jsonValueIterator = jsonArray.iterator();
        while (jsonValueIterator.hasNext()) {
            conceptClasses.add(new ConceptClass(this, jsonValueIterator.next().getAsObject()));
        }
        return conceptClasses;
    } else {
        throw new OEClientException(String.format("Error(%d) %s from server", response.getStatus(), response.getStatusInfo().toString()));
    }
}
项目:holon-jaxrs    文件:JaxrsClientRestClient.java   
@Override
public <T, R> ResponseEntity<T> invoke(RequestDefinition requestDefinition, HttpMethod method,
        RequestEntity<R> requestEntity, ResponseType<T> responseType, boolean onlySuccessfulStatusCode) {

    // invocation builder
    final Builder builder = configure(requestDefinition).request();
    // headers
    requestDefinition.getHeaders().forEach((n, v) -> builder.header(n, v));

    // invocation
    final javax.ws.rs.client.Invocation invocation = buildRequestEntity(requestEntity)
            .map(r -> builder.build(method.getMethodName(), r)).orElse(builder.build(method.getMethodName()));

    // invoke
    Response response = null;
    try {
        response = invocation.invoke();
    } catch (Exception e) {
        throw new HttpClientInvocationException(e);
    }

    if (response == null) {
        throw new HttpClientInvocationException("Invocation returned a null Response");
    }

    // check error status code
    if (onlySuccessfulStatusCode && !HttpStatus.isSuccessStatusCode(response.getStatus())) {
        throw new UnsuccessfulResponseException(new JaxrsRawResponseEntity(response));
    }

    return new JaxrsResponseEntity<>(response, responseType);
}
项目:sample-acmegifts    文件:UserResourceTest.java   
public Response processRequest(String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目:sample-acmegifts    文件:NotificationTest.java   
public Response processRequest(String url, String method, String payload)
    throws GeneralSecurityException, IOException {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  builder.header(
      HttpHeaders.AUTHORIZATION,
      "Bearer "
          + new JWTVerifier()
              .createJWT("fred", new HashSet<String>(Arrays.asList("orchestrator"))));
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目:sample-acmegifts    文件:JWTVerifier.java   
private Response processRequest(String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目:sample-acmegifts    文件:AuthResourceTest.java   
public static Response processRequest(
    String url, String method, String payload, String authHeader) {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  if (payload != null) {
    builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  }
  if (authHeader != null) {
    builder.header(HttpHeaders.AUTHORIZATION, authHeader);
  }
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目:sample-acmegifts    文件:NotificationTest.java   
public Response processRequest(String url, String method, String payload)
    throws GeneralSecurityException, IOException {
  Client client = ClientBuilder.newClient();
  WebTarget target = client.target(url);
  Builder builder = target.request();
  builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
  builder.header(
      HttpHeaders.AUTHORIZATION,
      "Bearer "
          + new JWTVerifier()
              .createJWT("fred", new HashSet<String>(Arrays.asList("orchestrator"))));
  return (payload != null)
      ? builder.build(method, Entity.json(payload)).invoke()
      : builder.build(method).invoke();
}
项目:soapbox-race-core    文件:OpenFireRestApiCli.java   
private Builder getBuilder(String path) {
    Client client = ClientBuilder.newClient();
    WebTarget target = client.target(openFireAddress).path(path);
    Builder request = target.request(MediaType.APPLICATION_XML);
    request.header("Authorization", openFireToken);
    return request;
}
项目:soapbox-race-core    文件:OpenFireRestApiCli.java   
public int getTotalOnlineUsers() {
    Builder builder = getBuilder("system/statistics/sessions");
    SessionsCount sessionsCount = builder.get(SessionsCount.class);
    int clusterSessions = sessionsCount.getClusterSessions();
    if (clusterSessions > 1) {
        return clusterSessions - 1;
    }
    return 0;
}