Java Code Examples for com.sun.jersey.api.client.Client#addFilter()
The following examples show how to use
com.sun.jersey.api.client.Client#addFilter() .
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: MailgunServlet.java From java-docs-samples with Apache License 2.0 | 6 votes |
@SuppressWarnings("VariableDeclarationUsageDistance") private ClientResponse sendComplexMessage(String recipient) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY)); FormDataMultiPart formData = new FormDataMultiPart(); formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">"); formData.field("to", recipient); formData.field("subject", "Complex Mailgun Example"); formData.field("html", "<html>HTML <strong>content</strong></html>"); ClassLoader classLoader = getClass().getClassLoader(); File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile()); formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE)); WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages"); return webResource .type(MediaType.MULTIPART_FORM_DATA_TYPE) .post(ClientResponse.class, formData); }
Example 2
Source File: MailgunServlet.java From java-docs-samples with Apache License 2.0 | 6 votes |
private ClientResponse sendComplexMessage(String recipient) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter("api", MAILGUN_API_KEY)); WebResource webResource = client.resource("https://api.mailgun.net/v3/" + MAILGUN_DOMAIN_NAME + "/messages"); FormDataMultiPart formData = new FormDataMultiPart(); formData.field("from", "Mailgun User <mailgun@" + MAILGUN_DOMAIN_NAME + ">"); formData.field("to", recipient); formData.field("subject", "Complex Mailgun Example"); formData.field("html", "<html>HTML <strong>content</strong></html>"); ClassLoader classLoader = getClass().getClassLoader(); File txtFile = new File(classLoader.getResource("example-attachment.txt").getFile()); formData.bodyPart(new FileDataBodyPart("attachment", txtFile, MediaType.TEXT_PLAIN_TYPE)); return webResource .type(MediaType.MULTIPART_FORM_DATA_TYPE) .post(ClientResponse.class, formData); }
Example 3
Source File: MailgunService.java From teammates with GNU General Public License v2.0 | 6 votes |
@Override public EmailSendingStatus sendEmail(EmailWrapper wrapper) { try (FormDataMultiPart email = parseToEmail(wrapper)) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter("api", Config.MAILGUN_APIKEY)); WebResource webResource = client.resource("https://api.mailgun.net/v3/" + Config.MAILGUN_DOMAINNAME + "/messages"); ClientResponse response = webResource.type(MediaType.MULTIPART_FORM_DATA_TYPE) .post(ClientResponse.class, email); return new EmailSendingStatus(response.getStatus(), response.getStatusInfo().getReasonPhrase()); } catch (IOException e) { log.warning("Could not clean up resources after sending email: " + TeammatesException.toStringWithStackTrace(e)); return new EmailSendingStatus(HttpStatus.SC_OK, e.getMessage()); } }
Example 4
Source File: UserRoleDelegate.java From pentaho-kettle with Apache License 2.0 | 6 votes |
private void initManaged( PurRepositoryMeta repositoryMeta, IUser userInfo ) throws JSONException { String baseUrl = repositoryMeta.getRepositoryLocation().getUrl(); String webService = baseUrl + ( baseUrl.endsWith( "/" ) ? "" : "/" ) + "api/system/authentication-provider"; HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter( userInfo.getLogin(), userInfo.getPassword() ); Client client = new Client(); client.addFilter( authFilter ); WebResource.Builder resource = client.resource( webService ).accept( MediaType.APPLICATION_JSON_TYPE ); /** * if set, _trust_user_ needs to be considered. See other places in pur-plugin's: * * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/PurRepositoryConnector.java#L97-L101 * @link https://github.com/pentaho/pentaho-kettle/blob/8.0.0.0-R/plugins/pur/core/src/main/java/org/pentaho/di/repository/pur/WebServiceManager.java#L130-L133 */ if ( StringUtils.isNotBlank( System.getProperty( "pentaho.repository.client.attemptTrust" ) ) ) { resource = resource.header( TRUST_USER, userInfo.getLogin() ); } String response = resource.get( String.class ); String provider = new JSONObject( response ).getString( "authenticationType" ); managed = "jackrabbit".equals( provider ); }
Example 5
Source File: ApiClient.java From forge-api-java-client with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: HmacClientFilterTest.java From jersey-hmac-auth with Apache License 2.0 | 5 votes |
@Test public void validateSignatureWhenContentIsPojo() throws Exception { Connection connection = null; try { // Start the server RequestConfiguration requestConfiguration = RequestConfiguration.builder().withApiKeyQueryParamName("passkey") .withSignatureHttpHeader("duck-duck-signature-header") .withTimestampHttpHeader("duck-duck-timestamp-header") .withVersionHttpHeader("duck-duck-version-header") .build(); ValidatingHttpServer server = new SignatureValidatingHttpServer(port, secretKey, requestConfiguration); connection = server.connect(); // Create a client with the filter that is under test Client client = createClient(); client.addFilter(new HmacClientFilter(apiKey, secretKey, client.getMessageBodyWorkers(), requestConfiguration)); client.addFilter(new GZIPContentEncodingFilter(true)); // Send a pizza in the request body Pizza pizza = new Pizza(); pizza.setTopping("olive"); client.resource(server.getUri()) .type(MediaType.APPLICATION_JSON_TYPE) .put(pizza); } finally { if (connection != null) { connection.close(); } } }
Example 7
Source File: HopServer.java From hop with Apache License 2.0 | 5 votes |
/** * 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 8
Source File: Carte.java From pentaho-kettle with Apache License 2.0 | 5 votes |
/** * 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 ); } }
Example 9
Source File: ApiClient.java From qbit-microservices-examples with Apache License 2.0 | 5 votes |
/** * Get an existing client or create a new client to handle HTTP request. */ private Client getClient() { if(!hostMap.containsKey(basePath)) { Client client = Client.create(); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); } return hostMap.get(basePath); }
Example 10
Source File: ApiClient.java From netphony-topology with Apache License 2.0 | 5 votes |
/** * Get an existing client or create a new client to handle HTTP request. */ private Client getClient() { if(!hostMap.containsKey(basePath)) { Client client = Client.create(); if (debugging) client.addFilter(new LoggingFilter()); hostMap.put(basePath, client); } return hostMap.get(basePath); }
Example 11
Source File: JCRRepositoryTest.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 5 votes |
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 12
Source File: RestClientFactory.java From qaf with MIT License | 5 votes |
public final Client getClient() { Client client = createClient(); client.addFilter(new ConnectionListenerFilter(getRequestListener())); client.addFilter(getRequestListener()); client.addFilter(getRequestTracker()); return client; }
Example 13
Source File: JAXRSTester.java From ice with Eclipse Public License 1.0 | 5 votes |
/** * This operation checks posting updates to the server. */ @Test public void checkPostingUpdates() { // Create the json message String message = "post={\"item_id\":\"5\", " + "\"client_key\":\"1234567890ABCDEFGHIJ1234567890ABCDEFGHIJ\", " + "\"posts\":[{\"type\":\"UPDATER_STARTED\",\"message\":\"\"}," + "{\"type\":\"FILE_MODIFIED\"," + "\"message\":\"/tmp/file\"}]}"; // Create the client Client jaxRSClient = Client.create(); // Create the filter that will let us login with basic HTTP // authentication. final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter("ice", "veryice"); jaxRSClient.addFilter(authFilter); // Add a filter for logging. This filter will automatically dump stuff // to stdout. jaxRSClient.addFilter(new LoggingFilter()); // Get the handle to the server as a web resource WebResource webResource = jaxRSClient .resource("http://localhost:8080/ice"); // Get the normal response from the server to make sure we can connect // to it webResource.accept(MediaType.TEXT_PLAIN).header("X-FOO", "BAR") .get(String.class); // Try posting something to the update page webResource.path("update").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(String.class, message); return; }
Example 14
Source File: AtlasBaseClient.java From atlas with Apache License 2.0 | 5 votes |
void initializeState(Configuration configuration, String[] baseUrls, UserGroupInformation ugi, String doAsUser) { this.configuration = configuration; Client client = getClient(configuration, ugi, doAsUser); if ((!AuthenticationUtil.isKerberosAuthenticationEnabled()) && basicAuthUser != null && basicAuthPassword != null) { final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(basicAuthUser, basicAuthPassword); client.addFilter(authFilter); } String activeServiceUrl = determineActiveServiceURL(baseUrls, client); atlasClientContext = new AtlasClientContext(baseUrls, client, ugi, doAsUser); service = client.resource(UriBuilder.fromUri(activeServiceUrl).build()); }
Example 15
Source File: ApiClient.java From openapi-generator with Apache License 2.0 | 5 votes |
/** * 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; }
Example 16
Source File: TimelineClientImpl.java From big-c with Apache License 2.0 | 4 votes |
protected void serviceInit(Configuration conf) throws Exception { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); UserGroupInformation realUgi = ugi.getRealUser(); if (realUgi != null) { authUgi = realUgi; doAsUser = ugi.getShortUserName(); } else { authUgi = ugi; doAsUser = null; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(YarnJacksonJaxbJsonProvider.class); connConfigurator = newConnConfigurator(conf); if (UserGroupInformation.isSecurityEnabled()) { authenticator = new KerberosDelegationTokenAuthenticator(); } else { authenticator = new PseudoDelegationTokenAuthenticator(); } authenticator.setConnectionConfigurator(connConfigurator); token = new DelegationTokenAuthenticatedURL.Token(); connectionRetry = new TimelineClientConnectionRetry(conf); client = new Client(new URLConnectionClientHandler( new TimelineURLConnectionFactory()), cc); TimelineJerseyRetryFilter retryFilter = new TimelineJerseyRetryFilter(); client.addFilter(retryFilter); if (YarnConfiguration.useHttps(conf)) { resURI = URI .create(JOINER.join("https://", conf.get( YarnConfiguration.TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS), RESOURCE_URI_STR)); } else { resURI = URI.create(JOINER.join("http://", conf.get( YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_ADDRESS), RESOURCE_URI_STR)); } LOG.info("Timeline service address: " + resURI); super.serviceInit(conf); }
Example 17
Source File: TimelineClientImpl.java From hadoop with Apache License 2.0 | 4 votes |
protected void serviceInit(Configuration conf) throws Exception { UserGroupInformation ugi = UserGroupInformation.getCurrentUser(); UserGroupInformation realUgi = ugi.getRealUser(); if (realUgi != null) { authUgi = realUgi; doAsUser = ugi.getShortUserName(); } else { authUgi = ugi; doAsUser = null; } ClientConfig cc = new DefaultClientConfig(); cc.getClasses().add(YarnJacksonJaxbJsonProvider.class); connConfigurator = newConnConfigurator(conf); if (UserGroupInformation.isSecurityEnabled()) { authenticator = new KerberosDelegationTokenAuthenticator(); } else { authenticator = new PseudoDelegationTokenAuthenticator(); } authenticator.setConnectionConfigurator(connConfigurator); token = new DelegationTokenAuthenticatedURL.Token(); connectionRetry = new TimelineClientConnectionRetry(conf); client = new Client(new URLConnectionClientHandler( new TimelineURLConnectionFactory()), cc); TimelineJerseyRetryFilter retryFilter = new TimelineJerseyRetryFilter(); client.addFilter(retryFilter); if (YarnConfiguration.useHttps(conf)) { resURI = URI .create(JOINER.join("https://", conf.get( YarnConfiguration.TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_HTTPS_ADDRESS), RESOURCE_URI_STR)); } else { resURI = URI.create(JOINER.join("http://", conf.get( YarnConfiguration.TIMELINE_SERVICE_WEBAPP_ADDRESS, YarnConfiguration.DEFAULT_TIMELINE_SERVICE_WEBAPP_ADDRESS), RESOURCE_URI_STR)); } LOG.info("Timeline service address: " + resURI); super.serviceInit(conf); }
Example 18
Source File: PizzaClient.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private static Client createClient(String apiKey, String secretKey) { Client client = Client.create(); client.addFilter(new HmacClientFilter(apiKey, secretKey, client.getMessageBodyWorkers())); return client; }
Example 19
Source File: HurlCli.java From jersey-hmac-auth with Apache License 2.0 | 4 votes |
private static Client createClient(String apiKey, String secretKey, RequestConfiguration requestConfiguration) { Client client = Client.create(); client.addFilter(new HmacClientFilter(apiKey, secretKey, client.getMessageBodyWorkers(), requestConfiguration)); return client; }
Example 20
Source File: WebServiceClient.java From nextreports-server with Apache License 2.0 | 4 votes |
protected Client createJerseyClient() { ClientConfig config = new DefaultClientConfig(); // DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); config.getClasses().add(XStreamXmlProvider.class); // ApacheHttpClient client = ApacheHttpClient.create(config); if (server.startsWith("https")) { log("* Use https protocol"); try { initSSL(config); } catch (Exception ex) { if (tm != null) { try { installCertificates(); initSSL(config); } catch (Exception e) { throw new RuntimeException(e); } } else { throw new RuntimeException(ex); } } } Client client = Client.create(config); if (isDebug()) { client.addFilter(new LoggingFilter()); } if ((username != null) && (password != null)) { // client.addFilter(new HTTPBasicAuthFilter(username, password)); String encodedPassword = password; if (passwordEncoder != null) { encodedPassword = passwordEncoder.encode(password); } client.addFilter(new HttpBasicAuthenticationFilter(username, encodedPassword)); // config.getState().setCredentials(null, null, -1, username, encodedPassword); } if (timeout != UNDEFINED) { client.setConnectTimeout(timeout); } return client; }