/** * Create job arguments that are used by CrowdClient to build a POST request for a new job on * Crowdflower */ void createArgumentMaps() { argumentMap = new LinkedMultiValueMap<String, String>(); includedCountries = new Vector<String>(); excludedCountries = new Vector<String>(); Iterator<Map.Entry<String, JsonNode>> jsonRootIt = template.fields(); for (Map.Entry<String, JsonNode> elt; jsonRootIt.hasNext(); ) { elt = jsonRootIt.next(); JsonNode currentNode = elt.getValue(); String currentKey = elt.getKey(); if (currentNode.isContainerNode()) { // special processing for these arrays: if (currentKey.equals(includedCountriesKey) || currentKey.equals(excludedCountriesKey)) { Iterator<JsonNode> jsonSubNodeIt = currentNode.elements(); for (JsonNode subElt; jsonSubNodeIt.hasNext(); ) { subElt = jsonSubNodeIt.next(); (currentKey.equals(includedCountriesKey) ? includedCountries : excludedCountries) .addElement(subElt.path(countryCodeKey).asText()); } } } else if (!currentNode.isNull() && argumentFilterSet.contains(currentKey)) { argumentMap.add(jobKey + "[" + currentKey + "]", currentNode.asText()); } if (currentKey == idKey) { this.id = currentNode.asText(); } } }
/** * Orders the job given by its jobid. Pay is per assigment, which is by default 5 units. * * @param job as CrowdJob * @param channels : a vector of channels, in which the job should be made available * @param units : number of units to order * @param payPerAssigment : pay in (dollar) cents for each assignments * @return JsonNode that Crowdflower returns */ JsonNode orderJob(CrowdJob job, Vector<String> channels, int units, int payPerAssigment) { Log LOG = LogFactory.getLog(getClass()); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.getMessageConverters().add(new FormHttpMessageConverter()); MultiValueMap<String, String> argumentMap = new LinkedMultiValueMap<String, String>(); argumentMap.add(debitKey, String.valueOf(units)); for (String channel : channels) { argumentMap.add(channelKey + "[]", channel); } updateVariable(job, jobPaymentKey, String.valueOf(payPerAssigment)); LOG.info( "Order Job: #" + job.getId() + " with " + units + " judgments for " + payPerAssigment + " cents (dollar) per assigment."); JsonNode result = restTemplate.postForObject(orderJobURL, argumentMap, JsonNode.class, job.getId(), apiKey); return result; }
/** * Obtain a new access token for the specified resource using the refresh token. * * @param resource The resource. * @param refreshToken The refresh token. * @return The access token, or null if failed. */ protected OAuth2AccessToken obtainAccessToken( OAuth2ProtectedResourceDetails resource, OAuth2RefreshToken refreshToken) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("grant_type", "refresh_token"); form.add("refresh_token", refreshToken.getValue()); return retrieveToken(form, resource); }
@Override public boolean login(String username, String password) throws ServiceException { RestTemplate restTemplate = this.restClient.getRestTemplate(); String url = this.restClient.createServiceUrl("/login"); HttpHeaders headers = this.restClient.getHttpHeaders(); headers.add("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_VALUE); MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("user", username); form.add("password", password); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<MultiValueMap<String, String>>(form, headers); LOG.info("Login " + username + " at " + url); UserStatusDto status = null; try { status = restTemplate.postForObject(url, entity, UserStatusDto.class); } catch (RestClientException e) { throw new ServiceException("Login failed: " + e.getMessage(), e); } if (status.getEvent() == UserEvent.AUTH_FAILURE) { return false; } LOG.debug("Login " + username + " successful"); this.user = status; return true; }
private static void loginAndSaveXAuthToken( final String user, final String password, final HttpHeaders headersToUpdate) { log.info("Authenticating user before subscribing to web socket"); String url = "http://dev.bearchoke.com:" + port + "/api/authenticate"; try { new RestTemplate() .execute( url, HttpMethod.POST, request -> { MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); map.add("username", user); map.add("password", password); new FormHttpMessageConverter() .write(map, MediaType.APPLICATION_FORM_URLENCODED, request); }, response -> { String xAuthToken = response.getHeaders().getFirst(ServerConstants.X_AUTH_TOKEN); log.info("Retrieved x-auth-token: " + xAuthToken); headersToUpdate.add(ServerConstants.X_AUTH_TOKEN, xAuthToken); return null; }); } catch (Exception ex) { log.error(ex.getMessage(), ex); } }
/** * @name createBugzillaUser * @description this method is used to create user for bugzilla at the time of binding as the name * as [email protected] as the service id is used to create the product and group so by * default this user will associate that group and product * @param serviceInstance * @return */ public BugzillaUser createBugzillaUser(ServiceInstance serviceInstance) { String userMailId = "admin@" + serviceInstance.getId() + ".com"; final String password = generatePassword(); BugzillaUser bugzillaUser = new BugzillaUser(); setProperties(); try { url = new URI(REST_CREATE_USER_URL); MultiValueMap<String, String> userData = new LinkedMultiValueMap<String, String>(); userData.add("email", userMailId); // a valid email required userData.add("full_name", userMailId); userData.add("password", password); HttpEntity<?> requestEntity = new HttpEntity<Object>(userData, createHeaders()); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.POST, requestEntity, String.class); ObjectMapper mapper = new ObjectMapper(); bugzillaUser = mapper.readValue(responseEntity.getBody(), BugzillaUser.class); if (bugzillaUser.getId() != null) { bugzillaUser.setEmail(userMailId); bugzillaUser.setPassword(password); } logger.info("Bugzilla User Created " + bugzillaUser.getId()); updateBugzillaUserAsAdmin(bugzillaUser); createComponent(serviceInstance.getId()); } catch (Exception e) { e.printStackTrace(); } return bugzillaUser; }
/** tests that an error occurs if you attempt to use bad client credentials. */ @Test @Ignore // Need a custom auth entry point to get the correct JSON response here. public void testInvalidClient() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "password"); formData.add("username", resource.getUsername()); formData.add("password", resource.getPassword()); formData.add("scope", "cloud_controller.read"); HttpHeaders headers = new HttpHeaders(); headers.set( "Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8")))); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); List<String> newCookies = response.getHeaders().get("Set-Cookie"); if (newCookies != null && !newCookies.isEmpty()) { fail("No cookies should be set. Found: " + newCookies.get(0) + "."); } assertEquals( "no-cache, no-store, max-age=0, must-revalidate", response.getHeaders().getFirst("Cache-Control")); assertEquals(401, response.getStatusCode().value()); @SuppressWarnings("unchecked") OAuth2Exception error = OAuth2Exception.valueOf(response.getBody()); assertEquals("Bad credentials", error.getMessage()); assertEquals("invalid_request", error.getOAuth2ErrorCode()); }
private MultiValueMap<String, String> getParametersForTokenRequest( AuthorizationCodeResourceDetails resource, OAuth2SecurityContext context) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("grant_type", "authorization_code"); form.add("code", context.getAuthorizationCode()); String redirectUri = resource.getPreEstablishedRedirectUri(); if (context != null && redirectUri == null) { // no pre-established redirect uri: use the preserved state // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(context.getPreservedState()); } else { // TODO: the state key is what should be sent, not the value form.add("state", String.valueOf(context.getPreservedState())); } if (redirectUri == null) { // still no redirect uri? just try the one for the current context... redirectUri = context == null ? null : context.getUserAuthorizationRedirectUri(); } form.add("redirect_uri", redirectUri); return form; }
/** * @name createProduct * @description Method is used in provisioning of service to create the product for bugzilla by * taking the service_instance as a name whenever the product is created at the same time with * same name the group for that product is created by bugzilla internally * @param productName * @return Product * @throws IOException */ public Product createProduct(String productName) throws IOException { if (getBugzillaProduct(productName).getProducts() != null && getBugzillaProduct(productName).getProducts().size() != 0) { updateProductGroup(productName); return getBugzillaProduct(productName).getProducts().get(0); } Product bugzillaProduct = new Product(); setProperties(); try { logger.info( "Bugzilla getBugzillaResource().getBugzillaServer() " + getBugzillaResource().getBugzillaServer()); url = new URI(REST_PRODUCT_URL); MultiValueMap<String, String> productData = new LinkedMultiValueMap<String, String>(); productData.add("name", productName); productData.add("description", productName + " as description"); productData.add("version", "1.0"); HttpEntity<?> requestEntity = new HttpEntity<Object>(productData, createHeaders()); ResponseEntity<String> responseEntity = getRestTemplate().exchange(url, HttpMethod.POST, requestEntity, String.class); ObjectMapper mapper = new ObjectMapper(); bugzillaProduct = mapper.readValue(responseEntity.getBody(), Product.class); logger.info("Bugzilla Product Created " + bugzillaProduct.getId()); if (bugzillaProduct.getId() != null) { bugzillaProduct = getBugzillaProduct(productName).getProducts().get(0); updateProductGroup(productName); } } catch (Exception e) { e.printStackTrace(); } return bugzillaProduct; }
private Map<String, Object> makeCall(String json, String method) throws PluggableTaskException { LOG.debug("Calling method: '%s', with JSON: %s", method, json); MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>(); postParameters.add("rest_data", json); postParameters.add("input_type", "JSON"); postParameters.add("method", method); postParameters.add("response_type", "JSON"); RestTemplate restTemplate = new RestTemplate(); String resultString = restTemplate.postForObject( ENTRY_POINT, postParameters, String.class, getParameter(PARAM_SERVER.getName()), getParameter(PARAM_SUGARINSTANCE.getName())); LOG.debug("Result contents: %s", resultString); // Tried to use Spring MappingJacksonHttpMessageConverter, but // server sends text/html mime type. Using Jackson directly: ObjectMapper mapper = new ObjectMapper(); Map<String, Object> result = null; try { result = mapper.readValue(resultString, Map.class); } catch (IOException ioe) { throw new PluggableTaskException(ioe); } return result; }
@Override public SlackMessageResponse meMessage(String message, String channelNameOrId) { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("channel", channelNameOrId); map.add("text", message); SlackMessageResponse slackResponse = post("/chat.meMessage", map, SlackMessageResponse.class); return slackResponse; }
public void proposeEdit( String venueId, String name, String address, String crossStreet, String city, String state, String zip, String phone, double latitude, double longitude, String primaryCategoryId) { requireUserAuthorization(); MultiValueMap<String, Object> params = new LinkedMultiValueMap<String, Object>(); params.add("name", name); params.add("address", address); params.add("crossStreet", crossStreet); params.add("city", city); params.add("state", state); params.add("zip", zip); params.add("phone", phone); params.add("ll", Double.toString(latitude) + "," + Double.toString(longitude)); params.add("primaryCategoryId", primaryCategoryId); post(buildUri(VENUES_ENDPOINT + venueId + "/proposeedit"), params, Map.class); }
/** * Para funcionar este teste precisa adicionar uma foto que tenha no computador e que altere no * arquivo application.properties a pasta na chave "pasta.upload" */ @Test public void testA_uploadPost() { MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("id", "1"); parts.add("file", new FileSystemResource("C:\\Users\\Mineiro\\Downloads\\foto1.jpg")); ResponseEntity<ProdutoJson> response = template.postForEntity(host + "/fotos/upload", parts, ProdutoJson.class); assertEquals(HttpStatus.OK, response.getStatusCode()); }
@Test public void queryParams() throws URISyntaxException { UriComponentsBuilder builder = UriComponentsBuilder.newInstance(); UriComponents result = builder.queryParam("baz", "qux", 42).build(); assertEquals("baz=qux&baz=42", result.getQuery()); MultiValueMap<String, String> expectedQueryParams = new LinkedMultiValueMap<>(2); expectedQueryParams.add("baz", "qux"); expectedQueryParams.add("baz", "42"); assertEquals(expectedQueryParams, result.getQueryParams()); }
@Override public SlackMessageResponse deleteMessage( String timestamp, String channelNameOrId, boolean asUser) { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("ts", timestamp); map.add("channel", channelNameOrId); map.add("as_user", Boolean.toString(asUser)); SlackMessageResponse slackResponse = get("/chat.delete", map, SlackMessageResponse.class); return slackResponse; }
@Override public SlackMessageResponse updateMessage( String timestamp, String channelNameOrId, boolean asUser, String message) { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("ts", timestamp); map.add("channel", channelNameOrId); map.add("text", message); map.add("as_user", String.valueOf(asUser)); SlackMessageResponse slackResponse = post("/chat.update", map, SlackMessageResponse.class); return slackResponse; }
public void writeScopesForService(String appIdentifier, List<GemoScopeBean> scopes) throws JsonParseException, JsonMappingException, IOException { List<String> scopeIds = scopeClient.getScopeIdsForScopes(scopes); for (String scopeId : scopeIds) { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("tableName", table); map.add("service_name", appIdentifier); map.add("scope_pkey", scopeId); insert(map); } }
@Override public SlackMessageResponse postMessage( String message, String channelNameOrId, String usernameOrBotName) { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("channel", channelNameOrId); map.add("text", message); map.add("username", usernameOrBotName); map.add("as_user", "false"); map.add("unfurl_links", "true"); SlackMessageResponse slackResponse = post("/chat.postMessage", map, SlackMessageResponse.class); return slackResponse; }
@Test public void testFieldPrefixCausesFieldReset() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("_postProcessed", "visible"); formData.add("postProcessed", "on"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertTrue(this.testBean.isPostProcessed()); formData.remove("postProcessed"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertFalse(this.testBean.isPostProcessed()); }
@Test public void testFieldDefaultNonBoolean() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("!name", "anonymous"); formData.add("name", "Scott"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertEquals("Scott", this.testBean.getName()); formData.remove("name"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertEquals("anonymous", this.testBean.getName()); }
@Override public SlackMessageResponse updateMessage( String timestamp, String channelNameOrId, boolean asUser, String message, List<SlackAttachment> attachments, boolean linkNames) throws SlackException { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add("ts", timestamp); map.add("channel", channelNameOrId); map.add("text", message); map.add("as_user", String.valueOf(asUser)); if (attachments != null && !attachments.isEmpty()) { try { map.add("attachments", new ObjectMapper().writeValueAsString(attachments)); } catch (JsonProcessingException e) { throw new SlackException(e); } } if (linkNames) { map.add("link_names", "1"); map.add("parse", "full"); } else { map.add("parse", "none"); } SlackMessageResponse slackResponse = post("/chat.update", map, SlackMessageResponse.class); return slackResponse; }
public AlchemyResponse crawlAndExtract(String url) throws Exception { AlchemyResponse alchemyResponse = new AlchemyResponse(); AlchemyResponse alchemyResponseURL = new AlchemyResponse(); if (logger.isTraceEnabled()) { logger.trace("Invoking Alchemy for url:" + url); } // Proxy settings // System.getProperties().put("proxySet", "true"); // System.getProperties().put("http.proxyHost", "192.168.100.40"); // System.getProperties().put("http.proxyPort", "8080"); MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); map.add(urlPropertyKey, url); Enumeration<String> keys = bundle.getKeys(); String key; while (keys.hasMoreElements()) { key = keys.nextElement(); map.add(key, bundle.getString(key)); } // header and message converter preparation HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new MappingJackson2HttpMessageConverter(new ObjectMapper())); messageConverters.add(new FormHttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); // call to alchymy try { alchemyResponse = restTemplate.postForObject( getRestServiceUrl() + "URLGetRankedNamedEntities", request, AlchemyResponse.class); alchemyResponseURL = restTemplate.postForObject( getRestServiceUrl() + "URLGetTitle", request, AlchemyResponse.class); alchemyResponse.setTitle(alchemyResponseURL.getTitle()); } catch (ResourceAccessException e) { throw new Exception("Alchemy online service not accessible.", e); } return alchemyResponse; }
/** tests that a client secret is required. */ @Test public void testSecretRequired() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "password"); formData.add("username", resource.getUsername()); formData.add("password", resource.getPassword()); formData.add("scope", "cloud_controller.read"); HttpHeaders headers = new HttpHeaders(); headers.set( "Authorization", "Basic " + new String(Base64.encode("no-such-client:".getBytes("UTF-8")))); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); ResponseEntity<String> response = serverRunning.postForString("/oauth/token", formData, headers); assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode()); }
private HttpEntity<MultiValueMap<String, ?>> generatePartialResourceRequest( UploadApplicationPayload application, CloudResources knownRemoteResources) throws IOException { MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(2); if (application.getNumEntries() > 0) { // If the entire app contents are cached, send nothing body.add("application", application); } ObjectMapper mapper = new ObjectMapper(); String knownRemoteResourcesPayload = mapper.writeValueAsString(knownRemoteResources); body.add("resources", knownRemoteResourcesPayload); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); return new HttpEntity<MultiValueMap<String, ?>>(body, headers); }
private void getDCAppTerms() { final String url = "http://www.dcapp.org/rest/taxonomy_vocabulary/getTree"; MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); body.add("vid", "12"); ResponseEntity<TermList> responseEntity = null; HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "xml"))); HttpEntity<?> requestEntity = new HttpEntity<Object>(body, requestHeaders); TermList termlist = null; try { RestTemplate restTemplate = new DCAppRestTemplate(10 * 1000); SimpleXmlHttpMessageConverter converter = new SimpleXmlHttpMessageConverter(); HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter(); restTemplate.getMessageConverters().add(converter); restTemplate.getMessageConverters().add(formHttpMessageConverter); restTemplate.getMessageConverters().add(stringHttpMessageConverternew); responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, TermList.class); termlist = responseEntity.getBody(); } catch (RestClientException e) { Log.e("DirectoryFragment", "Exception while retrieving terms listing.", e.getCause()); } if (termlist != null) { termlist.setIsParent(); DCAppApplication app = (DCAppApplication) getApplication(); app.setTermList(termlist); } }
/** * This method logs into a service by doing an standard http using the configuration in this * class. * * @param username the username to log into the application with * @param password the password to log into the application with * @return the url that the login redirects to */ public String login(String username, String password) { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.add(usernameInputFieldName, username); form.add(passwordInputFieldName, password); URI location = this.template.postForLocation(loginUrl(), form); return location.toString(); }
private Map resolveRequestHeaderMap(Class<? extends Map> mapType, NativeWebRequest webRequest) { if (MultiValueMap.class.isAssignableFrom(mapType)) { MultiValueMap<String, String> result; if (HttpHeaders.class.isAssignableFrom(mapType)) { result = new HttpHeaders(); } else { result = new LinkedMultiValueMap<String, String>(); } for (Iterator<String> iterator = webRequest.getHeaderNames(); iterator.hasNext(); ) { String headerName = iterator.next(); for (String headerValue : webRequest.getHeaderValues(headerName)) { result.add(headerName, headerValue); } } return result; } else { Map<String, String> result = new LinkedHashMap<String, String>(); for (Iterator<String> iterator = webRequest.getHeaderNames(); iterator.hasNext(); ) { String headerName = iterator.next(); String headerValue = webRequest.getHeader(headerName); result.put(headerName, headerValue); } return result; } }
@Test public void testWithCommaSeparatedStringArray() throws Exception { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("stringArray", "bar"); formData.add("stringArray", "abc"); formData.add("stringArray", "123,def"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertEquals("Expected all three items to be bound", 3, this.testBean.getStringArray().length); formData.remove("stringArray"); formData.add("stringArray", "123,def"); this.request.setBody(generateForm(formData)); this.binder.bind(createExchange()).blockMillis(5000); assertEquals("Expected only 1 item to be bound", 1, this.testBean.getStringArray().length); }
public MultiValueMap<String, String> getExcludedCountriesMap() { MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>(); for (String country : getExcludedCountries()) { map.add(jobKey + "[" + excludedCountriesKey + "][]", country); } return map; }
@Test public void testPartsBinding() { PartsBean bean = new PartsBean(); partsServlet.setBean(bean); MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); MockMultipartFile firstPart = new MockMultipartFile("fileName", "aValue".getBytes()); parts.add("firstPart", firstPart); parts.add("secondPart", "secondValue"); template.postForLocation(baseUrl + "/parts", parts); assertNotNull(bean.getFirstPart()); assertNotNull(bean.getSecondPart()); }