类com.sun.jersey.api.client.config.DefaultClientConfig源码实例Demo

下面列出了怎么用com.sun.jersey.api.client.config.DefaultClientConfig的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: usergrid   文件: RunnerCoordinator.java
/**
 * Starts the tests on given runners and puts them into RUNNING state, if indeed they were READY.
 *
 * @param runners   Runners that are going to run the tests
 * @param runNumber Run number of upcoming tests, this should be get from Run storage
 * @return          Map of resulting states of <code>runners</code>, after the operation
 */
public Map<Runner, State> start( Collection<Runner> runners, int runNumber ) {
    Map<Runner, State> states = new HashMap<Runner, State>( runners.size() );
    for( Runner runner: runners ) {
        lastRunNumbers.put( runner, runNumber );
        trustRunner( runner.getUrl() );
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create( clientConfig );
        LOG.info( "Runner to start: {}", runner.getUrl() );
        WebResource resource = client.resource( runner.getUrl() ).path( Runner.START_POST );
        BaseResult response = resource.type( MediaType.APPLICATION_JSON ).post( BaseResult.class );
        if( ! response.getStatus() ) {
            LOG.warn( "Tests at runner {} could not be started.", runner.getUrl() );
            LOG.warn( response.getMessage() );
            states.put( runner, null );
        }
        else {
            states.put( runner, response.getState() );
        }
    }
    return states;
}
 
源代码2 项目: pentaho-kettle   文件: RepositoryCleanupUtil.java
/**
 * Use REST API to authenticate provided credentials
 * 
 * @throws Exception
 */
@VisibleForTesting
void authenticateLoginCredentials() throws Exception {
  KettleClientEnvironment.init();

  if ( client == null ) {
    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    client = Client.create( clientConfig );
    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );
  }

  WebResource resource = client.resource( url + AUTHENTICATION + AdministerSecurityAction.NAME );
  String response = resource.get( String.class );

  if ( !response.equals( "true" ) ) {
    throw new Exception( Messages.getInstance().getString( "REPOSITORY_CLEANUP_UTIL.ERROR_0012.ACCESS_DENIED" ) );
  }
}
 
源代码3 项目: usergrid   文件: RunnerCoordinator.java
/**
 * Resets the given runners and puts them into READY state, if indeed they were STOPPED.
 *
 * @param runners   Runners to reset
 * @return          Map of resulting states of <code>runners</code>, after the operation
 */
public Map<Runner, State> reset( Collection<Runner> runners ) {
    Map<Runner, State> states = new HashMap<Runner, State>( runners.size() );
    for( Runner runner: runners ) {
        trustRunner( runner.getUrl() );
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create( clientConfig );
        WebResource resource = client.resource( runner.getUrl() ).path( Runner.RESET_POST );
        BaseResult response = resource.type( MediaType.APPLICATION_JSON ).post( BaseResult.class );
        if( ! response.getStatus() ) {
            LOG.warn( "Tests at runner {} could not be reset.", runner.getUrl() );
            LOG.warn( response.getMessage() );
            states.put( runner, null );
        }
        else {
            states.put( runner, response.getState() );
        }
    }
    return states;
}
 
源代码4 项目: hadoop   文件: TestRMHA.java
private void checkActiveRMWebServices() throws JSONException {

    // Validate web-service
    Client webServiceClient = Client.create(new DefaultClientConfig());
    InetSocketAddress rmWebappAddr =
        NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress());
    String webappURL =
        "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort();
    WebResource webResource = webServiceClient.resource(webappURL);
    String path = app.getApplicationId().toString();

    ClientResponse response =
        webResource.path("ws").path("v1").path("cluster").path("apps")
          .path(path).accept(MediaType.APPLICATION_JSON)
          .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject appJson = json.getJSONObject("app");
    assertEquals("ACCEPTED", appJson.getString("state"));
    // Other stuff is verified in the regular web-services related tests
  }
 
源代码5 项目: big-c   文件: TestRMHA.java
private void checkActiveRMWebServices() throws JSONException {

    // Validate web-service
    Client webServiceClient = Client.create(new DefaultClientConfig());
    InetSocketAddress rmWebappAddr =
        NetUtils.getConnectAddress(rm.getWebapp().getListenerAddress());
    String webappURL =
        "http://" + rmWebappAddr.getHostName() + ":" + rmWebappAddr.getPort();
    WebResource webResource = webServiceClient.resource(webappURL);
    String path = app.getApplicationId().toString();

    ClientResponse response =
        webResource.path("ws").path("v1").path("cluster").path("apps")
          .path(path).accept(MediaType.APPLICATION_JSON)
          .get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);

    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject appJson = json.getJSONObject("app");
    assertEquals("ACCEPTED", appJson.getString("state"));
    // Other stuff is verified in the regular web-services related tests
  }
 
源代码6 项目: forge-api-java-client   文件: ApiClient.java
/**
 * Build the Client used to make HTTP requests with the latest settings,
 * i.e. objectMapper and debugging.
 * TODO: better to use the Builder Pattern?
 */
public ApiClient rebuildHttpClient() {
  // Add the JSON serialization support to Jersey
  JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
  DefaultClientConfig conf = new DefaultClientConfig();
  conf.getSingletons().add(jsonProvider);
  Client client = Client.create(conf);
  if (debugging) {
    client.addFilter(new LoggingFilter());
  }
  
  //to solve the issue of GET:metadata/:guid with accepted encodeing is 'gzip' 
  //in the past, when clients use gzip header, actually it doesn't trigger a gzip encoding... So everything is fine 
  //After the release, the content is return in gzip, while the sdk doesn't handle it correctly
  client.addFilter(new GZIPContentEncodingFilter(false));

  this.httpClient = client;
  return this;
}
 
源代码7 项目: Processor   文件: Application.java
/**
 * Initializes root resource classes and provider singletons
 * @param servletConfig
 */
public Application(@Context ServletConfig servletConfig)
{
    this(
        servletConfig.getServletContext().getInitParameter(A.dataset.getURI()) != null ? getDataset(servletConfig.getServletContext().getInitParameter(A.dataset.getURI()), null) : null,
        servletConfig.getServletContext().getInitParameter(SD.endpoint.getURI()) != null ? servletConfig.getServletContext().getInitParameter(SD.endpoint.getURI()) : null,
        servletConfig.getServletContext().getInitParameter(A.graphStore.getURI()) != null ? servletConfig.getServletContext().getInitParameter(A.graphStore.getURI()) : null,
        servletConfig.getServletContext().getInitParameter(A.quadStore.getURI()) != null ? servletConfig.getServletContext().getInitParameter(A.quadStore.getURI()) : null,
        servletConfig.getServletContext().getInitParameter(org.apache.jena.sparql.engine.http.Service.queryAuthUser.getSymbol()) != null ? servletConfig.getServletContext().getInitParameter(org.apache.jena.sparql.engine.http.Service.queryAuthUser.getSymbol()) : null,
        servletConfig.getServletContext().getInitParameter(org.apache.jena.sparql.engine.http.Service.queryAuthPwd.getSymbol()) != null ? servletConfig.getServletContext().getInitParameter(org.apache.jena.sparql.engine.http.Service.queryAuthPwd.getSymbol()) : null,
        new MediaTypes(), getClient(new DefaultClientConfig()),
        servletConfig.getServletContext().getInitParameter(A.maxGetRequestSize.getURI()) != null ? Integer.parseInt(servletConfig.getServletContext().getInitParameter(A.maxGetRequestSize.getURI())) : null,
        servletConfig.getServletContext().getInitParameter(A.preemptiveAuth.getURI()) != null ? Boolean.parseBoolean(servletConfig.getServletContext().getInitParameter(A.preemptiveAuth.getURI())) : false,
        new LocationMapper(servletConfig.getServletContext().getInitParameter(AP.locationMapping.getURI()) != null ? servletConfig.getServletContext().getInitParameter(AP.locationMapping.getURI()) : null),
        servletConfig.getServletContext().getInitParameter(LDT.ontology.getURI()) != null ? servletConfig.getServletContext().getInitParameter(LDT.ontology.getURI()) : null,
        servletConfig.getServletContext().getInitParameter(AP.sitemapRules.getURI()) != null ? servletConfig.getServletContext().getInitParameter(AP.sitemapRules.getURI()) : null,
        servletConfig.getServletContext().getInitParameter(AP.cacheSitemap.getURI()) != null ? Boolean.valueOf(servletConfig.getServletContext().getInitParameter(AP.cacheSitemap.getURI())) : true
    );
}
 
源代码8 项目: eagle   文件: EagleServiceBaseClient.java
public EagleServiceBaseClient(String host, int port, String basePath, String username, String password) {
    this.host = host;
    this.port = port;
    this.basePath = basePath;
    this.baseEndpoint = buildBathPath().toString();
    this.username = username;
    this.password = password;

    ClientConfig cc = new DefaultClientConfig();
    cc.getProperties().put(DefaultClientConfig.PROPERTY_CONNECT_TIMEOUT, 60 * 1000);
    cc.getProperties().put(DefaultClientConfig.PROPERTY_READ_TIMEOUT, 60 * 1000);
    cc.getClasses().add(JacksonJsonProvider.class);
    cc.getProperties().put(URLConnectionClientHandler.PROPERTY_HTTP_URL_CONNECTION_SET_METHOD_WORKAROUND, true);
    this.client = Client.create(cc);
    client.addFilter(new com.sun.jersey.api.client.filter.GZIPContentEncodingFilter());
}
 
源代码9 项目: osiris   文件: RestRequestSender.java
public void uploadVoid(String url, File f, String formName, Headers... headers) {

		FormDataMultiPart form = new FormDataMultiPart().field(formName, f, MediaType.MULTIPART_FORM_DATA_TYPE);
		String urlCreated = createURI(url);
		ClientConfig cc = new DefaultClientConfig();
		cc.getClasses().add(MultiPartWriter.class);
		WebResource webResource = Client.create(cc).resource(urlCreated);

		Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA);

		for (Headers h : headers) {
			builder.header(h.getKey(), h.getValue());
		}

		builder.post(form);
	}
 
源代码10 项目: osiris   文件: RestRequestSender.java
public <T> ClientResponse<T> upload(String url, File f, Class<T> expectedResponse, Headers... headers) {
	
	@SuppressWarnings("resource")
	FormDataMultiPart form = new FormDataMultiPart();
	form.bodyPart(new FileDataBodyPart("file", f, MediaType.APPLICATION_OCTET_STREAM_TYPE));

	String urlCreated = createURI(url);
	ClientConfig cc = new DefaultClientConfig();
	cc.getClasses().add(MultiPartWriter.class);
	WebResource webResource = Client.create(cc).resource(urlCreated);
	Builder builder = webResource.type(MULTIPART_MEDIA).accept(MEDIA).accept("text/plain");
	for (Headers h : headers) {
		builder.header(h.getKey(), h.getValue());
	}

	com.sun.jersey.api.client.ClientResponse clienteResponse = null;

	clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, form);

	return new ClientResponse<T>(clienteResponse, expectedResponse);
}
 
源代码11 项目: osiris   文件: RestRequestSender.java
public ClientResponse<File> uploadNoMultipart(String url, File f, Headers... headers) throws FileNotFoundException {

		InputStream is = new FileInputStream(f);

		String urlCreated = createURI(url);
		ClientConfig cc = new DefaultClientConfig();
		cc.getClasses().add(MultiPartWriter.class);
		WebResource webResource = Client.create(cc).resource(urlCreated);
		Builder builder = webResource.type(MediaType.APPLICATION_OCTET_STREAM).accept(MEDIA).accept("text/plain");

		String sContentDisposition = "attachment; filename=\"" + f.getName() + "\"";
		builder.header("Content-Disposition", sContentDisposition);

		for (Headers h : headers) {
			builder.header(h.getKey(), h.getValue());
		}

		com.sun.jersey.api.client.ClientResponse clienteResponse = null;

		clienteResponse = builder.post(com.sun.jersey.api.client.ClientResponse.class, is);

		return new ClientResponse<File>(clienteResponse, File.class);
	}
 
源代码12 项目: docker-java   文件: DockerClient.java
private DockerClient(Config config) {
	restEndpointUrl = config.url + "/v" + config.version;
	ClientConfig clientConfig = new DefaultClientConfig();
	//clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

	SchemeRegistry schemeRegistry = new SchemeRegistry();
	schemeRegistry.register(new Scheme("http", config.url.getPort(), PlainSocketFactory.getSocketFactory()));
	schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

	PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
	// Increase max total connection
	cm.setMaxTotal(1000);
	// Increase default max connection per route
	cm.setDefaultMaxPerRoute(1000);

	HttpClient httpClient = new DefaultHttpClient(cm);
	client = new ApacheHttpClient4(new ApacheHttpClient4Handler(httpClient, null, false), clientConfig);

	client.setReadTimeout(10000);
	//Experimental support for unix sockets:
	//client = new UnixSocketClient(clientConfig);

	client.addFilter(new JsonClientFilter());
	client.addFilter(new LoggingFilter());
}
 
源代码13 项目: curator   文件: TestStringsWithJersey.java
@Test
public void     testEmptyServiceNames()
{
    ClientConfig    config = new DefaultClientConfig()
    {
        @Override
        public Set<Object> getSingletons()
        {
            Set<Object>     singletons = Sets.newHashSet();
            singletons.add(context);
            singletons.add(serviceNamesMarshaller);
            singletons.add(serviceInstanceMarshaller);
            singletons.add(serviceInstancesMarshaller);
            return singletons;
        }
    };
    Client          client = Client.create(config);
    WebResource     resource = client.resource("http://localhost:" + port);
    ServiceNames names = resource.path("/v1/service").get(ServiceNames.class);
    Assert.assertEquals(names.getNames(), Lists.<String>newArrayList());
}
 
源代码14 项目: roboconf-platform   文件: WsClient.java
/**
 * Constructor.
 * @param rootUrl the root URL (example: http://192.168.1.18:9007/dm/)
 */
public WsClient( String rootUrl ) {

	ClientConfig cc = new DefaultClientConfig();
	cc.getClasses().add( JacksonJsonProvider.class );
	cc.getClasses().add( ObjectMapperProvider.class );

	this.client = Client.create( cc );
	this.client.setFollowRedirects( true );

	WebResource resource = this.client.resource( rootUrl );
	this.applicationDelegate = new ApplicationWsDelegate( resource, this );
	this.managementDelegate = new ManagementWsDelegate( resource, this );
	this.debugDelegate = new DebugWsDelegate( resource, this );
	this.targetWsDelegate = new TargetWsDelegate( resource, this );
	this.schedulerDelegate = new SchedulerWsDelegate( resource, this );
	this.preferencesWsDelegate = new PreferencesWsDelegate( resource, this );
	this.authenticationWsDelegate = new AuthenticationWsDelegate( resource, this );
}
 
源代码15 项目: usergrid   文件: RunnerCoordinator.java
/**
 * Gets the run State of all given runners as a map.
 * <p>
 * <ul>
 *     <li>Key of map is the runner</li>
 *     <li>Value field is the state of a runner, or null if state could not be retrieved</li>
 * </ul>
 *
 * @param runners    Runners to get states
 * @return           Map of all Runner, State pairs
 */
public Map<Runner, State> getStates( Collection<Runner> runners ) {
    Map<Runner, State> states = new HashMap<Runner, State>( runners.size() );
    for( Runner runner: runners ) {
        trustRunner( runner.getUrl() );
        DefaultClientConfig clientConfig = new DefaultClientConfig();
        Client client = Client.create( clientConfig );
        LOG.info( "Runner to get state: {}", runner.getUrl() );
        WebResource resource = client.resource( runner.getUrl() ).path( Runner.STATUS_GET );
        BaseResult response = resource.type( MediaType.APPLICATION_JSON ).get( BaseResult.class );
        if( ! response.getStatus() ) {
            LOG.warn( "Could not get the state of Runner at {}", runner.getUrl() );
            LOG.warn( response.getMessage() );
            states.put( runner, null );
        }
        else {
            states.put( runner, response.getState() );
        }
    }
    return states;
}
 
源代码16 项目: maven-framework-project   文件: UserInfoClient.java
public static void main(String[] args) {

		String name = "Pavithra";
		int age = 25;

		ClientConfig config = new DefaultClientConfig();
		Client client = Client.create(config);
		WebResource resource = client.resource(BASE_URI);

		WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
		System.out.println("Client Response \n"
				+ getClientResponse(nameResource));
		System.out.println("Response \n" + getResponse(nameResource) + "\n\n");

		WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
		System.out.println("Client Response \n"
				+ getClientResponse(ageResource));
		System.out.println("Response \n" + getResponse(ageResource));
	}
 
源代码17 项目: cloudbreak   文件: YarnHttpClient.java
@Override
public void validateApiEndpoint() throws YarnClientException, MalformedURLException {
    YarnEndpoint dashEndpoint = new YarnEndpoint(apiEndpoint, YarnResourceConstants.APPLICATIONS_PATH);

    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    WebResource webResource = client.resource(dashEndpoint.getFullEndpointUrl().toString());
    ClientResponse response = webResource.accept("application/json").type("application/json").get(ClientResponse.class);

    // Validate HTTP 200 status code
    if (response.getStatus() != YarnResourceConstants.HTTP_SUCCESS) {
        String msg = String.format("Received %d status code from url %s, reason: %s",
                response.getStatus(),
                dashEndpoint.getFullEndpointUrl().toString(),
                response.getEntity(String.class));
        LOGGER.debug(msg);
        throw new YarnClientException(msg);
    }
}
 
源代码18 项目: cloudbreak   文件: YarnHttpClient.java
@Override
public void validateApiEndpoint() throws CloudbreakOrchestratorFailedException, MalformedURLException {
    YarnEndpoint dashEndpoint = new YarnEndpoint(
            apiEndpoint,
            YarnResourceConstants.APPLICATIONS_PATH
            );

    ClientConfig clientConfig = new DefaultClientConfig();
    Client client = Client.create(clientConfig);

    WebResource webResource = client.resource(dashEndpoint.getFullEndpointUrl().toString());
    ClientResponse response = webResource.accept("application/json").type("application/json").get(ClientResponse.class);

    // Validate HTTP 200 status code
    if (response.getStatus() != YarnResourceConstants.HTTP_SUCCESS) {
        String msg = String.format("Received %d status code from url %s, reason: %s",
                response.getStatus(),
                dashEndpoint.getFullEndpointUrl().toString(),
                response.getEntity(String.class));
        LOGGER.debug(msg);
        throw new CloudbreakOrchestratorFailedException(msg);
    }
}
 
源代码19 项目: pentaho-reporting   文件: JCRSolutionFileModel.java
public JCRSolutionFileModel( final String url,
                             final String username,
                             final String password,
                             final int timeout ) {
  if ( url == null ) {
    throw new NullPointerException();
  }
  this.url = url;
  descriptionEntries = new HashMap<FileName, String>();

  final ClientConfig config = new DefaultClientConfig();
  config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true );
  config.getProperties().put( ClientConfig.PROPERTY_READ_TIMEOUT, timeout );
  this.client = Client.create( config );
  this.client.addFilter( new CookiesHandlerFilter() ); // must be inserted before HTTPBasicAuthFilter
  this.client.addFilter( new HTTPBasicAuthFilter( username, password ) );
  this.majorVersion = "999";
  this.minorVersion = "999";
  this.releaseVersion = "999";
  this.buildVersion = "999";
  this.milestoneVersion = "999";
  this.loadTreePartially = Boolean.parseBoolean( PARTIAL_LOADING_ENABLED );
}
 
源代码20 项目: occurrence   文件: ApiClientConfiguration.java
/**
 * @return a new jersey client using a multithreaded http client
 */
public WebResource newApiClient() {
  ClientConfig cc = new DefaultClientConfig();
  cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
  cc.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, timeout);
  cc.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, timeout);
  cc.getClasses().add(JacksonJsonProvider.class);
  // use custom configured object mapper ignoring unknown properties
  cc.getClasses().add(ObjectMapperContextResolver.class);

  HttpClient http = HttpUtil.newMultithreadedClient(timeout, maxConnections, maxConnections);
  ApacheHttpClient4Handler hch = new ApacheHttpClient4Handler(http, null, false);
  Client client = new ApacheHttpClient4(hch, cc);

  LOG.info("Connecting to GBIF API: {}", url);
  return client.resource(url);
}
 
源代码21 项目: tr069-simulator   文件: CPEClientSession.java
public static void main(String[] args) {
	ClientConfig 	config 			= new DefaultClientConfig();
	Client 			client 			= Client.create(config);
	WebResource 	service 		= client.resource(getBaseURI());
	JSONObject 		data 			= new JSONObject();
	JSONObject 		status 			= new JSONObject();		
	String			filefolder  	= "//dump//microcell//";
	CpeDBReader 	confdb 			= new CpeDBReader().readFromGetMessages(filefolder);
	CpeActions 		cpeAction 		= new CpeActions(confdb);	
	
	ArrayList<EventStruct> eventKeyList = new ArrayList<EventStruct>();
	EventStruct eventStruct = new EventStruct();
	eventStruct.setEventCode("1 BOOT");
	eventKeyList.add(eventStruct);
	CpeActions cpeactions = new CpeActions(confdb);
	Envelope evn = cpeactions.doInform(eventKeyList);
	
}
 
源代码22 项目: hop   文件: HopServer.java
/**
 * Checks that HopServer is running and if so, shuts down the HopServer server
 *
 * @param hostname
 * @param port
 * @param username
 * @param password
 * @throws ParseException
 * @throws HopServerCommandException
 */
@VisibleForTesting
static void callStopHopServerRestService( String hostname, String port, String username, String password )
  throws ParseException, HopServerCommandException {
  // get information about the remote connection
  try {
    HopClientEnvironment.init();

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    Client client = Client.create( clientConfig );

    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );

    // check if the user can access the hop server. Don't really need this call but may want to check it's output at
    // some point
    String contextURL = "http://" + hostname + ":" + port + "/hop";
    WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
    String response = resource.get( String.class );
    if ( response == null || !response.contains( "<serverstatus>" ) ) {
      throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoServerFound", hostname, ""
        + port ) );
    }

    // This is the call that matters
    resource = client.resource( contextURL + "/stopHopServer" );
    response = resource.get( String.class );
    if ( response == null || !response.contains( "Shutting Down" ) ) {
      throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoShutdown", hostname, ""
        + port ) );
    }
  } catch ( Exception e ) {
    throw new HopServerCommandException( BaseMessages.getString( PKG, "HopServer.Error.NoServerFound", hostname, ""
      + port ), e );
  }
}
 
源代码23 项目: ambari-metrics   文件: AggregatorWebServiceTest.java
public AggregatorWebServiceTest() {
    super(new WebAppDescriptor.Builder(
            "org.apache.hadoop.metrics2.host.aggregator")
            .contextPath("jersey-guice-filter")
            .servletPath("/")
            .clientConfig(new DefaultClientConfig(JacksonJaxbJsonProvider.class))
            .build());
}
 
源代码24 项目: jerseyoauth2   文件: BaseTest.java
@Before
public void setUp()
{
	ClientConfig cc = new DefaultClientConfig();
	restClient = Client.create(cc);
	authClient = new ClientManagerClient(restClient);
	clientEntity = registerClient();
}
 
源代码25 项目: openapi-generator   文件: ApiClient.java
/**
 * Build the Client used to make HTTP requests with the latest settings,
 * i.e. objectMapper and debugging.
 * TODO: better to use the Builder Pattern?
 * @return API client
 */
public ApiClient rebuildHttpClient() {
  // Add the JSON serialization support to Jersey
  JacksonJsonProvider jsonProvider = new JacksonJsonProvider(objectMapper);
  DefaultClientConfig conf = new DefaultClientConfig();
  conf.getSingletons().add(jsonProvider);
  Client client = Client.create(conf);
  client.addFilter(new GZIPContentEncodingFilter(false));
  if (debugging) {
    client.addFilter(new LoggingFilter());
  }
  this.httpClient = client;
  return this;
}
 
源代码26 项目: localization_nifi   文件: WebUtils.java
/**
 * A helper method for creating clients. The client will be created using
 * the given configuration and security context. Additionally, the client
 * will be automatically configured for JSON serialization/deserialization.
 *
 * @param config client configuration
 * @param ctx security context, which may be null for non-secure client
 * creation
 *
 * @return a Client instance
 */
private static Client createClientHelper(final ClientConfig config, final SSLContext ctx) {

    final ClientConfig finalConfig = (config == null) ? new DefaultClientConfig() : config;

    if (ctx != null && StringUtils.isBlank((String) finalConfig.getProperty(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES))) {

        // custom hostname verifier that checks subject alternative names against the hostname of the URI
        final HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname, final SSLSession ssls) {

                try {
                    for (final Certificate peerCertificate : ssls.getPeerCertificates()) {
                        if (peerCertificate instanceof X509Certificate) {
                            final X509Certificate x509Cert = (X509Certificate) peerCertificate;
                            final List<String> subjectAltNames = CertificateUtils.getSubjectAlternativeNames(x509Cert);
                            if (subjectAltNames.contains(hostname.toLowerCase())) {
                                return true;
                            }
                        }
                    }
                } catch (final SSLPeerUnverifiedException | CertificateParsingException ex) {
                    logger.warn("Hostname Verification encountered exception verifying hostname due to: " + ex, ex);
                }

                return false;
            }
        };

        finalConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx));
    }

    finalConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    finalConfig.getClasses().add(ObjectMapperResolver.class);

    // web client for restful request
    return Client.create(finalConfig);

}
 
源代码27 项目: localization_nifi   文件: YandexTranslate.java
@OnScheduled
public void onScheduled(final ProcessContext context) {
    final ClientConfig config = new DefaultClientConfig();
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    config.getClasses().add(ObjectMapperResolver.class);

    client = Client.create(config);
}
 
源代码28 项目: pentaho-kettle   文件: Carte.java
/**
 * Checks that Carte is running and if so, shuts down the Carte server
 *
 * @param hostname
 * @param port
 * @param username
 * @param password
 * @throws ParseException
 * @throws CarteCommandException
 */
@VisibleForTesting
static void callStopCarteRestService( String hostname, String port, String username, String password )
  throws ParseException, CarteCommandException {
  // get information about the remote connection
  try {
    KettleClientEnvironment.init();

    ClientConfig clientConfig = new DefaultClientConfig();
    clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
    Client client = Client.create( clientConfig );

    client.addFilter( new HTTPBasicAuthFilter( username, Encr.decryptPasswordOptionallyEncrypted( password ) ) );

    // check if the user can access the carte server. Don't really need this call but may want to check it's output at
    // some point
    String contextURL = "http://" + hostname + ":" + port + "/kettle";
    WebResource resource = client.resource( contextURL + "/status/?xml=Y" );
    String response = resource.get( String.class );
    if ( response == null || !response.contains( "<serverstatus>" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
          + port ) );
    }

    // This is the call that matters
    resource = client.resource( contextURL + "/stopCarte" );
    response = resource.get( String.class );
    if ( response == null || !response.contains( "Shutting Down" ) ) {
      throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoShutdown", hostname, ""
          + port ) );
    }
  } catch ( Exception e ) {
    throw new Carte.CarteCommandException( BaseMessages.getString( PKG, "Carte.Error.NoServerFound", hostname, ""
        + port ), e );
  }
}
 
源代码29 项目: tez   文件: TimelineReaderFactory.java
@Override
public Client getHttpClient() {
  ClientConfig config = new DefaultClientConfig(JSONRootElementProvider.App.class);
  HttpURLConnectionFactory urlFactory = new PseudoAuthenticatedURLConnectionFactory(connectionConf);
  Client httpClient = new Client(new URLConnectionClientHandler(urlFactory), config);
  return httpClient;
}
 
源代码30 项目: hadoop   文件: TestTimelineWebServices.java
public TestTimelineWebServices() {
  super(new WebAppDescriptor.Builder(
      "org.apache.hadoop.yarn.server.applicationhistoryservice.webapp")
      .contextListenerClass(GuiceServletConfig.class)
      .filterClass(com.google.inject.servlet.GuiceFilter.class)
      .contextPath("jersey-guice-filter")
      .servletPath("/")
      .clientConfig(
          new DefaultClientConfig(YarnJacksonJaxbJsonProvider.class))
      .build());
}