/** * Sends an Activity to SCMActivity Plugin's REST api * @param activity ScmActivity object corresponding to commit found in push payload * @throws ScmSyncException on post failure */ private void jirasend(ScmActivity activity) throws ScmSyncException { // Setup Client Client client = Client.create(); WebResource webResource = client.resource(jiraRestUrl); client.addFilter(new HTTPBasicAuthFilter(jiraUser, jiraPassword)); // Post to SCMActivity ClientResponse clientResponse = webResource.type("application/json").post(ClientResponse.class, activity.toJson()); String result = clientResponse.getStatus() + " " + clientResponse.getEntity(String.class); logger.debug("Jira Send: \n\t" + activity.toString() + "\n\tResponse: " + result ); if (clientResponse.getStatus() == 201 ) { logger.info("OK " + activity.getChangeId()); } else { throw new ScmSyncException("Jira Rejected Activity because " + result + " " + activity.toString()); } }
private ClientResponse getClientResponse(Object st, String path) { String masterServer = "http://tinytank.lefrantguillaume.com/api/server/"; ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter("T0N1jjOQIDmA4cJnmiT6zHvExjoSLRnbqEJ6h2zWKXLtJ9N8ygVHvkP7Sy4kqrv", "lMhIq0tVVwIvPKSBg8p8YbPg0zcvihBPJW6hsEGUiS6byKjoZcymXQs5urequUo")); WebResource webResource = client.resource(masterServer + path); System.out.println("sending to data server : " + st); ClientResponse response = webResource .accept("application/json") .type("application/json") .post(ClientResponse.class, st); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } System.out.println("response from data server : " + response); return response; }
public int addJob(MsJob job, String username, String password) { Client client = Client.create(); HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password); client.addFilter(authFilter); WebResource webRes = client.resource(BASE_URI); // String data = "{\"projectId\":\"24\", \"dataDirectory\":\"test\", \"pipeline\":\"MACCOSS\", \"date\":\"2010-03-29\"}"; ClientResponse response = webRes.path("add").type("application/xml").accept("text/plain").post(ClientResponse.class, job); Status status = response.getClientResponseStatus(); if(status == Status.OK) { String jobId = response.getEntity(String.class); System.out.println(jobId); int idx = jobId.lastIndexOf("ID: "); return Integer.parseInt(jobId.substring(idx+4).trim()); } else { System.err.println(status.getStatusCode()+": "+status.getReasonPhrase()); System.err.println(response.getEntity(String.class)); return 0; } }
public void delete(int jobId, String username, String password) { Client client = Client.create(); HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password); client.addFilter(authFilter); WebResource webRes = client.resource(BASE_URI); ClientResponse response = webRes.path("delete/"+String.valueOf(jobId)).delete(ClientResponse.class); Status status = response.getClientResponseStatus(); if(status == Status.OK) { String resp = response.getEntity(String.class); System.out.println(resp); } else { System.err.println(status.getStatusCode()+": "+status.getReasonPhrase()); System.err.println(response.getEntity(String.class)); } }
/** * Fetches and configures a Web Resource to connect to eWAY * * @return A WebResource */ private WebResource getEwayWebResource() { ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter(APIKey, password)); if (this.debug) { client.addFilter(new LoggingFilter(System.out)); } // Set additional headers RapidClientFilter rapidFilter = new RapidClientFilter(); rapidFilter.setVersion(apiVersion); client.addFilter(rapidFilter); WebResource resource = client.resource(webUrl); return resource; }
/** * @param apiKey your Asana API key * @param connectionTimeout the connection timeout in MILLISECONDS * @param readTimeout the read timeout in MILLISECONDS */ public AbstractClient(String apiKey, int connectionTimeout, int readTimeout){ this.apiKey = apiKey; ClientConfig config = new DefaultClientConfig(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); JacksonJsonProvider provider = new JacksonJsonProvider(mapper); config.getSingletons().add(provider); //config.getClasses().add(JacksonJsonProvider.class); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter(apiKey, "")); client.setConnectTimeout(connectionTimeout); client.setReadTimeout(readTimeout); service = client.resource(UriBuilder.fromUri(BASE_URL).build()); }
public CPEClientSession (CpeActions cpeActions, String username, String passwd, String authtype) { this.cpeActions = cpeActions; this.authtype = authtype; this.username = username; this.passwd = passwd; String urlstr = ((ConfParameter)this.cpeActions.confdb.confs.get(this.cpeActions.confdb.props.getProperty("MgmtServer_URL"))).value; //"http://192.168.1.50:8085/ws?wsdl"; System.out.println("ACS MGMT URL -------> " + urlstr); service = ResourceAPI.getInstance().getResourceAPI(urlstr); if (username != null && passwd != null) { if (authtype.equalsIgnoreCase("digest")) { service.addFilter(new HTTPDigestAuthFilter(username, passwd)); } else { service.addFilter(new HTTPBasicAuthFilter(username, passwd)); } //System.out.println("==========================> " + username + " " + passwd); } //System.out.println(" 2nd time ==============> " + username + " " + passwd); }
/** * Returns jersey client to make any call to webservice * @return */ private Client getClient(boolean is_multipart) { if(m_client == null) { if(is_multipart) { ClientConfig config = new DefaultClientConfig(); config.getClasses().add(MultiPartWriter.class); m_client = Client.create(config); } else { m_client = new Client(); } if(!isTokenbasedAuth) { final HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(x_username, x_password); m_client.addFilter(authFilter); m_client.addFilter(new LoggingFilter()); } else { //TODO for token based authentication } } return m_client; }
/** * Use REST API to authenticate provided credentials * * @throws Exception */ private void authenticateLoginCredentials() throws Exception { 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, 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" ) ); } }
/** * Gets a client web resource builder for the base XOS REST API * with an optional additional URI. * * @param uri URI suffix to append to base URI * @return web resource builder */ public WebResource.Builder getClientBuilder(String uri) { Client client = Client.create(); client.addFilter(new HTTPBasicAuthFilter(AUTH_USER, AUTH_PASS)); WebResource resource = client.resource(baseUrl() + uri); log.info("XOS REST CALL>> {}", resource); return resource.accept(UTF_8).type(UTF_8); }
@Override public void setConf(Configuration conf) { super.setConf(conf); if (conf == null) { // Configured gets passed null before real conf. Why? I don't know. return; } serverHostname = conf.get(REST_API_CLUSTER_MANAGER_HOSTNAME, DEFAULT_SERVER_HOSTNAME); serverUsername = conf.get(REST_API_CLUSTER_MANAGER_USERNAME, DEFAULT_SERVER_USERNAME); serverPassword = conf.get(REST_API_CLUSTER_MANAGER_PASSWORD, DEFAULT_SERVER_PASSWORD); clusterName = conf.get(REST_API_CLUSTER_MANAGER_CLUSTER_NAME, DEFAULT_CLUSTER_NAME); // Add filter to Client instance to enable server authentication. client.addFilter(new HTTPBasicAuthFilter(serverUsername, serverPassword)); }
private HTTPBasicAuthFilter handleCredentials(MaterialDefinition definition) { HTTPBasicAuthFilter credentials = null; // // if (definition.getUsername() != null && definition.getPassword() != null) { // String username = materialSpecificDetails.get("username").toString(); // String password = super.securityService.decrypt(materialSpecificDetails.get("password").toString()); // // credentials = new HTTPBasicAuthFilter(username, password); // } return credentials; }
public GitHubEventsChangeTracker(String user, String password, String slug, String url) { getClient().addFilter(new HTTPBasicAuthFilter(user, password)); repository = createRepository(user, slug, url); webResource = getEventResource(); markState(); }
@ParametersAreNonnullByDefault public List<GitHubRepositoryHook> getHooks(Repository repository, String username, String password) { WebResource hooksWebResource = resource(repository, "/hooks"); final HTTPBasicAuthFilter httpBasicFilter = new HTTPBasicAuthFilter(username, password); return getAll(hooksWebResource, GitHubRepositoryHook[].class, httpBasicFilter); }
/** * Creates jersey HTTP client * * @param login Username on the remote server * @param password User's password * @return HTTP client */ private Client getClient(String login, String password) { ClientConfig config = new DefaultClientConfig(); config.getProperties().put(ClientConfig.PROPERTY_CONNECT_TIMEOUT, 1000); config.getProperties().put(ClientConfig.PROPERTY_READ_TIMEOUT, 2000); Client client = Client.create(config); client.setExecutorService(jerseyHttpClientExecutor); if (login != null && !login.isEmpty() && password != null) { log.debug("Creating HTTP client with authorized HTTPBasicAuthFilter."); client.addFilter(new HTTPBasicAuthFilter(login, password)); } else { log.debug("Creating HTTP client with anonymous HTTPBasicAuthFilter."); } return client; }
private Client getClient(String host, String username, String password, boolean tlsEnabled, boolean hostnameVerificationEnabled) throws NoSuchAlgorithmException { if (!hostMap.containsKey(host)) { ClientConfig clientConfig = getClientConfig(tlsEnabled, hostnameVerificationEnabled); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter(username, password)); if (isDebug) { client.addFilter(new LoggingFilter()); } hostMap.put(host, client); } return hostMap.get(host); }
/** * Fetches the operations list (list of changes) from the remote repository. * * @param remoteRegistry * harvested registry. * @return list of operations fetched from the registry. * @throws UniformInterfaceException * if remote repository's reply have unexpected format. */ private Operations getOperationsList(RemoteRegistry remoteRegistry) throws UniformInterfaceException { ClientConfig config = new DefaultClientConfig(); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(getHostnameVerifier(), getSSLContext())); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter("test", "test")); WebResource service = client.resource(getURI(remoteRegistry)); service.addFilter(new HTTPBasicAuthFilter("test", "test")); if (remoteRegistry.getLatestHarvestDate() != null) { service = service.queryParam("from", remoteRegistry.getLatestHarvestDate().toString()); } return service.accept(MediaType.APPLICATION_XML).get(Operations.class); }
public UserServiceClient(String domain, int port, boolean ssl, String username, String password) throws JAXBException, XMLStreamException { this.username = username; this.password = password; this.domain = domain; this.port = port; this.ssl = ssl; client = Client.create(); client.addFilter(new HTTPBasicAuthFilter(this.username, this.password)); logger.debug("Client Initialized with: " + getBaseUrl() + " for user: " + username); this.initializeJaxb(Users.class, User.class); }
private static ClientResponse getClientResponse(Object st, String path) { String masterServer = "http://tinytank.lefrantguillaume.com/api/client/"; ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter("T0N1jjOQIDmA4cJnmiT6zHvExjoSLRnbqEJ6h2zWKXLtJ9N8ygVHvkP7Sy4kqrv", "lMhIq0tVVwIvPKSBg8p8YbPg0zcvihBPJW6hsEGUiS6byKjoZcymXQs5urequUo")); WebResource webResource = client.resource(masterServer + path); ClientResponse response = webResource.accept("application/json").type("application/json").post(ClientResponse.class, st); if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } return response; }
public int addJobQueryParam(MsJob job, String username, String password) { Client client = Client.create(); HTTPBasicAuthFilter authFilter = new HTTPBasicAuthFilter(username, password); client.addFilter(authFilter); MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl(); queryParams.add("projectId", String.valueOf(job.getProjectId())); queryParams.add("dataDirectory", job.getDataDirectory()); queryParams.add("pipeline", job.getPipeline()); queryParams.add("date", "09/23/2010"); //HttpHeaders.AUTHORIZATION WebResource webRes = client.resource(BASE_URI); ClientResponse response = webRes.path("add").queryParams(queryParams) // .accept("text/plain"). // header(HttpHeaders.AUTHORIZATION, "Basic " // + new String(Base64.encode("user:password"), // Charset.forName("ASCII"))). .post(ClientResponse.class); Status status = response.getClientResponseStatus(); if(status == Status.OK) { String jobId = response.getEntity(String.class); System.out.println(jobId); return Integer.parseInt(jobId); } else { System.err.println(status.getStatusCode()+": "+status.getReasonPhrase()); System.err.println(response.getEntity(String.class)); return 0; } }
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()); }
TavernaServer(TavernaServer service, String username, String password) { Client client = createClient(); client.addFilter(new HTTPBasicAuthFilter(username, password)); authenticated = true; root = root(client, location = service.location); getServerVersionInfo(); }
public Neo4jRestConcreteBuilder(String serverRootUrl, String username, String password) { this.httpBasicAuthFilter = new HTTPBasicAuthFilter(username, password); // setting parameters related to neo4j up this.serverRootUrl = serverRootUrl; this.nodeEntryPointUri = this.serverRootUrl + "/node"; this.cypherEntryPointUri = this.serverRootUrl + "/cypher"; this.nodeLabelsEntryPointUriAppendex = "/labels"; }
public String authenticate(String uname, String pwd) throws Exception { logger.info("Authenticating user: " + username); username = uname; password = pwd; ClientConfig clientConfig = new DefaultClientConfig(); Client client = Client.create(clientConfig); client.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource resource = client.resource(ENDPOINT + "cms?login=true&username=" + username + "&password=" + password + "&output=json"); Builder builder = resource.getRequestBuilder(); builder = builder.accept(javax.ws.rs.core.MediaType.APPLICATION_JSON); builder = builder.type(javax.ws.rs.core.MediaType.APPLICATION_JSON); ClientResponse response = builder.get(ClientResponse.class); List<NewCookie> cookies = response.getCookies(); for (NewCookie cookie : cookies) { if (cookie.getName().matches("JSESSIONID_WS")) { JSESSIONID_WS = cookie; } } if(JSESSIONID_WS != null){ return JSESSIONID_WS.getValue(); }else{ return null; } }
/** * @param apiKey your Stripe api key * @param failOnUnknownProperties If true, a {@link org.codehaus.jackson.map.JsonMappingException} is thrown when * unknown Stripe response object properties are encountered. This is primarily used for * testing / debugging purposes. */ public Client(String apiKey, boolean failOnUnknownProperties) { ObjectMapper mapper = new ObjectMapper(); mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES); mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); mapper.registerModule(new StripeModule()); DefaultClientConfig config = new DefaultClientConfig(); config.getSingletons().add(new JacksonJsonProvider(mapper)); com.sun.jersey.api.client.Client client = com.sun.jersey.api.client.Client.create(config); client.addFilter(new HTTPBasicAuthFilter(apiKey, "")); service = client.resource(UriBuilder.fromUri(BASE_URL + VERSION + "/").build()); }
@Test public void authenticatedGetBook() { Client client = new Client(); client.addFilter(new HTTPBasicAuthFilter("jing", "jing")); assertBook(client, new Book(1, "testISDN", "dropwizard in action", "developing restful msa with dropwizard", 1)); }
@Override protected void sendEmailWithService(EmailWrapper wrapper) { 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); if (response.getStatus() != SUCCESS_CODE) { log.severe("Email failed to send: " + response.getStatusInfo().getReasonPhrase()); } }
private static String createRemoteClusters(String cbClientUsername, String cbClientPassword, String host, String port) { String uuid = getRemoteClusterRef(cbClientUsername, cbClientPassword, host, port); if(uuid != null) { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter(couchbaseUsername, couchbasePassword)); String url = "http://" + couchbaseIp + ":" + "8091"; WebResource couchbaseService = client.resource(UriBuilder.fromUri(url).build()); MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uuid", uuid); formData.add("name", clusterName); formData.add("hostname", host + ":" + port); formData.add("username", cbClientUsername); formData.add("password", cbClientPassword); ClientResponse response = couchbaseService.path("pools").path("default").path("remoteClusters").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if(response.getStatus() == 200) { LOG.debug("CouchbaseUtils.createRemoteClusters : " + "Remote cluter = " + clusterName + " created."); return uuid; } else { LOG.warn("CouchbaseUtils.createRemoteClusters : " + "Remote cluter = " + clusterName + " creation failed with msg = " + response.getEntity(String.class)); } } return null; }
private static String getRemoteClusterRef(String cbClientUsername, String cbClientPassword, String host, String port) { ClientConfig remoteConfig = new DefaultClientConfig(); Client remoteClient = Client.create(remoteConfig); remoteClient.addFilter(new HTTPBasicAuthFilter(cbClientUsername, cbClientPassword)); String url = "http://" + host + ":" + port; WebResource remoteServerService = remoteClient.resource(UriBuilder.fromUri(url).build()); String uuid = null; try { JSONObject obj = new JSONObject(remoteServerService.path("pools").path("default").path("remoteCluster").accept(MediaType.APPLICATION_JSON).get(String.class)); obj = obj.getJSONObject("buckets"); String uri = obj.getString("uri"); uuid = uri.substring(uri.indexOf("uuid=")+"uuid=".length()); } catch(Exception e) { LOG.warn("CouchbaseUtils.getRemoteClusterRef : " + e.getMessage()); } return uuid; }
public static void createReplication(String uuid) { ClientConfig config = new DefaultClientConfig(); Client client = Client.create(config); client.addFilter(new HTTPBasicAuthFilter(couchbaseUsername, couchbasePassword)); String url = "http://" + couchbaseIp + ":" + "8091"; WebResource couchbaseService = client.resource(UriBuilder.fromUri(url).build()); for(int i=0; i<fromBuckets.size(); i++) { MultivaluedMap formData = new MultivaluedMapImpl(); formData.add("uuid", uuid); formData.add("toCluster", clusterName); formData.add("fromBucket", fromBuckets.get(i)); formData.add("toBucket", toBuckets.get(i)); formData.add("replicationType", "continuous"); formData.add("type", "capi"); ClientResponse response = couchbaseService.path("controller").path("createReplication").type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).post(ClientResponse.class, formData); if(response.getStatus() == 200) { LOG.debug("CouchbaseUtils.createReplication : " + "Created Couchbase replication from Couchbase bukcet = " + fromBuckets.get(i) + " to Couchbase client bucket = " + toBuckets.get(i)); } else { LOG.warn("CouchbaseUtils.createReplication : " + "Failed to create Couchbase replication from Couchbase bukcet = " + fromBuckets.get(i) + " to Couchbase client bucket = " + toBuckets.get(i)); } } }
/** * Performs a login operation. The token is automatically associated with this client * connection. * * @param username The username. * @param password The password. * @return The authentication token. */ public String login(String username, String password) { WebResource resource = client.getClient().resource(client.uriBuilder("/login").build()); resource.addFilter(new HTTPBasicAuthFilter(username, password)); ClientResponse response = resource.get(ClientResponse.class); response.close(); client.setLoginTime(System.currentTimeMillis()); return client.getAuthToken(); }
@Before public void setUp() { ClientConfig config = new DefaultClientConfig(); m_client = Client.create(config); m_client.addFilter(new HTTPBasicAuthFilter("demo", "demo")); m_resource = m_client.resource("http://demo.opennms.org/opennms/rest/alarms"); }
@BeforeClass public static void startMethod() throws JSONException { final ClientConfig cc = new DefaultClientConfig(); final Client c = Client.create(cc); c.addFilter(new HTTPBasicAuthFilter("admin", "admin")); wr = c.resource(TestUtils.getUrlBase()); }
/** * Method startMethod. * @throws JSONException */ @BeforeClass public static void startMethod() throws JSONException{ // create a client: final ClientConfig cc = new DefaultClientConfig(); final Client c = Client.create(cc); c.addFilter(new HTTPBasicAuthFilter("admin", "admin")); wr = c.resource(TestUtils.getUrlBase()); }