com.sun.jersey.api.client.config.DefaultClientConfig Java Examples

The following examples show how to use com.sun.jersey.api.client.config.DefaultClientConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RunnerCoordinator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: DockerClient.java    From docker-java with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #3
Source File: TestStringsWithJersey.java    From curator with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: TestRMHA.java    From big-c with Apache License 2.0 6 votes vote down vote up
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
  }
 
Example #5
Source File: WsClient.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 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 );
}
 
Example #6
Source File: RunnerCoordinator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #7
Source File: UserInfoClient.java    From maven-framework-project with MIT License 6 votes vote down vote up
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));
	}
 
Example #8
Source File: ApiClient.java    From forge-api-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #9
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #10
Source File: Application.java    From Processor with Apache License 2.0 6 votes vote down vote up
/**
 * 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
    );
}
 
Example #11
Source File: YarnHttpClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example #12
Source File: RestRequestSender.java    From osiris with Apache License 2.0 6 votes vote down vote up
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);
	}
 
Example #13
Source File: TestRMHA.java    From hadoop with Apache License 2.0 6 votes vote down vote up
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
  }
 
Example #14
Source File: RestRequestSender.java    From osiris with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #15
Source File: RepositoryCleanupUtil.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * 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" ) );
  }
}
 
Example #16
Source File: CPEClientSession.java    From tr069-simulator with MIT License 6 votes vote down vote up
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);
	
}
 
Example #17
Source File: EagleServiceBaseClient.java    From eagle with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #18
Source File: RestRequestSender.java    From osiris with Apache License 2.0 6 votes vote down vote up
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);
	}
 
Example #19
Source File: ApiClientConfiguration.java    From occurrence with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
}
 
Example #20
Source File: RunnerCoordinator.java    From usergrid with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: JCRSolutionFileModel.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
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 );
}
 
Example #22
Source File: RestRequestSender.java    From osiris with Apache License 2.0 5 votes vote down vote up
public SimpleClientResponse upload(String url, File f, String formName) {
	@SuppressWarnings("resource")
	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);
	webResource.type(MULTIPART_MEDIA).accept(MEDIA).post(form);
	return new SimpleClientResponse(com.sun.jersey.api.client.ClientResponse.Status.NO_CONTENT);
}
 
Example #23
Source File: PerformanceTest.java    From jerseyoauth2 with MIT License 5 votes vote down vote up
@BeforeClass
public static void classSetup()
{
	ClientConfig cc = new DefaultClientConfig();
	Client restClient = Client.create(cc);
	ClientManagerClient authClient = new ClientManagerClient(restClient);
	clientEntity = authClient.createClient("confidential");		
	
	String code = authClient.authorizeClient(clientEntity, "test1 test2").getCode();
	assertNotNull(code);
	restClient.setFollowRedirects(false);
	
	client = new ResourceClient(clientEntity);
	token = client.getAccessToken(code);
}
 
Example #24
Source File: HopServer.java    From hop with Apache License 2.0 5 votes vote down vote up
/**
 * 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 );
  }
}
 
Example #25
Source File: RestRequestSender.java    From osiris with Apache License 2.0 5 votes vote down vote up
public void uploadVoid(String url, File f, String formName) {

		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);
		webResource.type(MULTIPART_MEDIA).accept(MEDIA).post(form);
	}
 
Example #26
Source File: NiFiClient.java    From ranger with Apache License 2.0 5 votes vote down vote up
protected WebResource getWebResource() {
    final ClientConfig config = new DefaultClientConfig();
    if (sslContext != null) {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(hostnameVerifier, sslContext));
    }

    final Client client = Client.create(config);
    return client.resource(url);
}
 
Example #27
Source File: AbstractJettyTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
protected WebResource.Builder getRequestBuilder(String path) {
  assertNotNull("HTTP server must be started first", httpServer);
  ClientConfig config = new DefaultClientConfig();
  config.getClasses().add(GsonMessageBodyHandler.class);
  Client client = Client.create(config);
  // Disable redirects so we can unit test them.
  client.setFollowRedirects(false);
  return client.resource(makeUrl(path)).getRequestBuilder().accept(MediaType.APPLICATION_JSON);
}
 
Example #28
Source File: JCRRepositoryTest.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void testJCRRepository() throws FileSystemException {
    if ( GraphicsEnvironment.isHeadless() ) {
      return;
    }

    String url = "http://localhost:8080/pentaho";

    final ClientConfig config = new DefaultClientConfig();
    config.getProperties().put( ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true );
    Client client = Client.create( config );
    client.addFilter( new HTTPBasicAuthFilter( "joe", "password" ) );

    final WebResource resource = client.resource( url + "/api/repo/files/children?depth=-1&filter=*" );
    final RepositoryFileTreeDto tree =
      resource.path( "" ).accept( MediaType.APPLICATION_XML_TYPE ).get( RepositoryFileTreeDto.class );

    printDebugInfo( tree );

    final List<RepositoryFileTreeDto> children = tree.getChildren();
    for ( int i = 0; i < children.size(); i++ ) {
      final RepositoryFileTreeDto child = children.get( i );
      printDebugInfo( child );
    }

/*
    final FileSystemOptions fileSystemOptions = new FileSystemOptions();
    final DefaultFileSystemConfigBuilder configBuilder = new DefaultFileSystemConfigBuilder();
    configBuilder.setUserAuthenticator(fileSystemOptions, new StaticUserAuthenticator(url, "joe", "password"));
    FileObject fileObject = VFS.getManager().resolveFile(url, fileSystemOptions);

    System.out.println(fileObject);
    FileObject inventoryReport = fileObject.resolveFile("public/steel-wheels/reports/Inventory.prpt");
    System.out.println(inventoryReport);
    System.out.println(inventoryReport.exists());
    final FileContent content = inventoryReport.getContent();
    System.out.println(content.getAttribute("param-service-url"));
    */
  }
 
Example #29
Source File: ApiBetaTest.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostInvalidJson() throws Exception {
  replayAndStart();

  ClientConfig config = new DefaultClientConfig();
  Client client = Client.create(config);
  ClientResponse response = client.resource(makeUrl("/apibeta/createJob"))
      .accept(MediaType.APPLICATION_JSON)
      .entity("{this is bad json}", MediaType.APPLICATION_JSON)
      .post(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
 
Example #30
Source File: PublishRestUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Used for REST Jersey calls
 */
private void initRestService() {
  ClientConfig clientConfig = new DefaultClientConfig();
  clientConfig.getClasses().add( MultiPartWriter.class );
  clientConfig.getFeatures().put( JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE );
  client = Client.create( clientConfig );
  client.addFilter( new HTTPBasicAuthFilter( username, password ) );
}